Input and output#

A frequent chore is to read a list of SMILES, print them back canonicalized, and sort them by molecular weight — and it needs no external toolkit. smiles is already the canonical SMILES, and exactMass the monoisotopic mass.

raw = ["OC(c1cc(O)c(O)cc1)CNC", "CCC(C)CCC", "CC(C)C",
       "O1c2c(OC1)ccc(C(O)C(=N)N)c2", "c1ccccc1"]
mols = [smiles(s, add=False) for s in raw]
print("sorted by exact mass:")
for m in sorted(mols, key=lambda g: g.exactMass):
    print(f"  {m.exactMass:8.3f}   {m.smiles}")
sorted by exact mass:
    58.078   C(C)(C)C
    78.047   c1ccccc1
   100.125   C(CC)(CCC)C
   183.090   OC(c1cc(O)c(O)cc1)CNC
   194.069   N=C(N)C(O)c1cc2OCOc2cc1

Every parsed molecule round-trips through the same graph, so the other formats are one attribute away — molfile (V2000 / V3000), inchi and inchiKey, smilesWithIds (atom-mapped) — alongside the readers smiles(), graphGMLString(), molfile(), graphDFS(), and the static constructors fromSMILES() / fromInChI().

13_canonical_smiles_io.py#
"""13. A small I/O task: canonicalize and sort SMILES.

A frequent chore: read a list of SMILES, print them back canonicalized, and
sort by molecular weight. MolFoundry does this without any external toolkit --
``graph.smiles`` is already the canonical SMILES and ``graph.exactMass`` the
monoisotopic mass.

Run:  python 13_canonical_smiles_io.py
"""
import _bootstrap
from molfoundry import smiles

# Pretend these came from a file, one SMILES per line.
raw = [
    "OC(c1cc(O)c(O)cc1)CNC",   # a catecholamine
    "CCC(C)CCC",               # 3-methylhexane
    "CC(C)C",                  # isobutane
    "O1c2c(OC1)ccc(C(O)C(=N)N)c2",
    "c1ccccc1",                # benzene
]

mols = [smiles(s, add=False) for s in raw]

print("Canonical SMILES (input order):")
for m in mols:
    print(f"   {m.smiles}")

print("\nSorted by exact mass:")
for m in sorted(mols, key=lambda g: g.exactMass):
    print(f"   {m.exactMass:8.3f}   {m.smiles}")

See also

The file-format guides document each reader and writer in full, including electron-graph parsing and atom-mapped reaction SMILES.