{"id":15359666,"url":"https://github.com/pckroon/pysmiles","last_synced_at":"2025-04-08T11:09:27.638Z","repository":{"id":46864677,"uuid":"128138679","full_name":"pckroon/pysmiles","owner":"pckroon","description":"A lightweight python-only library for reading and writing SMILES strings","archived":false,"fork":false,"pushed_at":"2025-03-20T13:05:16.000Z","size":293,"stargazers_count":152,"open_issues_count":7,"forks_count":21,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-04-01T09:32:03.596Z","etag":null,"topics":["cheminformatics","hacktoberfest","python","smiles","smiles-strings","writing-smiles"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pckroon.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-04-05T00:13:08.000Z","updated_at":"2025-01-28T12:41:51.000Z","dependencies_parsed_at":"2023-01-22T14:01:19.420Z","dependency_job_id":"db231cf1-b432-455f-a3ca-4be1071a0d91","html_url":"https://github.com/pckroon/pysmiles","commit_stats":{"total_commits":168,"total_committers":5,"mean_commits":33.6,"dds":0.5595238095238095,"last_synced_commit":"c43ff4455a6987df3bbe22cb02ffab7e2ae5cfa8"},"previous_names":[],"tags_count":8,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pckroon%2Fpysmiles","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pckroon%2Fpysmiles/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pckroon%2Fpysmiles/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pckroon%2Fpysmiles/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pckroon","download_url":"https://codeload.github.com/pckroon/pysmiles/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247829491,"owners_count":21002995,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cheminformatics","hacktoberfest","python","smiles","smiles-strings","writing-smiles"],"created_at":"2024-10-01T12:45:35.524Z","updated_at":"2025-04-08T11:09:27.605Z","avatar_url":"https://github.com/pckroon.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![Build Status](https://travis-ci.org/pckroon/pysmiles.svg?branch=master)](https://travis-ci.org/pckroon/pysmiles)\n[![Coverage Status](https://coveralls.io/repos/github/pckroon/pysmiles/badge.svg?branch=master)](https://coveralls.io/github/pckroon/pysmiles?branch=master)\n\n# pysmiles: The lightweight and pure-python SMILES reader and writer\n\nThis is a small project I started because I couldn't find any SMILES reader or\nwriter that was easy to install (read: Python only). Currently, the writer is\nextremely basic, and although it should produce valid SMILES they won't be\npretty, but see also issue #17. The reader is in a better state, and should be usable.\n\nSMILES strings are assumed to be as specified by the\n[OpenSmiles standard][opensmiles].\n\n## Molecules\nMolecules are depicted as [Networkx][networkx] graphs. Atoms are the nodes of\nthe graph, and bonds are the edges. Nodes can have the following attributes:\n- element: str. This describes the element of the atom. Defaults to '\\*'\n    meaning unknown.\n- aromatic: bool. Whether the atom is part of an (anti)-aromatic system. \n    Defaults to False.\n- isotope: float. The mass of the atom. Defaults to unknown.\n- hcount: int. The number of implicit hydrogens attached to this atom.\n    Defaults to 0.\n- charge: int. The charge of this atom. Defaults to 0.\n- class: int. The \"class\" of this atom. Defaults to 0.\n- rs_isomer and ez_isomer: See below.\n- stereo: Not yet used, but reserved for more interpretable stereochemical \n  information\n\nEdges have the following attributes:\n- order: Number. The bond order. 1.5 is used for aromatic bonds. Defaults to 1.\n\n## Reading SMILES\nThe function `read_smiles(smiles, explicit_hydrogen=False,\nzero_order_bonds=True, reinterpret_aromatic=True, strict=True)` can be used to \nparse a SMILES string. It should not be used to validate whether a string is \na valid SMILES string --- the function does very little validation whether \nyour SMILES string makes chemical sense.\nEdges in the created molecule will always have an 'order'\nattribute. Nodes will have the relevant attributes in so far they are\nspecified. Atoms for which the element is not known (\\*) will not have an\nelement attribute.\n- `explicit_hydrogen` determines whether hydrogen atoms should be\n    represented as explicit nodes in the created molecule, or implicit in the\n    'hcount' attribute.\n- `zero_order_bonds` determines whether zero-order bonds (.) in the SMILES\n    string should result in edges in the produced molecule.\n- `reinterpret_aromatic` determines whether aromaticity should be \n    reinterpreted, and determined from the constructed molecule, or whether\n    the aromaticity specifications from the SMILES string (lower case \n    elements) should be taken as leading. If `True`, will also set bond orders \n    to 1 for bonds that are not part of an aromatic ring and have a bond order \n    of 1.5. See also below. If `False`, will create a molecule using *only* the \n    information in the SMILES string.\n- `strict` determines whether the function be a bit more critical about what \n    constitutes a valid SMILES string. In particular, checks whether the \n    specified aromatic fragments can be kekulized, and whether atom valency \n    is sensible. \n\n### Stereochemical information\nTetrahedral chirality is stored on nodes in the 'rs_isomer' attribute. It \nconsists of 4 node indices. The first, together with the central atom, \nindicates the axis of rotation/observation. The last three indices indicate \nthe direction of rotation in counter-clockwise order. For example, when \nparsing the SMILES `N[C@](Br)(O)C` node 1 (the central carbon) will have \n'rs_isomer' attribute `(0, 2, 3, 4)`. This means when looking along the axis \n(0, 1) (nitrogen to carbon), the nodes 2 (bromine), 3 (oxygen), 4 (methyl) \nwill be in counter-clockwise order. If the central atom has an implicit hydrogen\n(which of course does not have its own node index) we use the index of the \ncentral atom instead.\nThere is currently no way to easily convert this to R/S labels.\n\nE/Z chirality around double bonds is encoded on nodes in the 'ez_isomer' \nattribute. This attribute consists of 4 node indices and 1 string indication \neither 'cis' or 'trans'. The node indices indicate the dihedral angle. For \nexample, when parsing the SMILES `Br/C=C\\F` node 0 (the bromine) will have\n'ez_isomer' attribute `[0, 1, 2, 3, 'cis']`. This means the dihedral angle of\nthe axes (0, 1) and (2, 3) around the central axis (1, 2) is 0 degrees. \nThere is currently no way to easily convert this to E/Z labels.\n\n### Aromaticity\nAromaticity in SMILES has little to do with how an organic chemist might \ninterpret the term. Here we use \"aromatic\" to mean \"delocalization induced \nmolecular equivalence\" (DIME). DIME means that molecular fragments that are \nequivalent under delocalization should get the same representation. As an \nexample, `C1=CC=CC=C1` and `C=1C=CC=CC1` are equivalent, and should both be \nrepresented as `c1ccccc1`. On the other hand, pyrolle (`c1c[nH]cc1`) can only\nbe represented as `C1=CNC=C1`, and is not considered aromatic. A series of \nblogposts with a decent writeup on the subject can be found [here][depth_first].\n\nDespite how simple it seems at a glance, here be dragons lurking in the details.\nThe main problem is that in order to determine whether an edge is aromatic, \nyou need to generate *all* simple cycles. To illustrate why this is a problem,\nlet's look at buckminsterfullerene: it contains a staggering *15,024,073* \ncycles! It's really not feasible to investigate all of those separately.\n\nTherefor we approximate the aromaticity for ring systems that are too large. By\ndefault we consider 30 atoms large. For the exact algorithm, please see the\ndocstring of `dekekulize`. The approximation usually works fine, but may \nerroneously mark some triangle edges as aromatic. If you have a SMILES \nstring with a large ring system for which the approximation does not work, \nplease open an issue. As a workaround, you can read the SMILES with \n`reinterpret_aromatic=False`, and manually call `correct_aromatic_rings` \nwith more appropriate thresholds.\n\nA second complication comes from wildcard (\\*) atoms. If possible we try to \nkekulize the provided molecule without using them, but there may be edge \ncases where this does not work as intended.\n\n## Writing SMILES\nThe function `write_smiles(molecule, default_element='*', start=None)` can be\nused to write SMILES strings from a molecule. The function does *not* check \nwhether your molecule makes chemical sense. Instead, it writes a SMILES \nrepresentation of the molecule you provided, and nothing else. It does not \nyet know how to write stereochemical information that is present in your \nmolecule, and will log a warning if this happens. See below if you need to \nsilence these.\n- `default_element` is the element to use for nodes that do not have an \n    'element' attribute.\n- `start` is the key of the node where the depth first traversal should be \n    started. Something clever is done if not specified.\n\n## Additional functions\nIn addition to these two core functions, four more functions are exposed that\ncan help in creating chemically relevant molecules with minimal work.\n\n- `fill_valence(mol, respect_hcount=True, respect_bond_order=True,\n                 max_bond_order=3)`\n    This function will fill the valence of all atoms in your molecule by \n    incrementing the 'hcount' and, if specified, bond orders.\n    - `repect_hcount`: bool. Whether existing hcounts can be overwritten.\n    - `respect_bond_order`: bool. Whether bond orders can be changed.\n    - `max_bond_order`: int. The maximum bond order that will be set.\n- `add_explicit_hydrogens(mol)`\n    This function transforms implicit hydrogens, specified by 'hcount' \n    attributes, to explicit nodes.\n- `remove_explicit_hydrogens(mol)`\n    This function does the inverse of `add_explicit_hydrogens`: it will remove\n    explicit hydrogen nodes and add them to the relevant 'hcount' attributes.\n- `correct_aromatic_rings(mol, strict=True, estimation_threshold=None,\n                          max_ring_size=None)`\n    This function marks all (anti)-aromatic atoms in your molecule, and sets \n    all bonds between (anti)-aromatic atoms to order 1.5.\n\n    It works by first finding all atoms that could participate in an aromatic\n    system. These are atoms that can make a double bond without introducing \n    a charge. Then, it tries to assign alternating double and single bonds  \n    between the atoms found. If it cannot and `strict` is `True` an error \n    will be raised. Otherwise, it starts to look for cycles that consist of \n    such alternating double and single bonds. Atoms in these cycles will be \n    marked as aromatic, and these edges will get a bond order of 1.5. The \n    relevant atoms that are not in any cycle will be marked as not-aromatic, \n    and these bonds will be assigned alternating bond orders of 1 and 2.\n- `kekulize(mol)`\n    Assigns alternating single and double bonds to all aromatic regions in\n    ``mol``. Will raise an error if it cannot.\n- `dekekulize(mol, estimation_threshold=None, max_ring_size=None)`\n    Finds all cycles in `mol` that consist of alternating single and double\n    bonds, and marks them as aromatic.\n\n## Examples\n### Reading\n```python\nfrom pysmiles import read_smiles\n\nsmiles = 'C1CC[13CH2]CC1C1CCCCC1'\nmol = read_smiles(smiles)\n\nprint(mol.nodes(data='element'))\n# [(0, 'C'),\n#  (1, 'C'),\n#  (2, 'C'),\n#  (3, 'C'),\n#  (4, 'C'),\n#  (5, 'C'),\n#  (6, 'C'),\n#  (7, 'C'),\n#  (8, 'C'),\n#  (9, 'C'),\n#  (10, 'C'),\n#  (11, 'C')]\nprint(mol.nodes(data='hcount'))\n# [(0, 2),\n#  (1, 2),\n#  (2, 2),\n#  (3, 2),\n#  (4, 2),\n#  (5, 1),\n#  (6, 1),\n#  (7, 2),\n#  (8, 2),\n#  (9, 2),\n#  (10, 2),\n#  (11, 2)]\n\nmol_with_H = read_smiles(smiles, explicit_hydrogen=True)\nprint(mol_with_H.nodes(data='element'))\n# [(0, 'C'),\n#  (1, 'C'),\n#  (2, 'C'),\n#  (3, 'C'),\n#  (4, 'C'),\n#  (5, 'C'),\n#  (6, 'C'),\n#  (7, 'C'),\n#  (8, 'C'),\n#  (9, 'C'),\n#  (10, 'C'),\n#  (11, 'C'),\n#  (12, 'H'),\n#  (13, 'H'),\n#  (14, 'H'),\n#  (15, 'H'),\n#  (16, 'H'),\n#  (17, 'H'),\n#  (18, 'H'),\n#  (19, 'H'),\n#  (20, 'H'),\n#  (21, 'H'),\n#  (22, 'H'),\n#  (23, 'H'),\n#  (24, 'H'),\n#  (25, 'H'),\n#  (26, 'H'),\n#  (27, 'H'),\n#  (28, 'H'),\n#  (29, 'H'),\n#  (30, 'H'),\n#  (31, 'H'),\n#  (32, 'H'),\n# (33, 'H')]\n```\n\n### Writing\n```python\nimport networkx as nx\nfrom pysmiles import write_smiles, fill_valence\n\nmol = nx.Graph()\nmol.add_edges_from([(0, 1), (1, 2), (1, 3), (3, 4), (1, 5), (3, 6)])\nfor idx, ele in enumerate('CCCCOCO'):\n    mol.nodes[idx]['element'] = ele\nmol.nodes[4]['charge'] = -1\nmol.nodes[4]['hcount'] = 0\nmol.edges[3, 6]['order'] = 2\n\nprint(write_smiles(mol))\n# [O-]C(=O)C([C])([C])[C]\nfill_valence(mol, respect_hcount=True)\nprint(write_smiles(mol))\n# [O-]C(=O)C(C)(C)C\n```\n\n## Logging\nPysmiles uses the python logging module to log warnings. If you need to silence\nthese, you can use the following snippet in your code:\n```python\nimport logging\nlogging.getLogger('pysmiles').setLevel(logging.CRITICAL)  # Anything higher than warning\n```\n\n## Limitations\n- The writer produces non-recommended SMILES strings (as per OpenSmiles).\n- The writer is better described as a \"serializer\": if the graph provided\n    doesn't make chemical sense the produced \"SMILES\" string will be an\n    exact representation of that graph. Because of this, the SMILES string\n    will be invalid though.\n- The writer cannot deal with stereochemistry, and ignores it.\n- There is no way to easily transform stereochemical information to \n  human-readable labels like R/S/E/Z.\n- Extended stereochemical centers, such as described by `NC(Br)=[C@]=C(O)C` \n    are not supported.\n- Although the SMILES `F/C(/Br)=C\\F` is valid, pysmiles does not understand it.\n- It only processes SMILES. This might later be extended to e.g. InChi, SLN,\n    SMARTS, etc.\n\n## Requirements\n- [networkx][networkx]\n\n## Similar projects\nThere are more python projects that deal with SMILES, and I try to list at \nleast some of them here. If yours is missing, feel free to open up a PR.\n- [PySMILE](https://github.com/jhosmer/PySmile): A similar named project, \n    capable of encoding/decoding SMILE format objects. Doesn't deal with \n    SMILES.\n- [RDKit](https://github.com/rdkit/rdkit): A collection of cheminformatics and \n    machine-learning software, capable of reading and writing SMILES, InChi, \n    and others.\n- [OpenEye Chem toolkit](https://www.eyesopen.com/oechem-tk): The OpenEye \n    chemistry toolkit is a programming library for chemistry and \n    cheminformatics. It is capable of dealing with (canonical) SMILES and \n    InChi.\n\n## License\nPySmiles is distributed under the Apache 2.0 license.\n    Copyright 2018 Peter C Kroon\n\n    Licensed under the Apache License, Version 2.0 (the \"License\");\n    you may not use this file except in compliance with the License.\n    You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n\n[opensmiles]: http://opensmiles.org/\n[networkx]: https://networkx.github.io/\n[depth_first]: https://depth-first.com/articles/2020/02/10/a-comprehensive-treatment-of-aromaticity-in-the-smiles-language/\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpckroon%2Fpysmiles","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpckroon%2Fpysmiles","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpckroon%2Fpysmiles/lists"}