diff --git a/.classpath b/.classpath deleted file mode 100644 index 149cb3c..0000000 --- a/.classpath +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/.gitignore b/.gitignore index b83d222..dcb312f 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,36 @@ -/target/ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +### MacOS ### +.DS_Store diff --git a/.project b/.project deleted file mode 100644 index e3d2998..0000000 --- a/.project +++ /dev/null @@ -1,23 +0,0 @@ - - - casekit - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - - diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 714351a..0000000 --- a/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/.settings/org.eclipse.m2e.core.prefs b/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f..0000000 --- a/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/LICENSE b/LICENSE index 65c5ca8..8000a6f 100644 --- a/LICENSE +++ b/LICENSE @@ -1,165 +1,504 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 - Copyright (C) 2007 Free Software Foundation, Inc. + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 + USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random + Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/README.md b/README.md index af6cd92..407e7ee 100644 --- a/README.md +++ b/README.md @@ -1,28 +1,21 @@ -# -# The Computer-Assisted-Structure-Elucidation Kit (CASEkit) +[![DOI](https://zenodo.org/badge/124278536.svg)](https://zenodo.org/badge/latestdoi/124278536) [![GitHub contributors](https://img.shields.io/github/contributors/michaelwenk/casekit.svg)](https://github.com/michaelwenk/casekit/graphs/contributors/) [![GitHub issues](https://img.shields.io/github/issues/michaelwenk/casekit.svg)](https://github.com/michaelwenk/casekit/issues/) [![GitHub release](https://img.shields.io/github/release/michaelwenk/casekit.svg)](https://github.com/michaelwenk/casekit/releases/) -Copyright 2017 Christoph Steinbeck - -License: MIT, see doc/mit.license +# The Computer-Assisted-Structure-Elucidation Kit (CASEkit) ## Introduction -This project hosts various Java classes for teaching and research dealing with spectral data in chemistry and metabolomics. -This project depends on the Chemistry Development Project (CDK), hosted under http://cdk.github.io/ -Please refer to these pages for updated information and the latest version of the CDK. CDK's API documentation is available though our [Github site](http://cdk.github.io/cdk/). - -## Releases +This project depends on the Chemistry Development Project (CDK), hosted under https://cdk.github.io/ +Please refer to these pages for updated information and the latest version of the CDK. CDK's API documentation is +available though our [Github site](http://cdk.github.io/cdk/). -Latest release of casekit is at https://github.com/steinbeck/casekit/releases/latest +## Download Source code -## Download Spectra Source code +This assumes that you have git working on your system and you have initialised your local repository. -This assumes that you have git working on your system and you have initialised your local repository. Refer to https://help.github.com/articles/set-up-git/ for more - -Then, downloading spectra is just a matter of +Then, downloading casekit is just a matter of ```bash -$ git clone https://github.com/steinbeck/casedk.git +$ git clone https://github.com/michaelwenk/casekit ``` ## Compiling @@ -30,82 +23,11 @@ $ git clone https://github.com/steinbeck/casedk.git Compiling the library is performed with Apache Maven and requires Java 1.7 or later: ```bash -spectra/$ mvn package -``` -will create an all-in-one-jar under ./target - -## Usage - -### Shift Prediction with HOSE codes - -The following classes are to demonstrate the prediction of Carbon-13 NMR spectra with HOSE codes. They only demonstrate the basic working principle and ignore, for example, stereochemistry, which can lead to large errors in, for example, the prediction of shifts for E/Z configurations of double bonds. If you want to know more about the details and a sophisticated system implementing them, please refer to Schutz V, Purtuc V, Felsinger S, Robien W (1997) CSEARCH-STEREO: A new generation of NMR database systems allowing three-dimensional spectrum prediction. Fresenius Journal of Analytical Chemistry 359:33–41. doi: 10.1007/s002160050531. - -#### NMRShiftDBSDFParser - -Takes the NMRShiftDB SDF with assigned spectra (download from help section of NMRShiftDB.org) and produces a Tab-separated file with HOSE codes and assigned shift values. This file can then be read by HOSECodePredictor and SimilarityRanker. - -```bash -usage: java -jar spectra.jar casekit.NMRShiftDBSDFParser -i -o [-v] '[-d ]' [-m ] -Generates a table of HOSE codes and assigned shifts from an NMRShiftDB SDF -file from http://nmrshiftdb.nmr.uni-koeln.de/portal/js_pane/P-Help. - - -i,--infile filename of NMRShiftDB SDF with spectra - (required) - -o,--outfile filename of generated HOSE code table (required) - -v,--verbose generate messages about progress of operation - -d,--picdir store pictures in given directory - -m,--maxspheres maximum sphere size up to which to generate HOSE - codes +cd casekit +mvn clean package ``` -#### HOSECodePredictor - -Predicts a spectrum (chemical shifts, to be precise) for a given molecule provided as SDF file. -It needs the TSV file generated by NMRShiftDBSDFParser as input. - -```bash -usage: java -jar casekit.jar casekit.HOSECodePredictor -s -i - [-v] [-d ] [-m ] -Predict NMR chemical shifts for a given molecule based on table of HOSE -codes and assigned shifts. - - -s,--hosecodes filename of TSV file with HOSE codes (required) - -i,--infile filename of with SDF/MOL file of structures to be - predicted (required) - -v,--verbose generate messages about progress of operation - -d,--picdir store pictures of structures with assigned shifts - in given directory - -m,--maxspheres maximum sphere size up to which to generate HOSE - codes. Default is 6 spheres if this option is - ommitted. - -Please report issues at https://github.com/steinbeck/spectra -``` - -#### SimilarityRanker - -Rank structures based on given experimental spectrum and similarity to -predicted spectrum. - -```bash -usage: java -jar casekit.jar casekit.SimilarityRanker -i -p -o - -s [-n ] [-v] -Rank structures based on given experimental spectrum and similarity to -predicted spectrum. - - -i,--infile filename of with SDF/MOL file of structures to be - ranked (required) - -p,--spectrum filename of CSV file with spectrum. Format of each - line: ; (required) - -o,--outpath path to store pictures of ranked output structures - (required) - -s,--hosecodes filename of TSV file with HOSE codes (required) - -n,--number number of structures in output file. Default is - 10, if this option is ommitted - -v,--verbose generate messages about progress of operation - -Please report issues at https://github.com/steinbeck/spectra -``` +will create an all-in-one-jar under ./target which you can use in your Java project. diff --git a/lib/commons-cli-1.4.jar b/lib/commons-cli-1.4.jar deleted file mode 100644 index 22deb30..0000000 Binary files a/lib/commons-cli-1.4.jar and /dev/null differ diff --git a/pom.xml b/pom.xml index 92d3954..2502a92 100644 --- a/pom.xml +++ b/pom.xml @@ -1,62 +1,91 @@ - - 4.0.0 - casekit - casekit - 1.0-SNAPSHOT - spectra - - - org.openscience.cdk - cdk-silent - 2.1-SNAPSHOT - - - org.openscience.cdk - cdk-ctab - 2.1-SNAPSHOT - - - org.openscience.cdk - cdk-depict - 2.1-SNAPSHOT - - - commons-cli - commons-cli - 1.3.1 - - - - src - - - maven-compiler-plugin - 3.3 - - 1.8 - 1.8 - - - - maven-assembly-plugin - 3.0.0 - - - jar-with-dependencies - - - - - make-assembly - package - - single - - - - - - + + 4.0.0 + org.openscience + casekit + 1.0-SNAPSHOT + casekit + + + UTF-8 + + + + src + + + org.apache.maven.plugins + maven-compiler-plugin + + 11 + 11 + true + + 3.8.1 + + + org.apache.maven.plugins + maven-assembly-plugin + 3.3.0 + + + jar-with-dependencies + + + + + make-assembly + package + + single + + + + + + + + + org.openscience.cdk + cdk-bundle + 2.5 + + + org.openscience.nmrshiftdb + predictorc + 1.0 + + + commons-cli + commons-cli + 1.3.1 + + + org.apache.commons + commons-lang3 + 3.5 + + + org.projectlombok + lombok + 1.18.16 + compile + + + com.fasterxml.jackson.core + jackson-databind + 2.11.3 + + + com.google.code.gson + gson + 2.8.6 + + + org.mongodb + bson + 4.2.3 + + diff --git a/src/casekit/HOSECodePredictor.java b/src/casekit/HOSECodePredictor.java deleted file mode 100644 index da6cbc2..0000000 --- a/src/casekit/HOSECodePredictor.java +++ /dev/null @@ -1,369 +0,0 @@ -/* -* This Open Source Software is provided to you under the MIT License - * Refer to doc/mit.license or https://opensource.org/licenses/MIT for more information - * - * Copyright (c) 2017, Christoph Steinbeck - */ - -package casekit; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.Hashtable; -import java.util.StringTokenizer; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.CommandLineParser; -import org.apache.commons.cli.DefaultParser; -import org.apache.commons.cli.HelpFormatter; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; -import org.openscience.cdk.CDKConstants; -import org.openscience.cdk.depict.DepictionGenerator; -import org.openscience.cdk.exception.CDKException; -import org.openscience.cdk.interfaces.IAtom; -import org.openscience.cdk.interfaces.IAtomContainer; -import org.openscience.cdk.io.iterator.IteratingSDFReader; -import org.openscience.cdk.silent.SilentChemObjectBuilder; -import org.openscience.cdk.tools.HOSECodeGenerator; - - -/** - * Predicts NMRS spectra by lookup of HOSE codes - * (Bremser, W., HOSE - A Novel Substructure Code, Analytica Chimica Acta, 1978, 103:355-365) - * parsed from a tab-separated value file, produced, for example, by the NMRShiftDBSDFParser - * tool provided in this package. - * The current version is hard coded to predict carbon spectra only. - * - *

- * This Open Source Software is provided to you under the MIT License - * Refer to doc/mit.license or https://opensource.org/licenses/MIT for more information - * - * Copyright (c) 2017, Christoph Steinbeck - * - * @author Christoph Steinbeck - * - */ -public class HOSECodePredictor { - - Hashtable> hoseLookup; - public boolean verbose = false; - int maxSpheres = 6; //How many maximum spheres to use for the prediction - boolean generatePictures = false; - String picdir = null; - String inFile = null; - String hoseCodeFile = null; - String hoseTSVfile = null; - - /** - * Initializes a HOSECodePredictor by reading HOSECodes and assigned shift values from - * from a tab-separated values (TSV) file, produced, for example, by the NMRShiftDBSDFParser - * tool provided in this package. - * Each line in the TSV file has the format - *

- * String hosecode <\t>double shiftvalue - *

- * @param hoseTSVfile tab-separated values (TSV) file with HOSECodes and assigned shift values - * @throws Exception Exception if TSV file cannot be read - */ - public HOSECodePredictor(String hoseTSVfile) throws Exception - { - readHOSECodeTable(hoseTSVfile); - } - - /** - * Initializes an empty HOSECodePredictor. Use readHOSECodeTable(String hoseTSVfile) to initialise. - * - * Each line in the TSV file has the format - *

- * String hosecode <\t>double shiftvalue - *

- * @param hoseTSVfile tab-separated values (TSV) file with HOSECodes and assigned shift values - * @throws IOException Exception if TSV file cannot be read - */ - public HOSECodePredictor() throws Exception - { - - } - - public void predictFile(String outFile) throws Exception - { - - IAtomContainer ac = null; - File hoseTSVfile = new File(inFile); - IteratingSDFReader iterator = new IteratingSDFReader( - new FileReader(outFile), - SilentChemObjectBuilder.getInstance() - ); - - while (iterator.hasNext()) - { - ac = iterator.next(); - predict(ac); - generatePicture(ac, picdir); - } - iterator.close(); - } - - public void readHOSECodeTable() throws Exception - { - readHOSECodeTable(this.hoseTSVfile); - } - - /** - * Reads HOSE code table from TSV file. Without this, no prediction can be performed. - * Each line in the TSV file has the format - *

- * String hosecode <\t>double shiftvalue - *

- * - * @param hoseTSVfile - * @throws Exception - */ - public void readHOSECodeTable(String hoseTSVfile) throws Exception - { - String line = null; - StringTokenizer strtok; - String hose; - Double shift; - ArrayList shifts; - int linecounter = 0; - - if (verbose) System.out.println("Start reading HOSE codes from " + hoseTSVfile); - - BufferedReader br = new BufferedReader(new FileReader(hoseTSVfile)); - hoseLookup = new Hashtable>(); - while((line = br.readLine()) != null) - { - strtok = new StringTokenizer(line, "\t"); - linecounter++; - hose = strtok.nextToken(); - shift = Double.parseDouble(strtok.nextToken()); - //System.out.println(hose + " ---- " + shift); - if (hoseLookup.containsKey(hose)) - { - shifts = hoseLookup.get(hose); - shifts.add(new Double(shift)); - //System.out.println("HOSE code already in hashtable. Adding to existing list."); - } - else - { - //System.out.println("HOSE code not in hashtable. Adding to new list."); - shifts = new ArrayList(); - shifts.add(new Double(shift)); - hoseLookup.put(hose, shifts); - } - } - br.close(); - if (verbose) System.out.println("Finished reading " + linecounter + " lines of HOSE codes."); - - } - - /** - * Predicts NMR chemical shifts based on a given HOSE code table read by the - * Constructor of this class. - * The predicted chemical shifts are assigned to each atom by - * as a property of type CDKConstants.NMRSHIFT_CARBON. - * They are also written as CDKConstants.COMMENT to aid the - * DepictionGenerator class to generate a picture with shift annotations - * for all carbon atoms. - * - * @param ac The IAtomContainer for which to predict the shift values - * @throws Exception Thrown if something goes wrong. - */ - public void predict(IAtomContainer ac) throws Exception - { - IAtom atom; - String hose = null; - Double shift = null; - HOSECodeGenerator hcg = new HOSECodeGenerator(); - DecimalFormat df = new DecimalFormat(); - df.setMaximumFractionDigits(2); - /** - * A visual appendix to the CDKConstants.NMRSHIFT_COMMENT annotation to show - * how many HOSE code spheres where used to predict this shift value. - */ - String[] sphereCount = - { - "'", - "''", - "'''", - "''''", - "'''''", - "'''''", - "''''''", - "'''''''" - }; - fixExplicitHydrogens(ac); - if (verbose) System.out.println("Entering prediction module"); - for (int f = 0; f < ac.getAtomCount(); f++) - { - atom = ac.getAtom(f); - if (verbose) System.out.println("Atom no. " + f); - if (atom.getAtomicNumber() == 6) - { - // We descend from N-sphere HOSE codes defined by maxSpheres to those with lower spheres - for (int g = maxSpheres; g > 0; g--) - { - hose = hcg.getHOSECode(ac, atom, g); - //System.out.println("Look-up for HOSE code " + hose); - try{ - shift = getShift(hose); - if (shift != null) - { - if (verbose) System.out.println("Shift " + df.format(shift) + " found with " + g + "-sphere HOSE code."); - ac.getAtom(f).setProperty(CDKConstants.NMRSHIFT_CARBON, df.format(shift)); - ac.getAtom(f).setProperty(CDKConstants.COMMENT, df.format(shift) + sphereCount[g - 1]); - //If we found a HOSE code of a higher sphere, we take that one and skip the lower ones - break; - } - } - catch(Exception e) - { - e.printStackTrace(); - - } - } - } - } - } - - public Double getShift(String hose) - { - double shiftvalue = 0.0; - if (!hoseLookup.containsKey(hose)) return null; - ArrayList list = hoseLookup.get(hose); - for (int f = 0; f < list.size(); f++) - { - shiftvalue = shiftvalue + ((Double) list.get(f)).doubleValue(); - } - shiftvalue = shiftvalue / list.size(); - if (verbose) System.out.println("Predicted HOSE code from " + list.size() + " values"); - - return new Double(shiftvalue); - } - - public void generatePicture(IAtomContainer ac, String path) throws IOException, CDKException - { - String moleculeTitle = ""; - /* Path separators differ in operating systems. Unix uses slash, windows backslash. - That's why Java offers this constant File.pathSeparator since it knows what OS it is running on */ - if (path.endsWith(File.separator)) - moleculeTitle = path + "mol.png"; - else - moleculeTitle = path + File.separator + "mol.png"; - DepictionGenerator dg = new DepictionGenerator().withSize(800, 800).withAtomColors().withAtomValues().withMolTitle().withFillToFit(); - dg.depict(ac).writeTo(moleculeTitle); - } - - - - /** - * This predictor cannot handle explicit hydrogens. Where therefore convert them to implicit first - */ - void fixExplicitHydrogens(IAtomContainer ac) - { - IAtom atomB; - for (IAtom atomA : ac.atoms()) - { - if (atomA.getAtomicNumber() == 1) - { - atomB = ac.getConnectedAtomsList(atomA).get(0); - atomB.setImplicitHydrogenCount(atomB.getImplicitHydrogenCount() +1 ); - ac.removeAtom(atomA); - } - } - } - - private void parseArgs(String[] args) throws ParseException - { - Options options = setupOptions(args); - CommandLineParser parser = new DefaultParser(); - try { - CommandLine cmd = parser.parse( options, args); - this.inFile = cmd.getOptionValue("infile"); - this.hoseTSVfile = cmd.getOptionValue("hosecodes"); - if (cmd.hasOption("maxspheres")) - { - this.maxSpheres = Integer.parseInt(cmd.getOptionValue("maxspheres")); - } - if (cmd.hasOption("verbose")) this.verbose = true; - - if (cmd.hasOption("picdir")) - { - this.generatePictures = true; - this.picdir = cmd.getOptionValue("picdir"); - - } - } catch (ParseException e) { - // TODO Auto-generated catch block - HelpFormatter formatter = new HelpFormatter(); - formatter.setOptionComparator(null); - String header = "Predict NMR chemical shifts for a given molecule based on table of HOSE codes and assigned shifts.\n\n"; - String footer = "\nPlease report issues at https://github.com/steinbeck/spectra"; - formatter.printHelp( "java -jar casekit.jar casekit.HOSECodePredictor", header, options, footer, true ); - throw new ParseException("Problem parsing command line"); - } - } - - private Options setupOptions(String[] args) - { - Options options = new Options(); - Option hosefile = Option.builder("s") - .required(true) - .hasArg() - .longOpt("hosecodes") - .desc("filename of TSV file with HOSE codes (required)") - .build(); - options.addOption(hosefile); - Option infile = Option.builder("i") - .required(true) - .hasArg() - .longOpt("infile") - .desc("filename of with SDF/MOL file of structures to be predicted (required)") - .build(); - options.addOption(infile); - Option verbose = Option.builder("v") - .required(false) - .longOpt("verbose") - .desc("generate messages about progress of operation") - .build(); - options.addOption(verbose); - Option picdir = Option.builder("d") - .required(false) - .hasArg() - .longOpt("picdir") - .desc("store pictures of structures with assigned shifts in given directory") - .build(); - options.addOption(picdir); - Option maxspheres = Option.builder("m") - .required(false) - .hasArg() - .longOpt("maxspheres") - .desc("maximum sphere size up to which to generate HOSE codes. Default is 6 spheres if this option is ommitted.") - .build(); - options.addOption(maxspheres); - return options; - } - - public static void main(String[] args) { - // TODO Auto-generated method stub - HOSECodePredictor hcp = null; - try { - hcp = new HOSECodePredictor(); - hcp.parseArgs(args); - hcp.readHOSECodeTable(); - hcp.predictFile(hcp.inFile); - } catch (Exception e) { - // We don't do anything here. Apache CLI will print a usage text. - if (hcp.verbose) e.printStackTrace(); - } - - } -} diff --git a/src/casekit/NMRShiftDBSDFParser.java b/src/casekit/NMRShiftDBSDFParser.java deleted file mode 100644 index 796fe4c..0000000 --- a/src/casekit/NMRShiftDBSDFParser.java +++ /dev/null @@ -1,256 +0,0 @@ -/* -* This Open Source Software is provided to you under the MIT License - * Refer to doc/mit.license or https://opensource.org/licenses/MIT for more information - * - * Copyright (c) 2017, Christoph Steinbeck - */ -package casekit; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.util.StringTokenizer; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.CommandLineParser; -import org.apache.commons.cli.DefaultParser; -import org.apache.commons.cli.HelpFormatter; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; -import org.openscience.cdk.CDKConstants; -import org.openscience.cdk.aromaticity.Aromaticity; -import org.openscience.cdk.depict.DepictionGenerator; -import org.openscience.cdk.exception.CDKException; -import org.openscience.cdk.interfaces.IAtomContainer; -import org.openscience.cdk.interfaces.IMolecularFormula; -import org.openscience.cdk.io.iterator.IteratingSDFReader; -import org.openscience.cdk.silent.SilentChemObjectBuilder; -import org.openscience.cdk.tools.HOSECodeGenerator; -import org.openscience.cdk.tools.manipulator.AtomContainerManipulator; - -/** - * Helper class to parse an NMRShiftDB SDF file with spectra assignments - * and convert it to a tab-separated values file with HOSE codes - * (Bremser, W., HOSE - A Novel Substructure Code, Analytica Chimica Acta, 1978, 103:355-365) - * and associated shift values. - * The TSV file can then be used by HOSECodePredictor to predict spectra - * - * @author Christoph Steinbeck - */ - -public class NMRShiftDBSDFParser { - BufferedWriter bw; - IMolecularFormula formula = null; - String comment = null; - String carbonNMR = null; - String hydrogenNMR = null; - String moleculeTitle = null; - int carbonNMRCount = 0; - int hydrogenNMRCount = 0; - int moleculeCount = 0; - String report = ""; - String temp = ""; - boolean generatePictures = false; - String picdir = null; - int hoseCodeCounter = 0; - int carbonCounter = 0; - String inFile = null; - String outFile = null; - boolean verbose = false; - int maxSpheres; - - public NMRShiftDBSDFParser(String[] args) throws Exception - { - parseArgs(args); - if (verbose) System.out.println("Starting HOSE code generation with " + maxSpheres + " sphere from " + inFile); - File fout = new File(outFile); - FileOutputStream fos = new FileOutputStream(fout); - bw = new BufferedWriter(new OutputStreamWriter(fos)); - - IAtomContainer ac = SilentChemObjectBuilder.getInstance().newAtomContainer(); - - IteratingSDFReader iterator = new IteratingSDFReader( - new FileReader(inFile), - SilentChemObjectBuilder.getInstance() - ); - - while (iterator.hasNext()) - { - ac = iterator.next(); - carbonNMR = (String)ac.getProperty("Spectrum 13C 0"); - hydrogenNMR = (String)ac.getProperty("Spectrum 1H 0"); - if (carbonNMR != null) - { - carbonNMRCount++; - ac = assignCarbonNMR(ac, carbonNMR); - generateHOSECodes(ac, maxSpheres); - } - if (hydrogenNMR != null) hydrogenNMRCount++; - moleculeCount ++; - if (generatePictures) generatePicture(ac, picdir); - } - iterator.close(); - report = "File contains " + moleculeCount + " molecules with " + carbonNMRCount + " carbon spectra and " + hydrogenNMRCount + " hydrogen spectra.\n"; - report += hoseCodeCounter + " HOSE codes generated for " + carbonCounter + "carbon atoms, and written to file."; - if (verbose) System.out.println(report); - bw.close(); - } - - IAtomContainer assignCarbonNMR(IAtomContainer ac, String nmrString) throws IOException, CDKException - { - String sigString = null, shiftString = null, multString = null, atomNumString = null; - StringTokenizer strTok1 = new StringTokenizer(nmrString, "|"); - StringTokenizer strTok2 = null; - while (strTok1.hasMoreTokens()) - { - sigString = strTok1.nextToken(); //System.out.println(sigString); - strTok2 = new StringTokenizer(sigString, ";"); - while (strTok2.hasMoreTokens()) - { - shiftString = strTok2.nextToken(); //System.out.println(shiftString); - multString = strTok2.nextToken(); //System.out.println(multString); - atomNumString = strTok2.nextToken(); //System.out.println(atomNumString); - try - { - ac.getAtom(Integer.parseInt(atomNumString)).setProperty(CDKConstants.NMRSHIFT_CARBON, Double.parseDouble(shiftString)); - ac.getAtom(Integer.parseInt(atomNumString)).setProperty(CDKConstants.COMMENT, Double.parseDouble(shiftString)); - }catch(Exception exc) - { - System.out.println("Failed to assign shift to atom no. " + Integer.parseInt(atomNumString) + " in molecule no " + moleculeCount + ", title: " + ac.getProperty(CDKConstants.TITLE) + " with " + ac.getAtomCount() + " atoms. "); - } - } - } - return ac; - } - - public void generateHOSECodes(IAtomContainer ac, int maxSpheres) throws Exception - { - String hose = null; - HOSECodeGenerator hcg = new HOSECodeGenerator(); - AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(ac); - Aromaticity.cdkLegacy().apply(ac); - for (int f = 0; f < ac.getAtomCount(); f++) - { - if (ac.getAtom(f).getAtomicNumber() == 6) - { - carbonCounter ++; - for (int g = 0; g < maxSpheres; g++) - { - hose = hcg.getHOSECode(ac, ac.getAtom(f), g + 1); - if (hose != null && ac.getAtom(f).getProperty(CDKConstants.NMRSHIFT_CARBON) != null) - { - bw.write(hose + "\t" + ac.getAtom(f).getProperty(CDKConstants.NMRSHIFT_CARBON)); - bw.newLine(); - hoseCodeCounter++; - } - } - } - } - } - - public void generatePicture(IAtomContainer ac, String picdir) throws IOException, CDKException - { - try - { - temp = ac.getProperty(CDKConstants.TITLE); - if (temp != null && temp.length() > 15) temp = temp.substring(0, 14) + "..."; - ac.setProperty(CDKConstants.TITLE, temp); - } - catch(Exception e) - { - System.out.println("Problem with title " + temp); - } - if (!picdir.endsWith(File.separator)) picdir += File.separator; - moleculeTitle = picdir + String.format("%03d", moleculeCount) + "-mol.png"; - if (verbose) System.out.println(moleculeTitle); - DepictionGenerator dg = new DepictionGenerator().withSize(800, 800).withAtomColors().withAtomValues().withMolTitle().withFillToFit(); - dg.depict(ac).writeTo(moleculeTitle); - } - - private void parseArgs(String[] args) throws ParseException - { - Options options = setupOptions(args); - CommandLineParser parser = new DefaultParser(); - try { - CommandLine cmd = parser.parse( options, args); - this.inFile = cmd.getOptionValue("infile"); - this.outFile = cmd.getOptionValue("outfile"); - if (cmd.hasOption("maxspheres")) - { - this.maxSpheres = Integer.parseInt(cmd.getOptionValue("maxspheres")); - } - if (cmd.hasOption("verbose")) this.verbose = true; - - if (cmd.hasOption("picdir")) - { - this.generatePictures = true; - this.picdir = cmd.getOptionValue("picdir"); - - } - } catch (ParseException e) { - // TODO Auto-generated catch block - HelpFormatter formatter = new HelpFormatter(); - - formatter.setOptionComparator(null); - String header = "Generates a table of HOSE codes and assigned shifts from an NMRShiftDB SDF file from http://nmrshiftdb.nmr.uni-koeln.de/portal/js_pane/P-Help.\n\n"; - String footer = "\nPlease report issues at https://github.com/steinbeck/spectra"; - formatter.printHelp( "java -jar casekit.jar casekit.NMRShiftDBSDFParser", header, options, footer, true ); - throw new ParseException("Problem parsing command line"); - } - } - - private Options setupOptions(String[] args) - { - Options options = new Options(); - Option infile = Option.builder("i") - .required(true) - .hasArg() - .longOpt("infile") - .desc("filename of NMRShiftDB SDF with spectra (required)") - .build(); - options.addOption(infile); - Option outfile = Option.builder("o") - .required(true) - .hasArg() - .longOpt("outfile") - .desc("filename of generated HOSE code table (required)") - .build(); - options.addOption(outfile); - Option verbose = Option.builder("v") - .required(false) - .longOpt("verbose") - .desc("generate messages about progress of operation") - .build(); - options.addOption(verbose); - Option picdir = Option.builder("d") - .required(false) - .hasArg() - .longOpt("picdir") - .desc("store pictures in given directory") - .build(); - options.addOption(picdir); - Option maxspheres = Option.builder("m") - .required(false) - .hasArg() - .longOpt("maxspheres") - .desc("maximum sphere size up to which to generate HOSE codes") - .build(); - options.addOption(maxspheres); - return options; - } - - public static void main(String[] args) - { - try { - new NMRShiftDBSDFParser(args); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - -} diff --git a/src/casekit/Result.java b/src/casekit/Result.java deleted file mode 100644 index e451948..0000000 --- a/src/casekit/Result.java +++ /dev/null @@ -1,37 +0,0 @@ -/* -* This Open Source Software is provided to you under the MIT License - * Refer to doc/mit.license or https://opensource.org/licenses/MIT for more information - * - * Copyright (c) 2017, Christoph Steinbeck - */ - -package casekit; - -import org.openscience.cdk.interfaces.IAtomContainer; - -public class Result { - public IAtomContainer ac; - public double score; - - public Result(IAtomContainer ac, double score) { - super(); - this.ac = ac; - this.score = score; - } - - public IAtomContainer getAc() { - return ac; - } - public void setAc(IAtomContainer ac) { - this.ac = ac; - } - public double getScore() { - return score; - } - - public void setScore(double score) { - this.score = score; - } - - -} \ No newline at end of file diff --git a/src/casekit/Signal.java b/src/casekit/Signal.java deleted file mode 100644 index 1e87f1f..0000000 --- a/src/casekit/Signal.java +++ /dev/null @@ -1,45 +0,0 @@ -/* -* This Open Source Software is provided to you under the MIT License - * Refer to doc/mit.license or https://opensource.org/licenses/MIT for more information - * - * Copyright (c) 2017, Christoph Steinbeck - */ - -package casekit; - -public class Signal { - - Double shift = null; - Integer mult = null; - - public Signal() { - // TODO Auto-generated constructor stub - } - - Signal(double shift) - { - setShift(shift); - } - - Signal(double shift, int mult) - { - setShift(shift); - setMult(mult); - } - - public Integer getMult() { - return mult; - } - public void setMult(Integer mult) { - this.mult = mult; - } - - public Double getShift() { - return shift; - } - - public void setShift(Double shift) { - this.shift = shift; - } - -} diff --git a/src/casekit/SimilarityRanker.java b/src/casekit/SimilarityRanker.java deleted file mode 100644 index a85d1b9..0000000 --- a/src/casekit/SimilarityRanker.java +++ /dev/null @@ -1,305 +0,0 @@ - -/* -* This Open Source Software is provided to you under the MIT License - * Refer to doc/mit.license or https://opensource.org/licenses/MIT for more information - * - * Copyright (c) 2017, Christoph Steinbeck - */ -package casekit; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.StringTokenizer; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.CommandLineParser; -import org.apache.commons.cli.DefaultParser; -import org.apache.commons.cli.HelpFormatter; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; -import org.openscience.cdk.CDKConstants; -import org.openscience.cdk.depict.DepictionGenerator; -import org.openscience.cdk.interfaces.IAtom; -import org.openscience.cdk.interfaces.IAtomContainer; -import org.openscience.cdk.io.iterator.IteratingSDFReader; -import org.openscience.cdk.silent.SilentChemObjectBuilder; - -/** - * SimilarityRanker uses a SpectrumPredictor and parses an SDF file, returning a configurable number of compounds and - * their ranked spectrum similarity. - * - * This Open Source Software is provided to you under the MIT License - * Refer to doc/mit.license or https://opensource.org/licenses/MIT for more information - * - * Copyright (c) 2017, Christoph Steinbeck - * - * @author steinbeck - * - */ -public class SimilarityRanker { - - public boolean verbose = true; - DecimalFormat df; - public int resultListSize = 100; - public String inFile = null; - public String outPath = null; - public String spectrumFile = null; - public String hoseTSVFile = null; - ArrayList spectrum = null; - ArrayList results = null; - - public boolean isVerbose() { - return verbose; - } - - public void setVerbose(boolean verbose) { - this.verbose = verbose; - } - - public int getResultListSize() { - return resultListSize; - } - - public void setResultListSize(int resultListSize) { - this.resultListSize = resultListSize; - } - - public SimilarityRanker() { - // TODO Auto-generated constructor stub - df = new DecimalFormat(); - df.setMaximumFractionDigits(2); - } - - public void readSpectrum() throws NumberFormatException, IOException - { - String line; - StringTokenizer strtok; - int linecounter = 0; - Double shift = null; - Integer mult = null; - Signal signal; - String tempString; - ArrayList spectrum = new ArrayList(); - BufferedReader br = new BufferedReader(new FileReader(spectrumFile)); - if (verbose) System.out.println("Start reading spectrum from " + spectrumFile); - while((line = br.readLine()) != null) - { - if (!line.startsWith("#") && line.trim().length() > 0) - { - strtok = new StringTokenizer(line, ";"); - if (verbose) System.out.println(line); - linecounter++; - - shift = Double.parseDouble(strtok.nextToken().trim()); - mult = Integer.parseInt(strtok.nextToken().trim()); - signal = new Signal(shift, mult); - spectrum.add(signal); - } - } - br.close(); - if (verbose) System.out.println("Read " + linecounter + " signals from spectrum in file " + spectrumFile); - - this.spectrum = spectrum; - } - - - public ArrayList rank() throws Exception - { - /* - * Iterate of SDF file given by input file, predict a spectrum and calculate a similarity with the - * spectrum given in @spectrum. - * Store the 10 most similar spectra in a list and write them to outFile in the end - */ - - HOSECodePredictor predictor = new HOSECodePredictor(hoseTSVFile); - IAtomContainer ac = null; - double similarity = 0.0; - double bestSimilarity = 1000000000.0; - results = new ArrayList(); - ResultComparator comp = new ResultComparator(); - IteratingSDFReader iterator = new IteratingSDFReader( - new FileReader(inFile), - SilentChemObjectBuilder.getInstance() - ); - - while (iterator.hasNext()) - { - ac = iterator.next(); - predictor.predict(ac); - similarity = calculateSimilarity(ac, spectrum); - if (results.size() > 0) - { - if (similarity < results.get(results.size()-1).getScore()) - { - bestSimilarity = similarity; - ac.setProperty(CDKConstants.TITLE, "Distance " + df.format(similarity)); - results.add(new Result(ac, similarity)); - results.sort(comp); - //After sorting, we remove the worst entry and thereby trim the results list to resultListSize - if (results.size() == resultListSize) results.remove(resultListSize - 1); - } - } - else results.add(new Result(ac, similarity)); - } - iterator.close(); - if (verbose) System.out.println("Calculation finished. Best similarity = " + bestSimilarity); - return results; - } - - public double calculateSimilarity(IAtomContainer ac, ArrayList spectrum) - { - double similarity = 0.0; - double lastDiff = 0.0; - int counter = 0; - String shift = null; - boolean matchFound = false; - double diff = 0.0; - double shifts[] = new double[spectrum.size()]; - for (IAtom atom : ac.atoms()) - { - if (atom.getAtomicNumber() == 6) - { - shift = atom.getProperty(CDKConstants.NMRSHIFT_CARBON); - if (shift != null) shifts[counter] = Double.parseDouble(shift); - else shifts[counter] = -1.0; - counter ++; - } - } - for (int f = 0; f < spectrum.size(); f++) - { - lastDiff = 10000000000.0; - matchFound = false; - for (int g = 0; g < spectrum.size(); g++) - { - if (shifts[f] > spectrum.get(g).getShift().doubleValue()) diff = shifts[f] - spectrum.get(g).getShift().doubleValue(); - else diff = spectrum.get(g).getShift().doubleValue() - shifts[f]; - df.format(diff); - if (diff < lastDiff) - { - lastDiff = diff; - matchFound = true; - } - } - if (matchFound) similarity += lastDiff; - } - return similarity/spectrum.size(); - } - - public void reportResults() throws Exception - { - String filename = null; - DepictionGenerator dg = null; - if (!outPath.endsWith(File.separator)) - outPath += File.separator; - for (int f = 0; f < results.size(); f++) - { - filename = outPath + String.format("%03d", f) + "-mol.png"; - dg = new DepictionGenerator().withSize(800, 800).withAtomColors().withAtomValues().withMolTitle().withFillToFit(); - dg.depict(results.get(f).getAc()).writeTo(filename); - } - } - - - class ResultComparator implements Comparator - { - public int compare(Result o1, Result o2) { - - if (o1.getScore() < o2.getScore()) return -1; - return 1; - } - } - - private void parseArgs(String[] args) throws ParseException - { - Options options = setupOptions(args); - CommandLineParser parser = new DefaultParser(); - try { - CommandLine cmd = parser.parse( options, args); - this.inFile = cmd.getOptionValue("infile"); - this.hoseTSVFile = cmd.getOptionValue("hosecodes"); - this.outPath = cmd.getOptionValue("outpath"); - this.spectrumFile = cmd.getOptionValue("spectrum"); - if (cmd.hasOption("numbers")) this.resultListSize = Integer.parseInt(cmd.getOptionValue("numbers")); - if (cmd.hasOption("verbose")) this.verbose = true; - } catch (ParseException e) { - // TODO Auto-generated catch block - HelpFormatter formatter = new HelpFormatter(); - formatter.setOptionComparator(null); - String header = "Ranke structures based on given experimental spectrum and similarity to predicted spectrum.\n\n"; - String footer = "\nPlease report issues at https://github.com/steinbeck/spectra"; - formatter.printHelp( "java -jar casekit.jar casekit.SimilarityRanker", header, options, footer, true ); - throw e; - } - } - - private Options setupOptions(String[] args) - { - Options options = new Options(); - - Option infile = Option.builder("i") - .required(true) - .hasArg() - .longOpt("infile") - .desc("filename of with SDF/MOL file of structures to be ranked (required)") - .build(); - options.addOption(infile); - Option spectrumfile = Option.builder("p") - .required(true) - .hasArg() - .longOpt("spectrum") - .desc("filename of CSV file with spectrum. Format of each line: ; (required)") - .build(); - options.addOption(spectrumfile); - Option outpath = Option.builder("o") - .required(true) - .hasArg() - .longOpt("outpath") - .desc("path to store pictures of ranked output structures (required)") - .build(); - options.addOption(outpath); - Option hosefile = Option.builder("s") - .required(true) - .hasArg() - .longOpt("hosecodes") - .desc("filename of TSV file with HOSE codes (required)") - .build(); - options.addOption(hosefile); - Option outputnumber = Option.builder("n") - .hasArg() - .longOpt("number") - .desc("number of structures in output file. Default is 10, if this option is ommitted") - .build(); - options.addOption(outputnumber); - - Option verbose = Option.builder("v") - .required(false) - .longOpt("verbose") - .desc("generate messages about progress of operation") - .build(); - options.addOption(verbose); - - return options; - } - - - public static void main(String[] args) { - SimilarityRanker sr = new SimilarityRanker(); - try { - sr.parseArgs(args); - sr.readSpectrum(); - sr.rank(); - sr.reportResults(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - -} diff --git a/src/casekit/io/FileSystem.java b/src/casekit/io/FileSystem.java new file mode 100644 index 0000000..63e0e9e --- /dev/null +++ b/src/casekit/io/FileSystem.java @@ -0,0 +1,120 @@ +/* + * The MIT License + * + * Copyright 2019 Michael Wenk [https://github.com/michaelwenk] + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package casekit.io; + +import casekit.nmr.model.DataSet; + +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class FileSystem { + + public static BufferedReader readFile(final String pathToFile) { + try { + return new BufferedReader(new FileReader(pathToFile)); + } catch (final IOException e) { + e.printStackTrace(); + } + + return null; + } + + public static boolean writeFile(final String pathToFile, final String content) { + try { + final FileWriter fileWriter = new FileWriter(pathToFile); + final BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); + bufferedWriter.write(content); + bufferedWriter.close(); + + return true; + } catch (final IOException e) { + e.printStackTrace(); + } + + return false; + } + + public static boolean cleanup(final String[] directoriesToCheck, final String pattern) { + boolean cleaned = false; + + for (final String dir : directoriesToCheck) { + try { + cleaned = Files.walk(Paths.get(dir)) + .map(Path::toFile) + .filter(file -> file.getAbsolutePath() + .contains(pattern)) + .allMatch(File::delete); + + } catch (final IOException e) { + System.out.println("Not all files could be deleted!"); + e.printStackTrace(); + } + } + + return cleaned; + } + + public static String getFileContent(final String pathToJsonFile) { + final BufferedReader bufferedReader = FileSystem.readFile(pathToJsonFile); + return bufferedReader + == null + ? null + : bufferedReader.lines() + .reduce("", (content, line) -> content + + line); + } + + public static List getSmilesListFromFile(final String pathToSmilesFile) { + final List smilesList = new ArrayList<>(); + try { + final BufferedReader bufferedReader = FileSystem.readFile(pathToSmilesFile); + if (bufferedReader + != null) { + String line; + while ((line = bufferedReader.readLine()) + != null) { + smilesList.add(line); + } + bufferedReader.close(); + } + } catch (final IOException e) { + e.printStackTrace(); + } + + return smilesList; + } + + public static List retrieveFromSmilesFile(final String pathToResultsFile) { + final List dataSetList = new ArrayList<>(); + final List smilesList = FileSystem.getSmilesListFromFile(pathToResultsFile); + + DataSet dataSet; + Map meta; + for (final String smiles : smilesList) { + meta = new HashMap<>(); + meta.put("smiles", smiles); + dataSet = new DataSet(); + dataSet.setMeta(meta); + + dataSetList.add(dataSet); + } + + return dataSetList; + } +} diff --git a/src/casekit/model/NMRSignal.java b/src/casekit/model/NMRSignal.java deleted file mode 100644 index 5639865..0000000 --- a/src/casekit/model/NMRSignal.java +++ /dev/null @@ -1,95 +0,0 @@ -package casekit.model; - -/* NMRSignal.java -* -* Copyright (C) Dr. Christoph Steinbeck -* -* Contact: christoph.steinbeck@uni-jena.de -* -* This software is published and distributed under MIT license -*/ - - -/** -* A class to store the properties of a single N-dimensional NMR signal -*/ - -public class NMRSignal { - - int dim; - - /** - * Am array of doubles to store the chemical shift of - */ - public float shift[]; - public String[] nucleus; - - /* Signal intensity in arbitrary values */ - public float intensity; - - public int phase; - public static int DIM_ONE = 1, DIM_TWO = 2, DIM_THREE = 3, DIM_FOUR = 4; - public static int SHIFT_PROTON = 0, SHIFT_HETERO = 1; - public static int PHASE_NEGATIVE = 2, PHASE_POSITIVE = 1, PHASE_NONE = 0; - public static String[] PHASENAMES = {"NONE", "POSITIVE", "NEGATIVE"}; - - public NMRSignal(String[] nucleus) { - this.dim = nucleus.length; - this.shift = new float[dim]; - this.nucleus = nucleus; - for (int f = 0; f < dim; f++) - shift[f] = 0; - intensity = 1; - phase = PHASE_POSITIVE; - } - - public NMRSignal(String[] nucleus, float[] shift, float intensity, int phase) { - this.dim = nucleus.length; - this.shift = shift; - this.nucleus = nucleus; - this.intensity = intensity; - this.phase = phase; - } - - public void setShift(float sshift, String nnucleus) { - for (int f = 0; f < nucleus.length; f++) { - if (nucleus[f].equals(nnucleus)) { - shift[f] = sshift; - break; - } - } - } - - public void setShift(float sshift, int dim) { - shift[dim] = sshift; - } - - public float getShift(String nnucleus) { - for (int f = 0; f < nucleus.length; f++) { - if (nucleus[f].equals(nnucleus)) { - return shift[f]; - } - } - - return Float.MAX_VALUE; - - } - - public float getShift(int dim) { - return shift[dim]; - } - - - public String toString() { - String s = ""; - s += dim + " -dimensional NMRSignal for nuclei "; - for (int f = 0; f < nucleus.length; f++) - s += nucleus[f] + "; "; - s += "\nShiftlist: "; - for (int f = 0; f < shift.length; f++) - s += shift[f] + "; "; - s += "\n\n"; - return s; - } - -} \ No newline at end of file diff --git a/src/casekit/model/NMRSpectrum.java b/src/casekit/model/NMRSpectrum.java deleted file mode 100644 index 27959b2..0000000 --- a/src/casekit/model/NMRSpectrum.java +++ /dev/null @@ -1,260 +0,0 @@ -package casekit.model; - -/* NMRSpectrum.java -* -* Copyright (C) 1997-2007 Christoph Steinbeck -* -* Contact: christoph.steinbeck@uni-jena.de -* -* This software is published and distributed under MIT License -*/ - -/** -* A Class to model an n-dimensional NMR spectrum, -* -*/ - -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import javax.swing.event.EventListenerList; -import java.util.ArrayList; -import java.util.List; - -public class NMRSpectrum extends ArrayList{ - - /** - * An arbitrary name that can be assigned to this spectrum for identification purposes. - */ - public String name = ""; - /** - * An arbitrary name to identify the type of this spectrum, like COSY, NOESY, HSQC, etc. I - * decided not to provide static Strings with given experiment type since the there are - * numerous experiments yielding basically identical information having different names - */ - public String specType = ""; - /** - * The actual spectrum, i.e. a collection of nmrSignals - */ - // protected NMRSignal[] nmrSignals; - /** - * This holds sorted list of Chemical Shifts of all axes. The first dimension addresses the - * axes, the second the shift values in this axis, starting from the highest value. - */ - public List shiftList; - /** - * Not yet clear if this is needed. - */ - public float[] pickPrecision; - /** - * Declares how many axes are in involved in this spectrum. - */ - public int dim = 1; - /** - * The nuclei of the different axes. - */ - public String nucleus[]; - /** - * The proton frequency of the spectrometer used to record this spectrum. - */ - public float spectrometerFrequency; - public String solvent = ""; - public String standard = ""; - /** - * Some standard nulcei for the 'nucleus' field. - */ - public static String NUC_PROTON = "1H"; - public static String NUC_CARBON = "13C"; - public static String NUC_NITROGEN = "15N"; - public static String NUC_PHOSPHORUS = "31P"; - // ... to be continued... - public static String[] SPECTYPE_BB = {NUC_CARBON}; - public static String[] SPECTYPE_DEPT = {NUC_CARBON}; - public static String[] SPECTYPE_HMQC = {NUC_PROTON, NUC_CARBON}; - public static String[] SPECTYPE_HSQC = {NUC_PROTON, NUC_CARBON}; - public static String[] SPECTYPE_NHCORR = {NUC_PROTON, NUC_NITROGEN}; - public static String[] SPECTYPE_HMBC = {NUC_PROTON, NUC_CARBON}; - public static String[] SPECTYPE_HHCOSY = {NUC_PROTON, NUC_PROTON}; - public static String[] SPECTYPE_NOESY = {NUC_PROTON, NUC_PROTON}; - protected transient EventListenerList changeListeners = new EventListenerList(); - - public NMRSpectrum(String[] nucleus, String name) { - this.dim = nucleus.length; // redundant, I know :-) - this.nucleus = nucleus; - shiftList = new ArrayList(dim); - for (int f = 0; f < dim; f++) { - shiftList.add(f, new ArrayList()); - } - this.name = name; - } - - /** - * Return the number of individual frequencies in the heteroatom shift list, which should be - * equal or smaller than the number of respective atoms - */ - public int getSignalNumber(int axis) { - return shiftList.get(axis).size(); - } - - /** - * Adds an NMRSignal to the NMRSpectrum. - */ - public void addSignal(NMRSignal thisSignal) { - add(thisSignal); - updateShiftLists(); - } - - /** - * Creates an empty signal with correct dimension - */ - public void newSignal() { - System.out.println("nucleus: " + nucleus.length + nucleus[0]); - add(new NMRSignal(nucleus)); - updateShiftLists(); - } - - /** - * Returns an NMRSignal at position number in the List - */ - public Object getSignal(int number) { - return get(number); - } - - /** - * Returns the position of an NMRSignal the List - */ - public int getSignalNumber(NMRSignal signal) { - for (int f = 0; f < size(); f++) { - if (((NMRSignal) get(f)) == signal) { - return f; - } - } - return -1; - } - - public void setSpectrometerFrequency(float sf) { - this.spectrometerFrequency = sf; - } - - public float getSpectrometerFrequency() { - return spectrometerFrequency; - } - - public void setSolvent(String solvent) { - this.solvent = solvent; - } - - public String getSolvent() { - return solvent; - } - - public void setStandard(String standard) { - this.standard = standard; - } - - public String getStandard() { - return standard; - } - - /** - * Returns the signal closest to the shift sought. If no Signal is found within the interval - * defined by pickprecision, null is returned. - */ - public Object pickClosestSignal(float shift, String nnucleus, - float pickprecision) { - int dim = -1, thisPosition = -1; - float diff = Float.MAX_VALUE; - for (int f = 0; f < nucleus.length; f++) { - if (nucleus[f].equals(nnucleus)) { - dim = f; - break; - } - } - - /* - * Now we search dimension dim for the chemical shift. - */ - for (int f = 0; f < size(); f++) { - if (diff > Math.abs(((NMRSignal) get(f)).shift[dim] - shift)) { - diff = Math.abs(((NMRSignal) get(f)).shift[dim] - shift); - diff = (float) Math.ceil(diff * 2) / 2; - thisPosition = f; - } - } - if (diff < pickprecision) { - return get(thisPosition); - } - return null; - } - - /** - * Returns a List with signals within the interval defined by pickprecision. If none is found - * an empty List is returned. - */ - public List pickSignals(float shift, String nnucleus, float pickprecision) { - int dim = -1; - List pickedSignals = new ArrayList(); - for (int f = 0; f < nucleus.length; f++) { - if (nucleus[f].equals(nnucleus)) { - dim = f; - break; - } - } - /* - * Now we search dimension dim for the chemical shift. - */ - for (int f = 0; f < size(); f++) { - if (pickprecision > Math.abs(((NMRSignal) get(f)).shift[dim] - - shift)) { - pickedSignals.add(get(f)); - } - } - return pickedSignals; - } - - /** - * Extracts a list of unique shifts from the list of cross signals and sorts them. This is to - * define the column and row headers for tables. - */ - protected void updateShiftLists() { - Float shift; - for (int i = 0; i < size(); i++) { - NMRSignal nmrSignal = (NMRSignal) get(i); - for (int j = 0; j < nmrSignal.shift.length; j++) { - shift = new Float(nmrSignal.shift[j]); - if (!shiftList.get(j).contains(shift)) { - shiftList.get(j).add(shift); - } - } - } - } - - /** - * Creates a 2D matrix of booleans, that models the set of crosspeaks in the 2D NMR spectrum. - * The dimensions are taken from hetAtomShiftList and protonShiftList, which again are - * produced by updateShiftLists based a collection of 2D nmrSignals - *

- * private void createMatrix(){ boolean found; float het, prot; int hetPos, protPos; - * hetCorMatrix = new boolean[hetAtomShiftList.length][protonShiftList.length]; for (int f = - * 0; f < size(); f++){ HetCorNMRSignal hetCorSignal = (HetCorNMRSignal)elementAt(f); prot = - * hetCorSignal.shift[NMRSignal.SHIFT_PROTON]; het = - * hetCorSignal.shift[NMRSignal.SHIFT_HETERO]; found = false; hetPos = - * isInShiftList(hetAtomShiftList, het, hetAtomShiftList.length); if (hetPos >= 0){ protPos = - * isInShiftList(protonShiftList, prot, protonShiftList.length); if ( protPos >= 0){ found = - * true; hetCorMatrix[hetPos][protPos] = true; } } } } - */ - public void report() { - String s = ""; - System.out.println("Report for nmr spectrum " + name + " of type " - + specType + ": "); - for (int i = 0; i < shiftList.size(); i++) { - System.out.println("ShiftList for dimension " + (i + 1) + ":"); - for (int j = 0; j < shiftList.get(i).size(); j++) { - s += shiftList.get(i).get(j) + "; "; - } - System.out.println(s + "\n"); - s = ""; - } - - } - -} diff --git a/src/casekit/nmr/analysis/ConnectivityStatistics.java b/src/casekit/nmr/analysis/ConnectivityStatistics.java new file mode 100644 index 0000000..d5498fb --- /dev/null +++ b/src/casekit/nmr/analysis/ConnectivityStatistics.java @@ -0,0 +1,423 @@ +package casekit.nmr.analysis; + +import casekit.nmr.model.DataSet; +import casekit.nmr.model.Spectrum; +import casekit.nmr.utils.Utils; +import org.openscience.cdk.interfaces.IAtom; +import org.openscience.cdk.interfaces.IAtomContainer; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +public class ConnectivityStatistics { + + /** + * @param dataSet + * @param atomType + * @param occurrenceStatistics multiplicity -> hybridization -> shift (int) -> elemental composition (mf) -> connected atom symbol -> [#found, #notFound] + */ + public static void buildOccurrenceStatistics(final DataSet dataSet, final String atomType, + final Map>>>> occurrenceStatistics) { + final Spectrum spectrum = dataSet.getSpectrum() + .toSpectrum(); + final IAtomContainer structure = dataSet.getStructure() + .toAtomContainer(); + final List elements = buildElements(structure); + final String elementsString = buildElementsString(elements); + + int shift, atomIndex; + IAtom atom; + String multiplicity, hybridization; + Set found, notFound; + for (int signalIndex = 0; signalIndex + < spectrum.getSignalCount(); signalIndex++) { + shift = spectrum.getShift(signalIndex, 0) + .intValue(); + for (int equivalenceIndex = 0; equivalenceIndex + < dataSet.getAssignment() + .getAssignment(0, signalIndex).length; equivalenceIndex++) { + atomIndex = dataSet.getAssignment() + .getAssignment(0, signalIndex, equivalenceIndex); + atom = structure.getAtom(atomIndex); + if (atom.getSymbol() + .equals(atomType)) { + multiplicity = Utils.getMultiplicityFromProtonsCount(atom.getImplicitHydrogenCount()); + if (multiplicity + == null) { + continue; + } + multiplicity = multiplicity.toLowerCase(); + hybridization = atom.getHybridization() + .name(); + occurrenceStatistics.putIfAbsent(multiplicity, new ConcurrentHashMap<>()); + occurrenceStatistics.get(multiplicity) + .putIfAbsent(hybridization, new ConcurrentHashMap<>()); + occurrenceStatistics.get(multiplicity) + .get(hybridization) + .putIfAbsent(shift, new ConcurrentHashMap<>()); + occurrenceStatistics.get(multiplicity) + .get(hybridization) + .get(shift) + .putIfAbsent(elementsString, new ConcurrentHashMap<>()); + // check for connected hetero atoms + found = new HashSet<>(); + for (final IAtom connectedAtom : structure.getConnectedAtomsList(atom)) { + if (connectedAtom.getSymbol() + .equals("H")) { + continue; + } + found.add(connectedAtom.getSymbol()); + } + for (final String connectedAtomType : found) { + occurrenceStatistics.get(multiplicity) + .get(hybridization) + .get(shift) + .get(elementsString) + .putIfAbsent(connectedAtomType, new Integer[]{0, 0}); + occurrenceStatistics.get(multiplicity) + .get(hybridization) + .get(shift) + .get(elementsString) + .get(connectedAtomType)[0] = occurrenceStatistics.get(multiplicity) + .get(hybridization) + .get(shift) + .get(elementsString) + .get(connectedAtomType)[0] + + 1; + } + notFound = new HashSet<>(elements); + notFound.removeAll(found); + for (final String notConnectedAtomType : notFound) { + occurrenceStatistics.get(multiplicity) + .get(hybridization) + .get(shift) + .get(elementsString) + .putIfAbsent(notConnectedAtomType, new Integer[]{0, 0}); + occurrenceStatistics.get(multiplicity) + .get(hybridization) + .get(shift) + .get(elementsString) + .get(notConnectedAtomType)[1] = occurrenceStatistics.get(multiplicity) + .get(hybridization) + .get(shift) + .get(elementsString) + .get(notConnectedAtomType)[1] + + 1; + } + } + } + } + } + + /** + * @param structure structure to build and add the statistics from + * @param heavyAtomsStatistics elemental composition (mf) -> connected atom pair -> #found + */ + public static void buildHeavyAtomsStatistics(final IAtomContainer structure, + final Map> heavyAtomsStatistics) { + final List elements = buildElements(structure); + final String elementsString = buildElementsString(elements); + heavyAtomsStatistics.putIfAbsent(elementsString, new HashMap<>()); + + for (final String combination : buildCombinations(elements)) { + heavyAtomsStatistics.get(elementsString) + .putIfAbsent(combination, 0); + } + + IAtom atom; + String atomPairKey; + final Map found = new HashMap<>(); + for (int i = 0; i + < structure.getAtomCount(); i++) { + atom = structure.getAtom(i); + // check for connected hetero atoms + for (final IAtom connectedAtom : structure.getConnectedAtomsList(atom)) { + if (connectedAtom.getSymbol() + .equals("H")) { + continue; + } + atomPairKey = buildAtomPairString(atom.getSymbol(), connectedAtom.getSymbol()); + found.putIfAbsent(atomPairKey, 0); + found.put(atomPairKey, found.get(atomPairKey) + + 1); + } + } + for (final String connectedAtomPair : found.keySet()) { + heavyAtomsStatistics.get(elementsString) + .put(connectedAtomPair, heavyAtomsStatistics.get(elementsString) + .get(connectedAtomPair) + + found.get(connectedAtomPair) + / 2); // divided by two since we count for both bond partners in the previous loop + } + } + + public static List buildElements(final IAtomContainer structure) { + final String mf = Utils.molecularFormularToString(Utils.getMolecularFormulaFromAtomContainer(structure)); + return buildElements(mf); + } + + public static List buildElements(final String mf) { + final List elements = new ArrayList<>(Utils.getMolecularFormulaElementCounts(mf) + .keySet()); + elements.remove("H"); + Collections.sort(elements); + + return elements; + } + + public static String buildElementsString(final List elements) { + return String.join(",", elements); + } + + public static String buildAtomPairString(final String atomType1, final String atomType2) { + final List atomPairList = new ArrayList<>(); + atomPairList.add(atomType1); + atomPairList.add(atomType2); + Collections.sort(atomPairList); + + return String.join("_", atomPairList); + } + + public static Set buildCombinations(final List elements) { + final Set combinations = new HashSet<>(); + for (final String element1 : elements) { + for (final String element2 : elements) { + combinations.add(buildAtomPairString(element1, element2)); + } + } + + return combinations; + } + + // /** + // * @param dataSetList + // * @param nucleus + // * @param connectivityStatistics multiplicity -> hybridization -> shift (int) -> connected atom symbol -> connected atom hybridization -> connected atom protons count -> occurrence + // */ + // @Deprecated + // public static void buildConnectivityStatistics(final List dataSetList, final String nucleus, + // final Map>>>>> connectivityStatistics) { + // final String atomType = Utils.getAtomTypeFromNucleus(nucleus); + // for (final DataSet dataSet : dataSetList) { + // if (!dataSet.getSpectrum() + // .getNuclei()[0].equals(nucleus)) { + // continue; + // } + // buildConnectivityStatistics(dataSet, atomType, connectivityStatistics); + // } + // } + // + // /** + // * @param dataSet + // * @param atomType + // * @param connectivityStatistics multiplicity -> hybridization -> shift (int) -> connected atom symbol -> connected atom hybridization -> connected atom protons count -> occurrence + // */ + // @Deprecated + // public static void buildConnectivityStatistics(final DataSet dataSet, final String atomType, + // final Map>>>>> connectivityStatistics) { + // final IAtomContainer structure = dataSet.getStructure() + // .toAtomContainer(); + // final Spectrum spectrum = dataSet.getSpectrum() + // .toSpectrum(); + // int shift, atomIndex; + // IAtom atom; + // String multiplicity, hybridization, connectedAtomType, connectedAtomHybridization; + // for (int signalIndex = 0; signalIndex + // < spectrum.getSignalCount(); signalIndex++) { + // shift = spectrum.getShift(signalIndex, 0) + // .intValue(); + // for (int equivalenceIndex = 0; equivalenceIndex + // < dataSet.getAssignment() + // .getAssignment(0, signalIndex).length; equivalenceIndex++) { + // atomIndex = dataSet.getAssignment() + // .getAssignment(0, signalIndex, equivalenceIndex); + // atom = structure.getAtom(atomIndex); + // if (atom.getSymbol() + // .equals(atomType)) { + // multiplicity = Utils.getMultiplicityFromProtonsCount(atom.getImplicitHydrogenCount()); + // if (multiplicity + // == null) { + // continue; + // } + // multiplicity = multiplicity.toLowerCase(); + // hybridization = atom.getHybridization() + // .name(); + // connectivityStatistics.putIfAbsent(multiplicity, new ConcurrentHashMap<>()); + // connectivityStatistics.get(multiplicity) + // .putIfAbsent(hybridization, new ConcurrentHashMap<>()); + // // check for connected hetero atoms + // for (final IAtom connectedAtom : structure.getConnectedAtomsList(atom)) { + // if (connectedAtom.getSymbol() + // .equals("H")) { + // continue; + // } + // connectedAtomType = connectedAtom.getSymbol(); + // if (connectedAtom.getHybridization() + // == null) { + // continue; + // } + // connectedAtomHybridization = connectedAtom.getHybridization() + // .name(); + // connectivityStatistics.get(multiplicity) + // .get(hybridization) + // .putIfAbsent(shift, new ConcurrentHashMap<>()); + // connectivityStatistics.get(multiplicity) + // .get(hybridization) + // .get(shift) + // .putIfAbsent(connectedAtomType, new ConcurrentHashMap<>()); + // connectivityStatistics.get(multiplicity) + // .get(hybridization) + // .get(shift) + // .get(connectedAtomType) + // .putIfAbsent(connectedAtomHybridization, new ConcurrentHashMap<>()); + // connectivityStatistics.get(multiplicity) + // .get(hybridization) + // .get(shift) + // .get(connectedAtomType) + // .get(connectedAtomHybridization) + // .putIfAbsent(connectedAtom.getImplicitHydrogenCount(), 0); + // connectivityStatistics.get(multiplicity) + // .get(hybridization) + // .get(shift) + // .get(connectedAtomType) + // .get(connectedAtomHybridization) + // .put(connectedAtom.getImplicitHydrogenCount(), connectivityStatistics.get( + // multiplicity) + // .get(hybridization) + // .get(shift) + // .get(connectedAtomType) + // .get(connectedAtomHybridization) + // .get(connectedAtom.getImplicitHydrogenCount()) + // + 1); + // } + // } + // } + // } + // } + // + // /** + // * @param connectivityStatistics multiplicity -> hybridization -> shift (int) -> connected atom symbol -> connected atom hybridization -> connected atom protons count -> occurrence + // * @param multiplicity + // * @param hybridization + // * @param shift + // * @param molecularFormulaElements + // * + // * @return + // */ + // @Deprecated + // public static Map>> extractConnectivities( + // final Map>>>>> connectivityStatistics, + // final String multiplicity, final String hybridization, final int shift, + // final Set molecularFormulaElements) { + // final Map>> extractedConnectivities = new HashMap<>(); + // if (connectivityStatistics.containsKey(multiplicity) + // && connectivityStatistics.get(multiplicity) + // .containsKey(hybridization) + // && connectivityStatistics.get(multiplicity) + // .get(hybridization) + // .containsKey(shift)) { + // for (final Map.Entry>> entry : connectivityStatistics.get( + // multiplicity) + // .get(hybridization) + // .get(shift) + // .entrySet()) { + // if (molecularFormulaElements.contains(entry.getKey())) { + // extractedConnectivities.put(entry.getKey(), entry.getValue()); + // } + // } + // } + // + // return extractedConnectivities; + // } + // + // @Deprecated + // public static Map>> filterExtractedConnectivitiesByHybridizations( + // final Map>> extractedConnectivities, + // final Set knownCarbonHybridizations) { + // // remove hybridization of carbons which we do not expect + // for (final String atomType : extractedConnectivities.keySet()) { + // if (atomType.equals("C")) { + // for (final int hybridization : new HashSet<>(extractedConnectivities.get(atomType) + // .keySet())) { + // if (!knownCarbonHybridizations.contains(hybridization)) { + // extractedConnectivities.get(atomType) + // .remove(hybridization); + // } + // } + // } + // } + // + // return extractedConnectivities; + // } + // + // @Deprecated + // public static Map>> filterExtractedConnectivitiesByCount( + // final Map>> extractedConnectivities, + // final double thresholdElementCount, final boolean onAtomTypeLevel) { + // final Map totalCounts = getTotalCounts(extractedConnectivities); + // final int totalCountsSum = getSum(new HashSet<>(totalCounts.values())); + // final Map>> filteredExtractedConnectivities = new HashMap<>(); + // extractedConnectivities.keySet() + // .forEach(neighborAtomType -> { + // int sum = 0; + // for (final Map.Entry> entryPerHybridization : extractedConnectivities.get( + // neighborAtomType) + // .entrySet()) { + // for (final Map.Entry entryProtonsCount : extractedConnectivities.get( + // neighborAtomType) + // .get(entryPerHybridization.getKey()) + // .entrySet()) { + // if (onAtomTypeLevel) { + // sum += entryProtonsCount.getValue(); + // } else if (entryProtonsCount.getValue() + // / (double) totalCountsSum + // >= thresholdElementCount) { + // filteredExtractedConnectivities.putIfAbsent(neighborAtomType, + // new HashMap<>()); + // filteredExtractedConnectivities.get(neighborAtomType) + // .putIfAbsent( + // entryPerHybridization.getKey(), + // new HashSet<>()); + // filteredExtractedConnectivities.get(neighborAtomType) + // .get(entryPerHybridization.getKey()) + // .add(entryProtonsCount.getKey()); + // } + // } + // } + // if (onAtomTypeLevel + // && sum + // / (double) totalCountsSum + // >= thresholdElementCount) { + // filteredExtractedConnectivities.putIfAbsent(neighborAtomType, new HashMap<>()); + // } + // }); + // + // return filteredExtractedConnectivities; + // } + // + // @Deprecated + // private static Map getTotalCounts( + // final Map>> extractedConnectivities) { + // final Map totalCounts = new HashMap<>(); + // for (final String key1 : extractedConnectivities.keySet()) { + // totalCounts.putIfAbsent(key1, 0); + // for (final int key2 : extractedConnectivities.get(key1) + // .keySet()) { + // for (final Map.Entry countsEntry : extractedConnectivities.get(key1) + // .get(key2) + // .entrySet()) { + // totalCounts.put(key1, totalCounts.get(key1) + // + countsEntry.getValue()); + // } + // } + // } + // + // return totalCounts; + // } + // + // @Deprecated + // private static int getSum(final Set values) { + // return values.stream() + // .reduce(0, (total, current) -> total += current); + // } +} diff --git a/src/casekit/nmr/analysis/HOSECodeShiftStatistics.java b/src/casekit/nmr/analysis/HOSECodeShiftStatistics.java new file mode 100644 index 0000000..e0fecad --- /dev/null +++ b/src/casekit/nmr/analysis/HOSECodeShiftStatistics.java @@ -0,0 +1,318 @@ +package casekit.nmr.analysis; + +import casekit.nmr.dbservice.COCONUT; +import casekit.nmr.dbservice.NMRShiftDB; +import casekit.nmr.fragments.model.ConnectionTree; +import casekit.nmr.hose.HOSECodeBuilder; +import casekit.nmr.model.DataSet; +import casekit.nmr.model.Signal; +import casekit.nmr.model.Spectrum; +import casekit.nmr.utils.Statistics; +import casekit.nmr.utils.Utils; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.reflect.TypeToken; +import org.bson.Document; +import org.openscience.cdk.exception.CDKException; +import org.openscience.cdk.interfaces.IAtomContainer; +import org.openscience.nmrshiftdb.util.ExtendedHOSECodeGenerator; + +import java.io.*; +import java.util.*; + +public class HOSECodeShiftStatistics { + + private final static Gson GSON = new GsonBuilder().setLenient() + .create(); + private final static ExtendedHOSECodeGenerator extendedHOSECodeGenerator = new ExtendedHOSECodeGenerator(); + + public static Map>> collectHOSECodeShifts(final List dataSetList, + final Integer maxSphere, + final boolean use3D, + final boolean withExplicitH) { + return collectHOSECodeShifts(dataSetList, maxSphere, use3D, withExplicitH, new HashMap<>()); + } + + /** + * This method expects datasets containing structures without explicit hydrogens. + * + * @param dataSetList + * @param maxSphere + * @param hoseCodeShifts + * + * @return + */ + public static Map>> collectHOSECodeShifts(final List dataSetList, + final Integer maxSphere, + final boolean use3D, + final boolean withExplicitH, + final Map>> hoseCodeShifts) { + for (final DataSet dataSet : dataSetList) { + insert(dataSet, maxSphere, use3D, withExplicitH, hoseCodeShifts); + } + + return hoseCodeShifts; + } + + public static boolean insert(final DataSet dataSet, final Integer maxSphere, final boolean use3D, + final boolean withExplicitH, + final Map>> hoseCodeShifts) { + final IAtomContainer structure; + Signal signal; + String hoseCode; + final String atomTypeSpectrum; + String solvent; + final Map atomIndexMap; // from explicit H to heavy atom + ConnectionTree connectionTree; + int maxSphereTemp; + List signalIndices; + structure = dataSet.getStructure() + .toAtomContainer(); + final Spectrum spectrum = dataSet.getSpectrum() + .toSpectrum(); + if (Utils.containsExplicitHydrogens(structure)) { + System.out.println("!!!Dataset skipped must not contain (previously set) explicit hydrogens!!!"); + return false; + } + // create atom index map to know which indices the explicit hydrogens will have + atomIndexMap = new HashMap<>(); + if (use3D + || withExplicitH) { + try { + int nextAtomIndexExplicitH = structure.getAtomCount(); + for (int i = 0; i + < structure.getAtomCount(); i++) { + if (structure.getAtom(i) + .getImplicitHydrogenCount() + != null) { + for (int j = 0; j + < structure.getAtom(i) + .getImplicitHydrogenCount(); j++) { + atomIndexMap.put(nextAtomIndexExplicitH, i); + nextAtomIndexExplicitH++; + } + } + } + + if (use3D) { + try { + Utils.placeExplicitHydrogens(structure); + } catch (final CDKException | IOException | ClassNotFoundException e) { + e.printStackTrace(); + } + } else { + Utils.convertImplicitToExplicitHydrogens(structure); + } + Utils.setAromaticityAndKekulize(structure); + } catch (final CDKException e) { + e.printStackTrace(); + return false; + } + } + solvent = dataSet.getSpectrum() + .getMeta() + == null + ? null + : dataSet.getSpectrum() + .getMeta() + .get("solvent"); + if (solvent + == null + || solvent.equals("")) { + solvent = "Unknown"; + } + atomTypeSpectrum = Utils.getAtomTypeFromNucleus(dataSet.getSpectrum() + .getNuclei()[0]); + for (int i = 0; i + < structure.getAtomCount(); i++) { + signalIndices = null; + if (structure.getAtom(i) + .getSymbol() + .equals(atomTypeSpectrum)) { + if (atomTypeSpectrum.equals("H")) { + // could be multiple signals + signalIndices = dataSet.getAssignment() + .getIndices(0, atomIndexMap.get(i)); + } else { + // should be one only + signalIndices = dataSet.getAssignment() + .getIndices(0, i); + } + } + if (signalIndices + != null) { + for (final Integer signalIndex : signalIndices) { + signal = spectrum.getSignal(signalIndex); + try { + if (maxSphere + == null) { + connectionTree = HOSECodeBuilder.buildConnectionTree(structure, i, null); + maxSphereTemp = connectionTree.getMaxSphere(true); + } else { + maxSphereTemp = maxSphere; + } + for (int sphere = 1; sphere + <= maxSphereTemp; sphere++) { + if (use3D) { + try { + hoseCode = extendedHOSECodeGenerator.getHOSECode(structure, structure.getAtom(i), + sphere); + } catch (final Exception e) { + // e.printStackTrace(); + continue; + } + } else { + hoseCode = HOSECodeBuilder.buildHOSECode(structure, i, sphere, false); + } + hoseCodeShifts.putIfAbsent(hoseCode, new HashMap<>()); + hoseCodeShifts.get(hoseCode) + .putIfAbsent(solvent, new ArrayList<>()); + hoseCodeShifts.get(hoseCode) + .get(solvent) + .add(signal.getShift(0)); + } + } catch (final CDKException e) { + e.printStackTrace(); + } + } + } + } + + return true; + } + + public static Map> buildHOSECodeShiftStatistics( + final Map>> hoseCodeShifts) { + + final Map> hoseCodeShiftStatistics = new HashMap<>(); + List values; + for (final Map.Entry>> hoseCodes : hoseCodeShifts.entrySet()) { + hoseCodeShiftStatistics.put(hoseCodes.getKey(), new HashMap<>()); + for (final Map.Entry> solvents : hoseCodes.getValue() + .entrySet()) { + values = new ArrayList<>(solvents.getValue()); + values = Statistics.removeOutliers(values, 1.5); + hoseCodeShiftStatistics.get(hoseCodes.getKey()) + .put(solvents.getKey(), + new Double[]{(double) values.size(), Collections.min(values), + Statistics.getMean(values), Statistics.getMedian(values), + Collections.max(values)}); + } + } + + return hoseCodeShiftStatistics; + } + + public static Map> buildHOSECodeShiftStatistics(final String[] pathsToNMRShiftDBs, + final String[] pathsToCOCONUTs, + final String[] nuclei, + final Integer maxSphere, + final boolean use3D, + final boolean withExplicitH) { + try { + final Map>> hoseCodeShifts = new HashMap<>(); + for (final String pathsToNMRShiftDB : pathsToNMRShiftDBs) { + HOSECodeShiftStatistics.collectHOSECodeShifts( + NMRShiftDB.getDataSetsFromNMRShiftDB(pathsToNMRShiftDB, nuclei), maxSphere, use3D, + withExplicitH, hoseCodeShifts); + } + for (final String pathsToCOCONUT : pathsToCOCONUTs) { + HOSECodeShiftStatistics.collectHOSECodeShifts( + COCONUT.getDataSetsWithShiftPredictionFromCOCONUT(pathsToCOCONUT, nuclei), maxSphere, use3D, + withExplicitH, hoseCodeShifts); + } + return HOSECodeShiftStatistics.buildHOSECodeShiftStatistics(hoseCodeShifts); + } catch (final FileNotFoundException | CDKException e) { + e.printStackTrace(); + } + + return new HashMap<>(); + } + + public static Map> buildHOSECodeShiftStatistics(final List dataSetList, + final Integer maxSphere, + final boolean use3D, + final boolean withExplicitH) { + return HOSECodeShiftStatistics.buildHOSECodeShiftStatistics( + collectHOSECodeShifts(dataSetList, maxSphere, use3D, withExplicitH)); + } + + public static boolean writeHOSECodeShiftStatistics(final Map> hoseCodeShifts, + final String pathToJsonFile) { + try { + final BufferedWriter bw = new BufferedWriter(new FileWriter(pathToJsonFile)); + bw.append("{"); + bw.newLine(); + bw.flush(); + + Document subDocument; + String json; + long counter = 0; + for (final Map.Entry> entry : hoseCodeShifts.entrySet()) { + subDocument = new Document(); + subDocument.append("HOSECode", entry.getKey()); + subDocument.append("values", GSON.toJson(entry.getValue())); + json = new Document(String.valueOf(counter), subDocument).toJson(); + bw.append(json, 1, json.length() + - 1); + if (counter + < hoseCodeShifts.size() + - 1) { + bw.append(","); + } + bw.newLine(); + bw.flush(); + + counter++; + } + + bw.append("}"); + bw.flush(); + bw.close(); + + return true; + } catch (final IOException e) { + e.printStackTrace(); + } + + return false; + } + + public static Map> readHOSECodeShiftStatistics( + final String pathToJsonFile) throws FileNotFoundException { + final BufferedReader br = new BufferedReader(new FileReader(pathToJsonFile)); + final Map> hoseCodeShiftStatistics = new HashMap<>(); + // add all task to do + br.lines() + .forEach(line -> { + if ((line.trim() + .length() + > 1) + || (!line.trim() + .startsWith("{") + && !line.trim() + .endsWith("}"))) { + final StringBuilder hoseCodeShiftsStatisticInJSON = new StringBuilder(); + if (line.endsWith(",")) { + hoseCodeShiftsStatisticInJSON.append(line, 0, line.length() + - 1); + } else { + hoseCodeShiftsStatisticInJSON.append(line); + } + final JsonObject jsonObject = JsonParser.parseString(hoseCodeShiftsStatisticInJSON.substring( + hoseCodeShiftsStatisticInJSON.toString() + .indexOf("{"))) + .getAsJsonObject(); + hoseCodeShiftStatistics.put(jsonObject.get("HOSECode") + .getAsString(), GSON.fromJson(jsonObject.get("values") + .getAsString(), + new TypeToken>() { + }.getType())); + } + }); + + return hoseCodeShiftStatistics; + } +} diff --git a/src/casekit/nmr/analysis/MultiplicitySectionsBuilder.java b/src/casekit/nmr/analysis/MultiplicitySectionsBuilder.java new file mode 100644 index 0000000..04dc01d --- /dev/null +++ b/src/casekit/nmr/analysis/MultiplicitySectionsBuilder.java @@ -0,0 +1,170 @@ +/* + * The MIT License + * + * Copyright (c) 2019 Michael Wenk [https://github.com/michaelwenk] + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package casekit.nmr.analysis; + +import casekit.nmr.model.Signal; +import casekit.nmr.model.Spectrum; + +import java.util.*; + +/** + * @author Michael Wenk [https://github.com/michaelwenk] + */ +public class MultiplicitySectionsBuilder { + + private final HashSet multiplicities; + private int minLimit, maxLimit, stepSize, steps; + + public MultiplicitySectionsBuilder() { + this.multiplicities = new HashSet<>(); + this.init(); + } + + private void init() { + this.multiplicities.clear(); + this.multiplicities.add("s"); + this.multiplicities.add("d"); + this.multiplicities.add("t"); + this.multiplicities.add("q"); + this.multiplicities.add("unknown"); + this.minLimit = -50; + this.maxLimit = 300; + this.stepSize = 5; + this.updateSteps(); // ppm range from -20 to 260 in 5 ppm steps + } + + /** + * Resets to following default values:

+ * multiplicties: S, D, T. Q
+ * min. ppm limit: -50
+ * max. ppm limit: 300
+ * step size: 5 + */ + public void reset() { + this.init(); + } + + public Map> buildMultiplicitySections(final Spectrum spectrum, final int dim) { + final Map> multiplicitySections = new HashMap<>(); + // init + for (final String multiplicity : this.multiplicities) { + multiplicitySections.put(multiplicity, new ArrayList<>()); + } + // set the mult. sections + Signal signal; + Integer shiftSection; + String multiplicity; + for (int i = 0; i + < spectrum.getSignalCount(); i++) { + signal = spectrum.getSignal(i); + shiftSection = this.calculateShiftSection(signal, dim); + if (shiftSection + == null) { + System.err.println("MultiplicitySectionsBuilder: signal or its chemical shift is missing: " + + signal); + continue; + } + multiplicity = this.checkMultiplicity(signal); + if (multiplicity + == null) { + System.err.println("MultiplicitySectionsBuilder: signal multiplicity is not in list: " + + signal); + continue; + } + multiplicitySections.get(multiplicity) + .add(shiftSection); + } + + return multiplicitySections; + } + + public Integer calculateShiftSection(final Signal signal, final int dim) { + if (signal + == null + || signal.getShift(dim) + == null) { + return null; + } + return (int) ((signal.getShift(dim) + - this.minLimit) + / this.stepSize); + } + + public String checkMultiplicity(final Signal signal) { + final String multiplicity = signal.getMultiplicity() + != null + ? signal.getMultiplicity() + : "unknown"; + if (!this.multiplicities.contains(multiplicity)) { + return null; + } + + return multiplicity; + } + + public Set getMultiplicities() { + return this.multiplicities; + } + + public boolean addMultiplicity(final String mult) { + return this.multiplicities.add(mult); + } + + public boolean removeMultiplicity(final String mult) { + return this.multiplicities.remove(mult); + } + + public boolean containsMultiplicity(final String mult) { + return this.multiplicities.contains(mult); + } + + public int getMinLimit() { + return this.minLimit; + } + + public void setMinLimit(final int minLimit) { + this.minLimit = minLimit; + this.updateSteps(); + } + + public int getMaxLimit() { + return this.maxLimit; + } + + public void setMaxLimit(final int maxLimit) { + this.maxLimit = maxLimit; + this.updateSteps(); + } + + public int getStepSize() { + return this.stepSize; + } + + public void setStepSize(final int stepSize) { + this.stepSize = stepSize; + this.updateSteps(); + } + + public int getSteps() { + return this.steps; + } + + private void updateSteps() { + this.steps = this.calculateSteps(this.minLimit, this.maxLimit, this.stepSize); + } + + public int calculateSteps(final int minLimit, final int maxLimit, final int stepSize) { + return (maxLimit + - minLimit) + / stepSize; + } +} diff --git a/src/casekit/nmr/dbservice/COCONUT.java b/src/casekit/nmr/dbservice/COCONUT.java new file mode 100644 index 0000000..577678e --- /dev/null +++ b/src/casekit/nmr/dbservice/COCONUT.java @@ -0,0 +1,102 @@ +package casekit.nmr.dbservice; + +import casekit.nmr.model.*; +import casekit.nmr.utils.Utils; +import org.openscience.cdk.exception.CDKException; +import org.openscience.cdk.interfaces.IAtomContainer; +import org.openscience.cdk.io.iterator.IteratingSDFReader; +import org.openscience.cdk.silent.SilentChemObjectBuilder; + +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.util.ArrayList; +import java.util.List; + +public class COCONUT { + + public static List getDataSetsWithShiftPredictionFromCOCONUT(final String pathToCOCONUT, + final String[] nuclei) throws CDKException, FileNotFoundException { + final List dataSetList = new ArrayList<>(); + final IteratingSDFReader iterator = new IteratingSDFReader(new FileReader(pathToCOCONUT), + SilentChemObjectBuilder.getInstance()); + IAtomContainer structure; + DataSet dataSet; + Spectrum spectrum; + Assignment assignment; + String[] split, split2; + String spectrumPropertyString, multiplicity; + double calcShift; + List closestSignalList; + int atomIndex; + + while (iterator.hasNext()) { + structure = iterator.next(); + dataSet = Utils.atomContainerToDataSet(structure); + + for (final String nucleus : nuclei) { + final String atomType = casekit.nmr.utils.Utils.getAtomTypeFromNucleus(nucleus); + final List atomIndices = Utils.getAtomTypeIndicesByElement(structure, atomType); + spectrumPropertyString = structure.getProperty("Predicted " + + nucleus + + " shifts", String.class); + if (spectrumPropertyString + == null) { + spectrumPropertyString = structure.getProperty("Predicted_" + + nucleus + + "_shifts", String.class); + } + if (spectrumPropertyString + == null) { + continue; + } + + spectrumPropertyString = spectrumPropertyString.replaceAll("[\\n\\r]", ";"); + split = spectrumPropertyString.split(";"); + spectrum = new Spectrum(); + spectrum.setNuclei(new String[]{nucleus}); + spectrum.setSignals(new ArrayList<>()); + assignment = new Assignment(); + assignment.setNuclei(spectrum.getNuclei()); + assignment.initAssignments(spectrum.getSignalCount()); + for (int i = 0; i + < split.length; i++) { + split2 = split[i].split("\\s+"); + atomIndex = atomIndices.get(i); + calcShift = Double.parseDouble(split2[1]); + multiplicity = Utils.getMultiplicityFromProtonsCount(structure.getAtom(atomIndex) + .getImplicitHydrogenCount()) + .toLowerCase(); + // add assignment (at first here because of search for already existing equivalent signals) + // just to be sure that we take the right signal if equivalences are present + closestSignalList = spectrum.pickByClosestShift(calcShift, 0, 0.0); + closestSignalList.retainAll(spectrum.pickByMultiplicity(multiplicity)); + if (closestSignalList.isEmpty()) { + assignment.addAssignment(0, new int[]{atomIndex}); + } else { + assignment.addAssignmentEquivalence(0, closestSignalList.get(0), atomIndex); + } + // add signal + spectrum.addSignal( + new Signal(new String[]{nucleus}, new Double[]{calcShift}, multiplicity, "signal", null, 1, + 0, null, null)); + } + + // if no spectrum could be built or the number of signals in spectrum is different than the atom number in molecule + if (Utils.getDifferenceSpectrumSizeAndMolecularFormulaCount(spectrum, + Utils.getMolecularFormulaFromString( + dataSet.getMeta() + .get("mf")), 0) + != 0) { + continue; + } + dataSet.setSpectrum(new SpectrumCompact(spectrum)); + dataSet.setAssignment(assignment); + + dataSetList.add(dataSet.buildClone()); + } + } + + return dataSetList; + } + +} diff --git a/src/casekit/nmr/dbservice/NMRShiftDB.java b/src/casekit/nmr/dbservice/NMRShiftDB.java new file mode 100644 index 0000000..5c2ae4a --- /dev/null +++ b/src/casekit/nmr/dbservice/NMRShiftDB.java @@ -0,0 +1,398 @@ +/* + * The MIT License + * + * Copyright 2019 Michael Wenk [https://github.com/michaelwenk] + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package casekit.nmr.dbservice; + +import casekit.nmr.model.*; +import casekit.nmr.utils.Utils; +import org.openscience.cdk.exception.CDKException; +import org.openscience.cdk.interfaces.IAtomContainer; +import org.openscience.cdk.io.iterator.IteratingSDFReader; +import org.openscience.cdk.silent.SilentChemObjectBuilder; +import org.openscience.cdk.tools.manipulator.AtomContainerManipulator; + +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class NMRShiftDB { + + public static String getSolvent(final String solventPropertyString, final String spectrumIndexInRecord) { + final String[] solventPropertyStringSplit = solventPropertyString.split(":"); + String solvent; + for (int i = 0; i + < solventPropertyStringSplit.length; i++) { + if (solventPropertyStringSplit[i].endsWith(spectrumIndexInRecord)) { + solvent = solventPropertyStringSplit[i + + 1]; + if (solvent.substring(solvent.length() + - 1) + .matches("\\d")) { + solvent = solvent.substring(0, solvent.length() + - 1); + } + if (solvent.substring(solvent.length() + - 1) + .matches("\\d")) { + solvent = solvent.substring(0, solvent.length() + - 1); + } + // solvent = solvent.substring(0, solvent.length() - 1); + solvent = solvent.trim(); + + return solvent; + } + } + + return null; + } + + public static List getSpectraProperties1D(final IAtomContainer ac, final String nucleus) { + final List spectraProperties1D = new ArrayList<>(); + for (final Object obj : ac.getProperties() + .keySet()) { + if (obj instanceof String + && ((String) obj).startsWith("Spectrum " + + nucleus)) { + spectraProperties1D.add((String) obj); + } + } + + return spectraProperties1D; + } + + /** + * Returns a {@link DataSet} class object + * for each valid molecule record in the given NMRShiftDB file. Valid means + * here that each molecule record has to contain the given spectrum + * property string as well as the number of signals in that spectrum has to + * be the same as atoms of that atom type in molecule. + * + * @param pathToNMRShiftDB path to NMRShiftDB file + * @param nuclei nuclei to get the spectra for + * + * @return + * + * @throws FileNotFoundException + * @throws CDKException + * @see DataSet + */ + public static List getDataSetsFromNMRShiftDB(final String pathToNMRShiftDB, + final String[] nuclei) throws FileNotFoundException, CDKException { + final List dataSets = new ArrayList<>(); + final IteratingSDFReader iterator = new IteratingSDFReader(new FileReader(pathToNMRShiftDB), + SilentChemObjectBuilder.getInstance()); + IAtomContainer structure; + Spectrum spectrum; + Assignment assignment; + DataSet dataSet; + List spectraProperties1D; + String[] split; + String spectrumIndexInRecord; + List explicitHydrogenIndices; + int[] temp; + + while (iterator.hasNext()) { + structure = iterator.next(); + AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(structure); + explicitHydrogenIndices = casekit.nmr.utils.Utils.getExplicitHydrogenIndices(structure); + Collections.sort(explicitHydrogenIndices); + dataSet = Utils.atomContainerToDataSet(structure); + + for (final String nucleus : nuclei) { + spectraProperties1D = getSpectraProperties1D(structure, nucleus); + for (final String spectrumProperty1D : spectraProperties1D) { + split = spectrumProperty1D.split("\\s"); + spectrumIndexInRecord = split[split.length + - 1]; + + // skip molecules which do not contain any of requested spectrum information + spectrum = NMRShiftDBSpectrumToSpectrum(structure.getProperty(spectrumProperty1D), nucleus); + // if no spectrum could be built or the number of signals in spectrum is different than the atom number in molecule + if ((spectrum + == null) + || casekit.nmr.utils.Utils.getDifferenceSpectrumSizeAndMolecularFormulaCount(spectrum, + Utils.getMolecularFormulaFromString( + dataSet.getMeta() + .get("mf")), + 0) + != 0) { + continue; + } + if (structure.getProperty("Solvent") + != null) { + spectrum.addMetaInfo("solvent", + getSolvent(structure.getProperty("Solvent"), spectrumIndexInRecord)); + } + if (structure.getProperty("Field Strength [MHz]") + != null) { + for (final String fieldStrength : structure.getProperty("Field Strength [MHz]") + .toString() + .split("\\s")) { + if (fieldStrength.startsWith(spectrumIndexInRecord + + ":")) { + try { + spectrum.addMetaInfo("spectrometerFrequency", fieldStrength.split( + spectrumIndexInRecord + + ":")[1]); + } catch (final NumberFormatException e) { + // e.printStackTrace(); + } + break; + } + } + } + + assignment = NMRShiftDBSpectrumToAssignment(structure.getProperty(spectrumProperty1D), nucleus); + if (assignment + != null + && !explicitHydrogenIndices.isEmpty()) { + int hCount; + for (int i = 0; i + < assignment.getSize(); i++) { + for (int k = 0; k + < assignment.getAssignment(0, i).length; k++) { + hCount = 0; + for (int j = 0; j + < explicitHydrogenIndices.size(); j++) { + if (explicitHydrogenIndices.get(j) + >= assignment.getAssignment(0, i, k)) { + break; + } + hCount++; + } + temp = assignment.getAssignment(0, i); + temp[k] = assignment.getAssignment(0, i, k) + - hCount; + assignment.setAssignment(0, i, temp); + } + } + } + dataSet.setSpectrum(new SpectrumCompact(spectrum)); + dataSet.setAssignment(assignment); + + dataSets.add(dataSet.buildClone()); + } + } + } + + return dataSets; + } + + // /** + // * Returns a hashmap containing combined keys (by "_") of solvents + // * and lists of calculated deviations between all given spectra for a + // * nucleus in molecule record as values.
+ // * Here, only molecule records in NMRShiftDB file are considered which have + // * at least two different spectra for same nucleus.
+ // * Example: "Spectrum 13C 0", "Spectrum 13C 1" will be used for given + // * nucleus 13C. + // * + // * @param pathToNMRShiftDB + // * @param nucleus + // * + // * @return + // * + // * @throws FileNotFoundException + // * @throws CDKException + // */ + // public static HashMap> getSolventDeviations(final String pathToNMRShiftDB, final String nucleus) throws FileNotFoundException, CDKException { + // int signalCount; + // Spectrum spectrum; + // Assignment assignment; + // final ArrayList> spectraSets = getSpectraFromNMRShiftDB(pathToNMRShiftDB, nucleus); + // HashMap> shiftsPerAtom; + // HashMap> solventsPerAtom; + // ArrayList solvents; + // String[] solventsToSort; + // + // final HashMap> deviations = new HashMap<>(); + // String combiKey; + // + // for (final ArrayList spectraSetInRecord : spectraSets) { + // shiftsPerAtom = new HashMap<>(); + // solventsPerAtom = new HashMap<>(); + // signalCount = -1; + // for (final Object[] spectrumAndAssignment : spectraSetInRecord) { + // spectrum = (Spectrum) spectrumAndAssignment[0]; + // assignment = (Assignment) spectrumAndAssignment[1]; + // if (signalCount == -1) { + // signalCount = spectrum.getSignalCount(); + // } else if (signalCount != spectrum.getSignalCount()) { + // continue; + // } + // for (final int atomIndex : assignment.getAssignments(0)) { + // if (!shiftsPerAtom.containsKey(atomIndex)) { + // shiftsPerAtom.put(atomIndex, new ArrayList<>()); + // solventsPerAtom.put(atomIndex, new ArrayList<>()); + // } + // shiftsPerAtom.get(atomIndex).add(spectrum.getSignal(assignment.getIndex(0, atomIndex)).getShift(0)); + // solventsPerAtom.get(atomIndex).add(spectrum.getSolvent()); + // } + // } + // if (shiftsPerAtom.isEmpty() || (shiftsPerAtom.get(Collections.min(shiftsPerAtom.keySet())).size() < 2)) { + // continue; + // } + // solvents = new ArrayList<>(solventsPerAtom.get(Collections.min(solventsPerAtom.keySet()))); + // // if(Collections.frequency(solvents, "Unreported") + Collections.frequency(solvents, "Unknown") > solvents.size() - 2){ + // // continue; + // // } + // + // for (final int atomIndex : shiftsPerAtom.keySet()) { + // for (int s1 = 0; s1 < solvents.size(); s1++) { + // // if(solvents.get(s1).equals("Unreported") || solvents.get(s1).equals("Unknown")){ + // // continue; + // // } + // for (int s2 = s1 + 1; s2 < solvents.size(); s2++) { + // // if (solvents.get(s2).equals("Unreported") || solvents.get(s2).equals("Unknown")) { + // // continue; + // // } + // solventsToSort = new String[2]; + // solventsToSort[0] = solvents.get(s1); + // solventsToSort[1] = solvents.get(s2); + // Arrays.sort(solventsToSort); + // combiKey = solventsToSort[0] + "_" + solventsToSort[1]; + // if (!deviations.containsKey(combiKey)) { + // deviations.put(combiKey, new ArrayList<>()); + // } + // deviations.get(combiKey).add(Math.abs(shiftsPerAtom.get(atomIndex).get(s1) - shiftsPerAtom.get(atomIndex).get(s2))); + // } + // } + // } + // } + // + // return deviations; + // } + // + // /** + // * @param pathToDB + // * + // * @return + // * + // * @throws FileNotFoundException + // * @deprecated + // */ + // public static Set getAtomTypesInDB(final String pathToDB) throws FileNotFoundException { + // final HashSet atomTypes = new HashSet<>(); + // final IteratingSDFReader iterator = new IteratingSDFReader(new FileReader(pathToDB), SilentChemObjectBuilder.getInstance()); + // while (iterator.hasNext()) { + // atomTypes.addAll(HOSECodeUtilities.getAtomTypesInAtomContainer(iterator.next())); + // } + // + // return atomTypes; + // } + + /** + * Creates a two dimensional array of a given NMRShiftDB casekit.nmr entry + * with all signal shift values, intensities, multiplicities and atom indices. + * + * @param NMRShiftDBSpectrum + * + * @return two dimensional array: + * 1. dimension: signal index (row); + * 2. dimension: signal shift value (column 1), signal intensity (column 2), + * signal multiplicity (column 3), atom index in structure (column 4) + */ + public static String[][] parseNMRShiftDBSpectrum(final String NMRShiftDBSpectrum) { + if (NMRShiftDBSpectrum.trim() + .isEmpty()) { + return new String[][]{}; + } + String[] signalSplit; + final String[] shiftsSplit = NMRShiftDBSpectrum.split("\\|"); + final String[][] values = new String[shiftsSplit.length][4]; + for (int i = 0; i + < shiftsSplit.length; i++) { + signalSplit = shiftsSplit[i].split(";"); + values[i][0] = signalSplit[0]; // shift value + values[i][1] = signalSplit[1].toLowerCase() + .split("[a-z]")[0]; // intensity + values[i][2] = signalSplit[1].split("\\d+\\.\\d+").length + > 0 + ? signalSplit[1].split("\\d+\\.\\d+")[1].toLowerCase() + : ""; // multiplicity + values[i][3] = signalSplit[2]; // atom index + } + + return values; + } + + public static Spectrum NMRShiftDBSpectrumToSpectrum(final String NMRShiftDBSpectrum, final String nucleus) { + if ((NMRShiftDBSpectrum + == null) + || NMRShiftDBSpectrum.trim() + .isEmpty()) { + return null; + } + final String[][] spectrumStringArray = parseNMRShiftDBSpectrum(NMRShiftDBSpectrum); + final Spectrum spectrum = new Spectrum(); + spectrum.setNuclei(new String[]{nucleus}); + spectrum.setSignals(new ArrayList<>()); + String multiplicity; + Double shift, intensity; + try { + for (int i = 0; i + < spectrumStringArray.length; i++) { + shift = Double.parseDouble(spectrumStringArray[i][0]); + intensity = Double.parseDouble(spectrumStringArray[i][1]); + multiplicity = spectrumStringArray[i][2].trim() + .isEmpty() + ? null + : spectrumStringArray[i][2].trim() + .toLowerCase(); + spectrum.addSignal( + new Signal(new String[]{nucleus}, new Double[]{shift}, multiplicity, "signal", intensity, 1, 0, + null, null)); + } + } catch (final Exception e) { + return null; + } + + return spectrum; + } + + public static Assignment NMRShiftDBSpectrumToAssignment(final String NMRShiftDBSpectrum, final String nucleus) { + if ((NMRShiftDBSpectrum + == null) + || NMRShiftDBSpectrum.trim() + .isEmpty()) { + return null; + } + final String[][] NMRShiftDBSpectrumStringArray = parseNMRShiftDBSpectrum(NMRShiftDBSpectrum); + final Spectrum spectrum = NMRShiftDBSpectrumToSpectrum(NMRShiftDBSpectrum, nucleus); + final Assignment assignment = new Assignment(); + assignment.setNuclei(spectrum.getNuclei()); + assignment.initAssignments(spectrum.getSignalCount()); + int signalIndex; + String multiplicity; + List closestSignalList; + for (int i = 0; i + < NMRShiftDBSpectrumStringArray.length; i++) { + // just to be sure that we take the right signal if equivalences are present + closestSignalList = spectrum.pickByClosestShift(Double.parseDouble(NMRShiftDBSpectrumStringArray[i][0]), 0, + 0.0); + multiplicity = NMRShiftDBSpectrumStringArray[i][2].trim() + .isEmpty() + ? null + : NMRShiftDBSpectrumStringArray[i][2].trim() + .toLowerCase(); + closestSignalList.retainAll(spectrum.pickByMultiplicity(multiplicity)); + signalIndex = closestSignalList.get(0); + + assignment.addAssignmentEquivalence(0, signalIndex, Integer.parseInt(NMRShiftDBSpectrumStringArray[i][3])); + } + + return assignment; + } +} diff --git a/src/casekit/nmr/dbservice/Utils.java b/src/casekit/nmr/dbservice/Utils.java new file mode 100644 index 0000000..4fb1bf2 --- /dev/null +++ b/src/casekit/nmr/dbservice/Utils.java @@ -0,0 +1,53 @@ +package casekit.nmr.dbservice; + +import org.openscience.cdk.exception.CDKException; +import org.openscience.cdk.io.SDFWriter; +import org.openscience.cdk.io.iterator.IteratingSDFReader; +import org.openscience.cdk.silent.SilentChemObjectBuilder; + +import java.io.BufferedWriter; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; + +public class Utils { + + public static int splitSDFile(final String pathToSDFile, final int maxMolPerFile) throws IOException, CDKException { + final IteratingSDFReader iterator = new IteratingSDFReader(new FileReader(pathToSDFile), + SilentChemObjectBuilder.getInstance()); + final String fileEnding = pathToSDFile.split("\\.")[1]; + BufferedWriter bufferedWriter; + SDFWriter sdfWriter; + int counter = 0; + int part = 1; + bufferedWriter = new BufferedWriter(new FileWriter(pathToSDFile.split("\\.")[0] + + "_" + + part + + "." + + fileEnding)); + sdfWriter = new SDFWriter(bufferedWriter); + while (iterator.hasNext()) { + if (counter + >= maxMolPerFile) { + sdfWriter.close(); + + part++; + bufferedWriter = new BufferedWriter(new FileWriter(pathToSDFile.split("\\.")[0] + + "_" + + part + + "." + + fileEnding)); + sdfWriter = new SDFWriter(bufferedWriter); + sdfWriter.write(iterator.next()); + counter = 1; + } else { + sdfWriter.write(iterator.next()); + } + counter++; + } + sdfWriter.close(); + + return part + - 1; + } +} diff --git a/src/casekit/nmr/elucidation/Constants.java b/src/casekit/nmr/elucidation/Constants.java new file mode 100644 index 0000000..02ab23b --- /dev/null +++ b/src/casekit/nmr/elucidation/Constants.java @@ -0,0 +1,96 @@ +package casekit.nmr.elucidation; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public class Constants { + + // valid strings from LSD webpage: C N N5 O S S4 S6 F Cl Br I P P5 Si B X + public static final Map nucleiMap = createNucleiMap(); + public static final Map defaultHybridizationMap = createDefaultHybridizationMap(); + public static final Map defaultProtonsCountPerValencyMap = createDefaultProtonsCountPerValencyMap(); + public static final Map defaultAtomLabelMap = createDefaultAtomLabelMap(); + public static final Map hybridizationConversionMap = createHybridizationConversionMap(); + + private static Map createNucleiMap() { + final Map nuclei = new HashMap<>(); + nuclei.put("C", "13C"); + nuclei.put("N", "15N"); + nuclei.put("H", "1H"); + nuclei.put("S", "33S"); + nuclei.put("F", "19F"); + nuclei.put("P", "31P"); + nuclei.put("Si", "29Si"); + + return Collections.unmodifiableMap(nuclei); + } + + private static Map createDefaultHybridizationMap() { + final Map defaultHybridization = new HashMap<>(); + defaultHybridization.put("C", new int[]{1, 2, 3}); + defaultHybridization.put("N", new int[]{1, 2, 3}); + defaultHybridization.put("S", new int[]{1, 2, 3}); + defaultHybridization.put("O", new int[]{2, 3}); + defaultHybridization.put("I", new int[]{3}); + defaultHybridization.put("F", new int[]{3}); + defaultHybridization.put("Cl", new int[]{3}); + defaultHybridization.put("Br", new int[]{3}); + defaultHybridization.put("P", new int[]{1, 2, 3}); + defaultHybridization.put("Si", new int[]{1, 2, 3}); + + return Collections.unmodifiableMap(defaultHybridization); + } + + private static Map createDefaultProtonsCountPerValencyMap() { + final Map defaultProtonsCountPerValency = new HashMap<>(); + defaultProtonsCountPerValency.put("C", new int[]{0, 1, 2, 3}); + defaultProtonsCountPerValency.put("N", new int[]{0, 1, 2}); + defaultProtonsCountPerValency.put("N5", new int[]{0, 1, 2, 3}); + defaultProtonsCountPerValency.put("N35", new int[]{0, 1, 2, 3}); + defaultProtonsCountPerValency.put("S", new int[]{0, 1}); + defaultProtonsCountPerValency.put("S4", new int[]{0, 1, 2, 3}); + defaultProtonsCountPerValency.put("S6", new int[]{0, 1, 2, 3}); + defaultProtonsCountPerValency.put("S246", new int[]{0, 1, 2, 3}); + defaultProtonsCountPerValency.put("O", new int[]{0, 1}); + defaultProtonsCountPerValency.put("I", new int[]{0}); + defaultProtonsCountPerValency.put("F", new int[]{0}); + defaultProtonsCountPerValency.put("Cl", new int[]{0}); + defaultProtonsCountPerValency.put("Br", new int[]{0}); + defaultProtonsCountPerValency.put("P", new int[]{0, 1, 2}); + defaultProtonsCountPerValency.put("P5", new int[]{0, 1, 2, 3}); + defaultProtonsCountPerValency.put("P35", new int[]{0, 1, 2, 3}); + defaultProtonsCountPerValency.put("Si", new int[]{0, 1, 2, 3}); + + return defaultProtonsCountPerValency; + } + + private static Map createDefaultAtomLabelMap() { + final Map defaultAtomLabel = new HashMap<>(); + defaultAtomLabel.put("C", "C"); + defaultAtomLabel.put("N", "N35"); + defaultAtomLabel.put("O", "O"); + defaultAtomLabel.put("S", "S246"); + defaultAtomLabel.put("I", "I"); + defaultAtomLabel.put("F", "F"); + defaultAtomLabel.put("Cl", "Cl"); + defaultAtomLabel.put("Br", "Br"); + defaultAtomLabel.put("P", "P35"); + defaultAtomLabel.put("Si", "Si"); + + return Collections.unmodifiableMap(defaultAtomLabel); + } + + private static Map createHybridizationConversionMap() { + // @TODO access this information from MongoDB and store it instead of hard coding it + // possible command in MongoDB: db.hybridizations.aggregate([{$match: {nucleus: "15N"}}, {$group: {_id: null, set: {$addToSet: "$hybridization"}}}]) + // nucleus -> hybridization string -> number + final Map hybridizationConversionMap = new HashMap<>(); + hybridizationConversionMap.put("PLANAR3", 3); + hybridizationConversionMap.put("SP3", 3); + hybridizationConversionMap.put("SP2", 2); + hybridizationConversionMap.put("SP1", 1); + + return Collections.unmodifiableMap(hybridizationConversionMap); + } +} diff --git a/src/casekit/nmr/elucidation/Utilities.java b/src/casekit/nmr/elucidation/Utilities.java new file mode 100644 index 0000000..2528d03 --- /dev/null +++ b/src/casekit/nmr/elucidation/Utilities.java @@ -0,0 +1,1114 @@ +package casekit.nmr.elucidation; + +import casekit.nmr.elucidation.model.Detections; +import casekit.nmr.elucidation.model.Grouping; +import casekit.nmr.elucidation.model.MolecularConnectivity; +import casekit.nmr.model.Signal; +import casekit.nmr.model.nmrium.Correlation; +import casekit.nmr.model.nmrium.Link; +import casekit.nmr.utils.Utils; + +import java.util.*; +import java.util.stream.Collectors; + +public class Utilities { + + public static void reduceDefaultHybridizationsAndProtonCountsOfHeteroAtoms(final List correlationList, + final Map>>> detectedConnectivities, + final Map> detectedHybridizations) { + if (detectedConnectivities + == null + || detectedConnectivities.isEmpty()) { + return; + } + final Map> allowedNeighborAtomHybridizations = buildAllowedNeighborAtomHybridizations( + correlationList, detectedConnectivities); + final Map> allowedNeighborAtomProtonCounts = buildAllowedNeighborAtomProtonCounts( + correlationList, detectedConnectivities); + // hetero atoms can bond to carbons only, due to that we can use further connectivity information + // do not allow bond between carbon and hetero atoms in certain hybridization states and proton counts + Correlation correlation; + for (int i = 0; i + < correlationList.size(); i++) { + correlation = correlationList.get(i); + // ignore C and H atoms + if (correlation.getAtomType() + .equals("C") + || correlation.getAtomType() + .equals("H")) { + continue; + } + final Set hybridizationsToAdd = allowedNeighborAtomHybridizations.containsKey( + correlation.getAtomType()) + ? allowedNeighborAtomHybridizations.get(correlation.getAtomType()) + : Arrays.stream(Constants.defaultHybridizationMap.get( + correlation.getAtomType())) + .boxed() + .collect(Collectors.toSet()); + final Set protonCountsToAdd = allowedNeighborAtomProtonCounts.containsKey( + correlation.getAtomType()) + ? allowedNeighborAtomProtonCounts.get(correlation.getAtomType()) + : Arrays.stream(Constants.defaultProtonsCountPerValencyMap.get( + correlation.getAtomType())) + .boxed() + .collect(Collectors.toSet()); + // but only if we have seen the hetero atom type in connectivity statistics + // and hybridization states or protons count was not set beforehand + if (correlation.getHybridization() + .isEmpty()) { + correlation.getHybridization() + .addAll(hybridizationsToAdd); + } else if (correlation.getEdited() + != null + && correlation.getEdited() + .containsKey("hybridization") + && !correlation.getEdited() + .get("hybridization") + && allowedNeighborAtomHybridizations.containsKey(correlation.getAtomType())) { + correlation.getHybridization() + .retainAll(hybridizationsToAdd); + } + if (correlation.getProtonsCount() + .isEmpty()) { + correlation.getProtonsCount() + .addAll(protonCountsToAdd); + } else if (correlation.getEdited() + != null + && correlation.getEdited() + .containsKey("protonsCount") + && !correlation.getEdited() + .get("protonsCount")) { + correlation.getProtonsCount() + .retainAll(protonCountsToAdd); + } + detectedHybridizations.putIfAbsent(i, new ArrayList<>()); + detectedHybridizations.get(i) + .addAll(correlation.getHybridization()); + } + } + + public static Map> buildAllowedNeighborAtomHybridizations( + final List correlationList, + final Map>>> detectedConnectivities) { + final Map> allowedHeteroAtomHybridizations = new HashMap<>(); + for (final Map.Entry>>> correlationEntry : detectedConnectivities.entrySet()) { + if (!correlationList.get(correlationEntry.getKey()) + .getAtomType() + .equals("C") + && !correlationList.get(correlationEntry.getKey()) + .getAtomType() + .equals("H")) { + continue; + } + for (final Map.Entry>> neighborAtomTypeEntry : correlationEntry.getValue() + .entrySet()) { + allowedHeteroAtomHybridizations.putIfAbsent(neighborAtomTypeEntry.getKey(), new HashSet<>()); + allowedHeteroAtomHybridizations.get(neighborAtomTypeEntry.getKey()) + .addAll(neighborAtomTypeEntry.getValue() + .keySet()); + } + } + + return allowedHeteroAtomHybridizations; + } + + public static Map> buildAllowedNeighborAtomProtonCounts( + final List correlationList, + final Map>>> detectedConnectivities) { + final Map> allowedHeteroAtomProtonCounts = new HashMap<>(); + for (final Map.Entry>>> correlationEntry : detectedConnectivities.entrySet()) { + if (!correlationList.get(correlationEntry.getKey()) + .getAtomType() + .equals("C") + && !correlationList.get(correlationEntry.getKey()) + .getAtomType() + .equals("H")) { + continue; + } + for (final Map.Entry>> neighborAtomTypeEntry : correlationEntry.getValue() + .entrySet()) { + allowedHeteroAtomProtonCounts.putIfAbsent(neighborAtomTypeEntry.getKey(), new HashSet<>()); + for (final Map.Entry> neighborHybridizationEntry : neighborAtomTypeEntry.getValue() + .entrySet()) { + allowedHeteroAtomProtonCounts.get(neighborAtomTypeEntry.getKey()) + .addAll(neighborHybridizationEntry.getValue()); + } + } + } + + return allowedHeteroAtomProtonCounts; + } + + public static Map>> buildForbiddenNeighbors( + final Map>> connectivities, final Set possibleNeighborAtomTypes) { + + // define forbidden neighbors (for carbons only) + // or put just an empty map which means the whole element is forbidden + final Map>> forbiddenNeighbors = new HashMap<>(); + for (final String possibleNeighborAtomType : possibleNeighborAtomTypes) { + if (possibleNeighborAtomType.equals("H")) { + continue; + } + forbiddenNeighbors.put(possibleNeighborAtomType, new HashMap<>()); + if (connectivities.containsKey(possibleNeighborAtomType)) { + for (final int defaultHybridization : Arrays.stream( + Constants.defaultHybridizationMap.get(possibleNeighborAtomType)) + .boxed() + .collect(Collectors.toList())) { + forbiddenNeighbors.get(possibleNeighborAtomType) + .put(defaultHybridization, Arrays.stream( + Constants.defaultProtonsCountPerValencyMap.get(possibleNeighborAtomType)) + .boxed() + .collect(Collectors.toSet())); + } + for (final int possibleNeighborHybridization : connectivities.get(possibleNeighborAtomType) + .keySet()) { + // remove found protons count per hybridzations from list of forbidden ones + for (final int forbiddenNeighborHybridization : new HashSet<>( + forbiddenNeighbors.get(possibleNeighborAtomType) + .keySet())) { + forbiddenNeighbors.get(possibleNeighborAtomType) + .get(forbiddenNeighborHybridization) + .removeAll(connectivities.get(possibleNeighborAtomType) + .get(possibleNeighborHybridization)); + if (forbiddenNeighbors.get(possibleNeighborAtomType) + .get(forbiddenNeighborHybridization) + .isEmpty()) { + forbiddenNeighbors.get(possibleNeighborAtomType) + .remove(forbiddenNeighborHybridization); + } + } + if (forbiddenNeighbors.get(possibleNeighborAtomType) + .isEmpty()) { + forbiddenNeighbors.remove(possibleNeighborAtomType); + break; + } + } + } + } + + return forbiddenNeighbors; + } + + + public static Map> buildFixedNeighborsByINADEQUATE(final List correlationList) { + final Map> fixedNeighbors = new HashMap<>(); + final Set uniqueSet = new HashSet<>(); + Correlation correlation; + for (int i = 0; i + < correlationList.size(); i++) { + correlation = correlationList.get(i); + // @TODO for now use INADEQUATE information of atoms without equivalences only + if (correlation.getEquivalence() + != 1) { + continue; + } + for (final Link link : correlation.getLink()) { + if (link.getExperimentType() + .equals("inadequate")) { + for (final int matchIndex : link.getMatch()) { + // insert BOND pair once only and not if equivalences exist + if (!uniqueSet.contains(i + + " " + + matchIndex) + && correlationList.get(matchIndex) + .getEquivalence() + == 1) { + fixedNeighbors.putIfAbsent(i, new HashSet<>()); + fixedNeighbors.get(i) + .add(matchIndex); + uniqueSet.add(i + + " " + + matchIndex); + uniqueSet.add(matchIndex + + " " + + i); + } + } + } + } + } + + return fixedNeighbors; + } + + private static boolean hasMatch(final Correlation correlation1, final Correlation correlation2, + final double tolerance) { + final Signal signal1 = Utils.extractFirstSignalFromCorrelation(correlation1); + final Signal signal2 = Utils.extractFirstSignalFromCorrelation(correlation2); + if (signal1 + == null + || signal2 + == null) { + return false; + } + int dim1 = -1; + int dim2 = -1; + String atomType; + for (int i = 0; i + < signal1.getNuclei().length; i++) { + atomType = Utils.getAtomTypeFromNucleus(signal1.getNuclei()[i]); + if (atomType.equals(correlation1.getAtomType())) { + dim1 = i; + break; + } + } + for (int i = 0; i + < signal2.getNuclei().length; i++) { + atomType = Utils.getAtomTypeFromNucleus(signal2.getNuclei()[i]); + if (atomType.equals(correlation2.getAtomType())) { + dim2 = i; + break; + } + } + if (dim1 + == -1 + || dim2 + == -1) { + return false; + } + + final double shift1 = signal1.getShift(dim1); + final double shift2 = signal2.getShift(dim2); + + return Math.abs(shift1 + - shift2) + <= tolerance; + + } + + private static Map>> findGroups(final List correlationList, + final Map tolerances) { + // cluster group index -> list of correlation index pair + final Map>> groups = new HashMap<>(); + int groupIndex = 0; + final Set inserted = new HashSet<>(); + int foundGroupIndex; + for (int i = 0; i + < correlationList.size(); i++) { + final Correlation correlation = correlationList.get(i); + if (inserted.contains(i) + || correlation.isPseudo()) { + continue; + } + groups.putIfAbsent(correlation.getAtomType(), new HashMap<>()); + // if we have a match somewhere then add the correlation index into to group + // if not then create a new group + foundGroupIndex = -1; + for (final Map.Entry> groupEntry : groups.get(correlation.getAtomType()) + .entrySet()) { + if (groupEntry.getValue() + .stream() + .anyMatch(correlationIndex -> hasMatch(correlation, correlationList.get(correlationIndex), + tolerances.get(correlation.getAtomType())))) { + foundGroupIndex = groupEntry.getKey(); + break; + } + } + if (foundGroupIndex + != -1) { + groups.get(correlation.getAtomType()) + .get(foundGroupIndex) + .add(i); + inserted.add(i); + } else { + groups.get(correlation.getAtomType()) + .put(groupIndex, new ArrayList<>()); + groups.get(correlation.getAtomType()) + .get(groupIndex) + .add(i); + inserted.add(i); + groupIndex++; + } + } + + return groups; + } + + private static Map> transformGroups( + final Map>> groups) { + final Map> transformedGroups = new HashMap<>(); + for (final Map.Entry>> atomTypeEntry : groups.entrySet()) { + transformedGroups.put(atomTypeEntry.getKey(), new HashMap<>()); + for (final Map.Entry> groupEntry : atomTypeEntry.getValue() + .entrySet()) { + for (final int correlationIndex : groupEntry.getValue()) { + transformedGroups.get(atomTypeEntry.getKey()) + .put(correlationIndex, groupEntry.getKey()); + } + } + } + + return transformedGroups; + } + + public static Grouping buildGroups(final List correlationList, final Map tolerances) { + final Map>> groups = findGroups(correlationList, tolerances); + + return new Grouping(tolerances, groups, transformGroups(groups)); + } + + private static List getProtonCounts(final List correlationList, final int index) { + final Correlation correlation = correlationList.get(index); + if (correlation.getProtonsCount() + != null + && !correlation.getProtonsCount() + .isEmpty()) { + // if protonCounts is already given + return correlation.getProtonsCount(); + } + final List protonCounts = new ArrayList<>(); + final int[] defaultProtonCounts = Constants.defaultProtonsCountPerValencyMap.get( + Constants.defaultAtomLabelMap.get(correlation.getAtomType())); + for (final int defaultProtonCount : defaultProtonCounts) { + protonCounts.add(defaultProtonCount); + } + + return protonCounts; + } + + private static List getHybridizations(final List correlationList, final int index, + final Map> detectedHybridizations) { + final Correlation correlation = correlationList.get(index); + final Set hybridizations = new HashSet<>(correlation.getHybridization() + != null + ? correlation.getHybridization() + : new ArrayList<>()); + if (detectedHybridizations.containsKey(index)) { + hybridizations.addAll(detectedHybridizations.get(index)); + } + if (hybridizations.isEmpty() + && correlation.getAtomType() + .equals("C") + && correlation.getProtonsCount() + .size() + == 1) { + if (correlation.getProtonsCount() + .get(0) + == 2) { + // a carbon with two protons can only be SP2 or SP3 + hybridizations.add(2); + hybridizations.add(3); + } else if (correlation.getProtonsCount() + .get(0) + == 3) { + // a carbon with three protons can only be SP3 + hybridizations.add(3); + } + } + if (hybridizations.isEmpty()) { + for (int i = 0; i + < Constants.defaultHybridizationMap.get(correlation.getAtomType()).length; i++) { + hybridizations.add(Constants.defaultHybridizationMap.get(correlation.getAtomType())[i]); + } + } + + return new ArrayList<>(hybridizations); + } + + public static Map buildIndicesMap(final List molecularConnectivityList) { + // index in correlation data -> [indices in PyLSD file...] + final Map indicesMap = new HashMap<>(); + // init element indices within correlations with same order as in correlation data input + int heavyAtomIndexInPyLSDFile = 1; + int protonIndexInPyLSDFile = 1; + int protonsToInsert; + Integer[] arrayToInsert; + for (final MolecularConnectivity molecularConnectivity : molecularConnectivityList) { + // set entry for each correlation with consideration of equivalences + if (!molecularConnectivity.getAtomType() + .equals("H")) { + if (molecularConnectivity.getHsqc() + != null) { + // insert for protons + protonsToInsert = molecularConnectivity.getEquivalence(); + arrayToInsert = new Integer[protonsToInsert]; + for (int j = 0; j + < arrayToInsert.length; j++) { + arrayToInsert[j] = protonIndexInPyLSDFile; + protonIndexInPyLSDFile++; + } + for (final int attachedProtonIndex : molecularConnectivity.getHsqc()) { + indicesMap.put(attachedProtonIndex, arrayToInsert); + } + } + // insert for heavy atom itself + indicesMap.put(molecularConnectivity.getIndex(), new Integer[molecularConnectivity.getEquivalence()]); + for (int j = 0; j + < molecularConnectivity.getEquivalence(); j++) { + indicesMap.get(molecularConnectivity.getIndex())[j] = heavyAtomIndexInPyLSDFile; + heavyAtomIndexInPyLSDFile++; + } + } + } + + return indicesMap; + } + + public static MolecularConnectivity findMolecularConnectivityByIndex( + final Map> molecularConnectivityMap, final String atomType, + final boolean exclude, final int index) { + for (final int correlationIndex : molecularConnectivityMap.keySet()) { + for (final MolecularConnectivity molecularConnectivity : molecularConnectivityMap.get(correlationIndex)) { + if (((exclude + && !molecularConnectivity.getAtomType() + .equals(atomType)) + || (!exclude + && molecularConnectivity.getAtomType() + .equals(atomType))) + && molecularConnectivity.getIndex() + == index) { + return molecularConnectivity; + } + } + } + + return null; + } + + private static List buildPossibilities(final Map indicesMap, + final List molecularConnectivityList, + final int correlationIndex, final Grouping grouping, + final boolean useGrouping) { + final MolecularConnectivity molecularConnectivity = molecularConnectivityList.get(correlationIndex); + // add possible indices from grouping + final int groupIndex; + final Set possibilities = new HashSet<>(); + if (useGrouping + && grouping.getTransformedGroups() + .containsKey(molecularConnectivity.getAtomType()) + && grouping.getTransformedGroups() + .get(molecularConnectivity.getAtomType()) + .containsKey(correlationIndex)) { + groupIndex = grouping.getTransformedGroups() + .get(molecularConnectivity.getAtomType()) + .get(correlationIndex); + for (final int groupMemberIndex : grouping.getGroups() + .get(molecularConnectivity.getAtomType()) + .get(groupIndex)) { + + if (indicesMap.containsKey(groupMemberIndex)) { + // add equivalence indices of group members + possibilities.addAll(Arrays.asList(indicesMap.get(groupMemberIndex))); + } + } + } else { + // add for equivalences only + possibilities.addAll(Arrays.asList(indicesMap.get(correlationIndex))); + } + + return new ArrayList<>(possibilities); + } + + public static Map> buildMolecularConnectivityMap( + final List molecularConnectivityList, final Detections detections, + final Grouping grouping, final Map defaultBondDistances) { + + final Map indicesMap = buildIndicesMap(molecularConnectivityList); + // correlation index -> [MolecularConnectivity] + final Map> molecularConnectivityMap = new HashMap<>(); + MolecularConnectivity newMolecularConnectivity; + + int index, correlationIndex, protonCorrelationIndex, protonIndex; + for (final MolecularConnectivity molecularConnectivity : molecularConnectivityList) { + correlationIndex = molecularConnectivity.getIndex(); + // skip in case of non-linked proton which has no index in indices map + if (!indicesMap.containsKey(correlationIndex)) { + continue; + } + for (int k = 0; k + < indicesMap.get(correlationIndex).length; k++) { + index = indicesMap.get(correlationIndex)[k]; + newMolecularConnectivity = new MolecularConnectivity(); + newMolecularConnectivity.setIndex(index); + newMolecularConnectivity.setAtomType(molecularConnectivity.getAtomType()); + newMolecularConnectivity.setEquivalence(1); + newMolecularConnectivity.setPseudo(molecularConnectivity.isPseudo()); + newMolecularConnectivity.setProtonCounts(molecularConnectivity.getProtonCounts()); + newMolecularConnectivity.setHybridizations(molecularConnectivity.getHybridizations()); + newMolecularConnectivity.setSignal(molecularConnectivity.getSignal()); + + if (!molecularConnectivity.getAtomType() + .equals("H") + && molecularConnectivity.getHsqc() + != null + && k + < indicesMap.get(molecularConnectivity.getHsqc() + .get(0)).length) { + // using the first proton correlation index from HSQC list is enough because show will direct to same heavy atom index + protonIndex = indicesMap.get(molecularConnectivity.getHsqc() + .get(0))[k]; + newMolecularConnectivity.setHsqc(new ArrayList<>()); + newMolecularConnectivity.getHsqc() + .add(protonIndex); + } + if (!molecularConnectivity.getAtomType() + .equals("H") + && molecularConnectivity.getHmbc() + != null) { + for (final Map.Entry entryHMBC : molecularConnectivity.getHmbc() + .entrySet()) { + protonCorrelationIndex = entryHMBC.getKey(); + if (indicesMap.containsKey(protonCorrelationIndex)) { + for (int l = 0; l + < indicesMap.get(protonCorrelationIndex).length; l++) { + protonIndex = indicesMap.get(protonCorrelationIndex)[l]; + if (newMolecularConnectivity.getHmbc() + == null) { + newMolecularConnectivity.setHmbc(new HashMap<>()); + } + newMolecularConnectivity.getHmbc() + .put(protonIndex, entryHMBC.getValue()); + } + } + } + } + if (molecularConnectivity.getAtomType() + .equals("H") + && molecularConnectivity.getCosy() + != null) { + for (final Map.Entry entryCOSY : molecularConnectivity.getCosy() + .entrySet()) { + protonCorrelationIndex = entryCOSY.getKey(); + if (indicesMap.containsKey(protonCorrelationIndex) + && k + < indicesMap.get(protonCorrelationIndex).length) { + protonIndex = indicesMap.get(protonCorrelationIndex)[k]; + if (newMolecularConnectivity.getCosy() + == null) { + newMolecularConnectivity.setCosy(new HashMap<>()); + } + newMolecularConnectivity.getCosy() + .put(protonIndex, entryCOSY.getValue()); + } + } + } + + molecularConnectivityMap.putIfAbsent(correlationIndex, new ArrayList<>()); + molecularConnectivityMap.get(correlationIndex) + .add(newMolecularConnectivity); + } + // set detections + for (final MolecularConnectivity molecularConnectivityTemp : molecularConnectivityMap.get( + correlationIndex)) { + if (detections.getForbiddenNeighbors() + .containsKey(correlationIndex)) { + molecularConnectivityTemp.setForbiddenNeighbors(detections.getForbiddenNeighbors() + .get(correlationIndex)); + } + if (detections.getSetNeighbors() + .containsKey(correlationIndex)) { + molecularConnectivityTemp.setSetNeighbors(detections.getSetNeighbors() + .get(correlationIndex)); + } + molecularConnectivityTemp.setGroupMembers( + buildPossibilities(indicesMap, molecularConnectivityList, correlationIndex, grouping, + // !molecularConnectivity.getAtomType() + // .equals("H")) + true)); + } + // fill in fixed neighbors + if (molecularConnectivity.getEquivalence() + == 1 + && detections.getFixedNeighbors() + .containsKey(correlationIndex)) { + MolecularConnectivity molecularConnectivityTemp; + for (final int correlationIndex2 : detections.getFixedNeighbors() + .get(correlationIndex)) { + molecularConnectivityTemp = molecularConnectivityList.get(correlationIndex2); + // use fixed neighbor information of atoms without equivalence equals 1 only + if (molecularConnectivityTemp.getEquivalence() + > 1) { + continue; + } + index = indicesMap.get(correlationIndex)[0]; + newMolecularConnectivity = findMolecularConnectivityByIndex(molecularConnectivityMap, + molecularConnectivity.getAtomType(), + false, index); + if (newMolecularConnectivity.getFixedNeighbors() + == null) { + newMolecularConnectivity.setFixedNeighbors(new ArrayList<>()); + } + newMolecularConnectivity.getFixedNeighbors() + .add(indicesMap.get(correlationIndex2)[0]); + } + } + } + + // filter out HMBC or COSY correlation to itself + for (final int correlationIndexTemp : molecularConnectivityMap.keySet()) { + for (final MolecularConnectivity molecularConnectivityTemp : molecularConnectivityMap.get( + correlationIndexTemp)) { + if (molecularConnectivityTemp.getHsqc() + != null) { + if (molecularConnectivityTemp.getHmbc() + != null) { + molecularConnectivityTemp.getHmbc() + .remove(molecularConnectivityTemp.getHsqc()); + } + if (molecularConnectivityTemp.getCosy() + != null) { + molecularConnectivityTemp.getCosy() + .remove(molecularConnectivityTemp.getHsqc()); + } + } + } + } + + return molecularConnectivityMap; + } + + public static List buildMolecularConnectivityList(final List correlationList, + final Detections detections, + final Grouping grouping, + final Map defaultBondDistances) { + final List molecularConnectivityList = new ArrayList<>(); + Correlation correlation; + int groupIndex; + Map signal2DMap; + Map jMap; + Map pathLengthMap; + MolecularConnectivity molecularConnectivity; + for (int correlationIndex = 0; correlationIndex + < correlationList.size(); correlationIndex++) { + correlation = correlationList.get(correlationIndex); + molecularConnectivity = new MolecularConnectivity(); + molecularConnectivity.setIndex(correlationIndex); + molecularConnectivity.setAtomType(correlation.getAtomType()); + molecularConnectivity.setSignal(Utils.extractFirstSignalFromCorrelation(correlation)); + molecularConnectivity.setEquivalence(correlation.getEquivalence()); + molecularConnectivity.setPseudo(correlation.isPseudo()); + + if (!correlation.getAtomType() + .equals("H")) { + molecularConnectivity.setProtonCounts(getProtonCounts(correlationList, correlationIndex)); + molecularConnectivity.setHybridizations( + getHybridizations(correlationList, correlationIndex, detections.getDetectedHybridizations())); + } + if (grouping.getGroups() + .containsKey(correlation.getAtomType()) + && grouping.getTransformedGroups() + .get(correlation.getAtomType()) + .containsKey(correlationIndex)) { + groupIndex = grouping.getTransformedGroups() + .get(correlation.getAtomType()) + .get(correlationIndex); + molecularConnectivity.setGroupMembers(grouping.getGroups() + .get(correlation.getAtomType()) + .get(groupIndex)); + } + for (final Link link : correlation.getLink()) { + if (link.getExperimentType() + .equals("hsqc") + || link.getExperimentType() + .equals("hmqc") + && !correlation.getAtomType() + .equals("H")) { + if (molecularConnectivity.getHsqc() + == null) { + molecularConnectivity.setHsqc(new ArrayList<>()); + } + for (final int matchIndex : link.getMatch()) { + molecularConnectivity.getHsqc() + .add(matchIndex); + } + } else if (link.getExperimentType() + .equals("hmbc") + || link.getExperimentType() + .equals("cosy")) { + if (link.getExperimentType() + .equals("hmbc") + && correlation.getAtomType() + .equals("H")) { + continue; + } + if (link.getExperimentType() + .equals("cosy") + && !correlation.getAtomType() + .equals("H")) { + continue; + } + // ignore H atoms without any attachment to a heavy atom + if (correlationList.get(correlationIndex) + .getAtomType() + .equals("H") + && correlationList.get(correlationIndex) + .getAttachment() + .keySet() + .isEmpty()) { + continue; + } + signal2DMap = (Map) link.getSignal(); + if (signal2DMap + != null + && signal2DMap.containsKey("j")) { + jMap = (Map) signal2DMap.get("j"); + } else { + jMap = null; + } + if (jMap + != null + && jMap.containsKey("pathLength")) { + pathLengthMap = (Map) jMap.get("pathLength"); + } else { + pathLengthMap = null; + } + + for (final int matchIndex : link.getMatch()) { + // ignore linked H atoms without any attachment to a heavy atom + if (correlationList.get(matchIndex) + .getAtomType() + .equals("H") + && correlationList.get(matchIndex) + .getAttachment() + .keySet() + .isEmpty()) { + continue; + } + if (link.getExperimentType() + .equals("hmbc")) { + if (molecularConnectivity.getHmbc() + == null) { + molecularConnectivity.setHmbc(new HashMap<>()); + } + molecularConnectivity.getHmbc() + .put(matchIndex, pathLengthMap + == null + ? defaultBondDistances.get("hmbc") + : new Integer[]{(int) pathLengthMap.get("from"), + (int) pathLengthMap.get("to")}); + } else { + if (molecularConnectivity.getCosy() + == null) { + molecularConnectivity.setCosy(new HashMap<>()); + } + molecularConnectivity.getCosy() + .put(matchIndex, pathLengthMap + == null + ? defaultBondDistances.get("cosy") + : new Integer[]{(int) pathLengthMap.get("from"), + (int) pathLengthMap.get("to")}); + } + } + } + } + + // set detections + if (detections.getForbiddenNeighbors() + .containsKey(correlationIndex)) { + molecularConnectivity.setForbiddenNeighbors(detections.getForbiddenNeighbors() + .get(correlationIndex)); + } + if (detections.getSetNeighbors() + .containsKey(correlationIndex)) { + molecularConnectivity.setSetNeighbors(detections.getSetNeighbors() + .get(correlationIndex)); + } + // fill in fixed neighbors + if (correlation.getEquivalence() + == 1 + && detections.getFixedNeighbors() + .containsKey(correlationIndex)) { + molecularConnectivity.setFixedNeighbors(new ArrayList<>()); + molecularConnectivity.getFixedNeighbors() + .add(correlationIndex); + } + + molecularConnectivityList.add(molecularConnectivity); + } + + return molecularConnectivityList; + } + + public static MolecularConnectivity getHeavyAtomMolecularConnectivity( + final Map> molecularConnectivityMap, final int protonIndex) { + for (final Map.Entry> entry : molecularConnectivityMap.entrySet()) { + for (final MolecularConnectivity molecularConnectivityTemp : entry.getValue() + .stream() + .filter(mc -> !mc.getAtomType() + .equals("H")) + .collect(Collectors.toSet())) { + if (molecularConnectivityTemp.getHsqc() + != null + && molecularConnectivityTemp.getHsqc() + .contains(protonIndex)) { + return molecularConnectivityTemp; + } + } + } + + return null; + } + + public static int findBondedHeavyAtomMolecularConnectivityIndex( + final List molecularConnectivityList, final int protonIndex) { + for (final MolecularConnectivity molecularConnectivityTemp : molecularConnectivityList.stream() + .filter(mc -> !mc.getAtomType() + .equals("H")) + .collect( + Collectors.toSet())) { + if (molecularConnectivityTemp.getHsqc() + != null + && molecularConnectivityTemp.getHsqc() + .contains(protonIndex)) { + return molecularConnectivityTemp.getIndex(); + } + } + + return -1; + } + + private static boolean checkDistance(final List molecularConnectivityList, final int index1, + final int index2, final Grouping grouping) { + final Double distanceValue = casekit.nmr.similarity.Utilities.getDistanceValue( + molecularConnectivityList.get(index1) + .getSignal(), molecularConnectivityList.get(index2) + .getSignal(), 0, 0, false, false, false, + grouping.getTolerances() + .get("H")); + + return distanceValue + != null; + } + + private static List swap(final MolecularConnectivity molecularConnectivity, final Grouping grouping, + final String experiment, + final List molecularConnectivityList, + final int correlationIndex, final Set swapped) { + final List newStatesList = new ArrayList<>(); + + List clonedMolecularConnectivityList; + int protonGroupIndex, molecularConnectivityIndexBondedToGroupMember; + Set swappedCopy; + MolecularConnectivity clonedMolecularConnectivity, clonedMolecularConnectivityBondedToGroupMember; + List protonGroupMemberList, indicesToSwap; + String swapKey; + Integer[] pathLengthProton; + if (experiment.equals("hsqc") + && molecularConnectivity.getHsqc() + != null) { + // loop over all matching protons in HSQC + for (final Integer protonIndex : molecularConnectivity.getHsqc()) { + // only change if it has a group entry + if (grouping.getTransformedGroups() + .containsKey("H") + && grouping.getTransformedGroups() + .get("H") + .containsKey(protonIndex)) { + protonGroupIndex = grouping.getTransformedGroups() + .get("H") + .get(protonIndex); + protonGroupMemberList = grouping.getGroups() + .get("H") + .get(protonGroupIndex) + .stream() + .filter(protonGroupMemberIndex -> !Objects.equals( + protonGroupMemberIndex, protonIndex) + && !molecularConnectivity.getHsqc() + .contains(protonGroupMemberIndex)) + .collect(Collectors.toList()); + for (final Integer protonGroupMemberIndex : protonGroupMemberList) { + indicesToSwap = new ArrayList<>(); + indicesToSwap.add(protonIndex); + indicesToSwap.add(protonGroupMemberIndex); + indicesToSwap.sort(Integer::compare); // to always keep the same order + swapKey = "hsqc_" + + indicesToSwap.stream() + .map(String::valueOf) + .collect(Collectors.joining("_")); + if (swapped.contains(swapKey) + || !checkDistance(molecularConnectivityList, protonIndex, protonGroupMemberIndex, + grouping)) { + continue; + } + // clone current list element + clonedMolecularConnectivity = Utils.cloneObject(molecularConnectivity, + MolecularConnectivity.class); + // remove the current proton and add the group member proton + clonedMolecularConnectivity.getHsqc() + .remove(protonIndex); + clonedMolecularConnectivity.getHsqc() + .add(protonGroupMemberIndex); + // copy current list + clonedMolecularConnectivityList = new ArrayList<>(molecularConnectivityList); + // set cloned and changed list element + clonedMolecularConnectivityList.set(correlationIndex, clonedMolecularConnectivity); + // check whether group member proton is attached to a heavy atom + molecularConnectivityIndexBondedToGroupMember = findBondedHeavyAtomMolecularConnectivityIndex( + molecularConnectivityList, protonGroupMemberIndex); + if (molecularConnectivityIndexBondedToGroupMember + >= 0) { + // remove the group member proton from heavy atom and add the current proton + clonedMolecularConnectivityBondedToGroupMember = Utils.cloneObject( + molecularConnectivityList.get(molecularConnectivityIndexBondedToGroupMember), + MolecularConnectivity.class); + clonedMolecularConnectivityBondedToGroupMember.getHsqc() + .remove(protonGroupMemberIndex); + clonedMolecularConnectivityBondedToGroupMember.getHsqc() + .add(protonIndex); + clonedMolecularConnectivityList.set(molecularConnectivityIndexBondedToGroupMember, + clonedMolecularConnectivityBondedToGroupMember); + } + + // System.out.println(" --> swapped HSQC at i: " + // + molecularConnectivity.getIndex() + // + " -> " + // + swapKey + // + " -> " + // + swapped); + swappedCopy = new HashSet<>(swapped); + swappedCopy.add(swapKey); + + newStatesList.add(new Object[]{clonedMolecularConnectivityList, correlationIndex + + 1, swappedCopy}); + } + } + } + } else if (experiment.equals("hmbc") + && molecularConnectivity.getHmbc() + != null) { + + // loop over all matching protons in HMBC + for (final Integer protonIndex : molecularConnectivity.getHmbc() + .keySet()) { + // only change if it has a group entry + if (grouping.getTransformedGroups() + .containsKey("H") + && grouping.getTransformedGroups() + .get("H") + .containsKey(protonIndex)) { + protonGroupIndex = grouping.getTransformedGroups() + .get("H") + .get(protonIndex); + protonGroupMemberList = grouping.getGroups() + .get("H") + .get(protonGroupIndex) + .stream() + .filter(protonGroupMemberIndex -> !Objects.equals( + protonGroupMemberIndex, protonIndex) + && (molecularConnectivity.getHsqc() + == null + || !molecularConnectivity.getHsqc() + .contains(protonGroupMemberIndex)) + && !molecularConnectivity.getHmbc() + .containsKey( + protonGroupMemberIndex)) + .collect(Collectors.toList()); + for (final Integer protonGroupMemberIndex : protonGroupMemberList) { + if (!checkDistance(molecularConnectivityList, protonIndex, protonGroupMemberIndex, grouping)) { + continue; + } + + // copy current list + clonedMolecularConnectivityList = new ArrayList<>(molecularConnectivityList); + // clone current list element + clonedMolecularConnectivity = Utils.cloneObject(molecularConnectivity, + MolecularConnectivity.class); + // remove the current proton and add the group member proton + pathLengthProton = clonedMolecularConnectivity.getHmbc() + .get(protonIndex); + clonedMolecularConnectivity.getHmbc() + .remove(protonIndex); + clonedMolecularConnectivity.getHmbc() + .putIfAbsent(protonGroupMemberIndex, pathLengthProton); + // set cloned and changed list element + clonedMolecularConnectivityList.set(correlationIndex, clonedMolecularConnectivity); + + // System.out.println(" --> swapped HMBC at i: " + // + molecularConnectivity.getIndex() + // + " -> " + // + swapped); + swappedCopy = new HashSet<>(swapped); + + newStatesList.add(new Object[]{clonedMolecularConnectivityList, correlationIndex + + 1, swappedCopy}); + } + } + } + } + + return newStatesList; + } + + private static List> buildCombinations( + final List initialMolecularConnectivityList, final Grouping grouping) { + + final List> molecularConnectivityListList = new ArrayList<>(); + molecularConnectivityListList.add(initialMolecularConnectivityList); + + // final Stack stack = new Stack<>(); + // stack.push(new Object[]{initialMolecularConnectivityList, 0, new HashSet<>()}); + // + // Object[] objects; + // List molecularConnectivityList; + // int correlationIndex; + // Set swapped; + // MolecularConnectivity molecularConnectivity; + // List newStateList, newStateList2; + // while (!stack.isEmpty()) { + // objects = stack.pop(); + // molecularConnectivityList = (List) objects[0]; + // correlationIndex = (int) objects[1]; + // swapped = (Set) objects[2]; + // if (correlationIndex + // >= molecularConnectivityList.size()) { + // molecularConnectivityListList.add(molecularConnectivityList); + // continue; + // } + // molecularConnectivity = molecularConnectivityList.get(correlationIndex); + // if (!grouping.getGroups() + // .containsKey(molecularConnectivity.getAtomType()) + // || molecularConnectivity.getAtomType() + // .equals("H")) { + // stack.push(new Object[]{molecularConnectivityList, correlationIndex + // + 1, swapped}); + // continue; + // } + // + // // HSQC + // newStateList = swap(molecularConnectivity, grouping, "hsqc", molecularConnectivityList, correlationIndex, + // swapped); + // // HMBC + // newStateList2 = new ArrayList<>(newStateList); + // // push unchanged stack data that HMBC can swap from previous data too + // newStateList2.add(new Object[]{molecularConnectivityList, correlationIndex, swapped}); + // for (final Object[] stateObjects : newStateList2) { + // newStateList.addAll( + // swap(molecularConnectivity, grouping, "hmbc", (List) stateObjects[0], + // correlationIndex, (Set) stateObjects[2])); + // } + // + // // push unchanged stack data as well + // newStateList.add(new Object[]{molecularConnectivityList, correlationIndex + // + 1, swapped}); + // + // // push all new states into the stack + // for (final Object[] newStateObjects : newStateList) { + // stack.push(newStateObjects); + // } + // } + + + return molecularConnectivityListList; + } + + public static List>> buildMolecularConnectivityMapCombinationList( + final List correlationList, final Detections detections, final Grouping grouping, + final Map defaultBondDistances) { + final List>> molecularConnectivityMapCombinationList = new ArrayList<>(); + // build original molecular connectivity list which comes from correlation data directly + final List initialMolecularConnectivityList = buildMolecularConnectivityList( + correlationList, detections, grouping, defaultBondDistances); + // build combinations out pf original molecular connectivity list by using grouping information + final List> molecularConnectivityListList = buildCombinations( + initialMolecularConnectivityList, grouping); + // for each combination build a molecular connectivity map which is used for PyLSD input file creation + for (final List molecularConnectivityList : molecularConnectivityListList) { + molecularConnectivityMapCombinationList.add( + buildMolecularConnectivityMap(molecularConnectivityList, detections, grouping, + defaultBondDistances)); + } + + return molecularConnectivityMapCombinationList; + } +} diff --git a/src/casekit/nmr/elucidation/lsd/LISTAndPROPUtilities.java b/src/casekit/nmr/elucidation/lsd/LISTAndPROPUtilities.java new file mode 100644 index 0000000..1de3426 --- /dev/null +++ b/src/casekit/nmr/elucidation/lsd/LISTAndPROPUtilities.java @@ -0,0 +1,222 @@ +package casekit.nmr.elucidation.lsd; + +import casekit.nmr.elucidation.model.MolecularConnectivity; +import casekit.nmr.model.Signal; +import casekit.nmr.utils.Statistics; + +import java.util.*; +import java.util.stream.Collectors; + +public class LISTAndPROPUtilities { + + public static void insertNoHeteroHeteroBonds(final StringBuilder stringBuilder, + final Map listMap) { + // create hetero atom list automatically to forbid hetero-hetero bonds + listMap.put("HETE", new Object[]{"L" + + (listMap.size() + + 1)}); + stringBuilder.append("HETE ") + .append((String) listMap.get("HETE")[0]) + .append("; hetero atoms\n"); + stringBuilder.append("PROP L1 0 L1 -; no hetero-hetero bonds\n"); + } + + public static void insertGeneralLISTs(final StringBuilder stringBuilder, final Map listMap, + final Map> molecularConnectivityMap, + final Set atomTypesByMf) { + final Set atomTypes = new HashSet<>(atomTypesByMf); + atomTypes.remove("H"); + Set elementIndices; + for (final String atomType : atomTypes) { + listMap.put(atomType, new Object[]{"L" + + (listMap.size() + + 1)}); + elementIndices = new HashSet<>(); + for (final int correlationIndex : molecularConnectivityMap.keySet()) { + elementIndices.addAll(molecularConnectivityMap.get(correlationIndex) + .stream() + .filter(molecularConnectivity -> molecularConnectivity.getAtomType() + .equals(atomType)) + .map(MolecularConnectivity::getIndex) + .collect(Collectors.toSet())); + } + + stringBuilder.append("LIST ") + .append(listMap.get(atomType)[0]); + for (final int elementIndex : elementIndices) { + stringBuilder.append(" ") + .append(elementIndex); + } + stringBuilder.append("; list of all ") + .append(atomType) + .append(" atoms") + .append("\n"); + } + } + + private static String buildListKey(final String atomType, final List hybridizations, + final List protonsCounts) { + return atomType + + "_" + + (!hybridizations.isEmpty() + ? hybridizations + : "*") + + "_" + + (!protonsCounts.isEmpty() + ? protonsCounts + : "*"); + } + + public static void insertHeavyAtomCombinationLISTs(final StringBuilder stringBuilder, + final Map listMap, + final Map> molecularConnectivityMap) { + final Map> atomIndicesMap = new LinkedHashMap<>(); + String listKey; + for (final int correlationIndex : molecularConnectivityMap.keySet()) { + for (final MolecularConnectivity molecularConnectivity : molecularConnectivityMap.get(correlationIndex)) { + if (molecularConnectivity.getAtomType() + .equals("H") + // || molecularConnectivity.getHybridizations() + // .size() + // != 1 + || molecularConnectivity.getProtonCounts() + .size() + != 1) { + continue; + } + listKey = buildListKey(molecularConnectivity.getAtomType(), new ArrayList<>(), + // correlation.getHybridization(), + molecularConnectivity.getProtonCounts()); + atomIndicesMap.putIfAbsent(listKey, new HashSet<>()); + atomIndicesMap.get(listKey) + .add(molecularConnectivity.getIndex()); + } + } + String[] split; + for (final Map.Entry> combinationEntry : atomIndicesMap.entrySet()) { + stringBuilder.append("LIST ") + .append("L") + .append(listMap.size() + + 1); + + for (final int pyLSDAtomIndex : combinationEntry.getValue()) { + stringBuilder.append(" ") + .append(pyLSDAtomIndex); + } + split = combinationEntry.getKey() + .split("_"); + stringBuilder.append("; ") + .append(split[0]) + .append("H") + .append(split[2]) + .append(", SP") + .append(split[1]) + .append("\n"); + + listMap.put(combinationEntry.getKey(), new Object[]{"L" + + (listMap.size() + + 1), combinationEntry.getValue().size()}); + } + } + + + private static boolean checkSkipPROPInsertion(final Map listMap, + final Map usedPropsCount, final String listKey, + final String mode) { + if (!listMap.containsKey(listKey)) { + return true; + } + // LSD crashes if we try to use more atoms with specific hybridization or/and proton count (in mode "allow") + // thus count and limit that usage as following: + // list name -> number of usages + usedPropsCount.putIfAbsent((String) listMap.get(listKey)[0], 1); + return mode.equals("allow") + && listMap.get(listKey).length + > 1 + && usedPropsCount.get((String) listMap.get(listKey)[0]) + > (int) listMap.get(listKey)[1]; + } + + private static void insertPROP(final StringBuilder stringBuilder, final Map listMap, + final String atomType, final Signal signal, final int indexInPyLSD, + final String listKey, final String mode) { + stringBuilder.append("PROP ") + .append(indexInPyLSD) + .append(mode.equals("forbid") + ? " 0 " + : " 1 ") + .append(listMap.get(listKey)[0]) + .append(mode.equals("forbid") + ? " -" + : " +") + .append(mode.equals("forbid") + ? "; no bonds between " + : "; at least one bond between ") + .append(indexInPyLSD) + .append(" (") + .append(atomType) + .append(", ") + .append(signal + != null + ? Statistics.roundDouble(signal.getShift(0), 2) + : "?") + .append(") and ") + .append(Arrays.toString(listMap.get(listKey))) + .append("\n"); + } + + public static void insertConnectionLISTsAndPROPs(final StringBuilder stringBuilder, + final Map listMap, + final Map> molecularConnectivityMap, + final String mode) { + String listKey; + Map>> neighborsTemp; + final Map usedPropsCount = new HashMap<>(); + for (final int correlationIndex : molecularConnectivityMap.keySet()) { + for (final MolecularConnectivity molecularConnectivity : molecularConnectivityMap.get(correlationIndex)) { + if (mode.equals("forbid")) { + neighborsTemp = molecularConnectivity.getForbiddenNeighbors(); + } else if (mode.equals("allow")) { + neighborsTemp = molecularConnectivity.getSetNeighbors(); + } else { + neighborsTemp = null; + } + if (neighborsTemp + != null) { + for (final String neighborAtomType : neighborsTemp.keySet()) { + // forbid/set bonds to whole element groups if there is an empty map for an atom type + if (neighborsTemp.get(neighborAtomType) + .isEmpty()) { + insertPROP(stringBuilder, listMap, molecularConnectivity.getAtomType(), + molecularConnectivity.getSignal(), molecularConnectivity.getIndex(), + neighborAtomType, mode); + } else { + for (final int neighborHybridization : neighborsTemp.get(neighborAtomType) + .keySet()) { + for (final int protonsCount : neighborsTemp.get(neighborAtomType) + .get(neighborHybridization)) { + listKey = buildListKey(neighborAtomType, neighborHybridization + == -1 + ? new ArrayList<>() + : List.of(neighborHybridization), + List.of(protonsCount)); + if (checkSkipPROPInsertion(listMap, usedPropsCount, listKey, mode)) { + continue; + } + if (listMap.containsKey(listKey)) { + insertPROP(stringBuilder, listMap, molecularConnectivity.getAtomType(), + molecularConnectivity.getSignal(), molecularConnectivity.getIndex(), + listKey, mode); + usedPropsCount.put((String) listMap.get(listKey)[0], + usedPropsCount.get((String) listMap.get(listKey)[0]) + + 1); + } + } + } + } + } + } + } + } + } +} diff --git a/src/casekit/nmr/elucidation/lsd/PyLSDInputFileBuilder.java b/src/casekit/nmr/elucidation/lsd/PyLSDInputFileBuilder.java new file mode 100644 index 0000000..8adad69 --- /dev/null +++ b/src/casekit/nmr/elucidation/lsd/PyLSDInputFileBuilder.java @@ -0,0 +1,647 @@ +package casekit.nmr.elucidation.lsd; + +import casekit.nmr.elucidation.Constants; +import casekit.nmr.elucidation.model.Detections; +import casekit.nmr.elucidation.model.ElucidationOptions; +import casekit.nmr.elucidation.model.Grouping; +import casekit.nmr.elucidation.model.MolecularConnectivity; +import casekit.nmr.model.DataSet; +import casekit.nmr.model.nmrium.Correlations; +import casekit.nmr.utils.Statistics; +import casekit.nmr.utils.Utils; + +import java.text.SimpleDateFormat; +import java.util.*; + +public class PyLSDInputFileBuilder { + + private static String buildHeader() { + final StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("; PyLSD input file created by casekit (https://github.com/michaelwenk/casekit)\n"); + final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z"); + final Date date = new Date(System.currentTimeMillis()); + stringBuilder.append("; ") + .append(formatter.format(date)); + + return stringBuilder.toString(); + } + + private static String buildFORM(final String mf, final Map elementCounts) { + final StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("; Molecular Formula: ") + .append(mf) + .append("\n"); + stringBuilder.append("FORM "); + elementCounts.forEach((elem, count) -> stringBuilder.append(elem) + .append(" ") + .append(count) + .append(" ")); + + return stringBuilder.toString(); + } + + private static String buildPIEC() { + return "PIEC 1"; + } + + private static String buildELIM(final int elimP1, final int elimP2) { + return "ELIM " + + elimP1 + + " " + + elimP2; + } + + private static String buildPossibilitiesString(final Collection possibilities) { + final StringBuilder possibilitiesStringBuilder = new StringBuilder(); + if (possibilities.size() + > 1) { + possibilitiesStringBuilder.append("("); + } + int counter = 0; + for (final int possibility : possibilities) { + possibilitiesStringBuilder.append(possibility); + if (counter + < possibilities.size() + - 1) { + possibilitiesStringBuilder.append(" "); + } + counter++; + } + if (possibilities.size() + > 1) { + possibilitiesStringBuilder.append(")"); + } + + return possibilitiesStringBuilder.toString(); + } + + private static Map buildStringBuilderMap( + final Map> molecularConnectivityMap) { + final Map stringBuilderMap = new HashMap<>(); + final Map> stringListMap = new HashMap<>(); + stringListMap.put("MULT", new ArrayList<>()); + stringListMap.put("HSQC", new ArrayList<>()); + stringListMap.put("HMBC", new ArrayList<>()); + stringListMap.put("COSY", new ArrayList<>()); + stringListMap.put("BOND", new ArrayList<>()); + stringListMap.put("SHIX", new ArrayList<>()); + stringListMap.put("SHIH", new ArrayList<>()); + StringBuilder stringBuilder, hybridizationStringBuilder, attachedProtonsCountStringBuilder; + List stringList; + int counter, firstOfEquivalenceIndexPyLSD; + Set groupMembers; // use as a Set to remove the actual value and not at a list index + MolecularConnectivity molecularConnectivityGroupMember, molecularConnectivityHeavyAtom; + final Map> addedBONDPairs = new HashMap<>(); + final Set addedKeysSHIH = new HashSet<>(); + for (final int correlationIndex : molecularConnectivityMap.keySet()) { + firstOfEquivalenceIndexPyLSD = -1; + for (final MolecularConnectivity molecularConnectivity : molecularConnectivityMap.get(correlationIndex)) { + if (firstOfEquivalenceIndexPyLSD + == -1) { + firstOfEquivalenceIndexPyLSD = molecularConnectivity.getIndex(); + } + if (!molecularConnectivity.getAtomType() + .equals("H")) { + + hybridizationStringBuilder = new StringBuilder(); + if (molecularConnectivity.getHybridizations() + .size() + > 1) { + hybridizationStringBuilder.append("("); + } + counter = 0; + for (final int hybrid : molecularConnectivity.getHybridizations()) { + hybridizationStringBuilder.append(hybrid); + if (counter + < molecularConnectivity.getHybridizations() + .size() + - 1) { + hybridizationStringBuilder.append(" "); + } + counter++; + } + if (molecularConnectivity.getHybridizations() + .size() + > 1) { + hybridizationStringBuilder.append(")"); + } + attachedProtonsCountStringBuilder = new StringBuilder(); + if (molecularConnectivity.getProtonCounts() + .size() + > 1) { + attachedProtonsCountStringBuilder.append("("); + } + counter = 0; + for (final int protonCount : molecularConnectivity.getProtonCounts()) { + attachedProtonsCountStringBuilder.append(protonCount); + if (counter + < molecularConnectivity.getProtonCounts() + .size() + - 1) { + attachedProtonsCountStringBuilder.append(" "); + } + counter++; + } + if (molecularConnectivity.getProtonCounts() + .size() + > 1) { + attachedProtonsCountStringBuilder.append(")"); + } + // MULT section + stringList = stringListMap.get("MULT"); + stringBuilder = new StringBuilder(); + stringBuilder.append("MULT ") + .append(molecularConnectivity.getIndex()) + .append(" ") + .append(Constants.defaultAtomLabelMap.get(molecularConnectivity.getAtomType())) + .append(" ") + .append(hybridizationStringBuilder) + .append(" ") + .append(attachedProtonsCountStringBuilder); + stringBuilder.append("; ") + .append(buildShiftString(molecularConnectivityMap, molecularConnectivity)); + if (molecularConnectivityMap.get(correlationIndex) + .size() + > 1 + && molecularConnectivity.getIndex() + != firstOfEquivalenceIndexPyLSD) { + stringBuilder.append("; equivalent to ") + .append(firstOfEquivalenceIndexPyLSD); + } + stringBuilder.append("\n"); + stringList.add(stringBuilder.toString()); + // HSQC section + if (molecularConnectivity.getHsqc() + != null) { + stringList = stringListMap.get("HSQC"); + stringBuilder = new StringBuilder(); + stringBuilder.append("HSQC ") + .append(molecularConnectivity.getIndex()) + .append(" ") + .append(molecularConnectivity.getHsqc() + .get(0)) + .append(buildShiftsComment(molecularConnectivityMap, molecularConnectivity, + casekit.nmr.elucidation.Utilities.findMolecularConnectivityByIndex( + molecularConnectivityMap, "H", false, + molecularConnectivity.getHsqc() + .get(0)))) + .append("\n"); + stringList.add(stringBuilder.toString()); + } + // HMBC section + if (molecularConnectivity.getHmbc() + != null) { + stringList = stringListMap.get("HMBC"); + for (final int protonIndexInPyLSD : molecularConnectivity.getHmbc() + .keySet()) { + // filter out group members which are directly bonded to that proton + groupMembers = new HashSet<>(molecularConnectivity.getGroupMembers()); + for (final int groupMemberIndex : new ArrayList<>(groupMembers)) { + molecularConnectivityGroupMember = casekit.nmr.elucidation.Utilities.findMolecularConnectivityByIndex( + molecularConnectivityMap, molecularConnectivity.getAtomType(), false, + groupMemberIndex); + if (molecularConnectivityGroupMember.getHsqc() + != null + && molecularConnectivityGroupMember.getHsqc() + .contains(protonIndexInPyLSD)) { + groupMembers.remove(groupMemberIndex); + } + } + if (!groupMembers.isEmpty()) { + stringBuilder = new StringBuilder(); + stringBuilder.append("HMBC ") + .append(buildPossibilitiesString(groupMembers)) + .append(" ") + .append(protonIndexInPyLSD) + .append(" ") + .append(molecularConnectivity.getHmbc() + .get(protonIndexInPyLSD)[0]) + .append(" ") + .append(molecularConnectivity.getHmbc() + .get(protonIndexInPyLSD)[1]) + .append(buildShiftsComment(molecularConnectivityMap, molecularConnectivity, + casekit.nmr.elucidation.Utilities.findMolecularConnectivityByIndex( + molecularConnectivityMap, "H", false, + protonIndexInPyLSD))) + .append("\n"); + if (!stringList.contains(stringBuilder.toString())) { + stringList.add(stringBuilder.toString()); + } + } + } + } + // BOND section + if (molecularConnectivity.getFixedNeighbors() + != null) { + stringList = stringListMap.get("BOND"); + for (final int bondedIndexInPyLSD : molecularConnectivity.getFixedNeighbors()) { + if (!addedBONDPairs.containsKey(molecularConnectivity.getIndex()) + || (addedBONDPairs.containsKey(molecularConnectivity.getIndex()) + && !addedBONDPairs.get(molecularConnectivity.getIndex()) + .contains(bondedIndexInPyLSD))) { + stringBuilder = new StringBuilder(); + stringBuilder.append("BOND ") + .append(molecularConnectivity.getIndex()) + .append(" ") + .append(bondedIndexInPyLSD) + .append(buildShiftsComment(molecularConnectivityMap, molecularConnectivity, + casekit.nmr.elucidation.Utilities.findMolecularConnectivityByIndex( + molecularConnectivityMap, "H", true, + bondedIndexInPyLSD))) + .append("\n"); + if (!stringList.contains(stringBuilder.toString())) { + stringList.add(stringBuilder.toString()); + } + addedBONDPairs.putIfAbsent(molecularConnectivity.getIndex(), new HashSet<>()); + addedBONDPairs.get(molecularConnectivity.getIndex()) + .add(bondedIndexInPyLSD); + addedBONDPairs.putIfAbsent(bondedIndexInPyLSD, new HashSet<>()); + addedBONDPairs.get(bondedIndexInPyLSD) + .add(molecularConnectivity.getIndex()); + } + } + } + } else if (molecularConnectivity.getAtomType() + .equals("H")) { + // COSY section + if (molecularConnectivity.getCosy() + != null) { + stringList = stringListMap.get("COSY"); + for (final int protonIndexInPyLSD : molecularConnectivity.getCosy() + .keySet()) { + groupMembers = new HashSet<>(molecularConnectivity.getGroupMembers()); + // 1) use only one attached proton of a CH2 group (optional) + final Set alreadyFoundHeavyAtomIndex = new HashSet<>(); + for (final int groupMemberIndex : new ArrayList<>(groupMembers)) { + molecularConnectivityHeavyAtom = casekit.nmr.elucidation.Utilities.getHeavyAtomMolecularConnectivity( + molecularConnectivityMap, groupMemberIndex); + if (molecularConnectivityHeavyAtom + == null + || alreadyFoundHeavyAtomIndex.contains( + molecularConnectivityHeavyAtom.getIndex())) { + groupMembers.remove(groupMemberIndex); + } else { + alreadyFoundHeavyAtomIndex.add(molecularConnectivityHeavyAtom.getIndex()); + } + } + // 2) filter out group members which would direct to itself when using COSY correlation + molecularConnectivityHeavyAtom = casekit.nmr.elucidation.Utilities.getHeavyAtomMolecularConnectivity( + molecularConnectivityMap, protonIndexInPyLSD); + if (molecularConnectivityHeavyAtom + != null) { + for (final int groupMemberIndex : new HashSet<>(groupMembers)) { + if (molecularConnectivityHeavyAtom.getHsqc() + .contains(groupMemberIndex)) { + groupMembers.remove(groupMemberIndex); + } + } + if (!groupMembers.isEmpty()) { + stringBuilder = new StringBuilder(); + stringBuilder.append("COSY ") + .append(buildPossibilitiesString(groupMembers)) + .append(" ") + .append(protonIndexInPyLSD) + .append(" ") + .append(molecularConnectivity.getCosy() + .get(protonIndexInPyLSD)[0]) + .append(" ") + .append(molecularConnectivity.getCosy() + .get(protonIndexInPyLSD)[1]) + .append(buildShiftsComment(molecularConnectivityMap, + molecularConnectivity, + casekit.nmr.elucidation.Utilities.findMolecularConnectivityByIndex( + molecularConnectivityMap, "H", + false, protonIndexInPyLSD))) + .append("\n"); + if (!stringList.contains(stringBuilder.toString())) { + stringList.add(stringBuilder.toString()); + } + } + } + } + } + } + // SHIH/SHIX section + if (molecularConnectivity.getSignal() + != null) { + stringList = stringListMap.get(molecularConnectivity.getAtomType() + .equals("H") + ? "SHIH" + : "SHIX"); + stringBuilder = new StringBuilder(); + stringBuilder.append(molecularConnectivity.getAtomType() + .equals("H") + ? "SHIH" + : "SHIX") + .append(" ") + .append(molecularConnectivity.getIndex()) + .append(" ") + .append(Statistics.roundDouble(molecularConnectivity.getSignal() + .getShift(0), 5)) + .append("\n"); + if (!stringList.contains(stringBuilder.toString())) { + if (!molecularConnectivity.getAtomType() + .equals("H")) { + stringList.add(stringBuilder.toString()); + } else if (!addedKeysSHIH.contains(molecularConnectivity.getIndex())) { + stringList.add(stringBuilder.toString()); + addedKeysSHIH.add(molecularConnectivity.getIndex()); + } + } + } + } + } + // put sections into stringBuilderMap + for (final String sectionKey : stringListMap.keySet()) { + stringBuilder = new StringBuilder(); + for (final String sectionLine : stringListMap.get(sectionKey)) { + stringBuilder.append(sectionLine); + } + stringBuilderMap.put(sectionKey, stringBuilder); + } + + return stringBuilderMap; + } + + private static String buildShiftString(final Map> molecularConnectivityMap, + final MolecularConnectivity molecularConnectivity) { + if (molecularConnectivity + == null + || molecularConnectivity.getSignal() + == null) { + return "?"; + } + + final String heavyAtomShiftString = ""; + // if (molecularConnectivity.getAtomType() + // .equals("H")) { + // MolecularConnectivity heavyAtomMolecularConnectivity = null; + // boolean found = false; + // for (final int correlationIndex : molecularConnectivityMap.keySet()) { + // for (final MolecularConnectivity molecularConnectivityTemp : molecularConnectivityMap.get( + // correlationIndex)) { + // if (molecularConnectivityTemp.getHsqc() + // != null + // && molecularConnectivityTemp.getHsqc() + // .contains(molecularConnectivity.getIndex())) { + // heavyAtomMolecularConnectivity = molecularConnectivityTemp; + // found = true; + // break; + // } + // } + // if (found) { + // break; + // } + // } + // if (heavyAtomMolecularConnectivity + // != null) { + // heavyAtomShiftString = " (" + // + buildShiftString(molecularConnectivityMap, heavyAtomMolecularConnectivity) + // + ")"; + // } + // } + + return Statistics.roundDouble(molecularConnectivity.getSignal() + .getShift(0), 3) + + heavyAtomShiftString; + } + + private static String buildShiftsComment(final Map> molecularConnectivityMap, + final MolecularConnectivity molecularConnectivity1, + final MolecularConnectivity molecularConnectivity2) { + return "; " + + molecularConnectivity1.getAtomType() + + ": " + + buildShiftString(molecularConnectivityMap, molecularConnectivity1) + + " -> " + + molecularConnectivity2.getAtomType() + + ": " + + buildShiftString(molecularConnectivityMap, molecularConnectivity2); + } + + private static String buildLISTsAndPROPs(final Map> molecularConnectivityMap, + final Map elementCounts, + final boolean allowHeteroHeteroBonds) { + final StringBuilder stringBuilder = new StringBuilder(); + // list key -> [list name, size] + final Map listMap = new HashMap<>(); + + // LIST and PROP for hetero hetero bonds to disallow in case hetero atoms are present + final boolean containsHeteroAtoms = elementCounts.keySet() + .stream() + .anyMatch(atomType -> !atomType.equals("C") + && !atomType.equals("H")); + if (containsHeteroAtoms + && !allowHeteroHeteroBonds) { + LISTAndPROPUtilities.insertNoHeteroHeteroBonds(stringBuilder, listMap); + } + // insert LIST for each heavy atom type in MF + LISTAndPROPUtilities.insertGeneralLISTs(stringBuilder, listMap, molecularConnectivityMap, + elementCounts.keySet()); + // insert list combinations of carbon and hybridization states + LISTAndPROPUtilities.insertHeavyAtomCombinationLISTs(stringBuilder, listMap, molecularConnectivityMap); + // insert forbidden connection lists and properties + LISTAndPROPUtilities.insertConnectionLISTsAndPROPs(stringBuilder, listMap, molecularConnectivityMap, "forbid"); + // insert set connection lists and properties + LISTAndPROPUtilities.insertConnectionLISTsAndPROPs(stringBuilder, listMap, molecularConnectivityMap, "allow"); + + return stringBuilder.toString(); + } + + private static String buildDEFFs(final String[] filterPaths, final String[] pathsToNeighborsFiles) { + final StringBuilder stringBuilder = new StringBuilder(); + // DEFF -> add filters + final Map filters = new LinkedHashMap<>(); + int counter = 1; + for (final String filterPath : filterPaths) { + filters.put("F" + + counter, filterPath); + counter++; + } + for (final String pathToNeighborsFiles : pathsToNeighborsFiles) { + filters.put("F" + + counter, pathToNeighborsFiles); + counter++; + } + + if (!filters.isEmpty()) { + stringBuilder.append("; externally defined filters\n"); + filters.forEach((label, filePath) -> stringBuilder.append("DEFF ") + .append(label) + .append(" \"") + .append(filePath) + .append("\"\n")); + stringBuilder.append("\n"); + } + + return stringBuilder.toString(); + } + + private static String buildFEXP(final Map fexpMap) { + final StringBuilder stringBuilder = new StringBuilder(); + + if (!fexpMap.isEmpty()) { + stringBuilder.append("FEXP \""); + int counter = 0; + for (final String label : fexpMap.keySet()) { + if (!fexpMap.get(label)) { + stringBuilder.append("NOT "); + } + stringBuilder.append(label); + if (counter + < fexpMap.keySet() + .size() + - 1) { + stringBuilder.append(" AND "); + } + counter++; + } + stringBuilder.append("\"\n"); + } + + return stringBuilder.toString(); + } + + private static String buildDEFFsAndFEXP(final ElucidationOptions elucidationOptions, final Detections detections) { + final StringBuilder stringBuilder = new StringBuilder(); + final Map fexpMap = new HashMap<>(); + for (int i = 0; i + < elucidationOptions.getFilterPaths().length; i++) { + fexpMap.put("F" + + (i + + 1), false); + } + // // build and write neighbors files + // final List pathsToNeighborsFilesToUse = new ArrayList<>(); + // if (Utilities.writeNeighborsFile(elucidationOptions.getPathsToNeighborsFiles()[0], correlationList, indicesMap, + // forbiddenNeighbors)) { + // fexpMap.put("F" + // + (fexpMap.size() + // + 1), false); + // pathsToNeighborsFilesToUse.add(elucidationOptions.getPathsToNeighborsFiles()[0]); + // } + // if (Utilities.writeNeighborsFile(elucidationOptions.getPathsToNeighborsFiles()[1], correlationList, indicesMap, + // setNeighbors)) { + // fexpMap.put("F" + // + (fexpMap.size() + // + 1), true); + // pathsToNeighborsFilesToUse.add(elucidationOptions.getPathsToNeighborsFiles()[1]); + // } + + // build and write fragments files + final List pathsToFragmentFilesToUse = new ArrayList<>(); + String pathToFragmentFile; + DataSet fragmentDataSet; + for (int i = 0; i + < detections.getFragments() + .size(); i++) { + fragmentDataSet = detections.getFragments() + .get(i); + if (fragmentDataSet.getAttachment() + == null + || !((boolean) fragmentDataSet.getAttachment() + .get("include"))) { + continue; + } + pathToFragmentFile = elucidationOptions.getPathToFragmentFiles() + + "_" + + i + + ".deff"; + if (Utilities.writeFragmentFile(pathToFragmentFile, fragmentDataSet)) { + fexpMap.put("F" + + (fexpMap.size() + + 1), true); + pathsToFragmentFilesToUse.add(pathToFragmentFile); + } + } + + // build DEFFs + stringBuilder.append( + buildDEFFs(elucidationOptions.getFilterPaths(), pathsToFragmentFilesToUse.toArray(String[]::new))) + .append("\n"); + // build FEXP + stringBuilder.append(buildFEXP(fexpMap)) + .append("\n"); + + return stringBuilder.toString(); + } + + + public static List buildPyLSDInputFileContentList(final Correlations correlations, final String mf, + final Detections detections, final Grouping grouping, + final ElucidationOptions elucidationOptions, + final Map defaultBondDistances) { + if (mf + == null + || mf.isEmpty()) { + return new ArrayList<>(); + } + final List inputFilesContentList = new ArrayList<>(); + // build different combinations + final List>> molecularConnectivityMapCombinationList = casekit.nmr.elucidation.Utilities.buildMolecularConnectivityMapCombinationList( + correlations.getValues(), detections, grouping, defaultBondDistances); + // for each combination insert an input file for PyLSD + for (final Map> molecularConnectivityMap : molecularConnectivityMapCombinationList) { + inputFilesContentList.add( + buildPyLSDInputFileContent(molecularConnectivityMap, mf, elucidationOptions, detections)); + } + + return inputFilesContentList; + } + + public static String buildPyLSDInputFileContent( + final Map> molecularConnectivityMap, final String mf, + final ElucidationOptions elucidationOptions, final Detections detections) { + + final Map elementCounts = new LinkedHashMap<>(Utils.getMolecularFormulaElementCounts(mf)); + final StringBuilder stringBuilder = new StringBuilder(); + // create header + stringBuilder.append(buildHeader()) + .append("\n\n"); + // FORM + stringBuilder.append(buildFORM(mf, elementCounts)) + .append("\n\n"); + // PIEC + stringBuilder.append(buildPIEC()) + .append("\n\n"); + // ELIM + if (elucidationOptions.isUseElim()) { + stringBuilder.append(buildELIM(elucidationOptions.getElimP1(), elucidationOptions.getElimP2())) + .append("\n\n"); + } + + final Map stringBuilderMap = buildStringBuilderMap(molecularConnectivityMap); + stringBuilder.append(stringBuilderMap.get("MULT") + .toString()) + .append("\n"); + stringBuilder.append(stringBuilderMap.get("HSQC") + .toString()) + .append("\n"); + + stringBuilder.append(stringBuilderMap.get("BOND") + .toString()) + .append("\n"); + stringBuilder.append(stringBuilderMap.get("HMBC") + .toString()) + .append("\n"); + stringBuilder.append(stringBuilderMap.get("COSY") + .toString()) + .append("\n"); + stringBuilder.append(stringBuilderMap.get("SHIX") + .toString()) + .append("\n"); + stringBuilder.append(stringBuilderMap.get("SHIH") + .toString()) + .append("\n"); + + // LIST PROP for certain limitations or properties of atoms in lists, e.g. hetero hetero bonds allowance + stringBuilder.append(buildLISTsAndPROPs(molecularConnectivityMap, elementCounts, + elucidationOptions.isAllowHeteroHeteroBonds())) + .append("\n"); + // DEFF and FEXP as filters (good/bad lists) + stringBuilder.append(buildDEFFsAndFEXP(elucidationOptions, detections)) + .append("\n"); + + return stringBuilder.toString(); + } +} diff --git a/src/casekit/nmr/elucidation/lsd/Utilities.java b/src/casekit/nmr/elucidation/lsd/Utilities.java new file mode 100644 index 0000000..5a1b841 --- /dev/null +++ b/src/casekit/nmr/elucidation/lsd/Utilities.java @@ -0,0 +1,204 @@ +package casekit.nmr.elucidation.lsd; + +import casekit.io.FileSystem; +import casekit.nmr.elucidation.Constants; +import casekit.nmr.model.DataSet; +import casekit.nmr.model.Signal; +import casekit.nmr.model.nmrium.Correlation; +import casekit.nmr.utils.Statistics; +import casekit.nmr.utils.Utils; +import org.openscience.cdk.interfaces.IAtom; +import org.openscience.cdk.interfaces.IAtomContainer; +import org.openscience.cdk.interfaces.IBond; + +import java.util.*; +import java.util.stream.Collectors; + +public class Utilities { + public static String buildSSTR(final int sstrIndex, final String atomType, final List hybridization, + final List protonsCount) { + if (hybridization.isEmpty()) { + hybridization.addAll(Arrays.stream(Constants.defaultHybridizationMap.get(atomType)) + .boxed() + .collect(Collectors.toList())); + } + if (protonsCount.isEmpty()) { + protonsCount.addAll(Arrays.stream(Constants.defaultProtonsCountPerValencyMap.get(atomType)) + .boxed() + .collect(Collectors.toList())); + } + final StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("SSTR S") + .append(sstrIndex) + .append(" ") + .append(atomType) + .append(" "); + if (hybridization.size() + == 1) { + stringBuilder.append(hybridization.get(0)) + .append(" "); + if (protonsCount.size() + == 1) { + stringBuilder.append(protonsCount.get(0)); + } else { + stringBuilder.append(buildMultipleValuesString(protonsCount)); + } + } else { + stringBuilder.append(buildMultipleValuesString(hybridization)); + stringBuilder.append(" "); + if (protonsCount.size() + == 1) { + stringBuilder.append(protonsCount.get(0)); + } else { + stringBuilder.append(buildMultipleValuesString(protonsCount)); + } + } + + return stringBuilder.toString(); + } + + private static String buildMultipleValuesString(final List values) { + final StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("("); + for (int l = 0; l + < values.size(); l++) { + stringBuilder.append(values.get(l)); + if (l + < values.size() + - 1) { + stringBuilder.append(" "); + } + } + stringBuilder.append(")"); + + return stringBuilder.toString(); + } + + public static boolean writeNeighborsFile(final String pathToNeighborsFile, final List correlationList, + final Map indicesMap, + final Map>>> neighbors) { + final StringBuilder stringBuilder = new StringBuilder(); + Correlation correlation; + Signal signal; + String atomType; + int indexInPyLSD; + int sstrIndex = 1, sstrIndexCorrelation; + Map>> neighborsTemp; + for (int i = 0; i + < correlationList.size(); i++) { + if (neighbors.containsKey(i)) { + correlation = correlationList.get(i); + signal = Utils.extractFirstSignalFromCorrelation(correlation); + atomType = correlation.getAtomType(); + neighborsTemp = neighbors.get(i); + + // put in the extracted information per correlation and equivalent + for (int k = 1; k + < indicesMap.get(i).length; k++) { + indexInPyLSD = (int) indicesMap.get(i)[k]; + for (final String neighborAtomType : neighborsTemp.keySet()) { + for (final Map.Entry> entryPerHybridization : neighborsTemp.get( + neighborAtomType) + .entrySet()) { + sstrIndexCorrelation = sstrIndex; + stringBuilder.append( + buildSSTR(sstrIndexCorrelation, atomType, correlation.getHybridization(), + correlation.getProtonsCount())); + stringBuilder.append("; ") + .append(atomType) + .append(" at ") + .append(signal + != null + ? Statistics.roundDouble(signal.getShift(0), 2) + : "?") + .append(" (") + .append(indexInPyLSD) + .append(")") + .append("\n"); + stringBuilder.append("ASGN S") + .append(sstrIndexCorrelation) + .append(" ") + .append(indexInPyLSD) + .append("\n"); + sstrIndex++; + + final List tempList = new ArrayList<>(); + if (entryPerHybridization.getKey() + != -1) { + tempList.add(entryPerHybridization.getKey()); + } + stringBuilder.append(buildSSTR(sstrIndex, neighborAtomType, tempList, + new ArrayList<>(entryPerHybridization.getValue()))) + .append("\n"); + stringBuilder.append("LINK S") + .append(sstrIndexCorrelation) + .append(" S") + .append(sstrIndex) + .append("\n") + .append("\n"); + sstrIndex++; + } + } + } + } + } + + System.out.println(stringBuilder); + + + return !stringBuilder.toString() + .isEmpty() + && FileSystem.writeFile(pathToNeighborsFile, stringBuilder.toString()); + } + + + public static boolean writeFragmentFile(final String pathToFragmentsFile, final DataSet fragmentDataSet) { + final StringBuilder stringBuilder = new StringBuilder(); + final IAtomContainer fragment = fragmentDataSet.getStructure() + .toAtomContainer(); + IAtom atom; + IBond bond; + final Map sstrMap = new HashMap<>(); + for (int i = 0; i + < fragment.getAtomCount(); i++) { + atom = fragment.getAtom(i); + sstrMap.put(atom, sstrMap.size() + + 1); + if (atom.getSymbol() + .equals("R")) { + stringBuilder.append("SSTR S") + .append(sstrMap.size()) + .append(" A (1 2 3) (0 1 2 3) ") + .append("\n"); + } else { + stringBuilder.append("SSTR S") + .append(sstrMap.size()) + .append(" ") + .append(atom.getSymbol()) + .append(" ") + .append(atom.getSymbol() + .equals("C") + ? Constants.hybridizationConversionMap.get(atom.getHybridization() + .name()) + : "(1 2 3)") + .append(" ") + .append(atom.getImplicitHydrogenCount()) + .append("\n"); + } + } + for (int i = 0; i + < fragment.getBondCount(); i++) { + bond = fragment.getBond(i); + stringBuilder.append("LINK S") + .append(sstrMap.get(bond.getBegin())) + .append(" S") + .append(sstrMap.get(bond.getEnd())) + .append("\n"); + } + System.out.println(stringBuilder); + + return !stringBuilder.toString() + .isEmpty() + && FileSystem.writeFile(pathToFragmentsFile, stringBuilder.toString()); + } +} diff --git a/src/casekit/nmr/elucidation/model/Detections.java b/src/casekit/nmr/elucidation/model/Detections.java new file mode 100644 index 0000000..cf65104 --- /dev/null +++ b/src/casekit/nmr/elucidation/model/Detections.java @@ -0,0 +1,23 @@ +package casekit.nmr.elucidation.model; + +import casekit.nmr.model.DataSet; +import lombok.*; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +@ToString +public class Detections { + + private Map> detectedHybridizations; + private Map>>> detectedConnectivities; + private Map>>> forbiddenNeighbors; + private Map>>> setNeighbors; + private Map> fixedNeighbors; + private List fragments; +} diff --git a/src/casekit/nmr/elucidation/model/ElucidationOptions.java b/src/casekit/nmr/elucidation/model/ElucidationOptions.java new file mode 100644 index 0000000..cba1d1f --- /dev/null +++ b/src/casekit/nmr/elucidation/model/ElucidationOptions.java @@ -0,0 +1,24 @@ +package casekit.nmr.elucidation.model; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +public class ElucidationOptions { + + // PyLSD options + private String[] filterPaths; + private String pathToNeighborsFiles; + private String pathToFragmentFiles; + private boolean allowHeteroHeteroBonds; + private boolean useElim; + private int elimP1; + private int elimP2; + private double shiftTolerance; + private double maximumAverageDeviation; +} diff --git a/src/casekit/nmr/elucidation/model/Grouping.java b/src/casekit/nmr/elucidation/model/Grouping.java new file mode 100644 index 0000000..7060471 --- /dev/null +++ b/src/casekit/nmr/elucidation/model/Grouping.java @@ -0,0 +1,19 @@ +package casekit.nmr.elucidation.model; + +import lombok.*; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@AllArgsConstructor +@NoArgsConstructor +@Getter +@Setter +@ToString +public class Grouping { + + Map tolerances = new HashMap<>(); + Map>> groups; + Map> transformedGroups; +} diff --git a/src/casekit/nmr/elucidation/model/MolecularConnectivity.java b/src/casekit/nmr/elucidation/model/MolecularConnectivity.java new file mode 100644 index 0000000..95099e9 --- /dev/null +++ b/src/casekit/nmr/elucidation/model/MolecularConnectivity.java @@ -0,0 +1,31 @@ +package casekit.nmr.elucidation.model; + +import casekit.nmr.model.Signal; +import lombok.*; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +@ToString +public class MolecularConnectivity { + + private int index; // e.g. index within PyLSD + private String atomType; + private Signal signal; + private int equivalence; + private boolean pseudo; + private List protonCounts; + private List hybridizations; + private List hsqc; + private Map hmbc; + private Map cosy; + private Map>> forbiddenNeighbors; + private Map>> setNeighbors; + private List fixedNeighbors; + private List groupMembers; +} diff --git a/src/casekit/nmr/filterandrank/FilterAndRank.java b/src/casekit/nmr/filterandrank/FilterAndRank.java new file mode 100644 index 0000000..c8e5f0c --- /dev/null +++ b/src/casekit/nmr/filterandrank/FilterAndRank.java @@ -0,0 +1,199 @@ +package casekit.nmr.filterandrank; + +import casekit.nmr.analysis.MultiplicitySectionsBuilder; +import casekit.nmr.elucidation.model.Detections; +import casekit.nmr.model.Assignment; +import casekit.nmr.model.DataSet; +import casekit.nmr.model.Spectrum; +import casekit.nmr.similarity.Similarity; +import casekit.nmr.utils.Statistics; +import org.openscience.cdk.fingerprint.BitSetFingerprint; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +public class FilterAndRank { + + public static List filterAndRank(final List dataSetList, final Spectrum querySpectrum, + final double shiftTolerance, final double maxAverageDeviation, + final boolean checkMultiplicity, final boolean checkEquivalencesCount, + final boolean allowLowerEquivalencesCount, + final MultiplicitySectionsBuilder multiplicitySectionsBuilder, + final boolean allowIncompleteMatch) { + return filterAndRank(dataSetList, querySpectrum, shiftTolerance, maxAverageDeviation, checkMultiplicity, + checkEquivalencesCount, allowLowerEquivalencesCount, multiplicitySectionsBuilder, + allowIncompleteMatch, null); + } + + public static List filterAndRank(final List dataSetList, final Spectrum querySpectrum, + final double shiftTolerance, final double maxAverageDeviation, + final boolean checkMultiplicity, final boolean checkEquivalencesCount, + final boolean allowLowerEquivalencesCount, + final MultiplicitySectionsBuilder multiplicitySectionsBuilder, + final boolean allowIncompleteMatch, final Detections detections) { + return rank(filter(dataSetList, querySpectrum, shiftTolerance, maxAverageDeviation, checkMultiplicity, + checkEquivalencesCount, allowLowerEquivalencesCount, multiplicitySectionsBuilder, + allowIncompleteMatch, detections)); + } + + public static List filter(final List dataSetList, final Spectrum querySpectrum, + final double shiftTolerance, final double maxAverageDeviation, + final boolean checkMultiplicity, final boolean checkEquivalencesCount, + final boolean allowLowerEquivalencesCount, + final MultiplicitySectionsBuilder multiplicitySectionsBuilder, + final boolean allowIncompleteMatch) { + + return filter(dataSetList, querySpectrum, shiftTolerance, maxAverageDeviation, checkMultiplicity, + checkEquivalencesCount, allowLowerEquivalencesCount, multiplicitySectionsBuilder, + allowIncompleteMatch, null); + } + + public static List filter(final List dataSetList, final Spectrum querySpectrum, + final double shiftTolerance, final double maxAverageDeviation, + final boolean checkMultiplicity, final boolean checkEquivalencesCount, + final boolean allowLowerEquivalencesCount, + final MultiplicitySectionsBuilder multiplicitySectionsBuilder, + final boolean allowIncompleteMatch, final Detections detections) { + if (querySpectrum.getNDim() + == 1 + && querySpectrum.getNuclei()[0].equals("13C")) { + return dataSetList.stream() + .filter(dataSet -> checkDataSet(dataSet, querySpectrum, shiftTolerance, + maxAverageDeviation, checkMultiplicity, + checkEquivalencesCount, allowLowerEquivalencesCount, + multiplicitySectionsBuilder, allowIncompleteMatch, + detections) + != null) + .collect(Collectors.toList()); + } + + return dataSetList; + } + + public static DataSet checkDataSet(final DataSet dataSet, final Spectrum querySpectrum, final double shiftTolerance, + final double maxAverageDeviation, final boolean checkMultiplicity, + final boolean checkEquivalencesCount, final boolean allowLowerEquivalencesCount, + final MultiplicitySectionsBuilder multiplicitySectionsBuilder, + final boolean allowIncompleteMatch) { + return checkDataSet(dataSet, querySpectrum, shiftTolerance, maxAverageDeviation, checkMultiplicity, + checkEquivalencesCount, allowLowerEquivalencesCount, multiplicitySectionsBuilder, + allowIncompleteMatch, null); + } + + public static DataSet checkDataSet(final DataSet dataSet, final Spectrum querySpectrum, final double shiftTolerance, + final double maxAverageDeviation, final boolean checkMultiplicity, + final boolean checkEquivalencesCount, final boolean allowLowerEquivalencesCount, + final MultiplicitySectionsBuilder multiplicitySectionsBuilder, + final boolean allowIncompleteMatch, final Detections detections) { + final Spectrum spectrum = dataSet.getSpectrum() + .toSpectrum(); + + + final Assignment spectralMatchAssignment = detections + != null + ? Similarity.matchSpectra(spectrum, querySpectrum, 0, 0, + shiftTolerance, checkMultiplicity, + checkEquivalencesCount, + allowLowerEquivalencesCount, + dataSet.getStructure() + .toAtomContainer(), + dataSet.getAssignment(), detections) + : Similarity.matchSpectra(spectrum, querySpectrum, 0, 0, + shiftTolerance, checkMultiplicity, + checkEquivalencesCount, + allowLowerEquivalencesCount); + dataSet.addAttachment("querySpectrumSignalCount", querySpectrum.getSignalCount()); + final boolean isCompleteSpectralMatch = spectrum.getSignalCount() + == spectralMatchAssignment.getSetAssignmentsCount(0); + dataSet.addAttachment("setAssignmentsCount", spectralMatchAssignment.getSetAssignmentsCount(0)); + dataSet.addAttachment("isCompleteSpectralMatch", isCompleteSpectralMatch); + dataSet.addAttachment("spectralMatchAssignment", spectralMatchAssignment); + + Double[] deviations = Similarity.getDeviations(spectrum, querySpectrum, 0, 0, spectralMatchAssignment); + if (allowIncompleteMatch) { + deviations = Arrays.stream(deviations) + .filter(Objects::nonNull) + .toArray(Double[]::new); + } + final Double averageDeviation = Statistics.calculateAverageDeviation(deviations); + if (averageDeviation + != null + && averageDeviation + <= maxAverageDeviation) { + dataSet.addAttachment("averageDeviation", averageDeviation); + final Double rmsd = Statistics.calculateRMSD(deviations); + dataSet.addAttachment("rmsd", rmsd); + + final BitSetFingerprint bitSetFingerprintQuerySpectrum = Similarity.getBitSetFingerprint(querySpectrum, 0, + multiplicitySectionsBuilder); + final BitSetFingerprint bitSetFingerprintDataSet = Similarity.getBitSetFingerprint(spectrum, 0, + multiplicitySectionsBuilder); + final Double tanimotoCoefficient = Similarity.calculateTanimotoCoefficient(bitSetFingerprintQuerySpectrum, + bitSetFingerprintDataSet); + dataSet.addAttachment("tanimoto", tanimotoCoefficient); + + return dataSet; + } + + return null; + } + + public static List rank(final List dataSetList) { + dataSetList.sort((dataSet1, dataSet2) -> { + final int setAssignmentsCountComparison = compareNumericDataSetAttachmentKey(dataSet1, dataSet2, + "setAssignmentsCount"); + if (setAssignmentsCountComparison + != 0) { + return -1 + * setAssignmentsCountComparison; + } + + return compareNumericDataSetAttachmentKey(dataSet1, dataSet2, "averageDeviation"); + }); + + return dataSetList; + } + + private static int compareNumericDataSetAttachmentKey(final DataSet dataSet1, final DataSet dataSet2, + final String attachmentKey) { + Double valueDataSet1 = null; + Double valueDataSet2 = null; + try { + valueDataSet1 = Double.parseDouble(String.valueOf(dataSet1.getAttachment() + .get(attachmentKey))); + } catch (final NullPointerException | NumberFormatException e) { + // e.printStackTrace(); + } + try { + valueDataSet2 = Double.parseDouble(String.valueOf(dataSet2.getAttachment() + .get(attachmentKey))); + } catch (final NullPointerException | NumberFormatException e) { + // e.printStackTrace(); + } + + if (valueDataSet1 + != null + && valueDataSet2 + != null) { + if (valueDataSet1 + < valueDataSet2) { + return -1; + } else if (valueDataSet1 + > valueDataSet2) { + return 1; + } + return 0; + } + if (valueDataSet1 + != null) { + return -1; + } else if (valueDataSet2 + != null) { + return 1; + } + + return 0; + } +} diff --git a/src/casekit/nmr/fragments/FragmentUtilities.java b/src/casekit/nmr/fragments/FragmentUtilities.java new file mode 100644 index 0000000..440c146 --- /dev/null +++ b/src/casekit/nmr/fragments/FragmentUtilities.java @@ -0,0 +1,199 @@ +package casekit.nmr.fragments; + +import casekit.nmr.elucidation.Constants; +import casekit.nmr.model.Assignment; +import casekit.nmr.model.DataSet; +import casekit.nmr.model.Spectrum; +import casekit.nmr.similarity.Similarity; +import casekit.nmr.utils.Utils; +import org.openscience.cdk.interfaces.IAtomContainer; + +import java.util.*; +import java.util.stream.Collectors; + +public class FragmentUtilities { + + public static LinkedHashMap> sortByFrequencies( + final Map> functionalGroupDataSetsMap) { + final LinkedHashMap> sortedCollection = new LinkedHashMap<>(); + final List>> sortedFrequencies = getSortedFrequencies( + functionalGroupDataSetsMap); + for (final Map.Entry> frequency : sortedFrequencies) { + sortedCollection.put(frequency.getKey(), frequency.getValue()); + } + + return sortedCollection; + } + + private static List>> getSortedFrequencies( + final Map> functionalGroupDataSets) { + return functionalGroupDataSets.entrySet() + .stream() + .sorted(Map.Entry.comparingByValue((list1, list2) -> -1 + * Integer.compare(list1.size(), list2.size()))) + .collect(Collectors.toList()); + } + + public static Map> collectBySmiles(final List functionalGroupDataSets) { + final Map> collection = new HashMap<>(); + String smiles; + for (final DataSet functionalGroupDataSet : functionalGroupDataSets) { + smiles = functionalGroupDataSet.getMeta() + .get("smiles"); + if (smiles + != null) { + collection.putIfAbsent(smiles, new ArrayList<>()); + collection.get(smiles) + .add(functionalGroupDataSet); + } + } + + return collection; + } + + public static void filterByCommonSubstructures(final Map> smilesCollection1, + final Map> smilesCollection2) { + // filter first by second collection + Set keysToRemove = new HashSet<>(); + for (final String keyCollection1 : smilesCollection1.keySet()) { + if (!smilesCollection2.containsKey(keyCollection1)) { + keysToRemove.add(keyCollection1); + } + } + for (final String keyCollection1 : keysToRemove) { + smilesCollection1.remove(keyCollection1); + } + // filter second by first collection + keysToRemove = new HashSet<>(); + for (final String keyCollection2 : smilesCollection2.keySet()) { + if (!smilesCollection1.containsKey(keyCollection2)) { + keysToRemove.add(keyCollection2); + } + } + for (final String keyCollection2 : keysToRemove) { + smilesCollection2.remove(keyCollection2); + } + } + + public static Map> getGoodlistAndBadlist(final List dataSetList, + final Spectrum querySpectrum, final String mf, + final double shiftTol, + final double maxAverageDeviation, + final boolean checkMultiplicity, + final List> queryHybridizationList) { + final List matches = new ArrayList<>(); + final List nonMatches = new ArrayList<>(); + Assignment matchAssignment; + for (final DataSet dataSet : dataSetList) { + matchAssignment = Similarity.matchSpectra(dataSet.getSpectrum() + .toSpectrum(), querySpectrum, 0, 0, shiftTol, + checkMultiplicity, true, true); + if (isMatch(dataSet, querySpectrum, mf, matchAssignment, maxAverageDeviation, queryHybridizationList)) { + matches.add(dataSet); + } else if (isNonMatch(dataSet, querySpectrum, mf, matchAssignment)) { + nonMatches.add(dataSet); + } + } + final Map> lists = new HashMap<>(); + lists.put("goodlist", matches); + lists.put("badlist", nonMatches); + + return lists; + } + + public static boolean isMatch(final DataSet dataSet, final Spectrum querySpectrum, final String mf, + final Assignment matchAssignment, final double maxAverageDeviation, + final List> queryHybridizationList) { + // check for nuclei + if (!dataSet.getSpectrum() + .getNuclei()[0].equals(querySpectrum.getNuclei()[0])) { + return false; + } + // check for structural problems in fragment regarding the molecular formula + if (!isStructuralMatch(dataSet, mf)) { + return false; + } + final Spectrum spectrum = dataSet.getSpectrum() + .toSpectrum(); + // check average deviation + final Double averageDeviation = Similarity.calculateAverageDeviation(spectrum, querySpectrum, 0, 0, + matchAssignment); + if (averageDeviation + == null + || averageDeviation + > maxAverageDeviation) { + return false; + } + // check hybridazations after knowing that all signals in dataset have an assignment + if (!checkHybridizations(dataSet, matchAssignment, queryHybridizationList)) { + return false; + } + dataSet.addAttachment("spectralMatchAssignment", matchAssignment); + final Double rmsd = Similarity.calculateRMSD(spectrum, querySpectrum, 0, 0, matchAssignment); + dataSet.addAttachment("averageDeviation", averageDeviation); + dataSet.addAttachment("rmsd", rmsd); + + + return true; + } + + public static boolean isNonMatch(final DataSet dataSet, final Spectrum querySpectrum, final String mf, + final Assignment matchAssigment) { + if (!isStructuralMatch(dataSet, mf)) { + return false; + } + boolean isSpectralMatch = false; + if (dataSet.getSpectrum() + .getNuclei()[0].equals(querySpectrum.getNuclei()[0])) { + if (matchAssigment + != null + && matchAssigment.getSetAssignmentsCount(0) + > 0) { + isSpectralMatch = true; + } + } + + return !isSpectralMatch; + } + + private static boolean isStructuralMatch(final DataSet dataSet, final String mf) { + final IAtomContainer fragment = dataSet.getStructure() + .toAtomContainer(); + // check molecular formula with atom types in group + // do not allow unsaturated fragments + return Utils.compareWithMolecularFormulaLessOrEqual(fragment, mf) + && !Utils.isSaturated(fragment); + } + + private static boolean checkHybridizations(final DataSet dataSet, final Assignment matchAssignment, + final List> queryHybridizationList) { + if (queryHybridizationList.isEmpty()) { + return true; + } + + final IAtomContainer fragment = dataSet.getStructure() + .toAtomContainer(); + final String atomType = Utils.getAtomTypeFromNucleus(dataSet.getSpectrum() + .getNuclei()[0]); + int signalIndexInDataSetSpectrum, signalIndexInQuerySpectrum; + for (int i = 0; i + < fragment.getAtomCount(); i++) { + if (fragment.getAtom(i) + .getSymbol() + .equals(atomType)) { + signalIndexInDataSetSpectrum = dataSet.getAssignment() + .getIndices(0, i) + .get(0); + signalIndexInQuerySpectrum = matchAssignment.getAssignment(0, signalIndexInDataSetSpectrum, 0); + if (!queryHybridizationList.get(signalIndexInQuerySpectrum) + .contains(Constants.hybridizationConversionMap.get(fragment.getAtom(i) + .getHybridization() + .name()))) { + return false; + } + } + } + + return true; + } +} diff --git a/src/casekit/nmr/fragments/fragmentation/Fragmentation.java b/src/casekit/nmr/fragments/fragmentation/Fragmentation.java new file mode 100644 index 0000000..8647a96 --- /dev/null +++ b/src/casekit/nmr/fragments/fragmentation/Fragmentation.java @@ -0,0 +1,475 @@ +package casekit.nmr.fragments.fragmentation; + +import casekit.nmr.fragments.model.ConnectionTree; +import casekit.nmr.model.*; +import casekit.nmr.utils.Utils; +import org.openscience.cdk.exception.CDKException; +import org.openscience.cdk.graph.Cycles; +import org.openscience.cdk.interfaces.IAtom; +import org.openscience.cdk.interfaces.IAtomContainer; +import org.openscience.cdk.interfaces.IBond; +import org.openscience.cdk.interfaces.IRingSet; +import org.openscience.cdk.ringsearch.RingSearch; + +import java.util.*; +import java.util.stream.Collectors; + +public class Fragmentation { + + /** + * Builds connection trees starting at each atom in structure, including ring atoms. + * Duplicates will be removed and subspectra and assignments set. + * + * @param dataSet dataset with structure to build the fragments from + * @param maxSphere maximum spherical limit for single atom fragment creation + * @param maxSphereRing maximum spherical limit for ring atom fragment creation + * @param maxRingSize maximum ring size when detecting rings + * @param withPseudoAtoms whether to place pseudo atoms in "outer" sphere + * + * @return + * + * @see #buildFragmentTrees(IAtomContainer, Integer, Integer, int, boolean) + */ + public static List buildFragmentDataSets(final DataSet dataSet, final Integer maxSphere, + final Integer maxSphereRing, final int maxRingSize, + final boolean withPseudoAtoms) { + + final List fragmentTrees = buildFragmentTrees(dataSet.getStructure() + .toAtomContainer(), maxSphere, + maxSphereRing, maxRingSize, withPseudoAtoms); + return fragmentTreesToSubDataSets(dataSet, fragmentTrees); + } + + public static List fragmentTreesToSubDataSets(final DataSet dataSet, + final List fragmentTrees) { + final List fragmentDataSetList = new ArrayList<>(); + final IAtomContainer structure = dataSet.getStructure() + .toAtomContainer(); + final Spectrum spectrum = dataSet.getSpectrum() + .toSpectrum(); + final String spectrumAtomType = Utils.getAtomTypeFromSpectrum(spectrum, 0); + List substructureAtomIndices, signalIndices; + IAtomContainer substructure; + Spectrum subspectrum; + Assignment subassignment; + IAtom atomInStructure; + Signal signal; + DataSet subDataSet; + Map meta; + String smiles; + for (final ConnectionTree fragmentTree : fragmentTrees) { + substructureAtomIndices = fragmentTree.getKeys(); + subspectrum = new Spectrum(); + subspectrum.setNuclei(dataSet.getSpectrum() + .getNuclei()); + subspectrum.setSignals(new ArrayList<>()); + subassignment = new Assignment(); + subassignment.setNuclei(subspectrum.getNuclei()); + subassignment.initAssignments(0); + for (int j = 0; j + < substructureAtomIndices.size(); j++) { + if (substructureAtomIndices.get(j) + >= structure.getAtomCount()) { + // current node/atom is pseudo + continue; + } + atomInStructure = structure.getAtom(substructureAtomIndices.get(j)); + if (atomInStructure.getSymbol() + .equals(spectrumAtomType) + || (spectrumAtomType.equals("H") + && atomInStructure.getImplicitHydrogenCount() + > 0)) { + signalIndices = dataSet.getAssignment() + .getIndices(0, substructureAtomIndices.get(j)); + if (signalIndices + == null + || signalIndices.isEmpty()) { + return null; + } + + for (final int index : signalIndices) { + signal = spectrum.getSignal(index) + .buildClone(); + final int atomIndex = j; + final List closestSignalIndexList = subspectrum.checkForEquivalences(signal, + new double[]{0.0}, + true); + if (closestSignalIndexList.isEmpty()) { + signal.setEquivalencesCount(1); + subspectrum.addSignal(signal); + subassignment.addAssignment(0, new int[]{atomIndex}); + } else { + final int signalIndex = closestSignalIndexList.get(0); + if (Arrays.stream(subassignment.getAssignment(0, signalIndex)) + .noneMatch(equiv -> equiv + == atomIndex)) { + subspectrum.getSignal(signalIndex) + .setEquivalencesCount(subspectrum.getSignal(signalIndex) + .getEquivalencesCount() + + 1); // + 1 because we add one atom only + subassignment.addAssignmentEquivalence(0, signalIndex, atomIndex); + } + } + } + } + } + subspectrum.addMetaInfo("solvent", dataSet.getSpectrum() + .getMeta() + .get("solvent")); + subspectrum.addMetaInfo("spectrometerFrequency", dataSet.getSpectrum() + .getMeta() + .get("spectrometerFrequency")); + + substructure = FragmentationUtilities.toAtomContainer(fragmentTree); + subDataSet = new DataSet(); + subDataSet.setStructure(new StructureCompact(substructure)); + subDataSet.setSpectrum(new SpectrumCompact(subspectrum)); + subDataSet.setAssignment(subassignment); + + meta = new HashMap<>(); + try { + smiles = casekit.nmr.utils.Utils.getSmilesFromAtomContainer(substructure); + meta.put("smiles", smiles); + + } catch (final CDKException e) { + e.printStackTrace(); + } + // meta.put("title", dataSet.getMeta() + // .get("title")); + meta.put("id", dataSet.getMeta() + .get("id")); + meta.put("mf", Utils.molecularFormularToString(Utils.getMolecularFormulaFromAtomContainer(substructure))); + subDataSet.setMeta(meta); + + fragmentDataSetList.add(subDataSet); + } + + return fragmentDataSetList; + } + + /** + * Builds fragments as atom containers starting at each atom in structure, including ring atoms. + * Duplicates will be removed. + * + * @param structure structure to build the fragments from + * @param maxSphere maximum spherical limit for single atom fragment creation + * @param maxSphereRing maximum spherical limit for ring atom fragment creation + * @param withPseudoAtoms whether to place pseudo atoms in "outer" sphere + * + * @return + * + * @see #buildFragmentTrees(IAtomContainer, Integer, Integer, int, boolean) + * @see FragmentationUtilities#toAtomContainer(ConnectionTree) + */ + public static List buildFragments(final IAtomContainer structure, final Integer maxSphere, + final Integer maxSphereRing, final int maxRingSize, + final boolean withPseudoAtoms) { + final List fragmentTrees = buildFragmentTrees(structure, maxSphere, maxSphereRing, maxRingSize, + withPseudoAtoms); + return fragmentTrees.stream() + .map(FragmentationUtilities::toAtomContainer) + .collect(Collectors.toList()); + } + + public static List buildRingFragmentTrees(final IAtomContainer structure, + final Integer maxSphereRing, final int maxRingSize, + final boolean withPseudoAtoms) { + final List ringFragmentTrees = new ArrayList<>(); + try { + // build ring fragment trees from detected rings and extend by given maximum sphere for rings + ConnectionTree connectionTreeRing, connectionTreeOuterSphere, subtreeToAdd; + final IRingSet ringSet = Cycles.all(structure, maxRingSize)//essential(structure) + .toRingSet(); + final List ringFragments = new ArrayList<>(); + for (int i = 0; i + < ringSet.getAtomContainerCount(); i++) { + ringFragments.add(ringSet.getAtomContainer(i)); + } + // add missing fused rings + final RingSearch ringSearch = new RingSearch(structure); + ringFragments.addAll(ringSearch.fusedRingFragments()); + List atomIndicesInRing; + Set atomIndicesOutOfRing; + IAtomContainer ringAtomContainer; + for (int i = 0; i + < ringFragments.size(); i++) { + ringAtomContainer = ringFragments.get(i); + // add already "visited" ring nodes + atomIndicesInRing = new ArrayList<>(); + for (int k = 0; k + < ringAtomContainer.getAtomCount(); k++) { + atomIndicesInRing.add(structure.indexOf(ringAtomContainer.getAtom(k))); + } + atomIndicesOutOfRing = new HashSet<>(); + for (int j = 0; j + < structure.getAtomCount(); j++) { + if (!atomIndicesInRing.contains(j)) { + atomIndicesOutOfRing.add(j); + } + } + connectionTreeRing = buildFragmentTree(structure, atomIndicesInRing.get(0), null, atomIndicesOutOfRing, + false); + // add missing outer sphere nodes to ring + for (int k = 0; k + < ringAtomContainer.getAtomCount(); k++) { + connectionTreeOuterSphere = Fragmentation.buildFragmentTree(structure, structure.indexOf( + ringAtomContainer.getAtom(k)), maxSphereRing, new HashSet<>(atomIndicesInRing), false); + if (connectionTreeOuterSphere.getMaxSphere(false) + == 0) { + continue; + } + for (final int key : connectionTreeOuterSphere.getNodeKeysInSphere(1)) { + subtreeToAdd = ConnectionTree.buildSubtree(connectionTreeOuterSphere, key); + if (!FragmentationUtilities.addToConnectionTree(connectionTreeRing, + connectionTreeOuterSphere.getRootNode() + .getKey(), + subtreeToAdd, connectionTreeOuterSphere.getBond( + connectionTreeOuterSphere.getRootNode() + .getKey(), key))) { + continue; + } + atomIndicesInRing.addAll(subtreeToAdd.getKeys()); + } + } + // close rings + FragmentationUtilities.closeRings(connectionTreeRing, structure); + // attach pseudo atoms if desired + if (withPseudoAtoms) { + FragmentationUtilities.attachPseudoAtoms(connectionTreeRing, structure); + } + ringFragmentTrees.add(connectionTreeRing); + } + } catch (final CDKException e) { + e.printStackTrace(); + } + + return ringFragmentTrees; + } + + /** + * Builds connection trees starting at each atom in structure, including ring atoms. + * Duplicates are removed. + * + * @param structure structure to build the fragments from + * @param maxSphere maximum spherical limit for single atom fragment creation + * @param maxSphereRing maximum spherical limit for ring atom fragment creation + * @param withPseudoAtoms whether to place pseudo atoms in "outer" sphere + * + * @return + * + * @see #buildRingFragmentTrees(IAtomContainer, Integer, int, boolean) + * @see #buildFragmentTree(IAtomContainer, int, Integer, Set, boolean) + * @see FragmentationUtilities#removeDuplicates(List) + */ + public static List buildFragmentTrees(final IAtomContainer structure, final Integer maxSphere, + final Integer maxSphereRing, final int maxRingSize, + final boolean withPseudoAtoms) { + // build fragment trees for rings + final List fragmentTrees = buildRingFragmentTrees(structure, maxSphereRing, maxRingSize, + withPseudoAtoms); + // build fragment for each single atom + for (int i = 0; i + < structure.getAtomCount(); i++) { + fragmentTrees.add( + Fragmentation.buildFragmentTree(structure, i, maxSphere, new HashSet<>(), withPseudoAtoms)); + } + FragmentationUtilities.removeDuplicates(fragmentTrees); + + return fragmentTrees; + } + + /** + * Creates an atom container from a given connection tree built by using {@link #buildFragmentTree(IAtomContainer, int, Integer, Set, boolean)}. + * + * @param ac atom container to go through + * @param rootAtomIndex root atom index to start from + * @param maxSphere spherical limit, a null value means no limit + * @param exclude atom indices which to exclude from search + * @param withPseudoAtoms places pseudo atoms in the "outer" sphere + * + * @return connection tree + * + * @see #BFS(IAtomContainer, ConnectionTree, Queue, Set, Set, Integer) + * @see #buildFragmentTree(IAtomContainer, int, Integer, Set, boolean) + */ + public static IAtomContainer buildFragment(final IAtomContainer ac, final int rootAtomIndex, + final Integer maxSphere, final Set exclude, + final boolean withPseudoAtoms) { + return FragmentationUtilities.toAtomContainer( + buildFragmentTree(ac, rootAtomIndex, maxSphere, exclude, withPseudoAtoms)); + } + + /** + * Builds a fragment as connection tree from a given structure.
+ * Until a certain maximum sphere, each reachable next neighbor atom + * is stored in a parent-child-relationship.
+ * And in addition, bonds between hetero atoms or carbon-hetero bonds will be kept. In such cases + * the maximum spherical limit will be ignored. + * + * @param structure atom container to go through + * @param rootAtomIndex root atom index to start from + * @param maxSphere spherical limit, a null value means no limit + * @param exclude atom indices which to exclude from search + * @param withPseudoAtoms places pseudo atoms in the "outer" sphere + * + * @return connection tree + */ + public static ConnectionTree buildFragmentTree(final IAtomContainer structure, final int rootAtomIndex, + final Integer maxSphere, final Set exclude, + final boolean withPseudoAtoms) { + // create queue and connection tree for BFS + final Queue queue = new LinkedList<>(); + queue.add(new int[]{rootAtomIndex, 0}); + final ConnectionTree connectionTree = new ConnectionTree(structure.getAtom(rootAtomIndex), rootAtomIndex); + + BFS(structure, connectionTree, queue, new HashSet<>(), exclude, maxSphere); + + // close rings + FragmentationUtilities.closeRings(connectionTree, structure); + // add pseudo atoms + if (withPseudoAtoms) { + FragmentationUtilities.attachPseudoAtoms(connectionTree, structure); + } + + return connectionTree; + } + + /** + * Function for extending a given connection tree only containing + * its root node (0th sphere) by means of Breadth-First-Search (BFS). + * Until a certain maximum sphere, each reachable next neighbor atom + * is stored in a parent-child-relationship. + * And in addition, bonds between hetero atoms, carbon-hetero bonds and triple bonds will be kept. + * In such cases the maximum spherical limit will be ignored. + *

+ * This method follows the rules given in section 7.4.1 of
+ * "Contemporary Computer-Assisted Approaches to Molecular Structure Elucidation (New Developments in NMR) by Mikhail E Elyashberg, Antony Williams and Kirill Blinov. Edited by William Price. RSC Publishing, 2012. ISBN: 978-1-84973-432-5; eISBN: 978-1-84973-457-8" + * + * @param ac atom container to go through + * @param connectionTree connection tree to expand, incl. the root node + * @param queue queue to use containing the atom index of the root node and start sphere + * @param visited atom indices which are already "visited" and + * should be ignored + * @param exclude atom indices which to exclude from search + * @param maxSphere spherical limit, a null value means no limit + */ + private static void BFS(final IAtomContainer ac, final ConnectionTree connectionTree, final Queue queue, + final Set visited, final Set exclude, final Integer maxSphere) { + // all nodes visited? + if (queue.isEmpty()) { + return; + } + final int[] queueValue = queue.remove(); + final int atomIndex = queueValue[0]; + final int sphere = queueValue[1]; + final IAtom atom = ac.getAtom(atomIndex); + // mark atom as visited + visited.add(atomIndex); + + IBond bond; + // add nodes and bonds in lower spheres + // go to all child nodes + int connectedAtomIndex; + for (final IAtom connectedAtom : ac.getConnectedAtomsList(atom)) { + connectedAtomIndex = ac.indexOf(connectedAtom); + bond = ac.getBond(atom, connectedAtom); + // add children to queue if not already visited and connection is allowed or maxSphere is not reached yet + if (!exclude.contains(connectedAtomIndex)) { + if (keepBond(atom, connectedAtom, bond) + || maxSphere + == null + || sphere + < maxSphere) { + // add children to queue if not already visited and not already waiting in queue + if (!visited.contains(connectedAtomIndex) + && !queue.contains(connectedAtomIndex)) { + queue.add(new int[]{connectedAtomIndex, sphere + + 1}); + connectionTree.addNode(connectedAtom, connectedAtomIndex, atomIndex, bond); + } + } + } + } + + // further extension of connection tree + BFS(ac, connectionTree, queue, visited, exclude, maxSphere); + } + + private static boolean keepBond(final IAtom atom1, final IAtom atom2, final IBond bond) { + // hetero-hetero or carbon-hetero + if ((isHeteroAtom(atom1) + && isHeteroAtom(atom2)) + || (isCarbonAtom(atom1) + && isHeteroAtom(atom2)) + || (isHeteroAtom(atom1) + && isCarbonAtom(atom2))) { + return true; + } + + // // do not cut ring bonds + // if (bond.isInRing()) { + // return true; + // } + + // carbon-carbon or carbon-hetero with higher bond order + if ( + // ((isCarbonAtom(atom1) + // && isHeteroAtom(atom2)) + // || (isHeteroAtom(atom1) + // && isCarbonAtom(atom2)) + // || (isCarbonAtom(atom1) + // && isCarbonAtom(atom2))) + // && + bond.getOrder() + .numeric() + >= 3 + // && !bond.isAromatic() + ) { + return true; + } + + // one carbon has bonds to multiple hetero atoms + if (isCarbonAtom(atom1) + && isHeteroAtom(atom2)) { + int heteroAtomCount = 0; + for (final IAtom atom3 : atom1.getContainer() + .getConnectedAtomsList(atom1)) { + if (isHeteroAtom(atom3)) { + heteroAtomCount++; + } + } + return heteroAtomCount + >= 2; + } else if (isHeteroAtom(atom1) + && isCarbonAtom(atom2)) { + int heteroAtomCount = 0; + for (final IAtom atom3 : atom2.getContainer() + .getConnectedAtomsList(atom2)) { + if (isHeteroAtom(atom3)) { + heteroAtomCount++; + } + } + return heteroAtomCount + >= 2; + } + + return false; + } + + private static boolean isHeteroAtom(final IAtom atom) { + return !atom.getSymbol() + .equals("H") + && !isCarbonAtom(atom); + } + + private static boolean isCarbonAtom(final IAtom atom) { + return atom.getSymbol() + .equals("C"); + } + + public static List buildFragmentAtomIndicesList(final IAtomContainer structure, final int rootAtomIndex, + final Integer maxSphere, final Set exclude, + final boolean withPseudoAtoms) { + return buildFragmentTree(structure, rootAtomIndex, maxSphere, exclude, withPseudoAtoms).getKeys(); + } +} diff --git a/src/casekit/nmr/fragments/fragmentation/FragmentationUtilities.java b/src/casekit/nmr/fragments/fragmentation/FragmentationUtilities.java new file mode 100644 index 0000000..893a5c9 --- /dev/null +++ b/src/casekit/nmr/fragments/fragmentation/FragmentationUtilities.java @@ -0,0 +1,257 @@ +package casekit.nmr.fragments.fragmentation; + +import casekit.nmr.fragments.model.ConnectionTree; +import casekit.nmr.fragments.model.ConnectionTreeNode; +import org.openscience.cdk.interfaces.IAtom; +import org.openscience.cdk.interfaces.IAtomContainer; +import org.openscience.cdk.interfaces.IBond; +import org.openscience.cdk.silent.Bond; +import org.openscience.cdk.silent.PseudoAtom; +import org.openscience.cdk.silent.SilentChemObjectBuilder; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +public class FragmentationUtilities { + + public static boolean adjustNodeKeys(final ConnectionTree fragmentTree, final IAtomContainer structure) { + int atomIndex; + for (final ConnectionTreeNode node : fragmentTree.getNodes(false)) { + atomIndex = structure.indexOf(node.getAtom()); + if (atomIndex + < 0) { + return false; + } + node.setKey(atomIndex); + } + fragmentTree.initKeySet(); + + return true; + } + + public static void removeDuplicates(final List fragmentTrees) { + final List> keySets = new ArrayList<>(); + final List fragmentsToRemove = new ArrayList<>(); + for (final ConnectionTree fragment : fragmentTrees) { + // ignore pseudo nodes + final Set keySet = fragment.getNodes(false) + .stream() + .filter(node -> !node.isPseudoNode()) + .map(ConnectionTreeNode::getKey) + .collect(Collectors.toSet()); + if (keySets.stream() + .noneMatch(keySetTemp -> keySetTemp.size() + == keySet.size() + && keySetTemp.containsAll(keySet))) { + keySets.add(keySet); + } else { + fragmentsToRemove.add(fragment); + } + } + fragmentTrees.removeAll(fragmentsToRemove); + } + + public static IAtomContainer closeRings(final IAtomContainer substructure, final IAtomContainer structure) { + final ConnectionTree fragmentTree = Fragmentation.buildFragmentTree(substructure, 0, null, new HashSet<>(), + false); + closeRings(fragmentTree, structure); + + return toAtomContainer(fragmentTree); + } + + public static void closeRings(final ConnectionTree connectionTree, final IAtomContainer structure) { + // close rings + IBond bond; + final int maxSphereTree = connectionTree.getMaxSphere(false); + for (int s = 0; s + <= maxSphereTree; s++) { + for (final ConnectionTreeNode nodeInSphere1 : connectionTree.getNodesInSphere(s, false)) { + // set connections (parent nodes) in sphere nodes which have to be connected -> ring closures + for (int s2 = s; s2 + <= maxSphereTree; s2++) { + for (final ConnectionTreeNode nodeInSphere2 : connectionTree.getNodesInSphere(s2, false)) { + if ((structure.getBond(nodeInSphere1.getAtom(), nodeInSphere2.getAtom()) + != null) + && !ConnectionTree.nodesFormRingClosure(nodeInSphere1, nodeInSphere2)) { + bond = structure.getBond(nodeInSphere1.getAtom(), nodeInSphere2.getAtom()); + connectionTree.addRingClosureNode(nodeInSphere1.getKey(), nodeInSphere2.getKey(), bond); + connectionTree.addRingClosureNode(nodeInSphere2.getKey(), nodeInSphere1.getKey(), bond); + } + } + } + } + } + } + + /** + * Reconstructs a structure from a given connection tree, + * including ring closures. + * + * @param connectionTree connection tree + * + * @return IAtomContainer + */ + public static IAtomContainer toAtomContainer(final ConnectionTree connectionTree) { + // create new atom container and add the connection trees structure, beginning at the root atom + final IAtomContainer ac = SilentChemObjectBuilder.getInstance() + .newAtomContainer(); + addToAtomContainer(connectionTree, ac, null, null); + + return ac; + } + + /** + * Adds a subtree to a node in another connection tree. + * + * @param connectionTree connection tree + * @param parentNodeKey parent node key in connection tree + * @param subtree subtree to add + * @param bondToLink bond + */ + public static boolean addToConnectionTree(final ConnectionTree connectionTree, final int parentNodeKey, + final ConnectionTree subtree, final IBond bondToLink) { + return ConnectionTree.addSubtree(connectionTree, parentNodeKey, subtree, bondToLink); + } + + /** + * Adds the substructure of a connection tree to an atom container.
+ * The substructure can be linked via a bond and an atom index in the container, but this is optional. + * If both, the bond and atom index to link, are not given (null) then the substructure will just be added + * to the atom container without linkage. + * + * @param connectionTree + * @param ac + * @param atomIndexInStructureToLink + * @param bondToLink + */ + public static void addToAtomContainer(final ConnectionTree connectionTree, final IAtomContainer ac, + final Integer atomIndexInStructureToLink, final IBond bondToLink) { + List nodesInSphere; + ConnectionTreeNode nodeInSphere, parentNode, partnerNode; + IBond bond, bondToParent; + // add root atom to given atom container and link it via a given linking bond + ac.addAtom(connectionTree.getRootNode() + .getAtom()); + if ((atomIndexInStructureToLink + != null) + && (bondToLink + != null)) { + final IBond bondToAdd = new Bond(ac.getAtom(atomIndexInStructureToLink), ac.getAtom(ac.getAtomCount() + - 1)); + bondToAdd.setOrder(bondToLink.getOrder()); + bondToAdd.setIsInRing(bondToLink.isInRing()); + bondToAdd.setIsAromatic(bondToLink.isAromatic()); + bondToAdd.setAtom(ac.getAtom(atomIndexInStructureToLink), 0); + bondToAdd.setAtom(ac.getAtom(ac.getAtomCount() + - 1), 1); + ac.addBond(bondToAdd); + } + // for each sphere: add the atom which is stored as node to atom container and set bonds between parent nodes + for (int s = 1; s + <= connectionTree.getMaxSphere(false); s++) { + // first add all atoms and its parents (previous sphere only, incl. bonds) to structure + nodesInSphere = connectionTree.getNodesInSphere(s, false); + for (int i = 0; i + < nodesInSphere.size(); i++) { + nodeInSphere = nodesInSphere.get(i); + if (nodeInSphere.isRingClosureNode()) { + continue; + } + ac.addAtom(nodeInSphere.getAtom()); + parentNode = nodeInSphere.getParent(); + bondToParent = nodeInSphere.getBondToParent(); + bond = new Bond(nodeInSphere.getAtom(), parentNode.getAtom(), bondToParent.getOrder()); + bond.setIsInRing(bondToParent.isInRing()); + bond.setIsAromatic(bondToParent.isAromatic()); + ac.addBond(bond); + } + } + for (int s = 1; s + <= connectionTree.getMaxSphere(true); s++) { + // and as second add the remaining bonds (ring closures) to structure + nodesInSphere = connectionTree.getNodesInSphere(s, true); + for (int i = 0; i + < nodesInSphere.size(); i++) { + nodeInSphere = nodesInSphere.get(i); + if (!nodeInSphere.isRingClosureNode()) { + continue; + } + parentNode = nodeInSphere.getParent(); + partnerNode = nodeInSphere.getRingClosureParent(); + if (ac.getBond(ac.getAtom(ac.indexOf(partnerNode.getAtom())), + ac.getAtom(ac.indexOf(parentNode.getAtom()))) + == null) { + bondToParent = nodeInSphere.getBondToParent(); + bond = new Bond(parentNode.getAtom(), partnerNode.getAtom(), bondToParent.getOrder()); + bond.setIsInRing(bondToParent.isInRing()); + bond.setIsAromatic(bondToParent.isAromatic()); + ac.addBond(bond); + } + } + } + } + + public static void attachPseudoAtoms(final ConnectionTree connectionTree, final IAtomContainer structure) { + int connectedAtomIndexInStructure; + // first check for atoms which we would add as pseudo atom but are then ring closures actually + // means we check for possible duplicated insertion + final Set connectedAtoms = new HashSet<>(); + final List ringClosureAtomToAdd = new ArrayList<>(); + for (final ConnectionTreeNode node : connectionTree.getNodes(false)) { + for (final IAtom connectedAtom : structure.getConnectedAtomsList(node.getAtom())) { + connectedAtomIndexInStructure = structure.indexOf(connectedAtom); + if (connectionTree.getBond(node.getKey(), connectedAtomIndexInStructure) + == null + && connectionTree.getBond(connectedAtomIndexInStructure, node.getKey()) + == null) { + if (connectedAtoms.contains(connectedAtom)) { + ringClosureAtomToAdd.add(connectedAtom); + } + connectedAtoms.add(connectedAtom); + } + } + } + ConnectionTreeNode connectedNode; + for (final ConnectionTreeNode node : connectionTree.getNodes(false)) { + for (final IAtom connectedAtom : structure.getConnectedAtomsList(node.getAtom())) { + connectedAtomIndexInStructure = structure.indexOf(connectedAtom); + if (connectionTree.getBond(node.getKey(), connectedAtomIndexInStructure) + == null + && connectionTree.getBond(connectedAtomIndexInStructure, node.getKey()) + == null) { + if (!ringClosureAtomToAdd.contains(connectedAtom)) { + addPseudoNode(connectionTree, structure.getAtomCount() + + connectionTree.getNodesCount(false), node.getKey(), + structure.getBond(node.getAtom(), connectedAtom)); + } else { + // add missing node for ring closure + if (!connectionTree.containsKey(connectedAtom.getIndex())) { + connectionTree.addNode(connectedAtom, connectedAtomIndexInStructure, node.getKey(), + structure.getBond(node.getAtom(), connectedAtom)); + } else { + // set the ring closure + connectedNode = connectionTree.getNode(connectedAtomIndexInStructure); + node.setRingClosureParent(connectedNode); + connectedNode.setRingClosureParent(node); + } + } + } + } + } + closeRings(connectionTree, structure); + } + + private static boolean addPseudoNode(final ConnectionTree connectionTree, final int pseudoNodeKey, + final int parentNodeKey, final IBond bondToParent) { + if (!connectionTree.addNode(new PseudoAtom("R"), pseudoNodeKey, parentNodeKey, bondToParent)) { + return false; + } + final ConnectionTreeNode pseudoNode = connectionTree.getNode(pseudoNodeKey); + pseudoNode.setIsPseudoNode(true); + + return true; + } +} diff --git a/src/casekit/nmr/fragments/functionalgroup/ErtlFunctionalGroupsFinder.java b/src/casekit/nmr/fragments/functionalgroup/ErtlFunctionalGroupsFinder.java new file mode 100644 index 0000000..a35da6b --- /dev/null +++ b/src/casekit/nmr/fragments/functionalgroup/ErtlFunctionalGroupsFinder.java @@ -0,0 +1,979 @@ +/** + * ErtlFunctionalGroupsFinder for CDK + * Copyright (C) 2019 Sebastian Fritsch + *

+ * Source code is available at + *

+ * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License + * as published by the Free Software Foundation; either version 2.1 + * of the License, or (at your option) any later version. + *

+ * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *

+ * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package casekit.nmr.fragments.functionalgroup; + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import org.openscience.cdk.graph.ConnectedComponents; +import org.openscience.cdk.graph.GraphUtil; +import org.openscience.cdk.graph.GraphUtil.EdgeToBondMap; +import org.openscience.cdk.interfaces.*; +import org.openscience.cdk.interfaces.IBond.Order; +import org.openscience.cdk.tools.ILoggingTool; +import org.openscience.cdk.tools.LoggingToolFactory; + +import java.util.*; + +/** + * Finds and extracts a molecules's functional groups in a purely rule-based manner. + *

+ * This class implements Peter Ertl's algorithm for the automated detection and extraction + * of functional groups in organic molecules + * [Ertl P. An algorithm to identify functional groups in organic molecules. J Cheminform. 2017; 9:36.]. + * + * @author Sebastian Fritsch + * @version 1.0.0.0 + */ +public class ErtlFunctionalGroupsFinder { + + private final static String CARBONYL_C_MARKER = "Carbonyl-C"; + private static final ILoggingTool log = LoggingToolFactory.createLoggingTool(ErtlFunctionalGroupsFinder.class); + private final Set nonmetalAtomicNumbers; + private final Mode mode; + private EdgeToBondMap bondMap; + private int[][] adjList; + private HashSet markedAtoms; + private HashMap aromaticHeteroAtoms; // key: atom idx, value: isInGroup + private Map> environmentsMap; + + /** + * Default constructor for ErtlFunctionalGroupsFinder. + */ + public ErtlFunctionalGroupsFinder() { + this(Mode.DEFAULT); + } + + /** + * Constructor for ErtlFunctionalGroupsFinder. + * + * @param mode working mode (see {@code ErtlFunctionalGroupsFinder.Mode}). + */ + public ErtlFunctionalGroupsFinder(final Mode mode) { + this.mode = mode; + + // init non-metal and non-metalloid atom numbers + this.nonmetalAtomicNumbers = ImmutableSet.of(1, 2, 6, 7, 8, 9, 10, 15, 16, 17, 18, 34, 35, 36, 53, 54, 86); + } + + private static final boolean isHeteroatom(final IAtom atom) { + final int atomicNr = atom.getAtomicNumber(); + return atomicNr + != 1 + && atomicNr + != 6; + } + + /** + * Find all functional groups contained in a molecule. + *

+ * NOTE: The input must consist of one connected structure and may not contain charged atoms, metals or metalloids. + * + * @param container the molecule which contains the functional groups (may not contain charged atoms, metals, + * metalloids or unconnected components!) + * + * @return a list with all functional groups found in the molecule. + */ + public List find(final IAtomContainer container) { + return this.find(container, true); + } + + /** + * Find all functional groups contained in a molecule. + *

+ * NOTE: The input must consist of one connected structure and may not contain charged atoms, metals or metalloids. + * + * @param container the molecule which contains the functional groups (may not contain charged atoms, metals, + * metalloids or unconnected components!) + * @param clone Use 'false' to reuse the input container's bonds and atoms in the extraction of the functional + * groups. This may speed up the extraction and lower the memory consumption for processing large + * amounts of data but corrupts the original input container. + * Use 'true' to work with a clone and leave the input container intact (default). + * + * @return a list with all functional groups found in the molecule. + */ + public List find(final IAtomContainer container, final boolean clone) { + // work with a clone? + final IAtomContainer mol; + if (clone) { + try { + mol = container.clone(); + } catch (final CloneNotSupportedException e) { + throw new IllegalStateException("Atom container could not be cloned"); + } + } else { + mol = container; + } + + // init GraphUtil & EdgeToBondMap + this.bondMap = EdgeToBondMap.withSpaceFor(mol); + this.adjList = GraphUtil.toAdjList(mol, this.bondMap); + + this.checkConstraints(mol); + + // atom marking + this.markAtoms(mol); + + // extract raw groups + final List groups = this.extractGroups(mol); + + // handle environment + if (this.mode + == Mode.DEFAULT) { + this.expandGeneralizedEnvironments(groups); + } else if (this.mode + == Mode.NO_GENERALIZATION) { + this.expandFullEnvironments(groups); + } else { + throw new IllegalStateException("Unknown mode."); + } + + // clear fields + this.bondMap = null; + this.adjList = null; + this.markedAtoms = null; + this.aromaticHeteroAtoms = null; + this.environmentsMap = null; + + return groups; + } + + /** + * Mark all atoms and store them in a set for further processing. + * + * @param molecule Molecule with atoms to mark + */ + private void markAtoms(final IAtomContainer molecule) { + if (this.isDbg()) { + log.debug("########## Starting search for atoms to mark ... ##########"); + } + + // store marked atoms + this.markedAtoms = Sets.newHashSetWithExpectedSize(molecule.getAtomCount()); + // store aromatic heteroatoms + this.aromaticHeteroAtoms = new HashMap<>(); + + for (int idx = 0; idx + < molecule.getAtomCount(); idx++) { + // skip atoms that already got marked in a previous iteration + if (this.markedAtoms.contains(idx)) { + continue; + } + final IAtom cAtom = molecule.getAtom(idx); + // skip aromatic atoms but add them to set + if (cAtom.isAromatic()) { + if (isHeteroatom(cAtom)) { + this.aromaticHeteroAtoms.put(idx, false); + } + continue; + } + + final int atomicNr = cAtom.getAtomicNumber(); + + // if C... + if (atomicNr + == 6) { + boolean isMarked = false; // to detect if foor loop ran with or without marking the C atom + int oNSCounter = 0; // count for the number of connected O, N & S atoms + for (final int connectedIdx : this.adjList[idx]) { + final IAtom connectedAtom = molecule.getAtom(connectedIdx); + final IBond connectedBond = this.bondMap.get(idx, connectedIdx); + + // if connected to Heteroatom or C in aliphatic double or triple bond... [CONDITIONS 2.1 & 2.2] + if (connectedAtom.getAtomicNumber() + != 1 + && ((connectedBond.getOrder() + == Order.DOUBLE + || connectedBond.getOrder() + == Order.TRIPLE) + && !connectedBond.isAromatic())) { + + // set the connected atom as marked + if (this.markedAtoms.add(connectedIdx)) { + final String connectedAtomCondition = connectedAtom.getAtomicNumber() + == 6 + ? "2.1/2.2" + : "1"; + if (this.isDbg()) { + log.debug(String.format("Marking Atom #%d (%s) - Met condition %s", connectedIdx, + connectedAtom.getSymbol(), connectedAtomCondition)); + } + } + + // set the current atom as marked and break out of connected atoms + if (this.isDbg()) { + log.debug(String.format("Marking Atom #%d (%s) - Met condition 2.1/2.2", idx, + cAtom.getSymbol())); + } + isMarked = true; + + // but check for carbonyl-C before break + if (connectedAtom.getAtomicNumber() + == 8 + && connectedBond.getOrder() + == Order.DOUBLE + && this.adjList[idx].length + == 3) { + if (this.isDbg()) { + log.debug(" - was flagged as Carbonly-C"); + } + cAtom.setProperty(CARBONYL_C_MARKER, true); + } + + break; + } + // if connected to O/N/S in single bond... + else if ((connectedAtom.getAtomicNumber() + == 7 + || connectedAtom.getAtomicNumber() + == 8 + || connectedAtom.getAtomicNumber() + == 16) + && connectedBond.getOrder() + == Order.SINGLE) { + // if connected O/N/S is not aromatic... + if (!connectedAtom.isAromatic()) { + // set the connected O/N/S atom as marked + if (this.isDbg()) { + log.debug(String.format("Marking Atom #%d (%s) - Met condition 1", connectedIdx, + connectedAtom.getSymbol())); + } + this.markedAtoms.add(connectedIdx); + + // if "acetal C" (2+ O/N/S in single bonds connected to sp3-C)... [CONDITION 2.3] + boolean isAllSingleBonds = true; + for (final int connectedInSphere2Idx : this.adjList[connectedIdx]) { + final IBond sphere2Bond = this.bondMap.get(connectedIdx, connectedInSphere2Idx); + if (sphere2Bond.getOrder() + != Order.SINGLE) { + isAllSingleBonds = false; + break; + } + } + if (isAllSingleBonds) { + oNSCounter++; + if (oNSCounter + > 1 + && this.adjList[idx].length + + cAtom.getImplicitHydrogenCount() + == 4) { + // set as marked and break out of connected atoms + if (this.isDbg()) { + log.debug(String.format("Marking Atom #%d (%s) - Met condition 2.3", idx, + cAtom.getSymbol())); + } + isMarked = true; + break; + } + } + } + // if part of oxirane, aziridine and thiirane ring... [CONDITION 2.4] + for (final int connectedInSphere2Idx : this.adjList[connectedIdx]) { + final IAtom connectedInSphere2Atom = molecule.getAtom(connectedInSphere2Idx); + if (connectedInSphere2Atom.getAtomicNumber() + == 6) { + for (final int connectedInSphere3Idx : this.adjList[connectedInSphere2Idx]) { + final IAtom connectedInSphere3Atom = molecule.getAtom(connectedInSphere3Idx); + if (connectedInSphere3Atom.equals(cAtom)) { + // set connected atoms as marked + if (this.isDbg()) { + log.debug(String.format("Marking Atom #%d (%s) - Met condition 2.4", + connectedInSphere2Idx, + connectedInSphere2Atom.getSymbol())); + } + if (this.isDbg()) { + log.debug(String.format("Marking Atom #%d (%s) - Met condition 2.4", + connectedInSphere3Idx, + connectedInSphere3Atom.getSymbol())); + } + this.markedAtoms.add(connectedInSphere2Idx); + this.markedAtoms.add(connectedInSphere3Idx); + // set current atom as marked and break out of connected atoms + if (this.isDbg()) { + log.debug(String.format("Marking Atom #%d (%s) - Met condition 2.4", idx, + cAtom.getSymbol())); + } + isMarked = true; + break; + } + } + } + } + } + } + if (isMarked) { + this.markedAtoms.add(idx); + continue; + } + // if none of the conditions 2.X apply, we have an unmarked C (not relevant here) + } + // if H... + else if (atomicNr + == 1) { + // convert to implicit H + final IAtom connectedAtom; + try { + connectedAtom = molecule.getAtom(this.adjList[idx][0]); + } catch (final ArrayIndexOutOfBoundsException e) { + break; + } + + + if (connectedAtom.getImplicitHydrogenCount() + == null) { + connectedAtom.setImplicitHydrogenCount(1); + } else { + connectedAtom.setImplicitHydrogenCount(connectedAtom.getImplicitHydrogenCount() + + 1); + } + continue; + } + // if heteroatom... (CONDITION 1) + else { + if (this.isDbg()) { + log.debug(String.format("Marking Atom #%d (%s) - Met condition 1", idx, cAtom.getSymbol())); + } + this.markedAtoms.add(idx); + continue; + } + } + if (this.isDbg()) { + log.debug(String.format("########## End of search. Marked %d/%d atoms. ##########", this.markedAtoms.size(), + molecule.getAtomCount())); + } + } + + /** + * Searches the molecule for groups of connected marked atoms and extracts each as a new functional group. + * The extraction process includes marked atom's "environments". Connected H's are captured implicitly. + * + * @param molecule the molecule which contains the functional groups + * + * @return a list of all functional groups (including "environments") extracted from the molecule + */ + private List extractGroups(final IAtomContainer molecule) { + if (this.isDbg()) { + log.debug("########## Starting identification & extraction of functional groups... ##########"); + } + + this.environmentsMap = Maps.newHashMapWithExpectedSize(molecule.getAtomCount()); + final int[] atomIdxToFGMap = new int[molecule.getAtomCount()]; + Arrays.fill(atomIdxToFGMap, -1); + int fGroupIdx = -1; + + while (!this.markedAtoms.isEmpty()) { + // search for another functional group + fGroupIdx++; + + // get next markedAtom as the starting node for the search + final int beginIdx = this.markedAtoms.iterator() + .next(); + if (this.isDbg()) { + log.debug(String.format("Searching new functional group from atom #%d (%s)...", beginIdx, + molecule.getAtom(beginIdx) + .getSymbol())); + } + + // do a BFS from there + final Queue queue = new ArrayDeque<>(); + queue.add(beginIdx); + + while (!queue.isEmpty()) { + final int currentIdx = queue.poll(); + + // we are only interested in marked atoms that are not yet included in a group + if (!this.markedAtoms.contains(currentIdx)) { + continue; + } + + // if it isn't... + final IAtom currentAtom = molecule.getAtom(currentIdx); + if (this.isDbg()) { + log.debug(String.format(" visiting marked atom: #%d (%s)", currentIdx, currentAtom.getSymbol())); + } + + // add its index to the functional group + atomIdxToFGMap[currentIdx] = fGroupIdx; + // also scratch the index from markedAtoms + this.markedAtoms.remove(currentIdx); + + // and take look at the connected atoms + final List currentEnvironment = new ArrayList<>(); + for (final int connectedIdx : this.adjList[currentIdx]) { + // add connected marked atoms to queue + if (this.markedAtoms.contains(connectedIdx)) { + queue.add(connectedIdx); + continue; + } + + // ignore already handled connected atoms + if (atomIdxToFGMap[connectedIdx] + >= 0) { + continue; + } + + // add unmarked connected aromatic heteroatoms + final IAtom connectedAtom = molecule.getAtom(connectedIdx); + if (isHeteroatom(connectedAtom) + && connectedAtom.isAromatic()) { + if (this.isDbg()) { + log.debug(" added connected aromatic heteroatom " + + connectedAtom.getSymbol()); + } + atomIdxToFGMap[connectedIdx] = fGroupIdx; + // note that this aromatic heteroatom has been added to a group + this.aromaticHeteroAtoms.put(connectedIdx, true); + } + + // add unmarked connected atoms to current marked atom's environment + final IBond connectedBond = this.bondMap.get(currentIdx, connectedIdx); + + final EnvironmentCalCType type; + if (connectedAtom.getAtomicNumber() + == 6) { + if (connectedAtom.isAromatic()) { + type = EnvironmentCalCType.C_AROMATIC; + } else { + type = EnvironmentCalCType.C_ALIPHATIC; + } + } else { + // aromatic heteroatom, so just ignore + continue; + } + currentEnvironment.add(new EnvironmentalC(type, connectedBond, connectedBond.getBegin() + == connectedAtom + ? 0 + : 1)); + } + this.environmentsMap.put(currentAtom, currentEnvironment); + + // debug logging + if (this.isDbg()) { + int cAromCount = 0, cAliphCount = 0; + for (final EnvironmentalC comp : currentEnvironment) { + if (comp.getType() + == EnvironmentCalCType.C_AROMATIC) { + cAromCount++; + } else if (comp.getType() + == EnvironmentCalCType.C_ALIPHATIC) { + cAliphCount++; + } + } + log.debug(String.format( + " logged marked atom's environment: C_ar:%d, C_al:%d (and %d implicit hydrogens)", + cAromCount, cAliphCount, currentAtom.getImplicitHydrogenCount())); + } + } + + if (this.isDbg()) { + log.debug(" search completed."); + } + } + + // also create FG for lone aromatic heteroatoms, not connected to a FG yet. + for (final int atomIdx : this.aromaticHeteroAtoms.keySet()) { + if (!this.aromaticHeteroAtoms.get(atomIdx)) { + fGroupIdx++; + atomIdxToFGMap[atomIdx] = fGroupIdx; + if (this.isDbg()) { + log.debug("Created FG for lone aromatic heteroatom: " + + molecule.getAtom(atomIdx) + .getSymbol()); + } + } + } + + final List fGs = this.partitionIntoGroups(molecule, atomIdxToFGMap, fGroupIdx + + 1); + + if (this.isDbg()) { + log.debug(String.format("########## Found & extracted %d functional groups. ##########", fGroupIdx + + 1)); + } + return fGs; + } + + /** + * Generalizes the full environments of functional groups, providing a good balance between preserving + * meaningful detail and generalization. + * + * @param fGroups the list of functional groups including "environments" + */ + private void expandGeneralizedEnvironments(final List fGroups) { + if (this.isDbg()) { + log.debug("########## Starting generalization of functional groups... ##########"); + } + + for (final IAtomContainer fGroup : fGroups) { + final int atomCount = fGroup.getAtomCount(); + + if (this.isDbg()) { + log.debug(String.format("Generalizing functional group (%d atoms)...", atomCount)); + } + + // prechecking for special cases... + if (fGroup.getAtomCount() + == 1) { + final IAtom atom = fGroup.getAtom(0); + final List environment = this.environmentsMap.get(atom); + + if (environment + != null) { + final int envCCount = environment.size(); + + // for H2N-C_env & HO-C_env -> do not replace H & C_env by R! + if ((atom.getAtomicNumber() + == 8 + && envCCount + == 1) + || (atom.getAtomicNumber() + == 7 + && envCCount + == 1)) { + if (this.isDbg()) { + log.debug(String.format( + " - found single atomic N or O FG with one env. C. Expanding environment...", + atom.getSymbol())); + } + this.expandEnvironment(atom, fGroup); + + final int hCount = atom.getImplicitHydrogenCount(); + if (hCount + != 0) { + if (this.isDbg()) { + log.debug(String.format(" - adding %d hydrogens...", hCount)); + } + this.addHydrogens(atom, hCount, fGroup); + atom.setImplicitHydrogenCount(0); + } + continue; + } + // for HN-(C_env)-C_env & HS-C_env -> do not replace H by R! (only C_env!) + if ((atom.getAtomicNumber() + == 7 + && envCCount + == 2) + || (atom.getAtomicNumber() + == 16 + && envCCount + == 1)) { + if (this.isDbg()) { + log.debug(" - found sec. amine or simple thiol"); + } + final int hCount = atom.getImplicitHydrogenCount(); + if (hCount + != 0) { + if (this.isDbg()) { + log.debug(String.format(" - adding %d hydrogens...", hCount)); + } + this.addHydrogens(atom, hCount, fGroup); + atom.setImplicitHydrogenCount(0); + } + if (this.isDbg()) { + log.debug(" - expanding environment..."); + } + this.expandEnvironmentGeneralized(atom, fGroup); + continue; + } + } else if (isHeteroatom(atom)) { + final int rAtomCount = atom.getValency(); + final Integer hCount = atom.getImplicitHydrogenCount(); + if (hCount + != null + && hCount + != 0) { + atom.setImplicitHydrogenCount(0); + } + final String atomTypeName = atom.getAtomTypeName(); + if (this.isDbg()) { + log.debug(String.format( + " - found single aromatic heteroatom (%s, Atomtype %s). Adding %d R-Atoms...", + atom.getSymbol(), atomTypeName, rAtomCount)); + } + this.addRAtoms(atom, rAtomCount, fGroup); + continue; + } + } + + // get atoms to process + final List fGroupAtoms = Lists.newArrayList(fGroup.atoms()); + + // process atoms... + for (final IAtom atom : fGroupAtoms) { + final List environment = this.environmentsMap.get(atom); + + if (environment + == null) { + if (atom.getImplicitHydrogenCount() + != 0) { + atom.setImplicitHydrogenCount(0); + } + final int rAtomCount = atom.getValency() + - 1; + if (this.isDbg()) { + log.debug(String.format(" - found connected aromatic heteroatom (%s). Adding %d R-Atoms...", + atom.getSymbol(), rAtomCount)); + } + this.addRAtoms(atom, rAtomCount, fGroup); + } + + // processing carbons... + if (atom.getAtomicNumber() + == 6) { + if (atom.getProperty(CARBONYL_C_MARKER) + == null) { + if (atom.getImplicitHydrogenCount() + != 0) { + atom.setImplicitHydrogenCount(0); + } + if (this.isDbg()) { + log.debug(" - ignoring environment for marked carbon atom"); + } + continue; + } else { + if (this.isDbg()) { + log.debug(" - found carbonyl-carbon. Expanding environment..."); + } + this.expandEnvironmentGeneralized(atom, fGroup); + continue; + } + } + // processing heteroatoms... + else { + if (this.isDbg()) { + log.debug(String.format(" - found heteroatom (%s). Expanding environment...", + atom.getSymbol())); + } + this.expandEnvironmentGeneralized(atom, fGroup); + continue; + } + } + } + + if (this.isDbg()) { + log.debug("########## Generalization of functional groups completed. ##########"); + } + } + + /** + * Expands the full environments of functional groups, converted into atoms and bonds. + * + * @param fGroups the list of functional groups including "environments" + */ + private void expandFullEnvironments(final List fGroups) { + if (this.isDbg()) { + log.debug("########## Starting expansion of full environments for functional groups... ##########"); + } + + for (final IAtomContainer fGroup : fGroups) { + final int atomCount = fGroup.getAtomCount(); + if (this.isDbg()) { + log.debug(String.format("Expanding environment on functional group (%d atoms)...", atomCount)); + } + + for (int i = 0; i + < atomCount; i++) { + final IAtom atom = fGroup.getAtom(i); + + if (this.isDbg()) { + log.debug(String.format(" - Atom #%d:% - Expanding environment...", i)); + } + this.expandEnvironment(atom, fGroup); + + final int hCount = atom.getImplicitHydrogenCount(); + if (hCount + != 0) { + if (this.isDbg()) { + log.debug(String.format(" - adding %d hydrogens...", hCount)); + } + this.addHydrogens(atom, hCount, fGroup); + atom.setImplicitHydrogenCount(0); + } + } + } + + if (this.isDbg()) { + log.debug("########## Expansion of full environments for functional groups completed. ##########"); + } + } + + private void expandEnvironment(final IAtom atom, final IAtomContainer container) { + final List environment = this.environmentsMap.get(atom); + + if (environment + == null + || environment.isEmpty()) { + if (this.isDbg()) { + log.debug(" found no environment to expand."); + } + return; + } + + int cAromCount = 0, cAliphCount = 0; + for (final EnvironmentalC envC : environment) { + final IAtom cAtom = atom.getBuilder() + .newInstance(IAtom.class, "C"); + cAtom.setAtomTypeName("C"); + cAtom.setImplicitHydrogenCount(0); + if (envC.getType() + == EnvironmentCalCType.C_AROMATIC) { + cAtom.setIsAromatic(true); + cAromCount++; + } else { + cAliphCount++; + } + + final IBond bond = envC.createBond(atom, cAtom); + + container.addAtom(cAtom); + container.addBond(bond); + } + + if (this.isDbg()) { + log.debug(String.format(" expanded environment: %dx C_ar and %dx C_al", cAromCount, cAliphCount)); + } + } + + // only call this on marked heteroatoms / carbonyl-C's! + private void expandEnvironmentGeneralized(final IAtom atom, final IAtomContainer container) { + + final List environment = this.environmentsMap.get(atom); + + if (environment + == null) { + if (this.isDbg()) { + log.debug(" found no environment to expand."); + } + return; + } + + int rAtomCount = environment.size(); + final int rAtomsForCCount = rAtomCount; + if (atom.getAtomicNumber() + == 8 + && atom.getImplicitHydrogenCount() + == 1) { + this.addHydrogens(atom, 1, container); + atom.setImplicitHydrogenCount(0); + if (this.isDbg()) { + log.debug(" expanded hydrogen on connected OH-Group"); + } + } else if (isHeteroatom(atom)) { + rAtomCount += atom.getImplicitHydrogenCount(); + } + this.addRAtoms(atom, rAtomCount, container); + + if (atom.getImplicitHydrogenCount() + != 0) { + atom.setImplicitHydrogenCount(0); + } + + if (this.isDbg()) { + log.debug(String.format(" expanded environment: %dx R-atom (incl. %d for H replacement)", rAtomCount, + rAtomCount + - rAtomsForCCount)); + } + } + + private final boolean isNonmetal(final IAtom atom) { + return this.nonmetalAtomicNumbers.contains(atom.getAtomicNumber()); + } + + private void addHydrogens(final IAtom atom, final int number, final IAtomContainer container) { + for (int i = 0; i + < number; i++) { + final IAtom hydrogen = atom.getBuilder() + .newInstance(IAtom.class, "H"); + hydrogen.setAtomTypeName("H"); + hydrogen.setImplicitHydrogenCount(0); + + container.addAtom(hydrogen); + container.addBond(atom.getBuilder() + .newInstance(IBond.class, atom, hydrogen, Order.SINGLE)); + } + } + + private void addRAtoms(final IAtom atom, final int number, final IAtomContainer container) { + for (int i = 0; i + < number; i++) { + final IPseudoAtom rAtom = atom.getBuilder() + .newInstance(IPseudoAtom.class, "R"); + rAtom.setAttachPointNum(1); + rAtom.setImplicitHydrogenCount(0); + + container.addAtom(rAtom); + container.addBond(atom.getBuilder() + .newInstance(IBond.class, atom, rAtom, Order.SINGLE)); + } + } + + private List partitionIntoGroups(final IAtomContainer sourceContainer, final int[] atomIdxToFGMap, + final int fGroupCount) { + final List groups = new ArrayList<>(fGroupCount); + for (int i = 0; i + < fGroupCount; i++) { + groups.add(sourceContainer.getBuilder() + .newInstance(IAtomContainer.class)); + } + + final Map atomtoFGMap = Maps.newHashMapWithExpectedSize(sourceContainer.getAtomCount()); + + // atoms + for (int atomIdx = 0; atomIdx + < sourceContainer.getAtomCount(); atomIdx++) { + final int fGroupId = atomIdxToFGMap[atomIdx]; + + if (fGroupId + == -1) { + continue; + } + + final IAtom atom = sourceContainer.getAtom(atomIdx); + final IAtomContainer myGroup = groups.get(fGroupId); + myGroup.addAtom(atom); + atomtoFGMap.put(atom, myGroup); + } + + // bonds + for (final IBond bond : sourceContainer.bonds()) { + final IAtomContainer beginGroup = atomtoFGMap.get(bond.getBegin()); + final IAtomContainer endGroup = atomtoFGMap.get(bond.getEnd()); + + if (beginGroup + == null + || endGroup + == null + || beginGroup + != endGroup) { + continue; + } + + beginGroup.addBond(bond); + } + + // single electrons + for (final ISingleElectron electron : sourceContainer.singleElectrons()) { + final IAtomContainer group = atomtoFGMap.get(electron.getAtom()); + if (group + != null) { + group.addSingleElectron(electron); + } + } + + // lone pairs + for (final ILonePair lonePair : sourceContainer.lonePairs()) { + final IAtomContainer group = atomtoFGMap.get(lonePair.getAtom()); + if (group + != null) { + group.addLonePair(lonePair); + } + } + + return groups; + } + + private boolean isDbg() { + return log.isDebugEnabled(); + } + + private boolean checkConstraints(final IAtomContainer molecule) { + for (final IAtom atom : molecule.atoms()) { + if (atom.getFormalCharge() + != null + && atom.getFormalCharge() + != 0) { + throw new IllegalArgumentException("Input molecule must not contain any charges."); + } + if (!this.isNonmetal(atom)) { + throw new IllegalArgumentException("Input molecule must not contain metals or metalloids."); + } + if (atom.getImplicitHydrogenCount() + == null) { + atom.setImplicitHydrogenCount(0); + } + } + + final ConnectedComponents cc = new ConnectedComponents(this.adjList); + if (cc.nComponents() + != 1) { + throw new IllegalArgumentException("Input molecule must consist of only a single connected stucture."); + } + + return true; + } + + /** + * Defines the working mode. + */ + public enum Mode { + /** + * Default mode including the generalization step. + */ + DEFAULT, + /** + * Skips the generalization step. Functional groups will keep their full "environment". + */ + NO_GENERALIZATION + } + + private enum EnvironmentCalCType {C_AROMATIC, C_ALIPHATIC} + + /** + * Describes one carbon atom in the environment of a marked atom. It can either be aromatic + * or aliphatic and also contains a clone of its connecting bond. + */ + private class EnvironmentalC { + private final EnvironmentCalCType type; + private final int bondIndex; + private final Order bondOrder; + private final IBond.Stereo bondStereo; + private final boolean[] bondFlags; + + public EnvironmentalC(final EnvironmentCalCType type, final IBond bond, final int indexInBond) { + this.type = type; + + this.bondIndex = indexInBond; + this.bondOrder = bond.getOrder(); + this.bondStereo = bond.getStereo(); + this.bondFlags = bond.getFlags(); + } + + public EnvironmentCalCType getType() { + return this.type; + } + + public IBond createBond(final IAtom targetAtom, final IAtom cAtom) { + final IBond bond = targetAtom.getBuilder() + .newInstance(IBond.class); + if (this.bondIndex + == 0) { + bond.setAtoms(new IAtom[]{cAtom, targetAtom}); + } else { + bond.setAtoms(new IAtom[]{targetAtom, cAtom}); + } + bond.setOrder(this.bondOrder); + bond.setStereo(this.bondStereo); + bond.setFlags(this.bondFlags); + + return bond; + } + } +} \ No newline at end of file diff --git a/src/casekit/nmr/fragments/functionalgroup/ErtlFunctionalGroupsUtilities.java b/src/casekit/nmr/fragments/functionalgroup/ErtlFunctionalGroupsUtilities.java new file mode 100644 index 0000000..bb5e9f6 --- /dev/null +++ b/src/casekit/nmr/fragments/functionalgroup/ErtlFunctionalGroupsUtilities.java @@ -0,0 +1,142 @@ +package casekit.nmr.fragments.functionalgroup; + +import casekit.nmr.fragments.fragmentation.Fragmentation; +import casekit.nmr.fragments.fragmentation.FragmentationUtilities; +import casekit.nmr.fragments.model.ConnectionTree; +import casekit.nmr.model.DataSet; +import casekit.nmr.utils.Utils; +import org.openscience.cdk.aromaticity.Aromaticity; +import org.openscience.cdk.aromaticity.ElectronDonation; +import org.openscience.cdk.exception.CDKException; +import org.openscience.cdk.graph.CycleFinder; +import org.openscience.cdk.graph.Cycles; +import org.openscience.cdk.interfaces.IAtom; +import org.openscience.cdk.interfaces.IAtomContainer; +import org.openscience.cdk.tools.manipulator.AtomContainerManipulator; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; + +public class ErtlFunctionalGroupsUtilities { + + public static final List buildFunctionalGroupDataSets(final List dataSetList, + final String[] nuclei) { + final List functionalGroupDataSets = new ArrayList<>(); + final ErtlFunctionalGroupsFinder ertlFunctionalGroupsFinder = new ErtlFunctionalGroupsFinder( + ErtlFunctionalGroupsFinder.Mode.NO_GENERALIZATION); + List subDataSetList; + List groups; + List fragmentTrees; + ConnectionTree fragmentTree; + IAtomContainer structure; + String atomTypeInSpectrum; + Aromaticity[] aromaticities; + for (final DataSet dataSet : dataSetList) { + structure = dataSet.getStructure() + .toAtomContainer(); + aromaticities = buildDefaultAromaticities(structure); + fragmentTrees = new ArrayList<>(); + for (final Aromaticity aromaticity : aromaticities) { + try { + Utils.setAromaticityAndKekulize(structure, aromaticity); + groups = ertlFunctionalGroupsFinder.find(structure, false); + } catch (final IllegalArgumentException | CDKException e) { + e.printStackTrace(); + continue; + } + restoreOriginalEnvironmentalCarbons(groups, structure); + fragmentTrees = new ArrayList<>(); + for (final IAtomContainer group : groups) { + // each group has to contain at least one atom of specific spectrum + atomTypeInSpectrum = casekit.nmr.utils.Utils.getAtomTypeFromNucleus(dataSet.getSpectrum() + .getNuclei()[0]); + if (atomTypeInSpectrum.equals("H")) { + if (AtomContainerManipulator.getImplicitHydrogenCount(group) + == 0) { + continue; + } + } else if (casekit.nmr.utils.Utils.getAtomTypeIndicesByElement(group, atomTypeInSpectrum) + .isEmpty()) { + continue; + } + fragmentTree = Fragmentation.buildFragmentTree(group, 0, null, new HashSet<>(), false); + FragmentationUtilities.adjustNodeKeys(fragmentTree, structure); + FragmentationUtilities.closeRings(fragmentTree, structure); + + fragmentTrees.add(fragmentTree); + } + } + FragmentationUtilities.removeDuplicates(fragmentTrees); + subDataSetList = Fragmentation.fragmentTreesToSubDataSets(dataSet, fragmentTrees); + if (subDataSetList + != null) { + functionalGroupDataSets.addAll(subDataSetList); + } + } + + return functionalGroupDataSets; + } + + /** + * Replaces the inserted environmental carbon atoms (new IAtom objects) by the + * carbon IAtom objects from original structure. + * + * @param groups groups created by ErtlFunctionalGroupFinder + * @param structure original structure used to create the groups + */ + private static void restoreOriginalEnvironmentalCarbons(final List groups, + final IAtomContainer structure) { + IAtomContainer group; + IAtom connectedAtomInGroup; + List atomList; + for (int i = 0; i + < groups.size(); i++) { + group = groups.get(i); + // convert explicit hydrogens back to implicit + casekit.nmr.utils.Utils.convertExplicitToImplicitHydrogens(group); + atomList = new ArrayList<>(); + // create a list (copy) of all atoms of the group because of atom removals and additions in group atom container + group.atoms() + .spliterator() + .forEachRemaining(atomList::add); + for (final IAtom atom : atomList) { + // detect whether the current atom is an "unknown" one, inserted as new environmental IAtom object + if (!structure.contains(atom)) { + // take its single parent from which should be in original + connectedAtomInGroup = group.getConnectedAtomsList(atom) + .get(0); + // remove the inserted atom and the bond to it + group.removeBond(atom, connectedAtomInGroup); + group.removeAtom(atom); + // from the parent node search for neighboring carbons which are not already in the group + // and add them + for (final IAtom connectedAtomInOriginalStructure : structure.getConnectedAtomsList( + connectedAtomInGroup)) { + if (connectedAtomInOriginalStructure.getSymbol() + .equals("C") + && !group.contains(connectedAtomInOriginalStructure)) { + group.addAtom(connectedAtomInOriginalStructure); + group.addBond(structure.getBond(connectedAtomInGroup, connectedAtomInOriginalStructure)); + } + } + } + } + } + } + + public static Aromaticity[] buildDefaultAromaticities(final IAtomContainer structure) { + final CycleFinder cycles = Cycles.all(structure.getAtomCount()); + final ElectronDonation[] models = new ElectronDonation[]{ElectronDonation.cdk(), + ElectronDonation.cdkAllowingExocyclic(), + ElectronDonation.daylight(), + ElectronDonation.piBonds()}; + final Aromaticity[] aromaticities = new Aromaticity[models.length]; + for (int i = 0; i + < models.length; i++) { + aromaticities[i] = new Aromaticity(models[i], cycles); + } + + return aromaticities; + } +} diff --git a/src/casekit/nmr/fragments/model/ConnectionTree.java b/src/casekit/nmr/fragments/model/ConnectionTree.java new file mode 100644 index 0000000..6731acc --- /dev/null +++ b/src/casekit/nmr/fragments/model/ConnectionTree.java @@ -0,0 +1,555 @@ +/* + * The MIT License + * + * Copyright (c) 2019 Michael Wenk [https://github.com/michaelwenk] + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package casekit.nmr.fragments.model; + +import casekit.nmr.hose.HOSECodeUtilities; +import org.openscience.cdk.interfaces.IAtom; +import org.openscience.cdk.interfaces.IBond; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * Represents a tree of connected atoms (nodes) of a molecule + * in a parent-child-relationship. + * + * @author Michael Wenk [https://github.com/michaelwenk] + * @see ConnectionTreeNode + */ +public class ConnectionTree { + private final ConnectionTreeNode root; + private final Set keySet; + private int maxSphere; + + public ConnectionTree(final IAtom rootAtom, final int key) { + this.root = new ConnectionTreeNode(rootAtom, key, 0, null, null); + this.keySet = new HashSet<>(); + this.keySet.add(this.root.getKey()); + this.maxSphere = 0; + } + + /** + * Checks whether two nodes form a ring closures in one connection tree. + * + * @param node1 first node + * @param node2 second node + * + * @return + */ + public static boolean nodesFormRingClosure(final ConnectionTreeNode node1, final ConnectionTreeNode node2) { + return ConnectionTree.hasRingClosureParent(node1, node2) + && ConnectionTree.hasRingClosureParent(node2, node1); + } + + public static boolean hasRingClosureParent(final ConnectionTreeNode node, + final ConnectionTreeNode ringClosureParentNode) { + for (final ConnectionTreeNode childNode : node.getChildNodes()) { + if (childNode.isRingClosureNode() + && (childNode.getRingClosureParent() + .getKey() + == ringClosureParentNode.getKey())) { + return true; + } + } + + return false; + } + + /** + * Checks whether a node is at a ring closures. + * + * @param node node to check + * + * @return + */ + public static boolean isAtRingClosure(final ConnectionTreeNode node) { + for (final ConnectionTreeNode childNode : node.getChildNodes()) { + if (childNode.isRingClosureNode()) { + return true; + } + } + return false; + } + + /** + * Returns a subtree of a given connection tree by using a given subtree root node. + * + * @param connectionTree connection tree + * @param rootNodeKey root node key for subtree to create + * + * @return + */ + public static ConnectionTree buildSubtree(final ConnectionTree connectionTree, final int rootNodeKey) { + if (!connectionTree.containsKey(rootNodeKey)) { + return null; + } + + final ConnectionTreeNode rootNode = connectionTree.getNode(rootNodeKey); + final ConnectionTree subtree = new ConnectionTree(rootNode.getAtom(), rootNode.getKey()); + + buildSubtree(subtree, rootNode, 1); + + return subtree; + } + + private static void buildSubtree(final ConnectionTree subtree, final ConnectionTreeNode parentNode, + final int sphere) { + int childNodeIndex = 0; + for (final ConnectionTreeNode childNode : parentNode.getChildNodes()) { + if (childNode.isRingClosureNode()) { + subtree.addRingClosureNode(parentNode.getKey(), childNode.getRingClosureParent() + .getKey(), childNode.getBondToParent()); + } else { + subtree.addNode(childNode.getAtom(), childNode.getKey(), parentNode.getKey(), + parentNode.getBondsToChildren() + .get(childNodeIndex)); + } + buildSubtree(subtree, childNode, sphere + + 1); + childNodeIndex++; + } + } + + public static boolean addSubtree(final ConnectionTree connectionTree, final int parentNodeKey, + final ConnectionTree subtree, final IBond bondToLink) { + if (!connectionTree.containsKey(parentNodeKey)) { + return false; + } + for (final int key : subtree.getKeys()) { + if (connectionTree.containsKey(key)) { + return false; + } + } + // check ring closure nodes in subtree whether their ring closure parents (on the other side) still exist + for (final ConnectionTreeNode node : subtree.getNodes(true)) { + if (node.isRingClosureNode() + && !subtree.containsKey(node.getRingClosureParent() + .getKey()) + // && !connectionTree.containsKey(node.getRingClosureParent() + // .getKey()) + ) { + if (node.getRingClosureParent() + != null) { + node.getRingClosureParent() + .setRingClosureParent(null); + } + node.getParent() + .removeChildNode(node); + } + } + + final ConnectionTreeNode parentNode = connectionTree.getNode(parentNodeKey); + for (final ConnectionTreeNode subtreeNode : subtree.getNodes(true)) { + if (subtreeNode + == subtree.getRootNode()) { + parentNode.addChildNode(subtree.getRootNode(), bondToLink); + subtree.getRootNode() + .setParent(parentNode); + subtree.getRootNode() + .setBondToParent(bondToLink); + connectionTree.addKey(subtree.getRootNode() + .getKey()); + subtree.getRootNode() + .setSphere(parentNode.getSphere() + + 1); + continue; + } + if (!subtreeNode.isRingClosureNode() + && !connectionTree.containsKey(subtreeNode.getKey())) { + connectionTree.addKey(subtreeNode.getKey()); + } else { + continue; + } + subtreeNode.setSphere(parentNode.getSphere() + + subtreeNode.getSphere() + + 1); + if (subtreeNode.getSphere() + > connectionTree.getMaxSphere(true)) { + connectionTree.maxSphere = subtreeNode.getSphere(); + } + } + + return true; + } + + public void initKeySet() { + this.keySet.clear(); + this.keySet.addAll(this.getNodes(false) + .stream() + .map(ConnectionTreeNode::getKey) + .collect(Collectors.toSet())); + } + + public boolean addKey(final int key) { + return this.keySet.add(key); + } + + public ConnectionTreeNode getRootNode() { + return this.root; + } + + public boolean addNode(final IAtom newNodeAtomData, final int newNodeKey, final int parentNodeKey, + final IBond bondToParent) { + if (this.containsKey(newNodeKey)) { + return false; + } + final ConnectionTreeNode parentNode = this.getNode(parentNodeKey); + this.addNode(new ConnectionTreeNode(newNodeAtomData, newNodeKey, parentNode.getSphere() + + 1, parentNode, bondToParent), parentNode); + + return true; + } + + public boolean addRingClosureNode(final int parentNodeKey, final int ringClosureParentNodeKey, + final IBond bondToParent) { + if (!this.containsKey(parentNodeKey) + || !this.containsKey(ringClosureParentNodeKey)) { + return false; + } + final ConnectionTreeNode parentNode = this.getNode(parentNodeKey); + this.addNode(new ConnectionTreeNode(this.getNode(ringClosureParentNodeKey), parentNode.getSphere() + + 1, parentNode, bondToParent), parentNode); + + return true; + } + + private void addNode(final ConnectionTreeNode newNode, final ConnectionTreeNode parentNode) { + parentNode.addChildNode(newNode, newNode.getBondToParent()); + + if (!newNode.isRingClosureNode()) { + this.keySet.add(newNode.getKey()); + } + if (newNode.getSphere() + > this.maxSphere) { + this.maxSphere = newNode.getSphere(); + } + } + + public int getMaxSphere(final boolean withRingClosureNodes) { + if (!withRingClosureNodes + && this.getNodesInSphere(this.maxSphere, false) + .isEmpty()) { + return this.maxSphere + - 1; + } + return this.maxSphere; + } + + public int getNodesCount(final boolean withRingClosureNodes) { + return this.getNodes(withRingClosureNodes) + .size(); + } + + public int getNodesCountInSphere(final int sphere, final boolean withRingClosureNodes) { + return this.getNodesInSphere(sphere, withRingClosureNodes) + .size(); + } + + public List getKeys() { + final List keys = new ArrayList<>(); + for (int s = 0; s + <= this.getMaxSphere(false); s++) { + for (final ConnectionTreeNode nodeInSphere : this.getNodesInSphere(s, false)) { + keys.add(nodeInSphere.getKey()); + } + } + + return keys; + } + + public List getNodes(final boolean withRingClosureNodes) { + final List nodes = new ArrayList<>(); + for (int s = 0; s + <= this.getMaxSphere(withRingClosureNodes); s++) { + nodes.addAll(this.getNodesInSphere(s, withRingClosureNodes)); + } + + return nodes; + } + + public boolean containsKey(final int key) { + return this.keySet.contains(key); + } + + public ConnectionTreeNode getNode(final int key) { + if (!this.containsKey(key)) { + return null; + } + + return this.findNode(key, this.root); + } + + private ConnectionTreeNode findNode(final int key, final ConnectionTreeNode currentNode) { + if (currentNode.isRingClosureNode()) { + return null; + } + if (currentNode.getKey() + == key) { + return currentNode; + } + ConnectionTreeNode result = null; + for (final ConnectionTreeNode childNode : currentNode.getChildNodes()) { + result = this.findNode(key, childNode); + if ((result + != null) + && (result.getKey() + == key)) { + break; + } + } + + return result; + } + + public int getNodeIndexInSphere(final ConnectionTreeNode node, final int sphere) { + + return this.getNodesInSphere(sphere, true) + .indexOf(node); + } + + public List getNodeKeysInSphere(final int sphere) { + final List keys = new ArrayList<>(); + for (final ConnectionTreeNode treeNode : this.getNodesInSphere(sphere, false)) { + if (!treeNode.isRingClosureNode()) { + keys.add(treeNode.getKey()); + } + } + + return keys; + } + + public List getNodesInSphere(final int sphere, final boolean withRingClosureNodes) { + final List nodesInSphere = this.findNodesInSphere(sphere, this.root, new ArrayList<>()); + if (withRingClosureNodes) { + return nodesInSphere; + } + // remove ring closure nodes + final List nodesInSphereToRemove = new ArrayList<>(); + for (final ConnectionTreeNode nodeInSphere : nodesInSphere) { + if (nodeInSphere.isRingClosureNode()) { + nodesInSphereToRemove.add(nodeInSphere); + } + } + nodesInSphere.removeAll(nodesInSphereToRemove); + + return nodesInSphere; + } + + private List findNodesInSphere(final int sphere, final ConnectionTreeNode currentNode, + final List indicesInSphere) { + if (currentNode.getSphere() + == sphere) { + indicesInSphere.add(currentNode); + return indicesInSphere; + } + for (final ConnectionTreeNode childNode : currentNode.getChildNodes()) { + this.findNodesInSphere(sphere, childNode, indicesInSphere); + } + + return indicesInSphere; + } + + public IBond getBond(final int nodeKey1, final int nodeKey2) { + if (!this.containsKey(nodeKey1) + || !this.containsKey(nodeKey2)) { + return null; + } + // node1 and node2 have parent-child-relationship + final ConnectionTreeNode node1 = this.getNode(nodeKey1); + for (final ConnectionTreeNode childNode : node1.getChildNodes()) { + if (!childNode.isRingClosureNode() + && (childNode.getKey() + == nodeKey2)) { + return childNode.getBondToParent(); + } + } + // if nodes form a ring closure + if (ConnectionTree.nodesFormRingClosure(node1, this.getNode(nodeKey2))) { + for (final ConnectionTreeNode childNode : node1.getChildNodes()) { + if (childNode.isRingClosureNode() + && (childNode.getRingClosureParent() + .getKey() + == nodeKey2)) { + return childNode.getBondToParent(); + } + } + } + + return null; + } + + public boolean hasParent(final int key, final int parentKey) { + if (!this.containsKey(key) + || !this.containsKey(parentKey)) { + return false; + } + + return this.getNode(key) + .getParent() + .getKey() + == parentKey; + } + + public boolean hasChild(final int key, final int childKey) { + if (!this.containsKey(key) + || !this.containsKey(childKey)) { + return false; + } + + return this.getNode(key) + .hasChild(childKey); + } + + public void removeNode(final int key) { + final ConnectionTreeNode node = this.getNode(key); + if (node + != null) { + final List children = new ArrayList<>(node.getChildNodes()); + for (final ConnectionTreeNode childNode : children) { + if (childNode.isRingClosureNode()) { + childNode.getRingClosureParent() + .removeChildNode(childNode); + } else { + this.removeNode(childNode.getKey()); + } + node.removeChildNode(childNode); + this.keySet.remove(childNode.getKey()); + } + final ConnectionTreeNode parent = node.getParent(); + if (parent + != null) { + parent.removeChildNode(node); + } + this.keySet.remove(node.getKey()); + } + } + + /** + * @param parentKey + * @param childKey1 + * @param childKey2 + * + * @return + */ + @Deprecated + public boolean swapChildNodes(final int parentKey, final int childKey1, final int childKey2) { + if (!this.containsKey(parentKey) + || !this.containsKey(childKey1) + || !this.containsKey(childKey2) + || !this.hasChild(parentKey, childKey1) + || !this.hasChild(parentKey, childKey2) + || !this.hasParent(childKey1, parentKey) + || !this.hasParent(childKey2, parentKey)) { + return false; + } + final ConnectionTreeNode parentNode = this.getNode(parentKey); + final ConnectionTreeNode childNode1 = this.getNode(childKey1); + final ConnectionTreeNode childNode2 = this.getNode(childKey2); + + final int indexChildNode1 = parentNode.getChildNodes() + .indexOf(childNode1); + final int indexChildNode2 = parentNode.getChildNodes() + .indexOf(childNode2); + Collections.swap(parentNode.getChildNodes(), indexChildNode1, indexChildNode2); + Collections.swap(parentNode.getBondsToChildren(), indexChildNode1, indexChildNode2); + + + return (parentNode.getChildNodes() + .indexOf(childNode1) + == indexChildNode2) + && (parentNode.getChildNodes() + .indexOf(childNode2) + == indexChildNode1); + } + + @Override + public String toString() { + final StringBuilder treeStringBuilder = new StringBuilder(); + for (int s = 0; s + <= this.maxSphere; s++) { + treeStringBuilder.append("[") + .append(s) + .append("]"); + for (final ConnectionTreeNode nodeInSphere : this.getNodesInSphere(s, true)) { + treeStringBuilder.append(" "); + if (nodeInSphere.isRingClosureNode()) { + treeStringBuilder.append("-") + .append(nodeInSphere.getParent() + .getKey()) + .append(": "); + } else { + treeStringBuilder.append(nodeInSphere.getKey()) + .append(": "); + } + if (nodeInSphere.hasAParent()) { + treeStringBuilder.append(HOSECodeUtilities.getSymbolForBond(nodeInSphere.getBondToParent())); + } + if (nodeInSphere.isRingClosureNode()) { + treeStringBuilder.append("&"); + } else { + treeStringBuilder.append(nodeInSphere.getAtom() + .getSymbol()); + } + if (s + > 0) { + treeStringBuilder.append(" ("); + treeStringBuilder.append(nodeInSphere.getParent() + .getKey()); + treeStringBuilder.append(") {"); + } else { + treeStringBuilder.append(" {"); + } + if (nodeInSphere.isRingClosureNode()) { + treeStringBuilder.append(nodeInSphere.getRingClosureParent() + .getKey()); + } else { + if (nodeInSphere.getChildNodes() + .size() + > 1) { + for (final ConnectionTreeNode childNode : nodeInSphere.getChildNodes()) { + if (childNode.isRingClosureNode()) { + treeStringBuilder.append("-") + .append(childNode.getRingClosureParent() + .getKey()) + .append(" "); + } else { + treeStringBuilder.append(childNode.getKey()) + .append(" "); + } + } + } else if (nodeInSphere.getChildNodes() + .size() + == 1) { + if (nodeInSphere.getChildNodes() + .get(0) + .isRingClosureNode()) { + treeStringBuilder.append("-") + .append(nodeInSphere.getChildNodes() + .get(0) + .getRingClosureParent() + .getKey()); + } else { + treeStringBuilder.append(nodeInSphere.getChildNodes() + .get(0) + .getKey()); + } + + } + } + + treeStringBuilder.append("} "); + } + } + + return treeStringBuilder.toString(); + } +} diff --git a/src/casekit/nmr/fragments/model/ConnectionTreeNode.java b/src/casekit/nmr/fragments/model/ConnectionTreeNode.java new file mode 100644 index 0000000..1ccd5f1 --- /dev/null +++ b/src/casekit/nmr/fragments/model/ConnectionTreeNode.java @@ -0,0 +1,235 @@ +/* + * The MIT License + * + * Copyright (c) 2019 Michael Wenk [https://github.com/michaelwenk] + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package casekit.nmr.fragments.model; + +import org.openscience.cdk.interfaces.IAtom; +import org.openscience.cdk.interfaces.IBond; + +import java.util.ArrayList; +import java.util.List; + +/** + * Represents a node in a connection tree {@link ConnectionTree}. + * + * @author Michael Wenk [https://github.com/michaelwenk] + */ +public class ConnectionTreeNode { + + private final List children; + private final List bondsToChildren; + private ConnectionTreeNode parent; + private IBond bondToParent; + private IAtom atom; + private Integer key; + private int sphere; + private boolean isRingClosure; + private ConnectionTreeNode ringClosureParent; + private boolean isPseudoNode; + + /** + * Pre-defined constructor for creating a non-ring closure node. + * + * @param atom + * @param key + * @param sphere + */ + public ConnectionTreeNode(final IAtom atom, final int key, final int sphere, final ConnectionTreeNode parent, + final IBond bondToParent) { + this.atom = atom; + this.key = key; + this.sphere = sphere; + this.parent = parent; + this.bondToParent = bondToParent; + this.children = new ArrayList<>(); + this.bondsToChildren = new ArrayList<>(); + this.isRingClosure = false; + this.isPseudoNode = false; + } + + /** + * Pre-defined constructor for creating a ring closure node. + * + * @param sphere + * @param ringClosurePartner + */ + public ConnectionTreeNode(final ConnectionTreeNode ringClosurePartner, final int sphere, + final ConnectionTreeNode parent, final IBond bondToParent) { + this.sphere = sphere; + this.parent = parent; + this.bondToParent = bondToParent; + this.children = new ArrayList<>(); + this.bondsToChildren = new ArrayList<>(); + this.isRingClosure = true; + this.ringClosureParent = ringClosurePartner; + this.isPseudoNode = false; + } + + public IAtom getAtom() { + return this.atom; + } + + public void setAtom(final IAtom atom) { + this.atom = atom; + } + + public ConnectionTreeNode getParent() { + return this.parent; + } + + public void setParent(final ConnectionTreeNode parent) { + this.parent = parent; + } + + public IBond getBondToParent() { + return this.bondToParent; + } + + public void setBondToParent(final IBond bondToParent) { + this.bondToParent = bondToParent; + } + + public List getChildNodes() { + return this.children; + } + + public List getBondsToChildren() { + return this.bondsToChildren; + } + + public Integer getKey() { + return this.key; + } + + public void setKey(final int key) { + this.key = key; + } + + public int getSphere() { + return this.sphere; + } + + public void setSphere(final int sphere) { + this.sphere = sphere; + } + + public void setIsRingClosureNode(final boolean isRingClosureNode) { + this.isRingClosure = isRingClosureNode; + } + + public boolean isRingClosureNode() { + return this.isRingClosure; + } + + public ConnectionTreeNode getRingClosureParent() { + return this.ringClosureParent; + } + + public void setRingClosureParent(final ConnectionTreeNode ringClosureParent) { + this.ringClosureParent = ringClosureParent; + } + + public void setIsPseudoNode(final boolean isPseudoNode) { + this.isPseudoNode = isPseudoNode; + } + + public boolean isPseudoNode() { + return this.isPseudoNode; + } + + public boolean addChildNode(final ConnectionTreeNode childNode, final IBond bondToChild) { + return this.addChildNode(childNode, bondToChild, this.getChildNodes() + .size()); + } + + public boolean addChildNode(final ConnectionTreeNode childNode, final IBond bondToChild, final int pos) { + if (!this.checkListIndex(this.getChildNodes() + .size(), pos)) { + return false; + } + this.getChildNodes() + .add(pos, childNode); + this.getBondsToChildren() + .add(pos, bondToChild); + + return true; + } + + private boolean checkListIndex(final int listLength, final int pos) { + return (pos + >= 0) + && (pos + <= listLength); + } + + public boolean removeChildNode(final ConnectionTreeNode childNode) { + final int indexOfChildNode = this.getChildNodes() + .indexOf(childNode); + if (indexOfChildNode + == -1) { + return false; + } + this.getChildNodes() + .remove(indexOfChildNode); + this.getBondsToChildren() + .remove(indexOfChildNode); + + return true; + } + + public boolean hasAParent() { + return this.parent + != null; + } + + public boolean hasChild(final int childKey) { + for (final ConnectionTreeNode childNode : this.children) { + if (!childNode.isRingClosureNode() + && (childNode.getKey() + == childKey)) { + return true; + } + } + + return false; + } + + public boolean hasChildren() { + return !this.children.isEmpty(); + } + + @Override + public String toString() { + return "ConnectionTreeNode{" + + "key=" + + this.key + + ", sphere=" + + this.sphere + + ", isRingClosure=" + + this.isRingClosure + + ", isPseudoNode=" + + this.isPseudoNode + + ", ..." + // + ", children=" + // + this.children + // + ", bondsToChildren=" + // + this.bondsToChildren + // + ", parent=" + // + this.parent + // + ", bondToParent=" + // + this.bondToParent + // + ", atom=" + // + this.atom + // + ", ringClosureParent=" + // + this.ringClosureParent + + '}'; + } +} diff --git a/src/casekit/nmr/hose/HOSECodeBuilder.java b/src/casekit/nmr/hose/HOSECodeBuilder.java new file mode 100644 index 0000000..f95fdcf --- /dev/null +++ b/src/casekit/nmr/hose/HOSECodeBuilder.java @@ -0,0 +1,582 @@ +/* + * The MIT License + * + * Copyright (c) 2019 Michael Wenk [https://github.com/michaelwenk] + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package casekit.nmr.hose; + + +import casekit.nmr.fragments.fragmentation.FragmentationUtilities; +import casekit.nmr.fragments.model.ConnectionTree; +import casekit.nmr.fragments.model.ConnectionTreeNode; +import org.openscience.cdk.exception.CDKException; +import org.openscience.cdk.interfaces.IAtom; +import org.openscience.cdk.interfaces.IAtomContainer; +import org.openscience.cdk.interfaces.IBond; +import org.openscience.cdk.silent.Atom; +import org.openscience.cdk.silent.SilentChemObjectBuilder; + +import java.util.*; + +/** + * Class to build HOSE code strings from molecules and vice versa + * by using connection trees as intermediate forms. + * + * @author Michael Wenk [https://github.com/michaelwenk] + */ +public class HOSECodeBuilder { + + /** + * Creates a partial sphere string content from the children of a given parent node. + * + * @param nodeInPrevSphere parent node to create a partial sphere string content from + * @param useBremserElementNotation whether to use Bremser notation + * + * @return + * + * @throws CDKException + */ + private static List buildPositionsInSphere(final ConnectionTreeNode nodeInPrevSphere, + final boolean useBremserElementNotation) throws CDKException { + final List nodesInSphere = nodeInPrevSphere.getChildNodes(); + final List positionsInSphere = new ArrayList<>(); + ConnectionTreeNode nodeInSphere; + IBond bond; + String position; + for (int j = 0; j + < nodesInSphere.size(); j++) { + nodeInSphere = nodesInSphere.get(j); + bond = nodeInPrevSphere.getBondsToChildren() + .get(j); + position = ""; + if (HOSECodeUtilities.getSymbolForBond(bond) + == null) { + throw new CDKException(Thread.currentThread() + .getStackTrace()[1].getMethodName() + + ": no bond information"); + } + position += HOSECodeUtilities.getSymbolForBond(bond); + if (nodeInSphere.isRingClosureNode()) { + position += "&"; + } else { + if (useBremserElementNotation) { + position += HOSECodeUtilities.toHOSECodeSymbol(nodeInSphere.getAtom() + .getSymbol()); + } else { + position += nodeInSphere.getAtom() + .getSymbol(); + } + // if(nodeInSphere.getAtom().getImplicitHydrogenCount() != null){ + // position += "[" + nodeInSphere.getAtom().getImplicitHydrogenCount() + "]"; + // } + position += buildFormalChargeCode(nodeInSphere.getAtom()); + } + positionsInSphere.add(position); + } + + return positionsInSphere; + } + + /** + * Builds the content of a sphere of the HOSE code which is to generate. + * + * @param connectionTree connection tree to use + * @param sphere sphere to selected from connection tree + * @param delimiter sphere's delimiter + * @param useBremserElementNotation whether to use Bremser notation + * + * @return + * + * @throws CDKException + */ + private static String buildSphereString(final ConnectionTree connectionTree, final int sphere, + final String delimiter, + final boolean useBremserElementNotation) throws CDKException { + StringBuilder sphereString = new StringBuilder(); + final List nodesInPrevSphere = connectionTree.getNodesInSphere(sphere + - 1, true); + ConnectionTreeNode nodeInPrevSphere; + // for all nodes in previous sphere + for (int i = 0; i + < nodesInPrevSphere.size(); i++) { + nodeInPrevSphere = nodesInPrevSphere.get(i); + // skip ring closure nodes + if (nodeInPrevSphere.isRingClosureNode()) { + if ((i + == nodesInPrevSphere.size() + - 1) + && sphereString.toString() + .endsWith(",")) { + sphereString = new StringBuilder(sphereString.substring(0, sphereString.length() + - 1)); + } + continue; + } + // for all child nodes in the requested sphere + if (nodeInPrevSphere.hasChildren()) { + for (final String position : buildPositionsInSphere(nodeInPrevSphere, useBremserElementNotation)) { + sphereString.append(position); + } + } + // add delimiter + if (i + < nodesInPrevSphere.size() + - 1) { + sphereString.append(delimiter); + } + } + + return sphereString.toString(); + } + + private static String buildFormalChargeCode(final IAtom atom) { + if ((atom + == null) + || (atom.getFormalCharge() + == null) + || (atom.getFormalCharge() + == 0)) { + return ""; + } + final String sign = atom.getFormalCharge() + < 0 + ? "-" + : "+"; + + return Math.abs(atom.getFormalCharge()) + == 1 + ? sign + : "'" + + sign + + Math.abs(atom.getFormalCharge()) + + "'"; + } + + /** + * Actual function to build a HOSE code. + * + * @param connectionTree connection tree to use + * @param useBremserElementNotation whether to use Bremser notation + * + * @return + * + * @throws CDKException + */ + private static String buildHOSECodeString(final ConnectionTree connectionTree, + final boolean useBremserElementNotation) throws CDKException { + final IAtom rootAtom = connectionTree.getRootNode() + .getAtom(); + final int maxSphere = connectionTree.getMaxSphere(true); + // zeroth sphere + final StringBuilder HOSECode = new StringBuilder(rootAtom.getSymbol() + + "-" + + (rootAtom.getBondCount() + + (rootAtom.getImplicitHydrogenCount() + == null + ? 0 + : rootAtom.getImplicitHydrogenCount())) + + buildFormalChargeCode(rootAtom)); + HOSECode.append(";"); + String delimiter; + // go through each sphere of the connection tree + for (int s = 1; s + <= maxSphere; s++) { + if (s + == 1) { + delimiter = ""; + } else { + delimiter = ","; + } + // create sphere string and add it to HOSE code string + HOSECode.append(buildSphereString(connectionTree, s, delimiter, useBremserElementNotation)); + if (s + == 1) { + HOSECode.append("("); + } + if (s + > 1 + && s + < maxSphere) { + HOSECode.append("/"); + } + } + if (maxSphere + == 0) { + HOSECode.append("("); + } + HOSECode.append(")"); + + return HOSECode.toString(); + } + + public static String buildHOSECode(final ConnectionTree connectionTree, + final boolean useBremserElementNotation) throws CDKException { + return buildHOSECodeString(connectionTree, useBremserElementNotation); + } + + public static String buildHOSECode(final IAtomContainer ac, final int rootAtomIndex, final Integer maxSphere, + final boolean useBremserElementNotation) throws CDKException { + return HOSECodeBuilder.buildHOSECode(HOSECodeBuilder.buildConnectionTree(ac, rootAtomIndex, maxSphere), + useBremserElementNotation); + } + + /** + * Builds a connection tree of an atom container with specific start atom + * and maximum number of spheres. + * If the atoms in the atom container are not fully connected, then the + * connection tree will be built until the last atom of all connected atoms + * to the start atom is reached. + * + * @param ac atom container + * @param rootAtomIndex starting atom + * @param maxSphere if this is set to null, then the connection tree of whole + * structure will be created + * + * @return + * + * @see ConnectionTree + */ + public static ConnectionTree buildConnectionTree(final IAtomContainer ac, final int rootAtomIndex, + final Integer maxSphere) { + return HOSECodeBuilder.buildConnectionTree(ac, rootAtomIndex, maxSphere, new HashSet<>()); + } + + /** + * Builds a connection tree of an atom container with specific start atom + * and maximum number of spheres. + * If the atoms in the atom container are not fully connected, then the + * connection tree will be built until the last atom of all connected atoms + * to the start atom is reached. + * + * @param ac atom container + * @param rootAtomIndex starting atom + * @param maxSphere if this is set to null, then the connection tree of whole + * structure will be created + * @param visited certain atom indices can be given here to ignore atoms + * in BFS; they are then seen as already visited and not included in + * the connection tree + * + * @return + * + * @see ConnectionTree + */ + public static ConnectionTree buildConnectionTree(final IAtomContainer ac, final int rootAtomIndex, + final Integer maxSphere, final Set visited) { + // create queue for BFS and add root atom index + final Queue queue = new LinkedList<>(); + queue.add(rootAtomIndex); + final ConnectionTree connectionTree = new ConnectionTree(ac.getAtom(rootAtomIndex), rootAtomIndex); + BFS(ac, connectionTree, queue, new HashSet<>(visited), maxSphere); + + HOSECodeUtilities.rankChildNodes(connectionTree); + + return connectionTree; + } + + /** + * Builds a connection tree from a given HOSE code.
+ * IMPORTANT: At the moment, ring closures can not be restored + * from an HOSE code because of ambiguities. + * So only a structural skeleton will be generated. + * + * @param HOSECode HOSE code + * @param useBremserElementNotation whether given HOSE code contains Bremser notation + * + * @return + * + * @throws CDKException + */ + public static ConnectionTree buildConnectionTree(final String HOSECode, + final boolean useBremserElementNotation) throws CDKException { + final Map> ringClosures = new HashMap<>(); + final List sphereStrings = HOSECodeUtilities.splitHOSECodeIntoSpheres(HOSECode); + IAtom atom; + IBond bond; + final int maxSphere; + String bondTypeString, atomTypeString, childElementCore; + Map> positionsInSphere; + ConnectionTreeNode parentNodeInPrevSphere; + // set maxSphere + maxSphere = sphereStrings.size() + - 1; + // zeroth sphere + positionsInSphere = HOSECodeUtilities.splitHOSECodeSphereIntoPositions(sphereStrings.get(0), true); + // create root atom + atom = new Atom(positionsInSphere.get(0) + .get(0)); + // add charge to root atom + atom.setFormalCharge(Integer.parseInt(positionsInSphere.get(0) + .get(1))); + final ConnectionTree connectionTree = new ConnectionTree(atom, 0); + // higher spheres + for (int sphere = 1; sphere + <= maxSphere; sphere++) { + // get positions (sections separated by comma) of current sphere + positionsInSphere = HOSECodeUtilities.splitHOSECodeSphereIntoPositions(sphereStrings.get(sphere), false); + // for all positions + for (final int positionIndex : positionsInSphere.keySet()) { + // for each child elements (symbols) in position + for (final String childElement : positionsInSphere.get(positionIndex)) { + // ignore children containing null value from previous nodes; previous node has no further (unvisited in BFS) connected atoms + if (childElement + == null) { + continue; + } + bondTypeString = ""; + atomTypeString = ""; + childElementCore = childElement; + childElementCore = childElementCore.replace("+", ""); + childElementCore = childElementCore.replace("-", ""); + childElementCore = childElementCore.replaceAll("\\d", ""); + // add new node and set bond to parent node or set a ring closure + if (childElementCore.contains("&")) { // ring closure + if (childElementCore.length() + == 2) { + bondTypeString = String.valueOf(childElementCore.charAt(0)); + } + // the parent node/atom in previous sphere and its key we already have of a ring closure; + // the bond information we already have too (see below) + parentNodeInPrevSphere = connectionTree.getNodesInSphere(sphere + - 1, true) + .get(positionIndex); + + if (!ringClosures.containsKey(sphere)) { + ringClosures.put(sphere, new ArrayList<>()); + } + bond = SilentChemObjectBuilder.getInstance() + .newBond(); + bond.setOrder(HOSECodeUtilities.getBondOrderForSymbol(bondTypeString)); + if (bondTypeString.equals("*")) { + bond.setIsInRing(true); + bond.setIsAromatic(true); + } else { + bond.setIsAromatic(false); + } + // store the ring closures and use them after looking at the HOSE code string + ringClosures.get(sphere) + .add(new Object[]{parentNodeInPrevSphere, bond}); + + + // // check whether the node in previous sphere is already involved in a ring closure; that should be not valid + // if(ConnectionTree.isAtRingClosure(parentNodeInPrevSphere)){ + // continue; + // } + // + // // TODO: what we still not can detect for sure is the correct second node/atom of a ring closure + // ConnectionTreeNode parentNodeInSphere = null; // null is just a dummy value and should be replaced by the correct ConnectionTreeNode object + // + // // TODO: check that the detected node in sphere is not null; could be removed after the implementation of detection of that node + // if(parentNodeInSphere == null){ + // continue; + // } + // // after that both node detections, check if that ring closure was already set beforehand by the reversed node order case + // if(ConnectionTree.nodesFormRingClosure(parentNodeInPrevSphere, parentNodeInSphere)){ + // continue; + // } + // // otherwise build a new bond and fill it with + // bond = SilentChemObjectBuilder.getInstance().newBond(); + // bond.setAtom(parentNodeInPrevSphere.getAtom(), 0); + // bond.setAtom(parentNodeInSphere.getAtom(), 1); + // bond.setOrder(HOSECodeUtilities.getBondOrderForSymbol(bondTypeString)); + // if (bondTypeString.equals("*")) { + // bond.setIsAromatic(true); + // } else { + // bond.setIsAromatic(false); + // } + // // set parent nodes as parents to each other, that one can detect them as ring closure afterwards + // parentNodeInPrevSphere.addParentNode(parentNodeInSphere, bond); + // connectionTree.addNode(null, -1 * parentNodeInPrevSphere.getKey(), parentNodeInPrevSphere.getKey(), bond, sphere + 1, true); + // parentNodeInSphere.addParentNode(parentNodeInPrevSphere, bond); + // connectionTree.addNode(null, -1 * parentNodeInSphere.getKey(), parentNodeInSphere.getKey(), bond, sphere + 1, true); + + } else if (HOSECodeUtilities.countAtoms(childElementCore) + == 1) { // each position contains either ring closures (&) or one element (e.g. C, Br), plus the bond information + if (childElementCore.length() + == 3) { // in case of bond type and an element with two letters, e.g. *Cl or =Br + bondTypeString = String.valueOf(childElementCore.charAt(0)); + atomTypeString = String.valueOf(childElementCore.charAt(1)); + atomTypeString += String.valueOf(childElementCore.charAt(2)); + } else if (childElementCore.length() + == 2) { // in case of bond type and an element with one letter or an element with two letters, e.g. Cl or =N + if (Character.isLetter(childElementCore.charAt(0))) { + atomTypeString = String.valueOf(childElementCore.charAt(0)); + } else { + bondTypeString = String.valueOf(childElementCore.charAt(0)); + } + atomTypeString += String.valueOf(childElementCore.charAt(1)); + } else if (childElementCore.length() + == 1) { // in case of an element with only one letter + atomTypeString = String.valueOf(childElementCore.charAt(0)); + } + // there has to be some information (at least an element) + if (atomTypeString.isEmpty()) { + throw new CDKException(Thread.currentThread() + .getStackTrace()[1].getMethodName() + + ": no atom information in child element"); + } + // otherwise set a new bond + bond = SilentChemObjectBuilder.getInstance() + .newBond(); + if (useBremserElementNotation) { + atomTypeString = HOSECodeUtilities.toElementSymbol(atomTypeString); + } + atom = new Atom(atomTypeString); + bond.setAtom(atom, 0); + bond.setAtom(connectionTree.getNodesInSphere(sphere + - 1, true) + .get(positionIndex) + .getAtom(), 1); + bond.setOrder(HOSECodeUtilities.getBondOrderForSymbol(bondTypeString)); + bond.setIsAromatic(bondTypeString.equals("*")); + // set formal charge to atom + if (childElement.contains("-")) { + final String[] splitAtSign = childElement.split("-"); + if (splitAtSign.length + == 1) { + atom.setFormalCharge(-1); + } else { + atom.setFormalCharge(-1 + * Integer.parseInt(splitAtSign[1])); + } + } + if (childElement.contains("+")) { + final String[] splitAtSign = childElement.split("\\+"); + if (splitAtSign.length + == 1) { + atom.setFormalCharge(1); + } else { + atom.setFormalCharge(Integer.parseInt(splitAtSign[1])); + } + } + // create a new node with the new build bond information to its parent node in the connection tree + connectionTree.addNode(atom, connectionTree.getNodesCount(false), + connectionTree.getNodesInSphere(sphere + - 1, true) + .get(positionIndex) + .getKey(), bond); + } else { + throw new CDKException(Thread.currentThread() + .getStackTrace()[1].getMethodName() + + ": no valid components in child element"); + } + } + } + } + + // @TODO after storing the ring closures, try to close the rings + // System.out.println(" -> spheres count with ring closures: " + ringClosures.size()); + // for (final int sphere : ringClosures.keySet()){ + // System.out.println(" -> number of ring closures in sphere: " + sphere + " -> " + ringClosures.get(sphere).size()); + // } + + HOSECodeUtilities.rankChildNodes(connectionTree); + + return connectionTree; + } + + /** + * Function for extending a given connection tree only containing + * its root node (0th sphere) by means of Breadth-First-Search (BFS). + * Until a certain maximum sphere, each reachable next neighbor atom + * is stored in a parent-child-relationship. + * + * @param ac atom container to go through + * @param connectionTree connection tree to expand, incl. the root node + * @param queue queue to use containing the atom index of the root node + * @param visited optional: atom indices which are already "visited" and + * should be ignored + * @param maxSphere maximum number of spheres for connection tree extension + */ + private static void BFS(final IAtomContainer ac, final ConnectionTree connectionTree, final Queue queue, + final Set visited, final Integer maxSphere) { + // all nodes visited? + if (queue.isEmpty()) { + return; + } + final int atomIndex = queue.remove(); + final IAtom atom = ac.getAtom(atomIndex); + final ConnectionTreeNode node = connectionTree.getNode(atomIndex); + final int sphere = node.getSphere(); + // check whether the current sphere is to high, if maxSphere parameter is set + if ((maxSphere + != null) + && (sphere + > maxSphere)) { + return; + } + // mark atom as visited + visited.add(atomIndex); + + IBond bond; + ConnectionTreeNode connectedAtomNode; + if ((maxSphere + != null) + && (sphere + == maxSphere)) { + // set connections (parent nodes) in last sphere nodes which have to be connected -> ring closures + // only parent nodes will be set to detect those ring closures again + for (final ConnectionTreeNode nodeInLastSphere : connectionTree.getNodesInSphere(maxSphere, false)) { + if ((ac.getBond(atom, nodeInLastSphere.getAtom()) + != null) + && !ConnectionTree.hasRingClosureParent(node, nodeInLastSphere) + && !ConnectionTree.hasRingClosureParent(nodeInLastSphere, node)) { + bond = ac.getBond(node.getAtom(), nodeInLastSphere.getAtom()); + connectionTree.addRingClosureNode(node.getKey(), nodeInLastSphere.getKey(), bond); + connectionTree.addRingClosureNode(nodeInLastSphere.getKey(), node.getKey(), bond); + } + } + } else { + // add nodes and bonds in lower spheres + // go to all child nodes + int connectedAtomIndex; + for (final IAtom connectedAtom : ac.getConnectedAtomsList(atom)) { + connectedAtomIndex = ac.indexOf(connectedAtom); + bond = ac.getBond(atom, connectedAtom); + // add children to queue if not already visited + if (!visited.contains(connectedAtomIndex)) { + // and not already waiting in queue + if (!queue.contains(connectedAtomIndex)) { + queue.add(connectedAtomIndex); + connectionTree.addNode(connectedAtom, connectedAtomIndex, node.getKey(), bond); + } else { + // node already exists in tree; add a further parent to connected atom (for ring closures) + connectedAtomNode = connectionTree.getNode(connectedAtomIndex); + if (!ConnectionTree.hasRingClosureParent(node, connectedAtomNode) + && !ConnectionTree.hasRingClosureParent(connectedAtomNode, node)) { + connectionTree.addRingClosureNode(connectedAtomIndex, node.getKey(), bond); + connectionTree.addRingClosureNode(node.getKey(), connectedAtomIndex, bond); + } + + } + } + } + } + // further extension of connectivity tree + BFS(ac, connectionTree, queue, visited, maxSphere); + } + + /** + * Reconstructs a structure from a given HOSE code string.
+ * IMPORTANT: Ring closures are not restored, see + * {@link #buildConnectionTree(String, boolean)}. + * + * @param HOSECode HOSE code + * @param useBremserElementNotation whether the HOSE code includes Bremser notation + * + * @return IAtomContainer + * + * @see #buildConnectionTree(String, boolean) + * @see FragmentationUtilities#toAtomContainer(ConnectionTree) + */ + public static IAtomContainer buildAtomContainer(final String HOSECode, + final boolean useBremserElementNotation) throws CDKException { + return FragmentationUtilities.toAtomContainer( + HOSECodeBuilder.buildConnectionTree(HOSECode, useBremserElementNotation)); + } +} \ No newline at end of file diff --git a/src/casekit/nmr/hose/HOSECodeUtilities.java b/src/casekit/nmr/hose/HOSECodeUtilities.java new file mode 100644 index 0000000..9165324 --- /dev/null +++ b/src/casekit/nmr/hose/HOSECodeUtilities.java @@ -0,0 +1,526 @@ +/* + * The MIT License + * + * Copyright (c) 2019 Michael Wenk [https://github.com/michaelwenk] + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package casekit.nmr.hose; + +import casekit.nmr.fragments.model.ConnectionTree; +import casekit.nmr.fragments.model.ConnectionTreeNode; +import org.openscience.cdk.interfaces.IBond; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class HOSECodeUtilities { + + /** + * Returns the summed subtree weight starting at a specific node in a connection + * tree. The weight of starting node is included here. + * + * @param node node to start und calculate the weight for + * + * @return + */ + public static int calculateSubtreeWeight(final ConnectionTreeNode node) { + return getSubtreeWeight(node, null); + } + + /** + * Returns the summed subtree weight starting at a specific node in a connection + * tree. The weight of starting node and the weight of bond to its given parent + * node is included here. + * + * @param node + * @param parentNode + * + * @return + */ + private static int getSubtreeWeight(final ConnectionTreeNode node, final ConnectionTreeNode parentNode) { + int weight = getNodeWeight(node, parentNode); + for (final ConnectionTreeNode childNode : node.getChildNodes()) { + weight += getSubtreeWeight(childNode, node); + } + + return weight; + } + + /** + * Returns the weight for a node and its connection to a parent node + * (optional). + * + * @param node node to get the weight from + * @param parentNode parent node of node or null + * + * @return the priority weight for node; plus the weight of + * the bond to its parent node if the parent node is not null + * + * @see HOSECodeUtilities#getSymbolPriorityWeight(String) + */ + public static Integer getNodeWeight(final ConnectionTreeNode node, final ConnectionTreeNode parentNode) { + int weight = 0; + if (parentNode + != null) { + final String bondSymbol = getSymbolForBond(node.getBondToParent()); + if (bondSymbol + == null) { + return null; + } + // add weight for bond type priority + if (!bondSymbol.isEmpty()) { + weight += getSymbolPriorityWeight(bondSymbol); + } + + } + // add weight for further symbol priority + if (node.isRingClosureNode()) { + weight += getSymbolPriorityWeight("&"); + } else { + weight += getSymbolPriorityWeight(node.getAtom() + .getSymbol()); + } + + return weight; + } + + /** + * Returns an ArrayList of ranked child node indices for a tree node. + * + * @param node node to rank the children + * + * @return + * + * @see #getNodeWeight(ConnectionTreeNode, ConnectionTreeNode) + */ + private static List getRankedChildNodesIndices(final ConnectionTreeNode node) { + final List childNodes = node.getChildNodes(); + final List rankedChildNodesIndices = new ArrayList<>(); + for (int i = 0; i + < childNodes.size(); i++) { + rankedChildNodesIndices.add(i); + } + rankedChildNodesIndices.sort((childNodeIndex1, childNodeIndex2) -> { + final int nodeWeightsComp = -1 + * Integer.compare(getNodeWeight(childNodes.get(childNodeIndex1), node), + getNodeWeight(childNodes.get(childNodeIndex2), node)); + if (nodeWeightsComp + != 0) { + return nodeWeightsComp; + } + return -1 + * Integer.compare(calculateSubtreeWeight(childNodes.get(childNodeIndex1)), + calculateSubtreeWeight(childNodes.get(childNodeIndex2))); + }); + + return rankedChildNodesIndices; + } + + /** + * Sorts the child nodes of a node by HOSE code priority and weight. + * + * @param node node with child nodes to rank + * + * @see #getNodeWeight(ConnectionTreeNode, ConnectionTreeNode) + */ + private static void rankChildNodes(final ConnectionTreeNode node) { + final List rankedChildNodesIndices = getRankedChildNodesIndices(node); + final List rankedChildNodes = new ArrayList<>(); + final List rankedChildNodeBonds = new ArrayList<>(); + for (int i = 0; i + < rankedChildNodesIndices.size(); i++) { + rankedChildNodes.add(node.getChildNodes() + .get(rankedChildNodesIndices.get(i))); + rankedChildNodeBonds.add(node.getBondsToChildren() + .get(rankedChildNodesIndices.get(i))); + } + node.getChildNodes() + .clear(); + node.getBondsToChildren() + .clear(); + node.getChildNodes() + .addAll(rankedChildNodes); + node.getBondsToChildren() + .addAll(rankedChildNodeBonds); + } + + /** + * Sorts the child nodes of each node in the connection tree by HOSE code + * priority and weight. + * + * @param connectionTree connection tree where to rank the child nodes of + * each node. + * + * @see #rankChildNodes(ConnectionTreeNode) + */ + public static void rankChildNodes(final ConnectionTree connectionTree) { + List nodesInSphere; + for (int sphere = 0; sphere + < connectionTree.getMaxSphere(true); sphere++) { + nodesInSphere = connectionTree.getNodesInSphere(sphere, true); + // for all nodes in sphere + for (int i = 0; i + < nodesInSphere.size(); i++) { + // findHits all child nodes of that node + if (nodesInSphere.get(i) + .hasChildren()) { + rankChildNodes(nodesInSphere.get(i)); + } + } + } + } + + /** + * Returns the number of non-empty spheres. + * For example: C-3;() -> 1, C-3;=N(C/) -> 3 + * + * @param HOSECode + * + * @return + */ + public static int getSpheresCount(final String HOSECode) { + int spheresCount = 0; + for (final String sphere : splitHOSECodeIntoSpheres(HOSECode)) { + if (!sphere.trim() + .isEmpty()) { + spheresCount++; + } + } + return spheresCount; + } + + /** + * Splits a HOSE code into a list of spheres as strings. + * + * @param HOSECode HOSE code + * + * @return ArrayList of all sphere strings + */ + public static List splitHOSECodeIntoSpheres(final String HOSECode) { + final List HOSECodeSpheres = new ArrayList<>(); + final String[] splitSpheres_0_1 = HOSECode.split(";"); + final String[] splitSpheres_1_2 = splitSpheres_0_1[1].split("\\("); + final String[] splitSpheres_2_n = splitSpheres_1_2[1].substring(0, splitSpheres_1_2[1].length() + - 1) + .split("/"); + HOSECodeSpheres.add(splitSpheres_0_1[0]); + HOSECodeSpheres.add(splitSpheres_1_2[0]); + for (int s = 0; s + < splitSpheres_2_n.length; s++) { + HOSECodeSpheres.add(splitSpheres_2_n[s]); + } + + return HOSECodeSpheres; + } + + /** + * Splits a HOSE code sphere into its positions. Each position includes all + * its elements. + * Example: {@code /CC,*N&,C/} results in: {@code {0: [C,C], 1: [*N,&], 2: [C]}} + * + * @param HOSECodeSphere HOSE code sphere + * @param isCenterSphere whether center (zeroth) sphere is given + * + * @return HashMap of ArrayLists containing elements for each position of that HOSE code sphere + */ + public static Map> splitHOSECodeSphereIntoPositions(final String HOSECodeSphere, + final boolean isCenterSphere) { + final Map> positions = new HashMap<>(); + // zeroth sphere + if (isCenterSphere) { + positions.put(0, new ArrayList<>()); + // add element + positions.get(0) + .add(HOSECodeSphere.split("-")[0]); + // zeroth sphere contains charges + if (HOSECodeSphere.endsWith("-")) { // add negative formal charge with value 1 + positions.get(0) + .add("-1"); + } else if (HOSECodeSphere.endsWith("+")) {// add positive formal charge with value 1 + positions.get(0) + .add("1"); + } else if (HOSECodeSphere.endsWith("'")) { // add formal charge with a higher value + positions.get(0) + .add(HOSECodeSphere.split("'")[1]); + } else { + positions.get(0) + .add("0"); + } + + return positions; + } + // higher spheres + char c; + StringBuilder elem = new StringBuilder(); + int positionCounter = 0; + boolean formalChargeDetected = false; + for (int i = 0; i + < HOSECodeSphere.length(); i++) { + c = HOSECodeSphere.charAt(i); + if ((c + == '=') + || (c + == '%') + || (c + == '*')) { + if (elem.length() + > 0) { + if (!positions.containsKey(positionCounter)) { + positions.put(positionCounter, new ArrayList<>()); + } + positions.get(positionCounter) + .add(elem.toString()); + elem = new StringBuilder(); + } + elem.append(c); + } else if (Character.isUpperCase(c) + || (c + == '&')) { + if ((elem.length() + > 0) + && (Character.isLetter(elem.charAt(elem.length() + - 1)) + || (elem.charAt(elem.length() + - 1) + == '&'))) { + if (!positions.containsKey(positionCounter)) { + positions.put(positionCounter, new ArrayList<>()); + } + positions.get(positionCounter) + .add(elem.toString()); + elem = new StringBuilder(); + elem.append(c); + } else if (formalChargeDetected) { + if (!positions.containsKey(positionCounter)) { + positions.put(positionCounter, new ArrayList<>()); + } + positions.get(positionCounter) + .add(elem.toString()); + elem = new StringBuilder(); + elem.append(c); + formalChargeDetected = false; + } else { + elem.append(c); + } + } else if (Character.isLowerCase(c)) { + elem.append(c); + } else if ((c + == '-') + || (c + == '+') + || Character.isDigit(c)) { + elem.append(c); + formalChargeDetected = true; + } else if (c + == ',') { + if (!positions.containsKey(positionCounter)) { + positions.put(positionCounter, new ArrayList<>()); + } + if (elem.length() + == 0) { + positions.get(positionCounter) + .add(null); + } else { + positions.get(positionCounter) + .add(elem.toString()); + elem = new StringBuilder(); + } + positionCounter++; + formalChargeDetected = false; + } + } + // add last element + if (elem.length() + > 0) { + if (!positions.containsKey(positionCounter)) { + positions.put(positionCounter, new ArrayList<>()); + } + positions.get(positionCounter) + .add(elem.toString()); + } else if (HOSECodeSphere.endsWith(",")) { + if (!positions.containsKey(positionCounter)) { + positions.put(positionCounter, new ArrayList<>()); + } + positions.get(positionCounter) + .add(null); + } + + return positions; + } + + /** + * Counts the number of occurring atoms within a given HOSE code. + * + * @param HOSECode HOSE code to analyse + * + * @return number of atoms within HOSE code + */ + public static int countAtoms(final String HOSECode) { + int counter = 0; + for (int k = 0; k + < HOSECode.length(); k++) { + // Check for uppercase letters + if (Character.isLetter(HOSECode.charAt(k)) + && Character.isUpperCase(HOSECode.charAt(k))) { + counter++; + } + } + + return counter; + } + + /** + * Returns the weight/cost for an HOSE code symbol regarding its priority. + * + * @param symbol HOSE code symbol + * + * @return weight/cost for the symbol + */ + public static int getSymbolPriorityWeight(final String symbol) { + switch (symbol) { + case "%": + return 15; + case "=": + return 14; + case "*": + return 13; + case "C": + return 12; + case "O": + return 11; + case "N": + return 10; + case "S": + return 9; + case "P": + return 8; + case "Si": + case "Q": + return 7; + case "B": + return 6; + case "F": + return 5; + case "Cl": + case "X": + return 4; + case "Br": + case "Y": + return 3; + case "I": + return 2; + case "&": + return 1; + case "H": + return 0; + default: + return 0; + } + } + + /** + * Converts an element symbol into notation as shown in origin article by + * Bremser. + * That includes: Si -> Q, Cl -> X, Br -> Y + * + * @param element + * + * @return HOSE code symbol as in origin article by Bremser + */ + public static String toHOSECodeSymbol(final String element) { + if (element.equals("Si")) { + return "Q"; + } + if (element.equals("Cl")) { + return "X"; + } + if (element.equals("Br")) { + return "Y"; + } + + return element; + } + + /** + * Converts an HOSE code symbol as shown in origin article by + * Bremser into default element notation. + * That includes: Q -> Si, X -> Cl, Y -> Br + * + * @param symbol + * + * @return default element notation + */ + public static String toElementSymbol(final String symbol) { + if (symbol.equals("Q")) { + return "Si"; + } + if (symbol.equals("X")) { + return "Cl"; + } + if (symbol.equals("Y")) { + return "Br"; + } + + return symbol; + } + + /** + * Returns the notation of bond information used in HOSE code. + * The bond has to contain its bond order and aromaticity information. + * + * @param bond bond containing bond order and aromaticity information + * + * @return HOSE code symbol for a bond + */ + public static String getSymbolForBond(final IBond bond) { + if (bond + != null) { + if (bond.isAromatic()) { + return "*"; + } + switch (bond.getOrder()) { + case SINGLE: + return ""; + case DOUBLE: + return "="; + case TRIPLE: + return "%"; + } + } + + return null; + } + + /** + * Returns the bond order from an HOSE code bond symbol. + * One has to consider that in this direction the aromatic HOSE code symbol + * (*) is ambiguous. It means either a single or a double aromatic bond. + * For that case, a single bond will always be returned. + * + * @param symbol HOSE code bond symbol + * + * @return bond order for a bond symbol or if symbol is unknown + */ + public static IBond.Order getBondOrderForSymbol(final String symbol) { + + switch (symbol) { + case "": + case "*": + return IBond.Order.SINGLE; + case "=": + return IBond.Order.DOUBLE; + case "%": + return IBond.Order.TRIPLE; + } + + return null; + } +} diff --git a/src/casekit/nmr/model/Assignment.java b/src/casekit/nmr/model/Assignment.java new file mode 100644 index 0000000..fd289c9 --- /dev/null +++ b/src/casekit/nmr/model/Assignment.java @@ -0,0 +1,261 @@ +/* + * The MIT License + * + * Copyright 2018 Michael Wenk [https://github.com/michaelwenk]. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package casekit.nmr.model; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * @author Michael Wenk [https://github.com/michaelwenk] + */ +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +public class Assignment { + + private String[] nuclei; + private int[][][] assignments; + + + public void initAssignments(final int length) { + final int[][][] temp = new int[this.getNDim()][length][0]; + for (int i = 0; i + < this.getNDim(); i++) { + for (int j = 0; j + < length; j++) { + temp[i][j] = new int[]{}; + } + } + this.assignments = temp; + } + + public int getNDim() { + return this.getNuclei().length; + } + + public boolean containsDim(final int dim) { + return dim + >= 0 + && dim + < this.getNDim(); + } + + public boolean compareNuclei(final String[] nuclei) { + return Arrays.equals(this.getNuclei(), nuclei); + } + + /** + * Sets an assignment array with value for an index position. + * + * @param dim + * @param index + * @param assignment + * + * @return + */ + public boolean setAssignment(final int dim, final int index, final int[] assignment) { + if (!this.containsDim(dim) + || !this.checkIndex(dim, index)) { + return false; + } + this.assignments[dim][index] = assignment; + + return true; + } + + public boolean setAssignments(final int dim, final int[][] assignments) { + if (!this.containsDim(dim) + || this.getSize() + != assignments.length) { + return false; + } + for (int i = 0; i + < this.getSize(); i++) { + this.setAssignment(dim, i, assignments[i]); + } + + return true; + } + + public int[] getAssignment(final int dim, final int index) { + if (!this.containsDim(dim) + || !this.checkIndex(dim, index)) { + return null; + } + + return this.assignments[dim][index]; + } + + public int getAssignment(final int dim, final int index, final int equivalenceIndex) { + if (!this.containsDim(dim) + || !this.checkIndex(dim, index)) { + return -1; + } + + return this.assignments[dim][index][equivalenceIndex]; + } + + public void addAssignmentEquivalence(final int dim, final int index, final int assignment) { + final int[] temp = this.getAssignment(dim, index); + final int[] equivalenceIndices = new int[temp.length + + 1]; + for (int j = 0; j + < temp.length; j++) { + equivalenceIndices[j] = temp[j]; + } + equivalenceIndices[equivalenceIndices.length + - 1] = assignment; + + this.setAssignment(dim, index, equivalenceIndices); + } + + public List getIndices(final int dim, final int assignment) { + if (!this.containsDim(dim)) { + return null; + } + final List indices = new ArrayList<>(); + for (int index = 0; index + < this.assignments[dim].length; index++) { + if (Arrays.stream(this.getAssignment(dim, index)) + .anyMatch(equiv -> equiv + == assignment)) { + indices.add(index); + } + } + + return indices; + } + + public int[][] getAssignments(final int dim) { + if (!this.containsDim(dim)) { + return null; + } + + return this.assignments[dim]; + } + + public int getSize() { + if (this.getNDim() + > 0) { + return this.assignments[0].length; + } + return 0; + } + + public int getSetAssignmentsCount(final int dim) { + int setAssignmentsCounter = 0; + if (this.containsDim(dim)) { + for (int j = 0; j + < this.assignments[dim].length; j++) { + if (this.assignments[dim][j].length + > 0) { + setAssignmentsCounter++; + } + } + } + return setAssignmentsCounter; + } + + public int getSetAssignmentsCountWithEquivalences(final int dim) { + int setAssignmentsCounter = 0; + if (this.containsDim(dim)) { + for (int j = 0; j + < this.assignments[dim].length; j++) { + setAssignmentsCounter += this.assignments[dim][j].length; + } + } + return setAssignmentsCounter; + } + + public boolean addAssignment(final int dim, final int[] assignment) { + if (!this.containsDim(dim)) { + return false; + } + final int[][][] newAssignments = new int[this.getNDim()][][]; + for (int d = 0; d + < this.getNDim(); d++) { + if (d + == dim) { + newAssignments[d] = new int[this.assignments[d].length + + 1][]; + for (int i = 0; i + < this.assignments[d].length; i++) { + newAssignments[d][i] = this.assignments[d][i]; + } + } else { + newAssignments[d] = this.assignments[d]; + } + } + newAssignments[dim][this.assignments[dim].length] = assignment; + this.assignments = newAssignments; + + return true; + } + + private boolean checkIndex(final int dim, final int index) { + return (index + >= 0) + && (index + < this.assignments[dim].length); + } + + public Assignment buildClone() { + final Assignment clone = new Assignment(); + clone.setNuclei(this.getNuclei() + .clone()); + final int[][][] values = new int[this.getNDim()][][]; + for (int dim = 0; dim + < this.getNDim(); dim++) { + values[dim] = new int[this.getSize()][]; + for (int i = 0; i + < this.assignments[dim].length; i++) { + values[dim][i] = new int[this.assignments[dim][i].length]; + for (int equiv = 0; equiv + < this.assignments[dim][i].length; equiv++) { + values[dim][i][equiv] = this.assignments[dim][i][equiv]; + } + } + } + clone.setAssignments(values); + + return clone; + } + + @Override + public String toString() { + return "Assignment{" + + "nuclei=" + + Arrays.toString(this.nuclei) + + ", assignments=" + + Arrays.deepToString(this.assignments) + + '}'; + } +} diff --git a/src/casekit/nmr/model/DataSet.java b/src/casekit/nmr/model/DataSet.java new file mode 100644 index 0000000..e5b285e --- /dev/null +++ b/src/casekit/nmr/model/DataSet.java @@ -0,0 +1,79 @@ +package casekit.nmr.model; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.openscience.cdk.interfaces.IAtomContainer; + +import java.util.HashMap; +import java.util.Map; + +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +public class DataSet { + + private StructureCompact structure; + private SpectrumCompact spectrum; + private Assignment assignment; + private Map meta; + private Map attachment; + + public DataSet(final IAtomContainer structure, final Spectrum spectrum, final Assignment assignment, + final Map meta, final Map attachment) { + this.structure = new StructureCompact(structure); + this.spectrum = new SpectrumCompact(spectrum); + this.assignment = assignment; + this.meta = new HashMap<>(meta); + this.attachment = new HashMap<>(attachment); + } + + public void addMetaInfo(final String key, final String value) { + if (this.meta + == null) { + this.meta = new HashMap<>(); + } + this.meta.put(key, value); + } + + public void removeMetaInfo(final String key) { + this.meta.remove(key); + } + + public void addAttachment(final String key, final Object object) { + if (this.attachment + == null) { + this.attachment = new HashMap<>(); + } + this.attachment.put(key, object); + } + + public void removeAttachment(final String key) { + this.attachment.remove(key); + } + + public DataSet buildClone() { + final Map metaTemp = this.meta + == null + ? new HashMap<>() + : new HashMap<>(this.meta); + return new DataSet(this.structure.buildClone(), this.spectrum.buildClone(), this.assignment.buildClone(), + new HashMap<>(metaTemp), new HashMap<>(this.attachment)); + } + + @Override + public String toString() { + return "DataSet{" + + "structure=" + + this.structure + + ", spectrum=" + + this.spectrum + + ", assignment=" + + this.assignment + + ", meta=" + + this.meta + + '}'; + } +} diff --git a/src/casekit/nmr/model/PathLength.java b/src/casekit/nmr/model/PathLength.java new file mode 100644 index 0000000..bffc529 --- /dev/null +++ b/src/casekit/nmr/model/PathLength.java @@ -0,0 +1,14 @@ +package casekit.nmr.model; + +import lombok.*; + +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +@ToString +public class PathLength { + + private int from; + private int to; +} diff --git a/src/casekit/nmr/model/Signal.java b/src/casekit/nmr/model/Signal.java new file mode 100644 index 0000000..09ab610 --- /dev/null +++ b/src/casekit/nmr/model/Signal.java @@ -0,0 +1,128 @@ +/* + * This class was adopted and modified from an earlier version by Christoph Steinbeck + */ + +/* + * The MIT License + * + * Copyright 2018 Michael Wenk [https://github.com/michaelwenk]. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package casekit.nmr.model; + +import casekit.nmr.model.nmrium.J; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.util.Arrays; + +/** + * @author Michael Wenk [https://github.com/michaelwenk] + */ +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +public class Signal { + + private String[] nuclei; + private Double[] shifts; + private String multiplicity; + private String kind; + private Double intensity; + private int equivalencesCount; + private Integer phase; + private J j; + private String id; + + + public int getNDim() { + return this.getNuclei().length; + } + + public boolean containsDim(final int dim) { + return dim + >= 0 + && dim + < this.getNDim(); + } + + public boolean compareNuclei(final String[] nuclei) { + return Arrays.equals(this.getNuclei(), nuclei); + } + + public boolean setShift(final Double shift, final int dim) { + if (!this.containsDim(dim)) { + return false; + } + this.shifts[dim] = shift; + + return true; + } + + public Double getShift(final int dim) { + if (!this.containsDim(dim)) { + return null; + } + return this.shifts[dim]; + } + + public Signal buildClone() { + final J clonedJ = this.j + != null + ? new J() + : null; + if (this.j + != null + && this.j.getPathLength() + != null) { + clonedJ.setPathLength(new PathLength(this.j.getPathLength() + .getFrom(), this.j.getPathLength() + .getTo())); + } + return new Signal(this.getNuclei() + .clone(), this.shifts.clone(), this.multiplicity, this.kind, this.intensity, + this.equivalencesCount, this.phase, clonedJ, this.id); + } + + @Override + public String toString() { + return "Signal{" + + "nuclei=" + + Arrays.toString(this.nuclei) + + ", shifts=" + + Arrays.toString(this.shifts) + + ", multiplicity='" + + this.multiplicity + + '\'' + + ", kind='" + + this.kind + + '\'' + + ", intensity=" + + this.intensity + + ", equivalencesCount=" + + this.equivalencesCount + + ", phase=" + + this.phase + + '}'; + } +} diff --git a/src/casekit/nmr/model/SignalCompact.java b/src/casekit/nmr/model/SignalCompact.java new file mode 100644 index 0000000..9fd74c8 --- /dev/null +++ b/src/casekit/nmr/model/SignalCompact.java @@ -0,0 +1,98 @@ +package casekit.nmr.model; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.util.Arrays; + +/** + * @author Michael Wenk [https://github.com/michaelwenk] + */ +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +public class SignalCompact { + + private String[] strings; // nucleus dim 1, nucleus dim 2, ... , multiplicity, signal kind + private Double[] doubles; // shift dim 1, shift dim 2, ... , intensity + private Integer[] integers; // dimensions, equivalence count, phase + + public SignalCompact(final Signal signal) { + this.strings = new String[signal.getNDim() + + 3]; + this.doubles = new Double[signal.getNDim() + + 1]; + for (int dim = 0; dim + < signal.getNDim(); dim++) { + this.strings[dim] = signal.getNuclei()[dim]; + this.doubles[dim] = signal.getShift(dim); + } + this.strings[signal.getNDim()] = signal.getMultiplicity(); + this.strings[signal.getNDim() + + 1] = signal.getKind(); + this.strings[signal.getNDim() + + 2] = signal.getId(); + this.doubles[signal.getNDim()] = signal.getIntensity(); + this.integers = new Integer[]{signal.getNDim(), signal.getEquivalencesCount(), signal.getPhase()}; + } + + public int dimensions() { + return this.integers[0]; + } + + public String[] nuclei() { + final int nDim = this.integers[0]; + final String[] nuclei = new String[nDim]; + for (int dim = 0; dim + < nDim; dim++) { + nuclei[dim] = this.strings[dim]; + } + return nuclei; + } + + public Signal toSignal() { + final Signal signal = new Signal(); + signal.setNuclei(this.nuclei()); + signal.setMultiplicity(this.strings[this.dimensions()]); + signal.setKind(this.strings[this.dimensions() + + 1]); + // @TODO remove following condition if not needed anymore (sherlock dataset storage is currently without signal ID) + signal.setId(this.strings.length + - this.dimensions() + >= 3 + ? this.strings[this.dimensions() + + 2] + : null); + signal.setShifts(new Double[this.dimensions()]); + for (int dim = 0; dim + < this.dimensions(); dim++) { + signal.setShift(this.doubles[dim], dim); + } + signal.setIntensity(this.doubles[this.dimensions()]); + signal.setEquivalencesCount(this.integers[1]); + signal.setPhase(this.integers[2]); + + return signal; + } + + + public SignalCompact buildClone() { + return new SignalCompact(this.strings.clone(), this.doubles.clone(), this.integers.clone()); + } + + @Override + public String toString() { + return "SignalCompact{" + + "strings=" + + Arrays.toString(this.strings) + + ", doubles=" + + Arrays.toString(this.doubles) + + ", integers=" + + Arrays.toString(this.integers) + + '}'; + } +} + diff --git a/src/casekit/nmr/model/Spectrum.java b/src/casekit/nmr/model/Spectrum.java new file mode 100644 index 0000000..5b5c905 --- /dev/null +++ b/src/casekit/nmr/model/Spectrum.java @@ -0,0 +1,446 @@ +/* + * This class was adopted and modified from an earlier version by Christoph Steinbeck + */ + + +/* + * The MIT License + * + * Copyright 2018 Michael Wenk [https://github.com/michaelwenk]. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package casekit.nmr.model; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * @author Michael Wenk [https://github.com/michaelwenk] + */ +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +public class Spectrum { + + private String[] nuclei; + private Map meta; + private List signals; + private int signalCount; + + public void addMetaInfo(final String key, final String value) { + if (this.meta + == null) { + this.meta = new HashMap<>(); + } + this.meta.put(key, value); + } + + public void removeMetaInfo(final String key) { + this.meta.remove(key); + } + + public int getNDim() { + return this.getNuclei().length; + } + + public boolean containsDim(final int dim) { + return dim + >= 0 + && dim + < this.getNDim(); + } + + public boolean compareNuclei(final String[] nuclei) { + return Arrays.equals(this.getNuclei(), nuclei); + } + + public int getSignalCountWithEquivalences() { + int sum = 0; + for (final Signal signal : this.getSignals()) { + sum += signal.getEquivalencesCount(); + } + return sum; + } + + /** + * Simply adds a signal to the end of the signal list without equivalence checks. + * + * @param signal signal to add + * + * @return + */ + public boolean addSignalWithoutEquivalenceSearch(final Signal signal) { + if ((signal + == null) + || !this.compareNuclei(signal.getNuclei())) { + return false; + } + // add signal at the end of signal list + this.signals.add(signal); + this.signalCount++; + + return true; + } + + /** + * Adds a signal to this spectrum with pickPrecision of 0 and enabled multiplicity check for equivalence search. + * + * @param signal signal to add + * + * @return + * + * @see #addSignal(Signal, double[], boolean) + */ + public Integer addSignal(final Signal signal) { + final double[] pickPrecisions = new double[signal.getNDim()]; + for (int dim = 0; dim + < signal.getNDim(); dim++) { + pickPrecisions[dim] = 0.0; + } + return this.addSignal(signal, pickPrecisions, true); + } + + /** + * Checks for equivalent signals in all dimensions. + * + * @param signal signal + * @param pickPrecisions picking precision per dimension + * @param checkMultiplicity whether multiplicity has to be checked too + * + * @return + */ + public List checkForEquivalences(final Signal signal, final double[] pickPrecisions, + final boolean checkMultiplicity) { + if (signal.getShift(0) + == null) { + return null; + } + // check for equivalent signals in all dimensions + final List closestSignalIndexList = this.pickByClosestShift(signal.getShift(0), 0, pickPrecisions[0]); + for (int dim = 1; dim + < this.getNDim(); dim++) { + closestSignalIndexList.retainAll(this.pickByClosestShift(signal.getShift(dim), dim, pickPrecisions[dim])); + } + if (checkMultiplicity) { + closestSignalIndexList.retainAll(this.pickByMultiplicity(signal.getMultiplicity())); + } + + return closestSignalIndexList; + } + + /** + * Adds a signal to this spectrum and stores an equivalent signal index. + * + * @param signal signal to add + * @param pickPrecisions precisions per dimension to find equivalent signals to store in + * @param checkMultiplicity indicates whether to compare the multiplicity of signal + * to add while searching for equivalences + * + * @return + */ + public Integer addSignal(final Signal signal, final double[] pickPrecisions, final boolean checkMultiplicity) { + if ((signal + == null) + || !this.compareNuclei(signal.getNuclei())) { + return null; + } + + final List closestSignalIndexList = this.checkForEquivalences(signal, pickPrecisions, + checkMultiplicity); + if (closestSignalIndexList + == null) { + return null; + } + // if no equivalent signal was found then just add as new signal + if (closestSignalIndexList.isEmpty()) { + this.addSignalWithoutEquivalenceSearch(signal); + return this.getSignalCount() + - 1; + } + // otherwise store as equivalence (in first hit only) + final Signal closestSignal = this.getSignal(closestSignalIndexList.get(0)); + closestSignal.setEquivalencesCount(closestSignal.getEquivalencesCount() + + signal.getEquivalencesCount()); + return closestSignalIndexList.get(0); + } + + public boolean removeSignal(final Signal signal) { + return this.removeSignal(this.getSignalIndex(signal)); + } + + public boolean removeSignal(final int signalIndex) { + if (!this.checkSignalIndex(signalIndex)) { + return false; + } + if (this.signals.remove(signalIndex) + != null) { + this.signalCount--; + + return true; + } + + return false; + } + + private boolean checkSignalIndex(final Integer signalIndex) { + return (signalIndex + != null) + && (signalIndex + >= 0) + && (signalIndex + < this.getSignalCount()); + } + + /** + * Returns a NMR Signal at position number in the signal list + * + * @param signalIndex + * + * @return + */ + public Signal getSignal(final int signalIndex) { + if (!this.checkSignalIndex(signalIndex)) { + return null; + } + + return this.signals.get(signalIndex); + } + + /** + * Sets a NMR Signal at position number in the signal list + * + * @param signalIndex signal index in list + * @param signal signal + * + * @return + */ + public boolean setSignal(final int signalIndex, final Signal signal) { + if (!this.checkSignalIndex(signalIndex) + || !this.compareNuclei(signal.getNuclei())) { + return false; + } + + this.signals.set(signalIndex, signal); + + return true; + } + + public Double getShift(final int signalIndex, final int dim) { + if (!this.checkSignalIndex(signalIndex)) { + return null; + } + + return this.getSignal(signalIndex) + .getShift(dim); + } + + public List getShifts(final int dim) { + return this.getSignals() + .stream() + .map(signal -> signal.getShift(dim)) + .collect(Collectors.toList()); + } + + public String getMultiplicity(final int signalIndex) { + if (!this.checkSignalIndex(signalIndex)) { + return null; + } + + return this.getSignal(signalIndex) + .getMultiplicity(); + } + + public Boolean hasEquivalences(final int signalIndex) { + if (!this.checkSignalIndex(signalIndex)) { + return null; + } + + return this.getEquivalencesCount(signalIndex) + > 1; + } + + public Integer getEquivalencesCount(final int signalIndex) { + if (!this.checkSignalIndex(signalIndex)) { + return null; + } + + return this.getSignal(signalIndex) + .getEquivalencesCount(); + } + + public List getEquivalencesCounts() { + return this.getSignals() + .stream() + .map(Signal::getEquivalencesCount) + .collect(Collectors.toList()); + } + + /** + * Returns the position of an NMRSignal the List + * + * @param signal + * + * @return + */ + public int getSignalIndex(final Signal signal) { + for (int s = 0; s + < this.signals.size(); s++) { + if (this.signals.get(s) + == signal) { + return s; + } + } + return -1; + } + + /** + * Returns the indices of signals with same multiplicity (even null values). + * + * @param multiplicity multiplicity to search for + * + * @return + */ + public List pickByMultiplicity(final String multiplicity) { + final List matchIndices = new ArrayList<>(); + for (int s = 0; s + < this.getSignalCount(); s++) { + if ((this.getSignal(s) + .getMultiplicity() + == null + && multiplicity + == null) + || (this.getSignal(s) + .getMultiplicity() + != null + && this.getSignal(s) + .getMultiplicity() + .equals(multiplicity))) { + matchIndices.add(s); + } + } + + return matchIndices; + } + + /** + * Returns the signal index (or indices) closest to the given shift. If no signal is found within the interval + * defined by {@code pickPrecision}, an empty list is returned. + * + * @param shift query shift + * @param dim dimension in spectrum to look in + * @param pickPrecision tolerance value for search window + * + * @return + */ + public List pickByClosestShift(final double shift, final int dim, final double pickPrecision) { + final List matchIndices = new ArrayList<>(); + if (!this.containsDim(dim)) { + return matchIndices; + } + double minDiff = pickPrecision; + // detect the minimal difference between a signal shift to the given query shift + for (int s = 0; s + < this.getSignalCount(); s++) { + if (Math.abs(this.getShift(s, dim) + - shift) + < minDiff) { + minDiff = Math.abs(this.getShift(s, dim) + - shift); + } + } + for (int s = 0; s + < this.getSignalCount(); s++) { + if (Math.abs(this.getShift(s, dim) + - shift) + == minDiff) { + matchIndices.add(s); + } + } + + return matchIndices; + } + + /** + * Returns a list of signal indices within the interval defined by + * pickPrecision. That list is sorted by the distances to the query shift. + * If none is found an empty ArrayList is returned. + * + * @param shift query shift + * @param dim dimension in spectrum to look in + * @param pickPrecision tolerance value for search window + * + * @return + */ + public List pickSignals(final Double shift, final int dim, final double pickPrecision) { + final List pickedSignals = new ArrayList<>(); + if (!this.containsDim(dim)) { + return pickedSignals; + } + for (int s = 0; s + < this.getSignalCount(); s++) { + if (Math.abs(this.getShift(s, dim) + - shift) + <= pickPrecision) { + pickedSignals.add(s); + } + } + // sort signal indices by distance to query shift + pickedSignals.sort(Comparator.comparingDouble(pickedSignalIndex -> Math.abs(shift + - this.getShift( + pickedSignalIndex, dim)))); + + return pickedSignals; + } + + public Spectrum buildClone() { + final Spectrum clone = new Spectrum(); + clone.setNuclei(this.getNuclei() + .clone()); + clone.setSignals(new ArrayList<>()); + for (int i = 0; i + < this.getSignalCount(); i++) { + clone.addSignal(this.getSignal(i) + .buildClone()); + } + clone.setMeta(new HashMap<>(this.getMeta())); + + return clone; + } + + @Override + public String toString() { + return "Spectrum{" + + "nuclei=" + + Arrays.toString(this.nuclei) + + ", meta=" + + this.meta + + ", signals=" + + this.signals + + ", signalCount=" + + this.signalCount + + '}'; + } +} diff --git a/src/casekit/nmr/model/SpectrumCompact.java b/src/casekit/nmr/model/SpectrumCompact.java new file mode 100644 index 0000000..3f7b31a --- /dev/null +++ b/src/casekit/nmr/model/SpectrumCompact.java @@ -0,0 +1,80 @@ +package casekit.nmr.model; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @author Michael Wenk [https://github.com/michaelwenk] + */ +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +public class SpectrumCompact { + + private String[] nuclei; + private Map meta; + private SignalCompact[] signals; + + public SpectrumCompact(final Spectrum spectrum) { + this.nuclei = spectrum.getNuclei(); + this.meta = spectrum.getMeta(); + this.signals = spectrum.getSignals() + .stream() + .map(SignalCompact::new) + .toArray(SignalCompact[]::new); + } + + public void addMetaInfo(final String key, final String value) { + if (this.meta + == null) { + this.meta = new HashMap<>(); + } + this.meta.put(key, value); + } + + public void removeMetaInfo(final String key) { + this.meta.remove(key); + } + + public Spectrum toSpectrum() { + final Spectrum spectrum = new Spectrum(); + spectrum.setNuclei(this.nuclei); + spectrum.setMeta(this.meta); + spectrum.setSignals(Arrays.stream(this.signals) + .map(SignalCompact::toSignal) + .collect(Collectors.toList())); + spectrum.setSignalCount(this.signals.length); + + return spectrum; + } + + public SpectrumCompact buildClone() { + final Map metaTemp = this.meta + == null + ? new HashMap<>() + : new HashMap<>(this.meta); + return new SpectrumCompact(this.nuclei.clone(), metaTemp, Arrays.stream(this.signals) + .map(SignalCompact::buildClone) + .toArray(SignalCompact[]::new)); + } + + @Override + public String toString() { + return "SpectrumCompact{" + + "nuclei=" + + Arrays.toString(this.nuclei) + + ", meta=" + + this.meta + + ", signals=" + + Arrays.toString(this.signals) + + '}'; + } +} diff --git a/src/casekit/nmr/model/StructureCompact.java b/src/casekit/nmr/model/StructureCompact.java new file mode 100644 index 0000000..74c36f7 --- /dev/null +++ b/src/casekit/nmr/model/StructureCompact.java @@ -0,0 +1,181 @@ +/* + * The MIT License + * + * Copyright (c) 2019 Michael Wenk [https://github.com/michaelwenk] + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package casekit.nmr.model; + +import casekit.nmr.utils.Utils; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.openscience.cdk.graph.matrix.ConnectionMatrix; +import org.openscience.cdk.interfaces.IAtom; +import org.openscience.cdk.interfaces.IAtomContainer; +import org.openscience.cdk.interfaces.IAtomType; +import org.openscience.cdk.interfaces.IBond; +import org.openscience.cdk.silent.Atom; +import org.openscience.cdk.silent.Bond; +import org.openscience.cdk.silent.PseudoAtom; +import org.openscience.cdk.silent.SilentChemObjectBuilder; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * @author Michael Wenk [https://github.com/michaelwenk] + */ +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +public class StructureCompact { + + private int[][][] bondProperties; // connected atom index, bond order, bond is in ring, bond is aromatic, bond stereo configuration + private Integer[][] atomProperties; // element symbol, hybridization, implicitHydrogenCount, valency, formalCharge, isInRingAtom, isAromaticAtom + + public StructureCompact(final IAtomContainer ac) { + final double[][] connectionMatrix = ConnectionMatrix.getMatrix(ac); + this.bondProperties = new int[connectionMatrix.length][][]; + List connectedAtomsList; + int[][] temp; + IBond bond; + for (int i = 0; i + < connectionMatrix.length; i++) { + connectedAtomsList = new ArrayList<>(); + for (int j = i + + 1; j + < connectionMatrix[i].length; j++) { + if (connectionMatrix[i][j] + >= 1) { + bond = ac.getBond(ac.getAtom(i), ac.getAtom(j)); + connectedAtomsList.add(new int[]{j, (int) connectionMatrix[i][j], bond.isInRing() + ? 1 + : 0, bond.isAromatic() + ? 1 + : 0, + bond.getStereo().ordinal()}); + } + } + temp = new int[connectedAtomsList.size()][]; + for (int k = 0; k + < connectedAtomsList.size(); k++) { + temp[k] = connectedAtomsList.get(k); + } + this.bondProperties[i] = temp; + } + this.atomProperties = new Integer[connectionMatrix.length][]; + + IAtom atom; + for (int i = 0; i + < connectionMatrix.length; i++) { + atom = ac.getAtom(i); + this.atomProperties[i] = new Integer[7]; + this.atomProperties[i][0] = atom.getSymbol() + .equals("R") + ? -1 + : atom.getAtomicNumber(); + this.atomProperties[i][1] = atom.getHybridization() + == null + ? -1 + : atom.getHybridization() + .ordinal(); + this.atomProperties[i][2] = atom.getImplicitHydrogenCount(); + this.atomProperties[i][3] = atom.getValency(); + this.atomProperties[i][4] = atom.getFormalCharge(); + this.atomProperties[i][5] = atom.isInRing() + ? 1 + : 0; + this.atomProperties[i][6] = atom.isAromatic() + ? 1 + : 0; + } + } + + public int atomCount() { + return this.atomProperties.length; + } + + public int bondCount() { + int bondCount = 0; + for (int i = 0; i + < this.bondProperties.length; i++) { + bondCount += this.bondProperties[i].length; + } + return bondCount; + } + + public IAtomContainer toAtomContainer() { + final IAtomContainer ac = SilentChemObjectBuilder.getInstance() + .newAtomContainer(); + IAtom atom; + for (int i = 0; i + < this.atomProperties.length; i++) { + atom = this.atomProperties[i][0] + == -1 + ? new PseudoAtom("R") + : new Atom(this.atomProperties[i][0]); + atom.setHybridization(this.atomProperties[i][1] + == -1 + ? null + : IAtomType.Hybridization.values()[this.atomProperties[i][1]]); + atom.setImplicitHydrogenCount(this.atomProperties[i][2]); + atom.setValency(this.atomProperties[i][3]); + atom.setFormalCharge(this.atomProperties[i][4]); + atom.setIsInRing(this.atomProperties[i][5] + == 1); + atom.setIsAromatic(this.atomProperties[i][6] + == 1); + + ac.addAtom(atom); + } + IBond bond; + for (int i = 0; i + < this.bondProperties.length; i++) { + for (int k = 0; k + < this.bondProperties[i].length; k++) { + bond = new Bond(ac.getAtom(i), ac.getAtom(this.bondProperties[i][k][0]), + Utils.getBondOrder(this.bondProperties[i][k][1])); + bond.setIsInRing(this.bondProperties[i][k][2] + == 1); + bond.setIsAromatic(this.bondProperties[i][k][3] + == 1); + if (this.bondProperties[i][k].length + == 5) { + // with stereo information + bond.setStereo(IBond.Stereo.values()[this.bondProperties[i][k][4]]); + } else { + // without stereo information + bond.setStereo(IBond.Stereo.NONE); + } + ac.addBond(bond); + } + } + + return ac; + } + + public StructureCompact buildClone() { + return new StructureCompact(Arrays.copyOf(this.bondProperties, this.bondProperties.length), + Arrays.copyOf(this.atomProperties, this.atomProperties.length)); + + } + + @Override + public String toString() { + return "StructureCompact{" + + "bondProperties=" + + Arrays.deepToString(this.bondProperties) + + ", atomProperties=" + + Arrays.deepToString(this.atomProperties) + + '}'; + } +} diff --git a/src/casekit/nmr/model/nmrium/Correlation.java b/src/casekit/nmr/model/nmrium/Correlation.java new file mode 100644 index 0000000..002ef81 --- /dev/null +++ b/src/casekit/nmr/model/nmrium/Correlation.java @@ -0,0 +1,52 @@ +/* + * MIT License + * + * Copyright (c) 2020 Michael Wenk (https://github.com/michaelwenk) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package casekit.nmr.model.nmrium; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +import java.util.List; +import java.util.Map; + +@NoArgsConstructor +@Getter +@Setter +@ToString + +public class Correlation { + + private String id; + private String atomType; + private Map label; + private List link; + private int equivalence; + private Map> attachment; + private List protonsCount; + private List hybridization; + private boolean pseudo; + private Map edited; +} diff --git a/src/casekit/nmr/model/nmrium/Correlations.java b/src/casekit/nmr/model/nmrium/Correlations.java new file mode 100644 index 0000000..4789e18 --- /dev/null +++ b/src/casekit/nmr/model/nmrium/Correlations.java @@ -0,0 +1,42 @@ +/* + * MIT License + * + * Copyright (c) 2020 Michael Wenk (https://github.com/michaelwenk) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package casekit.nmr.model.nmrium; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +import java.util.Map; + +@NoArgsConstructor +@Getter +@Setter +@ToString +public class Correlations + extends Default { + + private Map> state; +} diff --git a/src/casekit/nmr/model/nmrium/Default.java b/src/casekit/nmr/model/nmrium/Default.java new file mode 100644 index 0000000..12fb15e --- /dev/null +++ b/src/casekit/nmr/model/nmrium/Default.java @@ -0,0 +1,42 @@ +/* + * MIT License + * + * Copyright (c) 2020 Michael Wenk (https://github.com/michaelwenk) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package casekit.nmr.model.nmrium; + +import lombok.*; + +import java.util.List; +import java.util.Map; + +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +@ToString + +public class Default { + + private Map options; + private List values; +} diff --git a/src/casekit/nmr/model/nmrium/J.java b/src/casekit/nmr/model/nmrium/J.java new file mode 100644 index 0000000..507230c --- /dev/null +++ b/src/casekit/nmr/model/nmrium/J.java @@ -0,0 +1,16 @@ +package casekit.nmr.model.nmrium; + +import casekit.nmr.model.PathLength; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.*; + +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +@ToString +@JsonIgnoreProperties(ignoreUnknown = true) +public class J { + + private PathLength pathLength; +} diff --git a/src/casekit/nmr/model/nmrium/Link.java b/src/casekit/nmr/model/nmrium/Link.java new file mode 100644 index 0000000..b12fa59 --- /dev/null +++ b/src/casekit/nmr/model/nmrium/Link.java @@ -0,0 +1,51 @@ +/* + * MIT License + * + * Copyright (c) 2020 Michael Wenk (https://github.com/michaelwenk) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package casekit.nmr.model.nmrium; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +import java.util.List; +import java.util.Map; + +@NoArgsConstructor +@Getter +@Setter +@ToString +public class Link { + + private String experimentType; + private String experimentID; + private String[] atomType; + private Object signal; + private String axis; + private List match; + private String id; + private String experimentLabel; + private boolean pseudo; + private Map edited; +} diff --git a/src/casekit/nmr/model/nmrium/NMRiumData.java b/src/casekit/nmr/model/nmrium/NMRiumData.java new file mode 100644 index 0000000..1db6a33 --- /dev/null +++ b/src/casekit/nmr/model/nmrium/NMRiumData.java @@ -0,0 +1,45 @@ +/* + * MIT License + * + * Copyright (c) 2020 Michael Wenk (https://github.com/michaelwenk) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package casekit.nmr.model.nmrium; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +import java.util.List; + +@NoArgsConstructor +@Getter +@Setter +@ToString + +@JsonIgnoreProperties(ignoreUnknown = true) +public class NMRiumData { + + private List spectra; + private Correlations correlations; +} diff --git a/src/casekit/nmr/model/nmrium/Range.java b/src/casekit/nmr/model/nmrium/Range.java new file mode 100644 index 0000000..9618438 --- /dev/null +++ b/src/casekit/nmr/model/nmrium/Range.java @@ -0,0 +1,50 @@ +/* + * MIT License + * + * Copyright (c) 2020 Michael Wenk (https://github.com/michaelwenk) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package casekit.nmr.model.nmrium; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.*; + +import java.util.List; + +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +@ToString +@JsonIgnoreProperties(ignoreUnknown = true) +public class Range { + + private String id; + private String kind; + private List signals; + private Double absolute; + private Double from; + private Double to; + private Double integration; + private Double originFrom; + private Double originTo; + +} diff --git a/src/casekit/nmr/model/nmrium/Signal.java b/src/casekit/nmr/model/nmrium/Signal.java new file mode 100644 index 0000000..63223ca --- /dev/null +++ b/src/casekit/nmr/model/nmrium/Signal.java @@ -0,0 +1,18 @@ +package casekit.nmr.model.nmrium; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.*; + +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +@ToString +@JsonIgnoreProperties(ignoreUnknown = true) +public class Signal { + + private String id; + private String kind; + private String multiplicity; + private Integer sign; +} diff --git a/src/casekit/nmr/model/nmrium/Signal1D.java b/src/casekit/nmr/model/nmrium/Signal1D.java new file mode 100644 index 0000000..cb2b441 --- /dev/null +++ b/src/casekit/nmr/model/nmrium/Signal1D.java @@ -0,0 +1,51 @@ +/* + * MIT License + * + * Copyright (c) 2020 Michael Wenk (https://github.com/michaelwenk) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package casekit.nmr.model.nmrium; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.*; + +import java.util.List; +import java.util.Map; + +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +@ToString +@JsonIgnoreProperties(ignoreUnknown = true) +public class Signal1D + extends Signal { + + private double delta; + private Double integration; + private List> js; + private Double originDelta; + private List> peaks; + + public Signal1D(final Signal signal) { + super(signal.getId(), signal.getKind(), signal.getMultiplicity(), signal.getSign()); + } +} diff --git a/src/casekit/nmr/model/nmrium/Signal2D.java b/src/casekit/nmr/model/nmrium/Signal2D.java new file mode 100644 index 0000000..3ea26da --- /dev/null +++ b/src/casekit/nmr/model/nmrium/Signal2D.java @@ -0,0 +1,51 @@ +/* + * MIT License + * + * Copyright (c) 2020 Michael Wenk (https://github.com/michaelwenk) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package casekit.nmr.model.nmrium; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.*; + +import java.util.List; +import java.util.Map; + +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +@ToString +@JsonIgnoreProperties(ignoreUnknown = true) +public class Signal2D + extends Signal { + + + private Map x; + private Map y; + private J j; + private List> peaks; + + public Signal2D(final Signal signal) { + super(signal.getId(), signal.getKind(), signal.getMultiplicity(), signal.getSign()); + } +} diff --git a/src/casekit/nmr/model/nmrium/Spectrum.java b/src/casekit/nmr/model/nmrium/Spectrum.java new file mode 100644 index 0000000..08aac44 --- /dev/null +++ b/src/casekit/nmr/model/nmrium/Spectrum.java @@ -0,0 +1,123 @@ +/* + * MIT License + * + * Copyright (c) 2020 Michael Wenk (https://github.com/michaelwenk) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package casekit.nmr.model.nmrium; + +import casekit.nmr.model.Signal; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +@NoArgsConstructor +@Getter +@Setter +@ToString +@JsonIgnoreProperties(ignoreUnknown = true) +public class Spectrum { + + private String id; + private Map info; + private Map data; + private Map display; + private List filters; + private Map meta; + private Map originalData; + private Map originalInfo; + private Map source; + // depending on spectrum type + // 1D + private Default ranges; + private Map integrals; + private Map peaks; + // 2D + private Map processingController; + private Default zones; + + public casekit.nmr.model.Spectrum toSpectrum(final boolean considerSignalKind) { + final int dimension = (int) this.info.get("dimension"); + final boolean isFid = (boolean) this.info.get("isFid"); + + if (!isFid) { + if (dimension + == 1) { + final String nucleus = (String) this.info.get("nucleus"); + final casekit.nmr.model.Spectrum spectrum = new casekit.nmr.model.Spectrum(); + spectrum.setNuclei(new String[]{nucleus}); + this.ranges.getValues() + .forEach(range -> range.getSignals() + .forEach(signal1D -> { + if (considerSignalKind + && signal1D.getKind() + .equals("signal")) { + spectrum.addSignal(new Signal(new String[]{nucleus}, + new Double[]{ + signal1D.getDelta()}, + signal1D.getMultiplicity(), + signal1D.getKind(), null, 0, 0, + null, signal1D.getId())); + } + })); + spectrum.addMetaInfo("solvent", (String) this.info.get("solvent")); + spectrum.addMetaInfo("spectrumType", (String) this.info.get("experiment")); + + return spectrum; + + } else if (dimension + == 2) { + final String[] nuclei = ((ArrayList) this.info.get("nucleus")).toArray(new String[]{}); + final casekit.nmr.model.Spectrum spectrum = new casekit.nmr.model.Spectrum(); + spectrum.setNuclei(nuclei); + + this.zones.getValues() + .forEach(zone -> zone.getSignals() + .forEach(signal2D -> { + if (considerSignalKind + && signal2D.getKind() + .equals("signal")) { + spectrum.addSignal(new Signal(nuclei, new Double[]{ + (Double) signal2D.getX() + .get("delta"), (Double) signal2D.getY() + .get("delta")}, + signal2D.getMultiplicity(), + signal2D.getKind(), null, 0, 0, + signal2D.getJ(), + signal2D.getId())); + } + })); + spectrum.addMetaInfo("solvent", (String) this.info.get("solvent")); + spectrum.addMetaInfo("spectrumType", (String) this.info.get("experiment")); + + return spectrum; + } + } + + return null; + } +} diff --git a/src/casekit/nmr/model/nmrium/Zone.java b/src/casekit/nmr/model/nmrium/Zone.java new file mode 100644 index 0000000..279df4b --- /dev/null +++ b/src/casekit/nmr/model/nmrium/Zone.java @@ -0,0 +1,46 @@ +/* + * MIT License + * + * Copyright (c) 2020 Michael Wenk (https://github.com/michaelwenk) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package casekit.nmr.model.nmrium; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.*; + +import java.util.List; +import java.util.Map; + +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +@ToString +@JsonIgnoreProperties(ignoreUnknown = true) +public class Zone { + + private String id; + private String kind; + private List signals; + private Map x; + private Map y; +} diff --git a/src/casekit/nmr/prediction/Prediction.java b/src/casekit/nmr/prediction/Prediction.java new file mode 100644 index 0000000..63042d5 --- /dev/null +++ b/src/casekit/nmr/prediction/Prediction.java @@ -0,0 +1,504 @@ +/* + * The MIT License + * + * Copyright 2019 Michael Wenk [https://github.com/michaelwenk]. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package casekit.nmr.prediction; + + +import casekit.nmr.analysis.MultiplicitySectionsBuilder; +import casekit.nmr.elucidation.model.Detections; +import casekit.nmr.filterandrank.FilterAndRank; +import casekit.nmr.fragments.model.ConnectionTree; +import casekit.nmr.fragments.model.ConnectionTreeNode; +import casekit.nmr.hose.HOSECodeBuilder; +import casekit.nmr.model.*; +import casekit.nmr.utils.Statistics; +import casekit.nmr.utils.Utils; +import casekit.threading.MultiThreading; +import org.openscience.cdk.exception.CDKException; +import org.openscience.cdk.interfaces.IAtom; +import org.openscience.cdk.interfaces.IAtomContainer; +import org.openscience.cdk.silent.SilentChemObjectBuilder; +import org.openscience.cdk.smiles.SmilesGenerator; +import org.openscience.cdk.tools.CDKHydrogenAdder; +import org.openscience.cdk.tools.manipulator.AtomContainerManipulator; +import org.openscience.nmrshiftdb.util.AtomUtils; +import org.openscience.nmrshiftdb.util.ExtendedHOSECodeGenerator; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.function.Consumer; + +/** + * @author Michael Wenk [https://github.com/michaelwenk] + */ +public class Prediction { + + private final static ExtendedHOSECodeGenerator extendedHOSECodeGenerator = new ExtendedHOSECodeGenerator(); + + /** + * Diastereotopic distinctions are not provided yet. + * + * @param hoseCodeShiftStatistics + * @param structure + * @param solvent + * @param nucleus + * + * @return + */ + public static DataSet predict1D(final Map> hoseCodeShiftStatistics, + final IAtomContainer structure, final String nucleus, final String solvent) { + final int minMatchingSphere = 1; + final Spectrum spectrum = new Spectrum(); + spectrum.setNuclei(new String[]{nucleus}); + spectrum.addMetaInfo("solvent", solvent); + spectrum.setSignals(new ArrayList<>()); + final Assignment assignment = new Assignment(); + assignment.setNuclei(spectrum.getNuclei()); + assignment.initAssignments(0); + + final CDKHydrogenAdder hydrogenAdder = CDKHydrogenAdder.getInstance(SilentChemObjectBuilder.getInstance()); + String hoseCode, atomTypeSpectrum; + Signal signal; + Double shift; + Integer addedSignalIndex; + ConnectionTree connectionTree; + + try { + AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(structure); + Utils.convertExplicitToImplicitHydrogens(structure); + hydrogenAdder.addImplicitHydrogens(structure); + Utils.convertImplicitToExplicitHydrogens(structure); + Utils.setAromaticityAndKekulize(structure); + + for (int i = 0; i + < structure.getAtomCount(); i++) { + atomTypeSpectrum = Utils.getAtomTypeFromNucleus(nucleus); + if (structure.getAtom(i) + .getSymbol() + .equals(atomTypeSpectrum)) { + connectionTree = HOSECodeBuilder.buildConnectionTree(structure, i, null); + shift = null; + for (int s = connectionTree.getMaxSphere(true); s + >= minMatchingSphere; s--) { + hoseCode = HOSECodeBuilder.buildHOSECode(structure, i, s, false); + if (hoseCodeShiftStatistics.containsKey(hoseCode) + && hoseCodeShiftStatistics.get(hoseCode) + .containsKey(solvent)) { + shift = hoseCodeShiftStatistics.get(hoseCode) + .get(solvent)[3]; // take median value + break; + } + } + signal = new Signal(); + signal.setNuclei(spectrum.getNuclei()); + signal.setEquivalencesCount(1); + if (atomTypeSpectrum.equals("C")) { + signal.setMultiplicity(Utils.getMultiplicityFromProtonsCount( + AtomContainerManipulator.countHydrogens(structure, structure.getAtom(i)))); + } + + signal.setKind("signal"); + signal.setShifts(new Double[]{shift}); + addedSignalIndex = spectrum.addSignal(signal); + if (addedSignalIndex + == null + || addedSignalIndex + >= assignment.getSetAssignmentsCount(0)) { + assignment.addAssignment(0, new int[]{i}); + } else { + assignment.addAssignmentEquivalence(0, addedSignalIndex, i); + } + } + } + } catch (final CDKException e) { + e.printStackTrace(); + return null; + } + + return new DataSet(structure, spectrum, assignment, new HashMap<>(), new HashMap<>()); + } + + /** + * Predicts a 2D spectrum from two 1D spectra. Each 1D spectra needs to contain the same solvent information. + * Diastereotopic distinctions are not provided yet ({@link #predict1D(Map, IAtomContainer, String, String)}). + * + * @param hoseCodeShiftStatistics HOSE code shift statistics + * @param structure structure to use for prediction + * @param nuclei nuclei for 2D spectrum to predict + * @param solvent solvent + * @param minPathLength minimal path length + * @param maxPathLength maximal path length + * + * @return + * + * @see #predict1D(Map, IAtomContainer, String, String) + * @see #predict2D(IAtomContainer, Spectrum, Spectrum, Assignment, Assignment, int, int) + */ + public static DataSet predict2D(final Map> hoseCodeShiftStatistics, + final IAtomContainer structure, final String[] nuclei, final String solvent, + final int minPathLength, final int maxPathLength) { + final DataSet predictionDim1 = predict1D(hoseCodeShiftStatistics, structure, nuclei[0], solvent); + final DataSet predictionDim2 = predict1D(hoseCodeShiftStatistics, structure, nuclei[1], solvent); + return Prediction.predict2D(structure, predictionDim1.getSpectrum() + .toSpectrum(), predictionDim2.getSpectrum() + .toSpectrum(), + predictionDim1.getAssignment(), predictionDim2.getAssignment(), minPathLength, + maxPathLength); + } + + /** + * Predicts a 2D spectrum from two 1D spectra.
+ * Each 1D spectra needs to contain the same solvent information.
+ * Note: If 1H is used then it needs to be in first dimension, e.g. 1H, 13C. + * + * @param structure structure to use for prediction + * @param spectrumDim1 1D spectrum of first dimension + * @param spectrumDim2 1D spectrum of second dimension + * @param assignmentDim1 1D assignment of first dimension + * @param assignmentDim2 1D assignment of second dimension + * @param minPathLength minimal path length + * @param maxPathLength maximal path length + * + * @return + */ + public static DataSet predict2D(final IAtomContainer structure, final Spectrum spectrumDim1, + final Spectrum spectrumDim2, final Assignment assignmentDim1, + final Assignment assignmentDim2, final int minPathLength, final int maxPathLength) { + if (!spectrumDim1.getMeta() + .get("solvent") + .equals(spectrumDim2.getMeta() + .get("solvent"))) { + return null; + } + final String[] nuclei2D = new String[]{spectrumDim1.getNuclei()[0], spectrumDim2.getNuclei()[0]}; + final String atomTypeDim1 = casekit.nmr.utils.Utils.getAtomTypeFromNucleus(spectrumDim1.getNuclei()[0]); + final String atomTypeDim2 = casekit.nmr.utils.Utils.getAtomTypeFromNucleus(spectrumDim2.getNuclei()[0]); + + final Spectrum predictedSpectrum2D = new Spectrum(); + predictedSpectrum2D.setNuclei(nuclei2D); + predictedSpectrum2D.setSignals(new ArrayList<>()); + predictedSpectrum2D.addMetaInfo("solvent", spectrumDim1.getMeta() + .get("solvent")); + final Assignment assignment2D = new Assignment(); + assignment2D.setNuclei(predictedSpectrum2D.getNuclei()); + assignment2D.initAssignments(0); + + Signal signal2D; + IAtom atom; + Double shiftDim1, shiftDim2; + int addedSignalIndex; + ConnectionTree connectionTree; + List nodesInSphere; + List signalIndicesDim1, signalIndicesDim2; + for (int i = 0; i + < structure.getAtomCount(); i++) { + atom = structure.getAtom(i); + if (atom.getSymbol() + .equals(atomTypeDim1)) { + connectionTree = HOSECodeBuilder.buildConnectionTree(structure, i, maxPathLength); + for (int s = minPathLength; s + <= connectionTree.getMaxSphere(false); s++) { + nodesInSphere = connectionTree.getNodesInSphere(s, false); + for (final ConnectionTreeNode nodeInSphere : nodesInSphere) { + if (nodeInSphere.getAtom() + .getSymbol() + .equals(atomTypeDim2)) { + signal2D = new Signal(); + signal2D.setNuclei(nuclei2D); + signal2D.setKind("signal"); + signal2D.setEquivalencesCount(1); + // on first axis go through all possible assignments, i.e. in case of 1H + signalIndicesDim1 = assignmentDim1.getIndices(0, i); + for (final int signalIndexDim1 : signalIndicesDim1) { + shiftDim1 = spectrumDim1.getShift(signalIndexDim1, 0); + // on second axis go through all possible assignments, i.e. in case of 1H + signalIndicesDim2 = assignmentDim2.getIndices(0, nodeInSphere.getKey()); + for (final int signalIndexDim2 : signalIndicesDim2) { + shiftDim2 = spectrumDim2.getShift(signalIndexDim2, 0); + signal2D.setShifts(new Double[]{shiftDim1, shiftDim2}); + // add 2D signal + addedSignalIndex = predictedSpectrum2D.addSignal(signal2D); + if (addedSignalIndex + >= assignment2D.getSetAssignmentsCount(0)) { + assignment2D.addAssignment(0, new int[]{i}); + assignment2D.addAssignment(1, new int[]{nodeInSphere.getKey()}); + } else { + assignment2D.addAssignmentEquivalence(0, addedSignalIndex, i); + assignment2D.addAssignmentEquivalence(1, addedSignalIndex, + nodeInSphere.getKey()); + } + } + } + } + } + } + } + } + + return new DataSet(structure, predictedSpectrum2D, assignment2D, new HashMap<>(), new HashMap<>()); + } + + public static DataSet predictHSQC(final IAtomContainer structure, final Spectrum spectrumDim1, + final Spectrum spectrumDim2, final Assignment assignmentDim1, + final Assignment assignmentDim2) { + return predict2D(structure, spectrumDim1, spectrumDim2, assignmentDim1, assignmentDim2, 1, 1); + } + + public static DataSet predictHSQCEdited(final IAtomContainer structure, final Spectrum spectrumDim1, + final Spectrum spectrumDim2, final Assignment assignmentDim1, + final Assignment assignmentDim2) { + final DataSet dataSet = predictHSQC(structure, spectrumDim1, spectrumDim2, assignmentDim1, assignmentDim2); + final Spectrum spectrum = dataSet.getSpectrum() + .toSpectrum(); + + final String atomTypeDim2 = Utils.getAtomTypeFromSpectrum(spectrumDim2, 0); + IAtom atom; + int explicitHydrogensCount; + for (int i = 0; i + < spectrum.getSignalCount(); i++) { + atom = structure.getAtom(dataSet.getAssignment() + .getAssignment(1, i, 0)); + if (!atom.getSymbol() + .equals(atomTypeDim2)) { + continue; + } + explicitHydrogensCount = AtomContainerManipulator.countExplicitHydrogens(structure, atom); + if (explicitHydrogensCount + == 2) { + spectrum.getSignal(i) + .setPhase(-1); + } else if (explicitHydrogensCount + == 1 + || explicitHydrogensCount + == 3) { + spectrum.getSignal(i) + .setPhase(1); + } + } + + return dataSet; + } + + public static List predict1DByStereoHOSECodeAndFilter(final Spectrum querySpectrum, + final double shiftTolerance, + final double maximumAverageDeviation, + final boolean checkMultiplicity, + final boolean checkEquivalencesCount, + final boolean allowLowerEquivalencesCount, + final int maxSphere, + final List structureList, + final Map> hoseCodeShiftStatistics, + final Map multiplicitySectionsSettings, + final int nThreads) { + + + return predict1DByStereoHOSECodeAndFilter(querySpectrum, shiftTolerance, maximumAverageDeviation, + checkMultiplicity, checkEquivalencesCount, + allowLowerEquivalencesCount, null, maxSphere, structureList, + hoseCodeShiftStatistics, multiplicitySectionsSettings, nThreads); + } + + public static List predict1DByStereoHOSECodeAndFilter(final Spectrum querySpectrum, + final double shiftTolerance, + final double maximumAverageDeviation, + final boolean checkMultiplicity, + final boolean checkEquivalencesCount, + final boolean allowLowerEquivalencesCount, + final Detections detections, final int maxSphere, + final List structureList, + final Map> hoseCodeShiftStatistics, + final Map multiplicitySectionsSettings, + final int nThreads) { + final MultiplicitySectionsBuilder multiplicitySectionsBuilder = new MultiplicitySectionsBuilder(); + multiplicitySectionsBuilder.setMinLimit(multiplicitySectionsSettings.get(querySpectrum.getNuclei()[0])[0]); + multiplicitySectionsBuilder.setMaxLimit(multiplicitySectionsSettings.get(querySpectrum.getNuclei()[0])[1]); + multiplicitySectionsBuilder.setStepSize(multiplicitySectionsSettings.get(querySpectrum.getNuclei()[0])[2]); + + List dataSetList = new ArrayList<>(); + try { + final ConcurrentLinkedQueue dataSetConcurrentLinkedQueue = new ConcurrentLinkedQueue<>(); + final List> callables = new ArrayList<>(); + for (final IAtomContainer structure : structureList) { + callables.add( + () -> predict1DByStereoHOSECodeAndFilter(structure, querySpectrum, maxSphere, shiftTolerance, + maximumAverageDeviation, checkMultiplicity, + checkEquivalencesCount, allowLowerEquivalencesCount, + detections, hoseCodeShiftStatistics, + multiplicitySectionsBuilder)); + } + final Consumer consumer = (dataSet) -> { + if (dataSet + != null) { + dataSetConcurrentLinkedQueue.add(dataSet); + } + }; + MultiThreading.processTasks(callables, consumer, nThreads, 5); + dataSetList = new ArrayList<>(dataSetConcurrentLinkedQueue); + } catch (final Exception e) { + e.printStackTrace(); + } + + return dataSetList; + } + + private static DataSet predict1DByStereoHOSECodeAndFilter(final IAtomContainer structure, + final Spectrum querySpectrum, final int maxSphere, + final double shiftTolerance, + final double maxAverageDeviation, + final boolean checkMultiplicity, + final boolean checkEquivalencesCount, + final boolean allowLowerEquivalencesCount, + final Detections detections, + final Map> hoseCodeShiftStatistics, + final MultiplicitySectionsBuilder multiplicitySectionsBuilder) { + final String nucleus = querySpectrum.getNuclei()[0]; + final DataSet dataSet = predict1DByStereoHOSECode(structure, nucleus, maxSphere, hoseCodeShiftStatistics); + if (dataSet + != null) { + return FilterAndRank.checkDataSet(dataSet, querySpectrum, shiftTolerance, maxAverageDeviation, + checkMultiplicity, checkEquivalencesCount, allowLowerEquivalencesCount, + multiplicitySectionsBuilder, true, detections); + } + + return null; + } + + public static DataSet predict1DByStereoHOSECode(final IAtomContainer structure, final String nucleus, + final int maxSphere, + final Map> hoseCodeShiftStatistics) { + + final String atomType = Utils.getAtomTypeFromNucleus(nucleus); + + final Assignment assignment; + Signal signal; + Map hoseCodeObjectValues; + double predictedShift; + String hoseCode; + Double[] statistics; + int signalIndex, sphere, count; + Double min, max; + List medians; + + try { + Utils.placeExplicitHydrogens(structure); + Utils.setAromaticityAndKekulize(structure); + + final DataSet dataSet = Utils.atomContainerToDataSet(structure, false); + + final Spectrum predictedSpectrum = new Spectrum(); + predictedSpectrum.setNuclei(new String[]{nucleus}); + predictedSpectrum.setSignals(new ArrayList<>()); + + final Map> assignmentMap = new HashMap<>(); + final Map predictionMeta = new HashMap<>(); + for (int i = 0; i + < structure.getAtomCount(); i++) { + if (!structure.getAtom(i) + .getSymbol() + .equals(atomType)) { + continue; + } + medians = new ArrayList<>(); + sphere = maxSphere; + count = 0; + min = null; + max = null; + while (sphere + >= 1) { + try { + hoseCode = extendedHOSECodeGenerator.getHOSECode(structure, structure.getAtom(i), sphere); + hoseCodeObjectValues = hoseCodeShiftStatistics.get(hoseCode); + if (hoseCodeObjectValues + != null) { + for (final Map.Entry solventEntry : hoseCodeObjectValues.entrySet()) { + statistics = hoseCodeObjectValues.get(solventEntry.getKey()); + medians.add(statistics[3]); + count += statistics[0].intValue(); + min = min + == null + ? statistics[1] + : Double.min(min, statistics[1]); + max = max + == null + ? statistics[4] + : Double.max(max, statistics[4]); + } + break; + } + } catch (final Exception ignored) { + } + sphere--; + } + if (medians.isEmpty()) { + continue; + } + predictedShift = Statistics.getMean(medians); + signal = new Signal(); + signal.setNuclei(new String[]{nucleus}); + signal.setShifts(new Double[]{predictedShift}); + signal.setMultiplicity(Utils.getMultiplicityFromProtonsCount( + AtomUtils.getHcount(structure, structure.getAtom(i)))); // counts explicit H + signal.setEquivalencesCount(1); + + signalIndex = predictedSpectrum.addSignal(signal); + + assignmentMap.putIfAbsent(signalIndex, new ArrayList<>()); + assignmentMap.get(signalIndex) + .add(i); + + if (!predictionMeta.containsKey(signalIndex)) { + predictionMeta.put(signalIndex, new Double[]{(double) sphere, (double) count, min, max}); + } + } + + Utils.convertExplicitToImplicitHydrogens(structure); + dataSet.setStructure(new StructureCompact(structure)); + dataSet.addMetaInfo("smiles", SmilesGenerator.generic() + .create(structure)); + + dataSet.setSpectrum(new SpectrumCompact(predictedSpectrum)); + assignment = new Assignment(); + assignment.setNuclei(predictedSpectrum.getNuclei()); + assignment.initAssignments(predictedSpectrum.getSignalCount()); + + for (final Map.Entry> entry : assignmentMap.entrySet()) { + for (final int atomIndex : entry.getValue()) { + assignment.addAssignmentEquivalence(0, entry.getKey(), atomIndex); + } + } + dataSet.setAssignment(assignment); + + dataSet.addAttachment("predictionMeta", predictionMeta); + + return dataSet; + } catch (final Exception e) { + e.printStackTrace(); + } + + return null; + } +} diff --git a/src/casekit/nmr/similarity/Similarity.java b/src/casekit/nmr/similarity/Similarity.java new file mode 100644 index 0000000..785145b --- /dev/null +++ b/src/casekit/nmr/similarity/Similarity.java @@ -0,0 +1,392 @@ +/* + * The MIT License + * + * Copyright 2019 Michael Wenk [https://github.com/michaelwenk] + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package casekit.nmr.similarity; + +import casekit.nmr.analysis.MultiplicitySectionsBuilder; +import casekit.nmr.elucidation.model.Detections; +import casekit.nmr.model.Assignment; +import casekit.nmr.model.Signal; +import casekit.nmr.model.Spectrum; +import casekit.nmr.similarity.model.Distance; +import casekit.nmr.utils.Statistics; +import org.openscience.cdk.fingerprint.BitSetFingerprint; +import org.openscience.cdk.interfaces.IAtomContainer; +import org.openscience.cdk.similarity.Tanimoto; + +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class Similarity { + + /** + * Checks whether two spectra contain given dimensions. + * + * @param spectrum1 first spectrum + * @param spectrum2 second spectrum + * @param dim1 dimension to select in first spectrum + * @param dim2 dimension to select in second spectrum + * + * @return true if both spectra contain the selected dimension + */ + private static boolean checkDimensions(final Spectrum spectrum1, final Spectrum spectrum2, final int dim1, + final int dim2) { + return spectrum1.containsDim(dim1) + && spectrum2.containsDim(dim2); + } + + /** + * Calculates the continuous Tanimoto coefficient between two spectra in given dimensions. + * + * @param spectrum1 first spectrum + * @param spectrum2 second spectrum + * @param dim1 dimension in first spectrum to take the shifts from + * @param dim2 dimension in second spectrum to take the shifts from + * + * @return + */ + public static Double calculateTanimotoCoefficient(final Spectrum spectrum1, final Spectrum spectrum2, + final int dim1, final int dim2, + final MultiplicitySectionsBuilder multiplicitySectionsBuilder) { + if (!checkDimensions(spectrum1, spectrum2, dim1, dim2)) { + return null; + } + + return calculateTanimotoCoefficient(getBitSetFingerprint(spectrum1, dim1, multiplicitySectionsBuilder), + getBitSetFingerprint(spectrum2, dim2, multiplicitySectionsBuilder)); + } + + public static Double calculateTanimotoCoefficient(final BitSetFingerprint bitSetFingerprint1, + final BitSetFingerprint bitSetFingerprint2) { + if (bitSetFingerprint1 + == null + || bitSetFingerprint2 + == null) { + return null; + } + try { + return Tanimoto.calculate(bitSetFingerprint1, bitSetFingerprint2); + } catch (final IllegalArgumentException e) { + e.printStackTrace(); + } + + return null; + } + + public static BitSetFingerprint getBitSetFingerprint(final Spectrum spectrum, final int dim, + final MultiplicitySectionsBuilder multiplicitySectionsBuilder) { + final BitSetFingerprint bitSetFingerprint = new BitSetFingerprint(multiplicitySectionsBuilder.getSteps()); + final Map> multiplicitySections = multiplicitySectionsBuilder.buildMultiplicitySections( + spectrum, dim); + for (final Map.Entry> entry : multiplicitySections.entrySet()) { + for (final int section : entry.getValue()) { + bitSetFingerprint.set(section, true); + } + } + + return bitSetFingerprint; + } + + /** + * Returns deviations between two already matched spectra. + * + * @param spectrum1 first spectrum + * @param spectrum2 second spectrum + * @param dim1 dimension in first spectrum to take the shifts from + * @param dim2 dimension in second spectrum to take the shifts from + * @param assignments assignments from previous matching + * + * @return + */ + public static Double[] getDeviations(final Spectrum spectrum1, final Spectrum spectrum2, final int dim1, + final int dim2, final Assignment assignments) { + final Double[] deviations = new Double[spectrum1.getSignalCount()]; + Signal matchedSignalInSpectrum2; + for (int i = 0; i + < spectrum1.getSignalCount(); i++) { + if (assignments.getAssignment(0, i).length + == 0) { + deviations[i] = null; + } else { + matchedSignalInSpectrum2 = spectrum2.getSignal(assignments.getAssignment(0, i)[0]); + deviations[i] = Math.abs(spectrum1.getSignal(i) + .getShift(dim1) + - matchedSignalInSpectrum2.getShift(dim2)); + } + } + + return deviations; + } + + /** + * Returns deviations between matched shifts of two spectra. + * The matching procedure is already included here. + * + * @param spectrum1 first spectrum + * @param spectrum2 second spectrum + * @param dim1 dimension in first spectrum to take the shifts from + * @param dim2 dimension in second spectrum to take the shifts from + * @param shiftTol shift tolerance + * @param checkMultiplicity indicates whether to compare the multiplicity of matched signals + * @param checkEquivalencesCount indicates whether to compare the equivalences counts of matched signals + * @param allowLowerEquivalencesCount indicates to allow a lower equivalences counts spectrum 2 + * + * @return + * + * @see #matchSpectra(Spectrum, Spectrum, int, int, double, boolean, boolean, boolean) + */ + public static Double[] getDeviations(final Spectrum spectrum1, final Spectrum spectrum2, final int dim1, + final int dim2, final double shiftTol, final boolean checkMultiplicity, + final boolean checkEquivalencesCount, + final boolean allowLowerEquivalencesCount) { + final Assignment matchAssignments = matchSpectra(spectrum1, spectrum2, dim1, dim2, shiftTol, checkMultiplicity, + checkEquivalencesCount, allowLowerEquivalencesCount); + + return getDeviations(spectrum1, spectrum2, dim1, dim2, matchAssignments); + } + + /** + * Returns the average of all deviations of matched shifts between two + * spectra. + * + * @param spectrum1 first spectrum + * @param spectrum2 second spectrum + * @param dim1 dimension in first spectrum to take the shifts from + * @param dim2 dimension in second spectrum to take the shifts from + * @param shiftTol Tolerance value [ppm] used during peak picking in + * shift comparison + * @param checkMultiplicity indicates whether to compare the multiplicity of matched signals + * @param checkEquivalencesCount indicates whether to compare the equivalences counts of matched signals + * @param allowLowerEquivalencesCount indicates to allow a lower equivalences counts spectrum 2 + * + * @return + * + * @see #getDeviations(Spectrum, Spectrum, int, int, double, boolean, boolean, boolean) + * @see Statistics#calculateAverageDeviation(Double[]) + */ + public static Double calculateAverageDeviation(final Spectrum spectrum1, final Spectrum spectrum2, final int dim1, + final int dim2, final double shiftTol, + final boolean checkMultiplicity, + final boolean checkEquivalencesCount, + final boolean allowLowerEquivalencesCount) { + return Statistics.calculateAverageDeviation( + Similarity.getDeviations(spectrum1, spectrum2, dim1, dim2, shiftTol, checkMultiplicity, + checkEquivalencesCount, allowLowerEquivalencesCount)); + } + + /** + * Returns the average of all deviations of matched shifts between two + * spectra. + * + * @param spectrum1 first spectrum + * @param spectrum2 second spectrum + * @param dim1 dimension in first spectrum to take the shifts from + * @param dim2 dimension in second spectrum to take the shifts from + * @param assignments assignments from previous matching + * + * @return + * + * @see #getDeviations(Spectrum, Spectrum, int, int, double, boolean, boolean, boolean) + * @see Statistics#calculateAverageDeviation(Double[]) + */ + public static Double calculateAverageDeviation(final Spectrum spectrum1, final Spectrum spectrum2, final int dim1, + final int dim2, final Assignment assignments) { + return Statistics.calculateAverageDeviation( + Similarity.getDeviations(spectrum1, spectrum2, dim1, dim2, assignments)); + } + + /** + * Returns the average of all deviations of matched shifts between two + * spectra. + * + * @param spectrum1 first spectrum + * @param spectrum2 second spectrum + * @param dim1 dimension in first spectrum to take the shifts from + * @param dim2 dimension in second spectrum to take the shifts from + * @param shiftTol Tolerance value [ppm] used during peak picking in + * shift comparison + * @param checkMultiplicity indicates whether to compare the multiplicity of matched signals + * @param checkEquivalencesCount indicates whether to compare the equivalences counts of matched signals + * @param allowLowerEquivalencesCount indicates to allow a lower equivalences counts spectrum 2 + * + * @return + * + * @see #getDeviations(Spectrum, Spectrum, int, int, double, boolean, boolean, boolean) + * @see Statistics#calculateAverageDeviation(Double[]) + */ + public static Double calculateRMSD(final Spectrum spectrum1, final Spectrum spectrum2, final int dim1, + final int dim2, final double shiftTol, final boolean checkMultiplicity, + final boolean checkEquivalencesCount, + final boolean allowLowerEquivalencesCount) { + return Statistics.calculateRMSD( + Similarity.getDeviations(spectrum1, spectrum2, dim1, dim2, shiftTol, checkMultiplicity, + checkEquivalencesCount, allowLowerEquivalencesCount)); + } + + /** + * Returns the average of all deviations of matched shifts between two + * spectra. + * + * @param spectrum1 first spectrum + * @param spectrum2 second spectrum + * @param dim1 dimension in first spectrum to take the shifts from + * @param dim2 dimension in second spectrum to take the shifts from + * @param assignments assignments from previous matching + * + * @return + * + * @see #getDeviations(Spectrum, Spectrum, int, int, double, boolean, boolean, boolean) + * @see Statistics#calculateAverageDeviation(Double[]) + */ + public static Double calculateRMSD(final Spectrum spectrum1, final Spectrum spectrum2, final int dim1, + final int dim2, final Assignment assignments) { + return Statistics.calculateRMSD(Similarity.getDeviations(spectrum1, spectrum2, dim1, dim2, assignments)); + } + + /** + * Returns the closest shift matches between two spectra in selected dimensions + * as an Assignment object with one set dimension only.
+ * + * @param spectrum1 first spectrum (possible subspectrum) + * @param spectrum2 second spectrum + * @param dim1 dimension in first spectrum to take the shifts from + * @param dim2 dimension in second spectrum to take the shifts from + * @param shiftTolerance Tolerance value [ppm] used during spectra shift + * comparison + * @param checkMultiplicity indicates whether to compare the multiplicity of matched signals + * @param checkEquivalencesCount indicates whether to compare the equivalences counts of matched signals + * @param allowLowerEquivalencesCount indicates to allow a lower equivalences counts spectrum 2 + * + * @return Assignments with signal indices of spectrum and matched indices + * in query spectrum; null if one of the spectra does not + * contain the selected dimension + */ + public static Assignment matchSpectra(final Spectrum spectrum1, final Spectrum spectrum2, final int dim1, + final int dim2, final double shiftTolerance, final boolean checkMultiplicity, + final boolean checkEquivalencesCount, + final boolean allowLowerEquivalencesCount) { + return matchSpectra(spectrum1, spectrum2, dim1, dim2, shiftTolerance, checkMultiplicity, checkEquivalencesCount, + allowLowerEquivalencesCount, null, null, null); + } + + + /** + * Returns the closest shift matches between two spectra in all dimensions + * as one Assignment object with N set dimensions. + * N here means the number of dimensions in both spectra.
+ * Despite intensities are expected, they are still not considered here. + * + * @param spectrum1 first spectrum (possible subspectrum) + * @param spectrum2 second spectrum + * @param shiftTols tolerance values [ppm] per each dimension used during spectra shift + * comparisons + * @param checkMultiplicity indicates whether to compare the multiplicity of matched signals + * @param checkEquivalencesCount indicates whether to compare the equivalences counts of matched signals + * @param allowLowerEquivalencesCount indicates to allow a lower equivalences counts spectrum 2 + * + * @return Assignments with signal indices of spectrum1 and matched indices + * in spectrum2 for each dimension; null if the number of + * dimensions in both spectra is not the same or is different than the number of given + * shift tolerances + * + * @see #matchSpectra(Spectrum, Spectrum, int, int, double, boolean, boolean, boolean) + */ + public static Assignment matchSpectra(final Spectrum spectrum1, final Spectrum spectrum2, final double[] shiftTols, + final boolean checkMultiplicity, final boolean checkEquivalencesCount, + final boolean allowLowerEquivalencesCount) { + if ((spectrum1.getNDim() + != spectrum2.getNDim()) + || (spectrum1.getNDim() + != shiftTols.length)) { + return null; + } + final Assignment matchAssignment = new Assignment(); + matchAssignment.setNuclei(spectrum1.getNuclei()); + matchAssignment.initAssignments(spectrum1.getSignalCount()); + for (int dim = 0; dim + < spectrum1.getNDim(); dim++) { + matchAssignment.setAssignments(dim, matchSpectra(spectrum1, spectrum2, dim, dim, shiftTols[dim], + checkMultiplicity, checkEquivalencesCount, + allowLowerEquivalencesCount).getAssignments(0)); + } + + return matchAssignment; + } + + /** + * Returns the closest shift matches between two spectra in selected dimensions + * as an Assignment object with one set dimension only.
+ * + * @param spectrum1 first spectrum (possible subspectrum) + * @param spectrum2 second spectrum + * @param dim1 dimension in first spectrum to take the shifts from + * @param dim2 dimension in second spectrum to take the shifts from + * @param shiftTolerance Tolerance value [ppm] used during spectra shift + * comparison + * @param checkMultiplicity indicates whether to compare the multiplicity of matched signals + * @param checkEquivalencesCount indicates whether to compare the equivalences counts of matched signals + * @param allowLowerEquivalencesCount indicates to allow a lower equivalences counts spectrum 2 + * @param structure structure belonging to second spectrum + * @param assignment assignments between structure and second spectrum + * @param detections detections object which contains structural constraints + * + * @return Assignments with signal indices of spectrum and matched indices + * in query spectrum; null if one of the spectra does not + * contain the selected dimension + */ + public static Assignment matchSpectra(final Spectrum spectrum1, final Spectrum spectrum2, final int dim1, + final int dim2, final double shiftTolerance, final boolean checkMultiplicity, + final boolean checkEquivalencesCount, + final boolean allowLowerEquivalencesCount, final IAtomContainer structure, + final Assignment assignment, final Detections detections) { + if (!Similarity.checkDimensions(spectrum1, spectrum2, dim1, dim2)) { + return null; + } + final List distanceList = detections + != null + && structure + != null + && assignment + != null + ? Utilities.buildDistanceList(spectrum1, spectrum2, dim1, dim2, + shiftTolerance, checkMultiplicity, + checkEquivalencesCount, + allowLowerEquivalencesCount, structure, + assignment, detections) + : Utilities.buildDistanceList(spectrum1, spectrum2, dim1, dim2, + shiftTolerance, checkMultiplicity, + checkEquivalencesCount, + allowLowerEquivalencesCount); + + final Assignment matchAssignment = new Assignment(); + matchAssignment.setNuclei(spectrum1.getNuclei()); + matchAssignment.initAssignments(spectrum1.getSignalCount()); + final Set assignedSpectrum1 = new HashSet<>(); + final Set assignedSpectrum2 = new HashSet<>(); + for (final Distance distance : distanceList) { + if (!assignedSpectrum1.contains(distance.getSignalIndexSpectrum1()) + && !assignedSpectrum2.contains(distance.getSignalIndexSpectrum2())) { + for (int equiv = 0; equiv + < spectrum2.getEquivalencesCount(distance.getSignalIndexSpectrum2()); equiv++) { + matchAssignment.addAssignmentEquivalence(0, distance.getSignalIndexSpectrum1(), + distance.getSignalIndexSpectrum2()); + } + assignedSpectrum1.add(distance.getSignalIndexSpectrum1()); + assignedSpectrum2.add(distance.getSignalIndexSpectrum2()); + } + } + + return matchAssignment; + } +} diff --git a/src/casekit/nmr/similarity/Utilities.java b/src/casekit/nmr/similarity/Utilities.java new file mode 100644 index 0000000..23fe1aa --- /dev/null +++ b/src/casekit/nmr/similarity/Utilities.java @@ -0,0 +1,181 @@ +package casekit.nmr.similarity; + +import casekit.nmr.elucidation.Constants; +import casekit.nmr.elucidation.model.Detections; +import casekit.nmr.model.Assignment; +import casekit.nmr.model.Signal; +import casekit.nmr.model.Spectrum; +import casekit.nmr.similarity.model.Distance; +import org.openscience.cdk.interfaces.IAtom; +import org.openscience.cdk.interfaces.IAtomContainer; + +import java.util.*; + +public class Utilities { + + + /** + * @param spectrum1 first spectrum (possible subspectrum) + * @param spectrum2 second spectrum + * @param dim1 dim in first spectrum + * @param dim2 dim in second spectrum + * @param shiftTolerance shift tolerance + * @param checkMultiplicity whether to check multiplicity + * @param checkEquivalencesCount whether to check equivalences + * @param allowLowerEquivalencesCount whether to allow lower equivalences + * + * @return + */ + public static List buildDistanceList(final Spectrum spectrum1, final Spectrum spectrum2, final int dim1, + final int dim2, final double shiftTolerance, + final boolean checkMultiplicity, + final boolean checkEquivalencesCount, + final boolean allowLowerEquivalencesCount) { + final List distanceList = new ArrayList<>(); + Double distanceValue; + for (int i = 0; i + < spectrum1.getSignalCount(); i++) { + for (int j = 0; j + < spectrum2.getSignalCount(); j++) { + distanceValue = getDistanceValue(spectrum1.getSignal(i), spectrum2.getSignal(j), dim1, dim2, + checkMultiplicity, checkEquivalencesCount, allowLowerEquivalencesCount, + shiftTolerance); + if (distanceValue + != null) { + distanceList.add(new Distance(i, j, distanceValue)); + } + } + } + distanceList.sort(Comparator.comparingDouble(Distance::getValue)); + + return distanceList; + } + + public static Double getDistanceValue(final Signal signal1, final Signal signal2, final int dim1, final int dim2, + final boolean checkMultiplicity, final boolean checkEquivalencesCount, + final boolean allowLowerEquivalencesCount, final double shiftTolerance) { + boolean passed = true; + // @TODO maybe consider further parameters to check ? e.g. intensity + if (checkMultiplicity) { + passed = (signal1.getMultiplicity() + == null + && signal2.getMultiplicity() + == null) + || (signal1.getMultiplicity() + != null + && signal1.getMultiplicity() + .equalsIgnoreCase(signal2.getMultiplicity())); + } + if (passed + && checkEquivalencesCount) { + if (allowLowerEquivalencesCount) { + passed = signal1.getEquivalencesCount() + <= signal2.getEquivalencesCount(); + } else { + passed = signal1.getEquivalencesCount() + == signal2.getEquivalencesCount(); + } + } + if (!passed) { + return null; + } + final double distanceValue = Math.abs(signal1.getShift(dim1) + - signal2.getShift(dim2)); + + return distanceValue + > shiftTolerance + ? null + : distanceValue; + } + + /** + * @param spectrum1 first spectrum (possible subspectrum) + * @param spectrum2 second spectrum + * @param dim1 dim in first spectrum + * @param dim2 dim in second spectrum + * @param shiftTolerance shift tolerance + * @param checkMultiplicity whether to check multiplicity + * @param checkEquivalencesCount whether to check equivalences + * @param allowLowerEquivalencesCount whether to allow lower equivalences + * @param structure structure belonging to first spectrum + * @param assignment assignments between structure and first spectrum + * @param detections detections to use as structural filter within given structure + * + * @return + */ + public static List buildDistanceList(final Spectrum spectrum1, final Spectrum spectrum2, final int dim1, + final int dim2, final double shiftTolerance, + final boolean checkMultiplicity, + final boolean checkEquivalencesCount, + final boolean allowLowerEquivalencesCount, + final IAtomContainer structure, final Assignment assignment, + final Detections detections) { + final List distanceList = new ArrayList<>(); + Double distanceValue; + List hybridizations; + Set forbiddenNeighbors, setNeighbors, setNeighborsTemp; + IAtom atom; + boolean skip; + for (int i = 0; i + < spectrum1.getSignalCount(); i++) { + for (int j = 0; j + < spectrum2.getSignalCount(); j++) { + // check spectral constraints + distanceValue = getDistanceValue(spectrum1.getSignal(i), spectrum2.getSignal(j), dim1, dim2, + checkMultiplicity, checkEquivalencesCount, allowLowerEquivalencesCount, + shiftTolerance); + if (distanceValue + == null) { + continue; + } + skip = false; + // check structural constraints + forbiddenNeighbors = detections.getForbiddenNeighbors() + .get(j) + .keySet(); + setNeighbors = detections.getSetNeighbors() + .get(j) + .keySet(); + hybridizations = detections.getDetectedHybridizations() + .get(j); + for (int equiv = 0; equiv + < assignment.getAssignment(0, i).length; equiv++) { + atom = structure.getAtom(assignment.getAssignment(0, i, equiv)); + // if certain hybridizations are given and the atom's hybridization is known + if (!hybridizations.isEmpty() + && Constants.hybridizationConversionMap.containsKey(atom.getHybridization() + .name())) { + skip = !hybridizations.contains(Constants.hybridizationConversionMap.get(atom.getHybridization() + .name())); + if (skip) { + break; + } + } + setNeighborsTemp = new HashSet<>(setNeighbors); + for (final IAtom neighborAtom : structure.getConnectedAtomsList(atom)) { + skip = forbiddenNeighbors.contains(neighborAtom.getSymbol()); + if (skip) { + break; + } + setNeighborsTemp.remove(neighborAtom.getSymbol()); + } + if (!setNeighborsTemp.isEmpty()) { + skip = true; + } + if (skip) { + break; + } + } + if (skip) { + continue; + } + + // if passed all check then add to distance list + distanceList.add(new Distance(i, j, distanceValue)); + } + } + distanceList.sort(Comparator.comparingDouble(Distance::getValue)); + + return distanceList; + } +} diff --git a/src/casekit/nmr/similarity/model/Distance.java b/src/casekit/nmr/similarity/model/Distance.java new file mode 100644 index 0000000..f50dc34 --- /dev/null +++ b/src/casekit/nmr/similarity/model/Distance.java @@ -0,0 +1,38 @@ +package casekit.nmr.similarity.model; + +public class Distance { + + private final int signalIndexSpectrum1; + private final int signalIndexSpectrum2; + private final double value; + + public Distance(final int signalIndexSpectrum1, final int signalIndexSpectrum2, final double value) { + this.signalIndexSpectrum1 = signalIndexSpectrum1; + this.signalIndexSpectrum2 = signalIndexSpectrum2; + this.value = value; + } + + public int getSignalIndexSpectrum1() { + return this.signalIndexSpectrum1; + } + + public int getSignalIndexSpectrum2() { + return this.signalIndexSpectrum2; + } + + public double getValue() { + return this.value; + } + + @Override + public String toString() { + return "Distance{" + + "signalIndexSpectrum1=" + + this.signalIndexSpectrum1 + + ", signalIndexSpectrum2=" + + this.signalIndexSpectrum2 + + ", value=" + + this.value + + '}'; + } +} diff --git a/src/casekit/nmr/utils/Parser.java b/src/casekit/nmr/utils/Parser.java new file mode 100644 index 0000000..3a1a574 --- /dev/null +++ b/src/casekit/nmr/utils/Parser.java @@ -0,0 +1,79 @@ +package casekit.nmr.utils; + +import casekit.nmr.model.DataSet; +import org.openscience.cdk.exception.CDKException; +import org.openscience.cdk.io.iterator.IteratingSDFReader; +import org.openscience.cdk.silent.SilentChemObjectBuilder; +import org.openscience.cdk.smiles.SmilesParser; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +public class Parser { + + public static List parseSDFile(final String pathToFile) throws CDKException, FileNotFoundException { + return parseSDFile(new FileReader(pathToFile)); + } + + public static List parseSDFileContent(final String fileContent) throws CDKException { + final InputStream inputStream = new ByteArrayInputStream(fileContent.getBytes(StandardCharsets.UTF_8)); + return parseSDFile(new InputStreamReader(inputStream)); + } + + public static List parseSDFile(final Reader fileReader) throws CDKException { + final List dataSetList = new ArrayList<>(); + final IteratingSDFReader iterator = new IteratingSDFReader(fileReader, SilentChemObjectBuilder.getInstance()); + + while (iterator.hasNext()) { + dataSetList.add(Utils.atomContainerToDataSet(iterator.next())); + } + + return dataSetList; + } + + public static List parseSmilesFile(final String pathToFile) throws FileNotFoundException { + return parseSmilesFile(new FileReader(pathToFile)); + } + + public static List parseSmilesFileContent(final String fileContent) { + final InputStream inputStream = new ByteArrayInputStream(fileContent.getBytes(StandardCharsets.UTF_8)); + return parseSmilesFile(new InputStreamReader(inputStream)); + } + + public static List parseSmilesFile(final Reader fileReader) { + final List dataSetList = new ArrayList<>(); + final BufferedReader bufferedReader = new BufferedReader(fileReader); + final SmilesParser smilesParser = new SmilesParser(SilentChemObjectBuilder.getInstance()); + bufferedReader.lines() + .forEach(smiles -> { + try { + dataSetList.add(Utils.atomContainerToDataSet(smilesParser.parseSmiles(smiles))); + } catch (final CDKException e) { + e.printStackTrace(); + } + }); + + return dataSetList; + } + + public static List smilesFileToList(final String pathToFile) throws FileNotFoundException { + return smilesFileToList(new FileReader(pathToFile)); + } + + public static List smilesFileContentToList(final String fileContent) { + final InputStream inputStream = new ByteArrayInputStream(fileContent.getBytes(StandardCharsets.UTF_8)); + return smilesFileToList(new InputStreamReader(inputStream)); + } + + public static List smilesFileToList(final Reader fileReader) { + final List smilesList = new ArrayList<>(); + final BufferedReader bufferedReader = new BufferedReader(fileReader); + bufferedReader.lines() + .forEach(smilesList::add); + + return smilesList; + } + +} diff --git a/src/casekit/nmr/utils/Statistics.java b/src/casekit/nmr/utils/Statistics.java new file mode 100644 index 0000000..94cab89 --- /dev/null +++ b/src/casekit/nmr/utils/Statistics.java @@ -0,0 +1,335 @@ +package casekit.nmr.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +public class Statistics { + /** + * Detects outliers in given array list of input values and removes them.
+ * Here, outliers are those which are outside of a calculated lower and upper bound (whisker). + * The interquartile range (IQR) of the input values is therefore multiplied with a given value + * for whisker creation. + * + * @param input list of values to process + * @param multiplierIQR multiplier for IQR to use for lower and upper bound creation + * + * @return new array list without values outside the generated boundaries + */ + public static List removeOutliers(final List input, final double multiplierIQR) { + final List values = new ArrayList<>(); + if (input.size() + <= 1) { + return values; + } + final double[] boundaries = getLowerAndUpperBoundaries(input, multiplierIQR); + final double lowerBound = boundaries[0]; + final double upperBound = boundaries[1]; + + for (final Double value : input) { + if (value + >= lowerBound + && value + <= upperBound) { + values.add(value); + } + } + + return values; + } + + /** + * Detects outliers in given array list of input values and returns them.
+ * Here, outliers are those which are outside of a calculated lower and upper bound (whisker). + * The interquartile range (IQR) of the input values is therefore multiplied with a given value + * for whisker creation. + * + * @param input list of values to process + * @param multiplierIQR multiplier for IQR to use for lower and upper bound creation + * + * @return new array list with values outside the generated boundaries + */ + public static List getOutliers(final List input, final double multiplierIQR) { + final List outliers = new ArrayList<>(); + if (input.size() + <= 1) { + return outliers; + } + final double[] boundaries = getLowerAndUpperBoundaries(input, multiplierIQR); + final double lowerBound = boundaries[0]; + final double upperBound = boundaries[1]; + for (final Double value : input) { + if (value + < lowerBound + || value + > upperBound) { + outliers.add(value); + } + } + + return outliers; + } + + public static double[] getLowerAndUpperBoundaries(final List input, final double multiplierIQR) { + Collections.sort(input); + final List data1 = input.subList(0, input.size() + / 2); + final List data2; + if (input.size() + % 2 + == 0) { + data2 = input.subList(input.size() + / 2, input.size()); + } else { + data2 = input.subList(input.size() + / 2 + + 1, input.size()); + } + final double q1 = getMedian(data1); + final double q3 = getMedian(data2); + final double iqr = q3 + - q1; + final double lowerBound = q1 + - multiplierIQR + * iqr; + final double upperBound = q3 + + multiplierIQR + * iqr; + + return new double[]{lowerBound, upperBound}; + } + + /** + * @param data + * + * @return + */ + public static Double getMedian(final List data) { + if ((data + == null) + || data.isEmpty()) { + return null; + } + if (data.size() + == 1) { + return data.get(0); + } + Collections.sort(data); + if (data.size() + % 2 + == 1) { + return data.get(data.size() + / 2); + } else { + return (data.get(data.size() + / 2 + - 1) + + data.get(data.size() + / 2)) + / 2.0; + } + } + + /** + * @param data + * + * @return + */ + public static Double getMean(final Collection data) { + if ((data + == null) + || data.isEmpty()) { + return null; + } + double sum = 0; + int nullCounter = 0; + for (final Double d : data) { + if (d + != null) { + sum += d; + } else { + nullCounter++; + } + } + return ((data.size() + - nullCounter) + != 0) + ? (sum + / (data.size() + - nullCounter)) + : null; + } + + /** + * @param data + * + * @return + */ + public static Double getStandardDeviation(final List data) { + if ((data + == null) + || data.isEmpty()) { + return null; + } + final Double variance = getVariance(data); + + return (variance + != null) + ? Math.sqrt(variance) + : null; + } + + /** + * @param data + * + * @return + */ + public static Double getVariance(final Collection data) { + if ((data + == null) + || data.isEmpty()) { + return null; + } + final int nullCounter = Collections.frequency(data, null); + double quadrSum = 0.0; + final Double mean = getMean(data); + if (mean + == null) { + return null; + } + for (final Double d : data) { + if (d + != null) { + quadrSum += Math.pow(d + - mean, 2); + } + } + + return ((data.size() + - nullCounter) + != 0) + ? (quadrSum + / (data.size() + - nullCounter)) + : null; + } + + /** + * @param data + * + * @return + */ + public static Double getMean(final Double[] data) { + if ((data + == null) + || (data.length + == 0)) { + return null; + } + double sum = 0; + int nullCounter = 0; + for (final Double d : data) { + if (d + != null) { + sum += d; + } else { + nullCounter++; + } + } + return ((data.length + - nullCounter) + != 0) + ? (sum + / (data.length + - nullCounter)) + : null; + } + + public static Double roundDouble(final Double value, final int decimalPlaces) { + if (value + == null) { + return null; + } + final int decimalFactor = (int) (Math.pow(10, decimalPlaces)); + + return (Math.round(value + * decimalFactor) + / (double) decimalFactor); + } + + /** + * @param data + * + * @return + */ + public static Double getRMSD(final Double[] data) { + if (data + == null + || data.length + == 0) { + return null; + } + if (data.length + == 1) { + return data[0]; + } + int nullCounter = 0; + double qSum = 0; + for (final Double d : data) { + if (d + != null) { + qSum += d + * d; + } else { + nullCounter++; + } + } + + return ((data.length + - nullCounter) + != 0) + ? Math.sqrt(qSum + / (data.length + - nullCounter)) + : null; + } + + /** + * Returns the average of all deviations within a given input array. + * + * @param deviations array of deviations + * + * @return + */ + public static Double calculateAverageDeviation(final Double[] deviations) { + // every signal has to have a match + for (final Double deviation : deviations) { + if (deviation + == null) { + return null; + } + } + + return getMean(deviations); + } + + /** + * Returns the average of all deviations within a given input array. + * + * @param data array of deviations + * + * @return + */ + public static Double calculateRMSD(final Double[] data) { + // every signal has to have a match + for (final Double value : data) { + if (value + == null) { + return null; + } + } + + return getRMSD(data); + } +} diff --git a/src/casekit/nmr/utils/Utils.java b/src/casekit/nmr/utils/Utils.java new file mode 100644 index 0000000..519b156 --- /dev/null +++ b/src/casekit/nmr/utils/Utils.java @@ -0,0 +1,782 @@ +package casekit.nmr.utils; + +import casekit.nmr.elucidation.Constants; +import casekit.nmr.model.Signal; +import casekit.nmr.model.Spectrum; +import casekit.nmr.model.*; +import casekit.nmr.model.nmrium.*; +import com.google.gson.Gson; +import org.openscience.cdk.aromaticity.Aromaticity; +import org.openscience.cdk.aromaticity.ElectronDonation; +import org.openscience.cdk.aromaticity.Kekulization; +import org.openscience.cdk.atomtype.CDKAtomTypeMatcher; +import org.openscience.cdk.exception.CDKException; +import org.openscience.cdk.graph.CycleFinder; +import org.openscience.cdk.graph.Cycles; +import org.openscience.cdk.interfaces.*; +import org.openscience.cdk.layout.StructureDiagramGenerator; +import org.openscience.cdk.silent.SilentChemObjectBuilder; +import org.openscience.cdk.smiles.SmiFlavor; +import org.openscience.cdk.smiles.SmilesGenerator; +import org.openscience.cdk.tools.CDKHydrogenAdder; +import org.openscience.cdk.tools.manipulator.AtomContainerManipulator; +import org.openscience.cdk.tools.manipulator.AtomTypeManipulator; +import org.openscience.cdk.tools.manipulator.MolecularFormulaManipulator; +import org.openscience.nmrshiftdb.util.AtomUtils; + +import java.io.IOException; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public class Utils { + + private static final StructureDiagramGenerator structureDiagramGenerator = new StructureDiagramGenerator(); + + /** + * Specified for carbons only -> not generic!!! + * + * @param protonsCount + * + * @return + */ + public static String getMultiplicityFromProtonsCount(final int protonsCount) { + switch (protonsCount) { + case 0: + return "s"; + case 1: + return "d"; + case 2: + return "t"; + case 3: + return "q"; + default: + return null; + } + } + + public static String getMultiplicityFromProtonsCount(final Correlation correlation) { + if (correlation.getAtomType() + .equals("C") + && correlation.getProtonsCount() + .size() + == 1) { + return getMultiplicityFromProtonsCount(correlation.getProtonsCount() + .get(0)); + } + return null; + } + + public static String getAtomTypeFromSpectrum(final Spectrum spectrum, final int dim) { + if (spectrum.containsDim(dim)) { + return getAtomTypeFromNucleus(spectrum.getNuclei()[dim]); + } + + return null; + } + + public static String getAtomTypeFromNucleus(final String nucleus) { + final String[] nucleusSplit = nucleus.split("\\d"); + return nucleusSplit[nucleusSplit.length + - 1]; + } + + public static IMolecularFormula getMolecularFormulaFromString(final String mf) { + return MolecularFormulaManipulator.getMolecularFormula(mf, SilentChemObjectBuilder.getInstance()); + } + + public static String getSmilesFromAtomContainer(final IAtomContainer ac) throws CDKException { + // SmiFlavor.Unique instead of SmiFlavor.Absolute because current errors with InChI generator + final SmilesGenerator smilesGenerator = new SmilesGenerator(SmiFlavor.Unique); + + return smilesGenerator.create(ac); + } + + public static String getAlphabeticMF(final String mf) { + final StringBuilder mfAlphabeticStringBuilder = new StringBuilder(); + final Map mfAlphabeticMap = new TreeMap<>(getMolecularFormulaElementCounts(mf)); + for (final Map.Entry entry : mfAlphabeticMap.entrySet()) { + mfAlphabeticStringBuilder.append(entry.getKey()); + if (entry.getValue() + > 1) { + mfAlphabeticStringBuilder.append(entry.getValue()); + } + } + + return mfAlphabeticStringBuilder.toString(); + } + + public static Map getMolecularFormulaElementCounts(final String mf) { + final LinkedHashMap counts = new LinkedHashMap<>(); + final List elements = new ArrayList<>(); + Matcher matcher = Pattern.compile("([A-Z][a-z]{0,1})") + .matcher(mf); + while (matcher.find()) { + elements.add(matcher.group(1)); + } + int count; + for (final String element : elements) { + matcher = Pattern.compile("(" + + element + + "\\d+)") + .matcher(mf); + count = 1; + if (matcher.find()) { + count = Integer.parseInt(matcher.group(1) + .split(element)[1]); + } + counts.put(element, count); + } + + return counts; + } + + public static int getAtomTypeCount(final IAtomContainer structure, final String atomType) { + return getAtomTypeIndicesByElement(structure, atomType).size(); + } + + public static int getAtomTypeCount(final String mf, final String atomType) { + return MolecularFormulaManipulator.getElementCount(getMolecularFormulaFromString(mf), atomType); + } + + public static boolean compareWithMolecularFormulaLessOrEqual(final IAtomContainer structure, final String mf) { + if (mf + == null + || mf.trim() + .isEmpty()) { + return false; + } + for (final String atomType : getAtomTypesInAtomContainer(structure)) { + if (!atomType.equals("R") + && getAtomTypeCount(structure, atomType) + > getAtomTypeCount(mf, atomType)) { + return false; + } + } + return AtomContainerManipulator.getImplicitHydrogenCount(structure) + <= getAtomTypeCount(mf, "H"); + + + } + + public static boolean compareWithMolecularFormulaEqual(final IAtomContainer structure, final String mf) { + if (mf + == null + || mf.trim() + .isEmpty()) { + return false; + } + for (final String atomType : getAtomTypesInAtomContainer(structure)) { + if (getAtomTypeCount(structure, atomType) + != getAtomTypeCount(mf, atomType)) { + return false; + } + } + return AtomContainerManipulator.getImplicitHydrogenCount(structure) + == Utils.getAtomTypeCount(mf, "H"); + } + + /** + * Returns a hashmap consisting of lists of atom indices in an atom container. + * This is done for all atom types (e.g. C or Br) in given atom container. + * + * @param ac IAtomContainer to look in + * + * @return + * + * @see #getAtomTypeIndicesByElement(IAtomContainer, String) + */ + public static Map> getAtomTypeIndices(final IAtomContainer ac) { + + final Map> atomTypeIndices = new HashMap<>(); + final Set atomTypes = new HashSet<>(); + for (final IAtom heavyAtom : AtomContainerManipulator.getHeavyAtoms(ac)) { + atomTypes.add(heavyAtom.getSymbol()); + } + for (final String atomType : atomTypes) { + atomTypeIndices.put(atomType, getAtomTypeIndicesByElement(ac, atomType)); + } + + return atomTypeIndices; + } + + /** + * Returns a list of atom indices in an atom container for a given atom + * type (e.g. C or Br) + * + * @param ac IAtomContainer to use for search + * @param atomType Atom type to find in atom container + * + * @return + */ + public static List getAtomTypeIndicesByElement(final IAtomContainer ac, final String atomType) { + + final ArrayList indices = new ArrayList<>(); + for (int i = 0; i + < ac.getAtomCount(); i++) { + if (ac.getAtom(i) + .getSymbol() + .equals(atomType)) { + indices.add(i); + } + } + + return indices; + } + + public static IMolecularFormula getMolecularFormulaFromAtomContainer(final IAtomContainer ac) { + return MolecularFormulaManipulator.getMolecularFormula(ac); + } + + public static String molecularFormularToString(final IMolecularFormula molecularFormula) { + return MolecularFormulaManipulator.getString(molecularFormula); + } + + public static int getDifferenceSpectrumSizeAndMolecularFormulaCount(final Spectrum spectrum, + final IMolecularFormula molFormula, + final int dim) throws CDKException { + if (!spectrum.containsDim(dim)) { + throw new CDKException(Thread.currentThread() + .getStackTrace()[2].getClassName() + + "." + + Thread.currentThread() + .getStackTrace()[2].getMethodName() + + ": invalid dimension in spectrum given"); + } + final String atomType = getAtomTypeFromSpectrum(spectrum, dim); + int atomsInMolFormula = 0; + if (molFormula + != null) { + atomsInMolFormula = MolecularFormulaManipulator.getElementCount(molFormula, atomType); + } + return atomsInMolFormula + - spectrum.getSignalCountWithEquivalences(); + } + + /** + * Returns the casekit.nmr isotope identifier for a given element, e.g. C -> 13C. + * Elements defined so far: C, H, N, P, F, D, O, S, Si, B, Pt. + * + * @param element element's symbol (e.g. "C") + * + * @return + */ + public static String getIsotopeIdentifier(final String element) { + switch (element) { + case "C": + return "13C"; + case "H": + return "1H"; + case "N": + return "15N"; + case "P": + return "31P"; + case "F": + return "19F"; + case "O": + return "17O"; + case "S": + return "33S"; + case "Si": + return "29Si"; + case "B": + return "11B"; + case "Pt": + return "195Pt"; + default: + return element; + } + } + + public static Set getAtomTypesInAtomContainer(final IAtomContainer ac) { + final HashSet atomTypes = new HashSet<>(); + for (final IAtom atom : ac.atoms()) { + atomTypes.add(atom.getSymbol()); + } + + return atomTypes; + } + + public static boolean isValidBondAddition(final IAtomContainer ac, final int atomIndex, final IBond bondToAdd) { + float bondOrderSum = getBondOrderSum(ac, atomIndex, true); + bondOrderSum += getBondOrderAsNumeric(bondToAdd); + + // System.out.print(atomIndex + " --> " + HOSECodeUtilities.getBondOrderSum(ac, atomIndex, true) + " + " + HOSECodeUtilities.getBondOrderAsNumeric(bondToAdd)); + final IAtom atom = ac.getAtom(atomIndex); + // @TODO include different valencies: N3, N5, S2, S4, S6 etc. + // -1 for cases with heterocyclic aromatics, like the N in the small aromatic ring in coffein if we want to add the bond to the CH3 group + if (atom.isAromatic() + && (atom.getSymbol() + .equals("N") + || atom.getSymbol() + .equals("S") + || atom.getSymbol() + .equals("P"))) { + // System.out.print("[ -1 ]"); + bondOrderSum -= 1; + } + // System.out.print(" = " + bondOrderSum + " <= " + atom.getValency() + " ? -> " + (bondOrderSum <= atom.getValency()) + "\n"); + + // @TODO include charges + return bondOrderSum + <= atom.getValency(); + } + + public static boolean isSaturated(final IAtomContainer ac, final int atomIndex) { + final IAtom atom = ac.getAtom(atomIndex); + if (atom.getSymbol() + .equals("R")) { + return false; + } + return atom.getValency() + != null + && getBondOrderSum(ac, atomIndex, true).intValue() + >= atom.getValency(); + } + + public static boolean isSaturated(final IAtomContainer ac) { + for (int i = 0; i + < ac.getAtomCount(); i++) { + if (!isSaturated(ac, i)) { + return false; + } + } + + return true; + } + + public static List getUnsaturatedAtomIndices(final IAtomContainer ac) { + final List unsaturatedAtomIndices = new ArrayList<>(); + for (int i = 0; i + < ac.getAtomCount(); i++) { + // set the indices of unsaturated atoms in substructure + if (!isSaturated(ac, i)) { + unsaturatedAtomIndices.add(i); + } + } + return unsaturatedAtomIndices; + } + + public static void addImplicitHydrogens(final IAtomContainer ac) throws CDKException { + final CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.getInstance(ac.getBuilder()); + IAtomType type; + for (final IAtom atom : ac.atoms()) { + type = matcher.findMatchingAtomType(ac, atom); + AtomTypeManipulator.configure(atom, type); + } + final CDKHydrogenAdder adder = CDKHydrogenAdder.getInstance(ac.getBuilder()); + adder.addImplicitHydrogens(ac); + } + + public static void addExplicitHydrogens(final IAtomContainer ac) throws CDKException { + addImplicitHydrogens(ac); + convertImplicitToExplicitHydrogens(ac); + } + + public static void convertImplicitToExplicitHydrogens(final IAtomContainer ac) { + AtomContainerManipulator.convertImplicitToExplicitHydrogens(ac); + } + + /** + * Checks whether a structure contains explicit hydrogen atoms or not. + * + * @param ac structure to check + * + * @return + */ + public static boolean containsExplicitHydrogens(final IAtomContainer ac) { + return getExplicitHydrogenCount(ac) + > 0; + } + + /** + * Stores all explicit hydrogens as implicit counter for the bonded heavy + * atoms and removes those from the atom container.
+ * Also, a HashMap containing non-hydrogen atoms and its indices + * before the removals will be returned which one can use for atom index + * comparison (before and after the removals). + * + * @param ac the structure to lsd + * + * @return + * + * @see #containsExplicitHydrogens(IAtomContainer) + */ + public static Map convertExplicitToImplicitHydrogens(final IAtomContainer ac) { + // create a list of atom indices which one can use for index comparison (before vs. after) after removing the explicit hydrogens + final Map atomIndices = new HashMap<>(); + final List toRemoveList = new ArrayList<>(); + IAtom atomB; + for (final IAtom atomA : ac.atoms()) { + // check each atom whether it is an hydrogen; + // if yes then store (increase) the number of implicit hydrogens + // for its bonded heavy atom + if (atomA.getSymbol() + .equals("H")) { + atomB = ac.getConnectedAtomsList(atomA) + .get(0); + if (atomB.getImplicitHydrogenCount() + == null) { + atomB.setImplicitHydrogenCount(0); + } + atomB.setImplicitHydrogenCount(atomB.getImplicitHydrogenCount() + + 1); + toRemoveList.add(atomA); + } else { + // store all non-hydrogen atoms and their indices + atomIndices.put(atomA, atomA.getIndex()); + } + + } + // remove all explicit hydrogen atoms + for (final IAtom iAtom : toRemoveList) { + ac.removeAtom(iAtom); + } + + return atomIndices; + } + + /** + * @param ac + * + * @return + */ + public static List getExplicitHydrogenIndices(final IAtomContainer ac) { + final List explicitHydrogenIndicesList = new ArrayList<>(); + for (int i = 0; i + < ac.getAtomCount(); i++) { + if (ac.getAtom(i) + .getSymbol() + .equals("H")) { + explicitHydrogenIndicesList.add(i); + } + } + + return explicitHydrogenIndicesList; + } + + /** + * @param ac + * + * @return + */ + public static int getExplicitHydrogenCount(final IAtomContainer ac) { + return getExplicitHydrogenIndices(ac).size(); + } + + public static void setAromaticity(final IAtomContainer ac) throws CDKException { + AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(ac); + final ElectronDonation model = ElectronDonation.cdkAllowingExocyclic(); + final CycleFinder cycles = Cycles.all(ac.getAtomCount()); + final Aromaticity aromaticity = new Aromaticity(model, cycles); + aromaticity.apply(ac); + } + + public static void setAromaticityAndKekulize(final IAtomContainer ac) throws CDKException { + setAromaticity(ac); + Kekulization.kekulize(ac); + } + + public static void setAromaticity(final IAtomContainer ac, final Aromaticity aromaticity) throws CDKException { + AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(ac); + aromaticity.apply(ac); + } + + public static void setAromaticityAndKekulize(final IAtomContainer ac, + final Aromaticity aromaticity) throws CDKException { + setAromaticity(ac, aromaticity); + Kekulization.kekulize(ac); + } + + /** + * Removes atoms from a given atom type from an atom container. + * + * @param ac IAtomContainer object where to remove the atoms + * @param atomType Atom type (element's name, e.g. C or Br) + * + * @return IAtomContainer where the atoms were removed + */ + public static IAtomContainer removeAtoms(final IAtomContainer ac, final String atomType) { + + final ArrayList toRemoveList = new ArrayList<>(); + for (final IAtom atomA : ac.atoms()) { + if (atomA.getSymbol() + .equals(atomType)) {// detect whether the current atom A is a from the given atom type + toRemoveList.add(atomA); + } + } + for (final IAtom iAtom : toRemoveList) { + ac.removeAtom(iAtom); + } + + return ac; + } + + public static boolean checkIndexInAtomContainer(final IAtomContainer ac, final int atomIndex) { + return ((atomIndex + >= 0) + && atomIndex + < ac.getAtomCount()); + } + + /** + * Returns the bond order for a numeric order value. + * + * @param orderAsNumeric + * + * @return + */ + public static IBond.Order getBondOrder(final int orderAsNumeric) { + for (final IBond.Order order : IBond.Order.values()) { + if (order.numeric() + == orderAsNumeric) { + return order; + } + } + + return null; + } + + public static Float getBondOrderAsNumeric(final IBond bond) { + if (bond + == null) { + return null; + } + final float bondOrderAsNumeric; + if (bond.isAromatic()) { + bondOrderAsNumeric = (float) 1.5; + } else { + bondOrderAsNumeric = bond.getOrder() + .numeric(); + } + + return bondOrderAsNumeric; + } + + public static Float getBondOrderSum(final IAtomContainer ac, final int atomIndex, + final boolean includeImplicitHydrogenCount) { + if (!checkIndexInAtomContainer(ac, atomIndex)) { + return null; + } + float bondsOrderSum = 0; + final IAtom atom = ac.getAtom(atomIndex); + for (final IBond bond : ac.getConnectedBondsList(atom)) { + bondsOrderSum += getBondOrderAsNumeric(bond); + } + if (includeImplicitHydrogenCount + && (atom.getImplicitHydrogenCount() + != null)) { + bondsOrderSum += atom.getImplicitHydrogenCount(); + } + + return bondsOrderSum; + } + + /** + * @param structure molecule to build the DataSet from and + * 1) all atom types and configuration will be perceived, + * 2) explicit hydrogens will be converted to implicit ones, + * 3) setting of aromaticity and Kekulization + * + * @return + * + * @throws CDKException + */ + public static DataSet atomContainerToDataSet(final IAtomContainer structure) throws CDKException { + return atomContainerToDataSet(structure, true); + } + + /** + * @param structure molecule to build the DataSet from + * @param configure if set to true then + * 1) all atom types and configuration will be perceived, + * 2) explicit hydrogens will be converted to implicit ones, + * 3) setting of aromaticity and Kekulization + * + * @return + * + * @throws CDKException + */ + public static DataSet atomContainerToDataSet(final IAtomContainer structure, + final boolean configure) throws CDKException { + if (configure) { + final CDKHydrogenAdder hydrogenAdder = CDKHydrogenAdder.getInstance(SilentChemObjectBuilder.getInstance()); + AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(structure); + if (Utils.containsExplicitHydrogens(structure)) { + // remove explicit hydrogens + Utils.removeAtoms(structure, "H"); + } + hydrogenAdder.addImplicitHydrogens(structure); + setAromaticityAndKekulize(structure); + } + final Map meta = new HashMap<>(); + // meta.put("title", structure.getTitle()); + final String source = structure.getProperty("nmrshiftdb2 ID", String.class) + != null + ? "nmrshiftdb" + : structure.getProperty("SMILES_ID", String.class) + != null + ? "coconut" + : null; + if (source + != null) { + meta.put("source", source); + meta.put("id", source.equals("nmrshiftdb") + ? structure.getProperty("nmrshiftdb2 ID", String.class) + : structure.getProperty("SMILES_ID", String.class) + .split("\\.")[0]); + } + final String mf = molecularFormularToString( + casekit.nmr.utils.Utils.getMolecularFormulaFromAtomContainer(structure)); + meta.put("mfOriginal", mf); + meta.put("mf", buildAlphabeticMF(mf)); + try { + final String smiles = getSmilesFromAtomContainer(structure); + meta.put("smiles", smiles); + } catch (final CDKException e) { + e.printStackTrace(); + } + final DataSet dataSet = new DataSet(); + dataSet.setStructure(new StructureCompact(structure)); + dataSet.setMeta(meta); + dataSet.setAttachment(new HashMap<>()); + + return dataSet; + } + + public static String buildAlphabeticMF(final String mf) { + final StringBuilder mfAlphabetic = new StringBuilder(); + final Map mfAlphabeticMap = new TreeMap<>(Utils.getMolecularFormulaElementCounts(mf)); + for (final Map.Entry entry : mfAlphabeticMap.entrySet()) { + mfAlphabetic.append(entry.getKey()); + if (entry.getValue() + > 1) { + mfAlphabetic.append(entry.getValue()); + } + } + + return mfAlphabetic.toString(); + } + + public static Signal extractFirstSignalFromCorrelation(final Correlation correlation) { + if (correlation.isPseudo()) { + return null; + } + final List nonPseudoLinks = correlation.getLink() + .stream() + .filter(linkTemp -> !linkTemp.isPseudo()) + .collect(Collectors.toList()); + if (nonPseudoLinks.isEmpty()) { + return null; + } + final Link link = nonPseudoLinks.get(0); + final Map signalMap = (Map) link.getSignal(); + final String multiplicity = Utils.getMultiplicityFromProtonsCount(correlation); + final casekit.nmr.model.nmrium.Signal signal = new casekit.nmr.model.nmrium.Signal((String) signalMap.get("id"), + (String) signalMap.get( + "kind"), + multiplicity, + signalMap.containsKey("sign") + ? (int) Double.parseDouble( + String.valueOf( + signalMap.get( + "sign"))) + : null); + // 1D signal + if (signalMap.containsKey("delta")) { + final Signal1D signal1D = new Signal1D(signal); + signal1D.setDelta((double) signalMap.get("delta")); + + return new Signal(new String[]{Constants.nucleiMap.get(correlation.getAtomType())}, + new Double[]{signal1D.getDelta()}, signal1D.getMultiplicity(), signal1D.getKind(), null, + correlation.getEquivalence(), signal1D.getSign(), null, signal1D.getId()); + } else if (signalMap.containsKey("x")) { + // 2D signal + final Signal2D signal2D = new Signal2D(signal); + signal2D.setX((Map) signalMap.get("x")); + signal2D.setY((Map) signalMap.get("y")); + if (signalMap.containsKey("j")) { + final Map jMap = (Map) signalMap.get("j"); + final Map pathLengthMap = (Map) jMap.get("pathLength"); + signal2D.setJ(new J(new PathLength((int) pathLengthMap.get("from"), (int) pathLengthMap.get("to")))); + } + final double shift = link.getAxis() + .equals("x") + ? (double) signal2D.getX() + .get("delta") + : (double) signal2D.getY() + .get("delta"); + + return new Signal(new String[]{Constants.nucleiMap.get(correlation.getAtomType())}, new Double[]{shift}, + signal2D.getMultiplicity(), signal2D.getKind(), null, correlation.getEquivalence(), + signal2D.getSign(), signal2D.getJ(), signal2D.getId()); + } + + return null; + } + + public static Spectrum correlationListToSpectrum1D(final List correlationList, final String nucleus) { + final String atomType = Utils.getAtomTypeFromNucleus(nucleus); + final List correlationListAtomType = correlationList.stream() + .filter(correlation -> correlation.getAtomType() + .equals(atomType) + && !correlation.isPseudo()) + .collect(Collectors.toList()); + final Spectrum spectrum = new Spectrum(); + spectrum.setNuclei(new String[]{nucleus}); + spectrum.setSignals(new ArrayList<>()); + + Signal signal; + for (final Correlation correlation : correlationListAtomType) { + signal = extractFirstSignalFromCorrelation(correlation); + if (signal + != null) { + signal.setId(correlation.getId()); + spectrum.addSignalWithoutEquivalenceSearch(signal); + } + } + + return spectrum; + } + + public static T cloneObject(final T object, final Class clazz) { + final Gson gson = new Gson(); + final String jsonString = gson.toJson(object, clazz); + return gson.fromJson(jsonString, clazz); + } + + public static void placeExplicitHydrogens( + final IAtomContainer structure) throws CDKException, IOException, ClassNotFoundException { + if (structure.getBondCount() + == 0) { + return; + } + // store bond stereo information + final int[] ordinals = new int[structure.getBondCount()]; + int k = 0; + for (final IBond bond : structure.bonds()) { + ordinals[k] = bond.getStereo() + .ordinal(); + k++; + } + // set 2D coordinates + structureDiagramGenerator.setMolecule(structure); + structureDiagramGenerator.generateCoordinates(structure); + /* !!! No explicit H in mol !!! */ + Utils.convertExplicitToImplicitHydrogens(structure); + /* add explicit H atoms */ + AtomUtils.addAndPlaceHydrogens(structure); + // restore bond stereo information + k = 0; + for (final IBond bond : structure.bonds()) { + bond.setStereo(IBond.Stereo.values()[ordinals[k]]); + + k++; + if (k + >= ordinals.length) { + break; + } + } + } +} diff --git a/src/casekit/threading/MultiThreading.java b/src/casekit/threading/MultiThreading.java new file mode 100644 index 0000000..85713fd --- /dev/null +++ b/src/casekit/threading/MultiThreading.java @@ -0,0 +1,44 @@ +package casekit.threading; + +import java.util.Collection; +import java.util.concurrent.*; +import java.util.function.Consumer; + +public class MultiThreading { + + public static ExecutorService initExecuter(final int nThreads) { + return Executors.newFixedThreadPool(nThreads); + } + + public static void stopExecuter(final ExecutorService executor, final long seconds) { + executor.shutdown(); + try { + if (!executor.awaitTermination(seconds, TimeUnit.SECONDS)) { + System.err.println("killing non-finished tasks!"); + executor.shutdownNow(); + } + } catch (final InterruptedException e) { + System.err.println("killing non-finished tasks!"); + executor.shutdownNow(); + } + } + + public static void processTasks(final Collection> callables, final Consumer consumer, + final int nThreads, final long seconds) throws InterruptedException { + // initialize an executor for parallelization + final ExecutorService executor = initExecuter(nThreads); + // execute all task in parallel + executor.invokeAll(callables) + .stream() + .map(future -> { + try { + return future.get(); + } catch (final InterruptedException | ExecutionException e) { + throw new IllegalStateException(e); + } + }) + .forEach(consumer); + // shut down the executor service + stopExecuter(executor, seconds); + } +}