Commit 5546011f authored by Tristen  Liu's avatar Tristen Liu
Browse files

12 test molecules + Script for creating input files based on SMILES string

parent 1c742cb5
Loading
Loading
Loading
Loading

testcases/LICENSE.md

0 → 100644
+202 −0
Original line number Diff line number Diff line

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "{}"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright {yyyy} {name of copyright owner}

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

testcases/README.md

0 → 100644
+260 −0
Original line number Diff line number Diff line
[![Build Status](https://travis-ci.org/pckroon/pysmiles.svg?branch=master)](https://travis-ci.org/pckroon/pysmiles)
[![Coverage Status](https://coveralls.io/repos/github/pckroon/pysmiles/badge.svg?branch=master)](https://coveralls.io/github/pckroon/pysmiles?branch=master)

# pysmiles: The lightweight and pure-python SMILES reader and writer

This is a small project I started because I couldn't find any SMILES reader or
writer that was easy to install (read: Python only). Currently, the writer is
extremely basic, and although it should produce valid SMILES they won't be
pretty, but see also issue #17. The reader is in a better state, and should be usable.

SMILES strings are assumed to be as specified by the
[OpenSmiles standard][opensmiles].

## Molecules
Molecules are depicted as [Networkx][networkx] graphs. Atoms are the nodes of
the graph, and bonds are the edges. Nodes can have the following attributes:
- element: str. This describes the element of the atom. Defaults to '\*'
    meaning unknown.
- aromatic: bool. Whether the atom is part of an (anti)-aromatic system. 
    Defaults to False.
- isotope: float. The mass of the atom. Defaults to unknown.
- hcount: int. The number of implicit hydrogens attached to this atom.
    Defaults to 0.
- charge: int. The charge of this atom. Defaults to 0.
- class: int. The "class" of this atom. Defaults to 0.

Edges have the following attributes:
- order: Number. The bond order. 1.5 is used for aromatic bonds. Defaults to 1.

There is currently no way of specifying stereo chemical information, and this
is discarded upon reading. Somewhere in the future this will probably be
stored in the "stereo" attribute of nodes.

## Reading SMILES
The function `read_smiles(smiles, explicit_hydrogen=False,
zero_order_bonds=True, reinterpret_aromatic=True)` can be used to parse a
SMILES string. It should not be used to validate whether a string is a valid
SMILES string --- the function does very little validation whether your SMILES string makes chemical sense.
Edges in the created molecule will always have an 'order'
attribute. Nodes will have the relevant attributes in so far they are
specified. Atoms for which the element is not known (\*) will not have an
element attribute.
- `explicit_hydrogen` determines whether hydrogen atoms should be
    represented as explicit nodes in the created molecule, or implicit in the
    'hcount' attribute.
- `zero_order_bonds` determines whether zero-order bonds (.) in the SMILES
    string should result in edges in the produced molecule.
- `reinterpret_aromatic` determines whether aromaticity should be 
    reinterpreted, and determined from the constructed molecule, or whether
    the aromaticity specifications from the SMILES string (lower case 
    elements) should be taken as leading. If `True`, will also set bond orders 
    to 1 for bonds that are not part of an aromatic ring and have a bond order 
    of 1.5. If `False`, will create a molecule using *only* the information in 
    the SMILES string.

### Stereochemical information
Currently the library cannot handle stereochemical information, neither E/Z nor
R/S. Any stereochemical information that was in the SMILES string will be
*discarded* upon parsing. This means there will be no difference between
parsing *e.g.* `N[C@](Br)(O)C`, `N[C@@](Br)(O)C` and `NC(Br)(O)C`. Parsing
these *will result in the same molecule*. The same holds for *e.g.* `F/C=C/F`
and `FC=CF`. These will result in the same molecule.

Whenever stereochemical information is being discarded a warning will be
logged using the built-in `logging` module. If you want to disable all the
messages logged by `pysmiles` you can add the following snippet to your code,
without interfering with any logging by your own code:

```python
import logging
logging.getLogger('pysmiles').setLevel(logging.CRITICAL)  # Anything higher than warning
```


## Writing SMILES
The function `write_smiles(molecule, default_element='*', start=None)` can be
used to write SMILES strings from a molecule. The function does *not* check 
whether your molecule makes chemical sense. Instead, it writes a SMILES 
representation of the molecule you provided, and nothing else.
- `default_element` is the element to use for nodes that do not have an 
    'element' attribute.
- `start` is the key of the node where the depth first traversal should be 
    started. Something clever is done if not specified.

## Additional functions
In addition to these two core functions, four more functions are exposed that
can help in creating chemically relevant molecules with minimal work.

- `fill_valence(mol, respect_hcount=True, respect_bond_order=True,
                 max_bond_order=3)`
    This function will fill the valence of all atoms in your molecule by 
    incrementing the 'hcount' and, if specified, bond orders. Note that it does
    not use 'charge' attribute to find the correct valence.
    - `repect_hcount`: bool. Whether existing hcounts can be overwritten.
    - `respect_bond_order`: bool. Whether bond orders can be changed
    - `max_bond_order`: int. The maximum bond order that will be set.
- `add_explicit_hydrogens(mol)`
    This function transforms implicit hydrogens, specified by 'hcount' 
    attributes, to explicit nodes.
- `remove_explicit_hydrogens(mol)`
    This function does the inverse of `add_explicit_hydrogens`: it will remove
    explicit hydrogen nodes and add them to the relevant 'hcount' attributes.
- `correct_aromatic_rings(mol)`
    This function marks all (anti)-aromatic atoms in your molecule, and sets 
    all bonds between (anti)-aromatic atoms to order 1.5.
    It fills the valence of all atoms (see also `fill_valence`) before trying
    to figure our which atoms are aromatic. It works by first finding all 
    atoms that are in a ring. Next, for every atom in every ring it is checked
    whether the atoms are sp2 hybridized (note that this is a vague term. 
    Strictly speaking we check whether their element is something that *could*
    be aromatic, and whether they have 2 or 3 bonds.). Finally, the number of 
    electrons per ring is counted, and if this is even, the atoms in the ring
    are said to be aromatic.
    This function is the most fragile in the whole library, and I expect it to
    produce wrong answers in some cases. In particular for fused (aromatic)
    ring systems (such as indole) and rings with extracyclic heteroatoms
    (O=C1C=CC=C1). Buyer beware.

## Examples
### Reading
```python
from pysmiles import read_smiles

smiles = 'C1CC[13CH2]CC1C1CCCCC1'
mol = read_smiles(smiles)

print(mol.nodes(data='element'))
# [(0, 'C'),
#  (1, 'C'),
#  (2, 'C'),
#  (3, 'C'),
#  (4, 'C'),
#  (5, 'C'),
#  (6, 'C'),
#  (7, 'C'),
#  (8, 'C'),
#  (9, 'C'),
#  (10, 'C'),
#  (11, 'C')]
print(mol.nodes(data='hcount'))
# [(0, 2),
#  (1, 2),
#  (2, 2),
#  (3, 2),
#  (4, 2),
#  (5, 1),
#  (6, 1),
#  (7, 2),
#  (8, 2),
#  (9, 2),
#  (10, 2),
#  (11, 2)]

mol_with_H = read_smiles(smiles, explicit_hydrogen=True)
print(mol_with_H.nodes(data='element'))
# [(0, 'C'),
#  (1, 'C'),
#  (2, 'C'),
#  (3, 'C'),
#  (4, 'C'),
#  (5, 'C'),
#  (6, 'C'),
#  (7, 'C'),
#  (8, 'C'),
#  (9, 'C'),
#  (10, 'C'),
#  (11, 'C'),
#  (12, 'H'),
#  (13, 'H'),
#  (14, 'H'),
#  (15, 'H'),
#  (16, 'H'),
#  (17, 'H'),
#  (18, 'H'),
#  (19, 'H'),
#  (20, 'H'),
#  (21, 'H'),
#  (22, 'H'),
#  (23, 'H'),
#  (24, 'H'),
#  (25, 'H'),
#  (26, 'H'),
#  (27, 'H'),
#  (28, 'H'),
#  (29, 'H'),
#  (30, 'H'),
#  (31, 'H'),
#  (32, 'H'),
# (33, 'H')]
```

### Writing
```python
import networkx as nx
from pysmiles import write_smiles, fill_valence

mol = nx.Graph()
mol.add_edges_from([(0, 1), (1, 2), (1, 3), (3, 4), (1, 5), (3, 6)])
for idx, ele in enumerate('CCCCOCO'):
    mol.nodes[idx]['element'] = ele
mol.nodes[4]['charge'] = -1
mol.nodes[4]['hcount'] = 0
mol.edges[3, 6]['order'] = 2

print(write_smiles(mol))
# [O-]C(=O)C([C])([C])[C]
fill_valence(mol, respect_hcount=True)
print(write_smiles(mol))
# [O-]C(=O)C(C)(C)C
```

## Limitations
- The writer produces non-recommended SMILES strings (as per OpenSmiles).
- The writer is better described as a "serializer": if the graph provided
    doesn't make chemical sense the produced "SMILES" string will be an
    exact representation of that graph. Because of this, the SMILES string
    will be invalid though.
- `fill_valence` does not use 'charge' to find the correct valence.
- `correct_aromatic_rings` is fragile.
- There is currently no way of specifying stereo chemical information. The 
    parser can deal with it, but it will be discarded.
- It only processes SMILES. This might later be extended to e.g. InChi, SLN,
    SMARTS, etc.

## Requirements
- [networkx][networkx]

## Similar projects
There are more python projects that deal with SMILES, and I try to list at 
least some of them here. If yours is missing, feel free to open up a PR.
- [PySMILE](https://github.com/jhosmer/PySmile): A similar named project, 
    capable of encoding/decoding SMILE format objects. Doesn't deal with 
    SMILES.
- [RDKit](https://github.com/rdkit/rdkit): A collection of cheminformatics and 
    machine-learning software, capable of reading and writing SMILES, InChi, 
    and others.
- [OpenEye Chem toolkit](https://www.eyesopen.com/oechem-tk): The OpenEye 
    chemistry toolkit is a programming library for chemistry and 
    cheminformatics. It is capable of dealing with (canonical) SMILES and 
    InChi.

## License
PySmiles is distributed under the Apache 2.0 license.
    Copyright 2018 Peter C Kroon

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


[opensmiles]: http://opensmiles.org/
[networkx]: https://networkx.github.io/
+48 −0
Original line number Diff line number Diff line
from pysmiles import read_smiles
import networkx as nx

# returns the order number of the edge that appears using nx.edge_list
def get_bond_order(line):
     return int(line.split("{'order': ")[1].rstrip('}\n'))

# multiplies the edge pair by the order number
def process_content(content):
    new_content = ""
    for line in content:
        # Check if the line contains bond order information
        if "{'order':" in line:
            bond_order = get_bond_order(line)
            vertex_pair = ' '.join(line.split()[:2])
            for i in range(bond_order):
             new_content += vertex_pair + '\n'
        else:
            new_content += line
    return new_content

if __name__ == "__main__":
    # replace with name of molecule
    mol_name = "Vitamin-C"
    
    # replace with smiles string of molecule
    smiles = 'C([C@@H]([C@@H]1C(=C(C(=O)O1)O)O)O)O'
    mol_with_H = read_smiles(smiles, explicit_hydrogen=True)
    file_path = "./molecules/" + mol_name + ".txt"

    nx.write_edgelist(mol_with_H, file_path)

    nodes = mol_with_H.nodes(data='element')
    mol_data = mol_name + '\n'
    mol_data += str(len(nodes)) + '\n'
    for a in nodes:
      mol_data += a[1] + '\n'

    # Read the existing contents of the file
    with open(file_path, 'r') as file:
        edgelist = file.read()

    modified_edgelist = process_content(edgelist.split('\n'))
    # Write the new content at the beginning and the original content
    with open(file_path, 'w') as file:
        file.write(mol_data + modified_edgelist)

+55 −0
Original line number Diff line number Diff line
L-Theanine
26
C
C
N
C
O
C
C
C
C
O
O
N
H
H
H
H
H
H
H
H
H
H
H
H
H
H
0 1
0 12
0 13
0 14
1 2
1 15
1 16
2 3
2 17
3 4
3 4
3 5
5 6
5 18
5 19
6 7
6 20
6 21
7 8
7 11
7 22
8 9
8 9
8 10
10 23
11 24
11 25
+44 −0
Original line number Diff line number Diff line
Vitamin-C
20
C
C
C
C
C
C
O
O
O
O
O
O
H
H
H
H
H
H
H
H
0 1
0 11
0 12
0 13
1 2
1 10
1 14
2 3
2 7
2 15
3 4
3 4
3 9
4 5
4 8
5 6
5 6
5 7
8 16
9 17
10 18
11 19
Loading