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
-
-
-
- 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
+ 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