# OEChem TK

> Core cheminformatics toolkit for molecular representation, manipulation, and file I/O

## Links
- [Full Documentation](https://docs.eyesopen.com/toolkits/python/oechemtk/index.html)
- [Theory](https://docs.eyesopen.com/toolkits/python/oechemtk/theory.html)
- [Code Examples](https://docs.eyesopen.com/toolkits/python/oechemtk/oechem_examples_summary.html)
- [API Reference](https://docs.eyesopen.com/toolkits/python/oechemtk/api.html)

## Core API - Function Quick Reference

### File I/O Operations

```
oemolistream(filename: str) -> OEMolStreamBase
  Use for: Reading molecules from files (SDF, MOL2, PDB, SMILES, etc.)
  Example: ifs = oemolistream("molecules.sdf")
  See: OEChem Functions

oemolostream(filename: str) -> OEMolStreamBase
  Use for: Writing molecules to files with automatic format detection
  Example: ofs = oemolostream("output.sdf")
  See: OEChem Functions

OEReadMolecule(istream: OEMolStreamBase, mol: OEMolBase) -> bool
  Use for: Reading next molecule from input stream into molecule object
  Example: while OEReadMolecule(ifs, mol): process(mol)
  See: OEChem Functions

OEWriteMolecule(ostream: OEMolStreamBase, mol: OEMolBase) -> bool
  Use for: Writing a molecule to output stream
  Example: OEWriteMolecule(ofs, mol)
  See: OEChem Functions
```

### Molecule Creation & Manipulation

```
OEGraphMol() -> OEGraphMol
  Use for: Creating a standard molecule object for most operations
  Example: mol = OEGraphMol()
  See: OEChem Classes

OEMol() -> OEMol
  Use for: Creating multi-conformer molecule object
  Example: mcmol = OEMol()
  See: OEChem Classes

OESmilesToMol(mol: OEMolBase, smiles: str) -> bool
  Use for: Converting SMILES string to molecule object
  Example: OESmilesToMol(mol, "c1ccccc1")
  See: OEChem Functions

OEAddMols(dst: OEMolBase, src: OEMolBase) -> bool
  Use for: Combining two molecules into one (e.g., for complexes)
  Example: OEAddMols(complex, ligand)
  See: OEChem Functions

OEDeleteAtom(mol: OEMolBase, atom: OEAtomBase) -> bool
  Use for: Removing an atom from a molecule
  Example: OEDeleteAtom(mol, atom)
  See: OEChem Functions
```

### Molecular Properties & Analysis

```
OECalculateMolecularWeight(mol: OEMolBase) -> float
  Use for: Computing molecular weight
  Example: mw = OECalculateMolecularWeight(mol)
  See: OEChem Functions

OECount(mol: OEMolBase, pred: OEUnaryPredicate) -> int
  Use for: Counting atoms/bonds matching a predicate
  Example: natoms = OECount(mol, OEIsHeavy())
  See: OEChem Functions

OENetCharge(mol: OEMolBase) -> int
  Use for: Getting total formal charge of molecule
  Example: charge = OENetCharge(mol)
  See: OEChem Functions

OEMolecularFormula(mol: OEMolBase) -> str
  Use for: Getting molecular formula string
  Example: formula = OEMolecularFormula(mol)
  See: OEChem Functions
```

### Structure Perception & Preparation

```
OEAssignAromaticFlags(mol: OEMolBase, model: int = OEAroModel_OpenEye) -> bool
  Use for: Perceiving and assigning aromaticity
  Example: OEAssignAromaticFlags(mol)
  See: OEChem Functions

OEFindRingAtomsAndBonds(mol: OEMolBase) -> bool
  Use for: Identifying ring atoms and bonds
  Example: OEFindRingAtomsAndBonds(mol)
  See: OEChem Functions

OEPerceiveChiral(mol: OEMolBase) -> bool
  Use for: Perceiving stereochemistry from 3D coordinates
  Example: OEPerceiveChiral(mol)
  See: OEChem Functions

OEAddExplicitHydrogens(mol: OEMolBase) -> bool
  Use for: Adding explicit hydrogen atoms
  Example: OEAddExplicitHydrogens(mol)
  See: OEChem Functions

OESuppressHydrogens(mol: OEMolBase) -> bool
  Use for: Removing explicit hydrogens (implicit representation)
  Example: OESuppressHydrogens(mol)
  See: OEChem Functions

OE3DToInternalStereo(mol: OEMolBase) -> bool
  Use for: Converting 3D coordinates to internal stereo representation
  Example: OE3DToInternalStereo(mol)
  See: OEChem Functions
```

### Substructure Search & Pattern Matching

```
OESubSearch(mol: OEMolBase, pattern: OEQMolBase) -> OESubSearch
  Use for: Creating substructure search object for pattern matching
  Example: ss = OESubSearch(pattern); ss.Match(mol)
  See: OEChem Classes

OESubSearch.Match(mol: OEMolBase, unique: bool = True) -> iterator
  Use for: Finding all substructure matches in molecule
  Example: for match in ss.Match(mol): process(match)
  See: OEChem Classes

OEParseSmarts(pattern: str) -> OEQMol
  Use for: Creating SMARTS query molecule for pattern matching
  Example: qmol = OEParseSmarts("[#6]1:[#6]:[#6]:[#6]:[#6]:[#6]:1")
  See: OEChem Functions

OEHasSubstructMatch(mol: OEMolBase, pattern: OEQMolBase) -> bool
  Use for: Quick check if molecule contains substructure
  Example: if OEHasSubstructMatch(mol, pattern): process()
  See: OEChem Functions
```

### 2D Coordinate Generation

```
OEGenerate2DCoordinates(mol: OEMolBase) -> bool
  Use for: Generating 2D coordinates for depiction
  Example: OEGenerate2DCoordinates(mol)
  See: OEChem Functions

OEPrepareDepiction(mol: OEMolBase) -> bool
  Use for: Preparing molecule for high-quality 2D depiction
  Example: OEPrepareDepiction(mol)
  See: OEChem Functions
```

### Atom & Bond Traversal

```
OEMolBase.GetAtoms() -> iterator
  Use for: Iterating over all atoms in molecule
  Example: for atom in mol.GetAtoms(): process(atom)
  See: OEChem Classes

OEMolBase.GetBonds() -> iterator
  Use for: Iterating over all bonds in molecule
  Example: for bond in mol.GetBonds(): process(bond)
  See: OEChem Classes

OEAtomBase.GetBonds() -> iterator
  Use for: Iterating over bonds connected to an atom
  Example: for bond in atom.GetBonds(): process(bond)
  See: OEChem Classes
```

### Tagged Data (SD Data)

```
OEGetSDData(mol: OEMolBase, tag: str) -> str
  Use for: Reading SD data field from molecule
  Example: value = OEGetSDData(mol, "IC50")
  See: OEChem Functions

OESetSDData(mol: OEMolBase, tag: str, value: str) -> bool
  Use for: Setting SD data field on molecule
  Example: OESetSDData(mol, "IC50", "5.2")
  See: OEChem Functions

OEHasSDData(mol: OEMolBase, tag: str) -> bool
  Use for: Checking if SD data field exists
  Example: if OEHasSDData(mol, "IC50"): value = OEGetSDData(mol, "IC50")
  See: OEChem Functions
```

### SMILES Generation

```
OECreateCanSmiString(mol: OEMolBase) -> str
  Use for: Generating canonical SMILES string
  Example: smiles = OECreateCanSmiString(mol)
  See: OEChem Functions

OECreateIsoSmiString(mol: OEMolBase) -> str
  Use for: Generating isomeric SMILES (with stereochemistry)
  Example: smiles = OECreateIsoSmiString(mol)
  See: OEChem Functions
```

## Common Patterns - Complete Working Examples

### Pattern: Read and Process Molecules from File

```python
from openeye import oechem

ifs = oechem.oemolistream("input.sdf")
mol = oechem.OEGraphMol()

while oechem.OEReadMolecule(ifs, mol):
    # Process each molecule
    mw = oechem.OECalculateMolecularWeight(mol)
    smiles = oechem.OECreateCanSmiString(mol)
    print(f"{mol.GetTitle()}: MW={mw:.2f}, SMILES={smiles}")

ifs.close()
```
Use when: Processing molecules from any supported file format (SDF, MOL2, PDB, SMILES)

### Pattern: Write Molecules to File

```python
from openeye import oechem

ofs = oechem.oemolostream("output.sdf")
mol = oechem.OEGraphMol()

# Create or read molecules
oechem.OESmilesToMol(mol, "c1ccccc1")
mol.SetTitle("benzene")
oechem.OESetSDData(mol, "Property", "value")

oechem.OEWriteMolecule(ofs, mol)
ofs.close()
```
Use when: Writing molecules to files with automatic format detection from extension

### Pattern: Substructure Search

```python
from openeye import oechem

# Create pattern from SMARTS
pattern = oechem.OEQMol()
oechem.OEParseSmarts(pattern, "c1ccccc1")  # benzene ring

# Search in molecule
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccc(cc1)CCO")

ss = oechem.OESubSearch(pattern)
for match in ss.Match(mol):
    print(f"Found match with {match.NumAtoms()} atoms")
```
Use when: Finding specific substructures or functional groups in molecules

### Pattern: Convert SMILES to Molecule with Preparation

```python
from openeye import oechem

mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "CCO")

# Prepare molecule
oechem.OEAddExplicitHydrogens(mol)
oechem.OEAssignAromaticFlags(mol)
oechem.OEFindRingAtomsAndBonds(mol)

# Generate 2D coordinates for depiction
oechem.OEGenerate2DCoordinates(mol)
```
Use when: Creating molecules from SMILES and preparing them for further processing

### Pattern: Iterate Over Atoms and Bonds

```python
from openeye import oechem

mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "CCO")

# Iterate over atoms
for atom in mol.GetAtoms():
    print(f"Atom {atom.GetIdx()}: {oechem.OEGetAtomicSymbol(atom.GetAtomicNum())}")
    
    # Iterate over bonds of this atom
    for bond in atom.GetBonds():
        nbr = bond.GetNbr(atom)
        print(f"  Bonded to atom {nbr.GetIdx()}")
```
Use when: Analyzing molecular structure or implementing custom algorithms

### Pattern: Read and Filter Molecules

```python
from openeye import oechem

ifs = oechem.oemolistream("input.sdf")
ofs = oechem.oemolostream("filtered.sdf")
mol = oechem.OEGraphMol()

while oechem.OEReadMolecule(ifs, mol):
    mw = oechem.OECalculateMolecularWeight(mol)
    if 200.0 <= mw <= 500.0:
        oechem.OEWriteMolecule(ofs, mol)

ifs.close()
ofs.close()
```
Use when: Filtering molecules based on properties or structural features

### Pattern: Work with SD Data Fields

```python
from openeye import oechem

mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "CCO")

# Set SD data
oechem.OESetSDData(mol, "IC50", "5.2")
oechem.OESetSDData(mol, "Assay", "Binding")

# Read SD data
if oechem.OEHasSDData(mol, "IC50"):
    ic50 = oechem.OEGetSDData(mol, "IC50")
    print(f"IC50: {ic50}")

# Iterate over all SD data
for dp in oechem.OEGetSDDataPairs(mol):
    print(f"{dp.GetTag()}: {dp.GetValue()}")
```
Use when: Working with SDF files containing associated data fields

### Pattern: Perceive and Check Stereochemistry

```python
from openeye import oechem

mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "C[C@H](O)CC")

# Perceive stereochemistry
oechem.OEPerceiveChiral(mol)

# Check for chiral centers
for atom in mol.GetAtoms():
    if atom.IsChiral():
        print(f"Atom {atom.GetIdx()} is chiral")
        
# Generate isomeric SMILES with stereochemistry
iso_smiles = oechem.OECreateIsoSmiString(mol)
print(f"Isomeric SMILES: {iso_smiles}")
```
Use when: Working with stereochemistry or generating stereo-aware SMILES

### Pattern: Combine Molecules (Create Complex)

```python
from openeye import oechem

# Create protein and ligand
protein = oechem.OEGraphMol()
ligand = oechem.OEGraphMol()

# Read from files
pfs = oechem.oemolistream("protein.pdb")
lfs = oechem.oemolistream("ligand.sdf")
oechem.OEReadMolecule(pfs, protein)
oechem.OEReadMolecule(lfs, ligand)

# Combine into complex
complex_mol = oechem.OEGraphMol(protein)
oechem.OEAddMols(complex_mol, ligand)
```
Use when: Creating protein-ligand complexes or combining molecular fragments

### Pattern: Count Atoms with Predicates

```python
from openeye import oechem

mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccccc1CCO")

# Count different atom types
heavy_atoms = oechem.OECount(mol, oechem.OEIsHeavy())
aromatic_atoms = oechem.OECount(mol, oechem.OEIsAromaticAtom())
carbon_atoms = oechem.OECount(mol, oechem.OEIsCarbon())

print(f"Heavy: {heavy_atoms}, Aromatic: {aromatic_atoms}, Carbon: {carbon_atoms}")
```
Use when: Analyzing molecular composition or filtering based on atom counts

### Pattern: Generate Canonical SMILES for Comparison

```python
from openeye import oechem

mol1 = oechem.OEGraphMol()
mol2 = oechem.OEGraphMol()

oechem.OESmilesToMol(mol1, "c1ccccc1")
oechem.OESmilesToMol(mol2, "C1=CC=CC=C1")

# Generate canonical SMILES for comparison
smiles1 = oechem.OECreateCanSmiString(mol1)
smiles2 = oechem.OECreateCanSmiString(mol2)

if smiles1 == smiles2:
    print("Molecules are identical")
```
Use when: Comparing molecules or creating unique identifiers

### Pattern: Prepare Molecule for Depiction

```python
from openeye import oechem

mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccc(cc1)C(=O)O")

# Suppress hydrogens for cleaner depiction
oechem.OESuppressHydrogens(mol)

# Prepare for high-quality 2D depiction
oechem.OEPrepareDepiction(mol)

# Now ready for rendering with OEDepict
```
Use when: Preparing molecules for 2D visualization or depiction

### Pattern: Handle Multi-Conformer Molecules

```python
from openeye import oechem

# Use OEMol for multi-conformer support
mcmol = oechem.OEMol()
oechem.OESmilesToMol(mcmol, "CCO")

# Add conformers (typically from conformer generation)
# Each conformer shares the same connectivity

for conf in mcmol.GetConfs():
    # Process each conformer
    energy = conf.GetEnergy()
    print(f"Conformer {conf.GetIdx()}: Energy={energy}")
```
Use when: Working with multiple conformations of the same molecule

### Pattern: Read Molecules with Format Options

```python
from openeye import oechem

# Configure input stream with specific options
ifs = oechem.oemolistream()
ifs.SetFormat(oechem.OEFormat_SDF)
ifs.SetFlavor(oechem.OEFormat_SDF, oechem.OEIFlavor_SDF_Default)

if not ifs.open("input.sdf"):
    print("Unable to open file")
    
mol = oechem.OEGraphMol()
while oechem.OEReadMolecule(ifs, mol):
    # Process molecule
    pass
```
Use when: Need fine control over file reading behavior or format-specific options

## API Decision Guide

### File I/O
- For reading molecules: use `oemolistream` (auto-detects format from extension)
- For writing molecules: use `oemolostream` (auto-detects format from extension)
- For explicit format control: use `SetFormat()` and `SetFlavor()` on streams
- For single molecule: use `OEReadMolecule()` / `OEWriteMolecule()`
- For multiple molecules: iterate with `while OEReadMolecule(ifs, mol)` loop

### Molecule Objects
- For single conformer: use `OEGraphMol()` (most common, faster)
- For multi-conformer: use `OEMol()` (when working with conformer ensembles)
- For query molecules (SMARTS): use `OEQMol()` with `OEParseSmarts()`
- For read-only operations: `OEMolBase` interface is sufficient

### Structure Perception
- For aromaticity: use `OEAssignAromaticFlags()` (required before many operations)
- For ring perception: use `OEFindRingAtomsAndBonds()` (required for ring queries)
- For stereochemistry from 3D: use `OEPerceiveChiral()`
- For stereochemistry from 2D: use `OE3DToInternalStereo()` after coordinate generation

### Hydrogen Handling
- To add explicit H: use `OEAddExplicitHydrogens()` (for force fields, 3D work)
- To remove explicit H: use `OESuppressHydrogens()` (for depiction, SMILES)
- Default behavior: most file formats preserve H representation as-is

### SMILES Generation
- For unique identifier: use `OECreateCanSmiString()` (canonical, no stereo)
- For stereochemistry: use `OECreateIsoSmiString()` (includes stereo information)
- For absolute stereo: use `OECreateAbsSmiString()` (absolute stereochemistry)

### Substructure Search
- For single query: use `OESubSearch` class with `Match()` method
- For quick existence check: use `OEHasSubstructMatch()` (faster, no match details)
- For SMARTS patterns: create with `OEParseSmarts()` first
- For multiple queries: reuse `OESubSearch` object, call `Match()` on different molecules

### Coordinate Generation
- For 2D depiction: use `OEPrepareDepiction()` (high quality) or `OEGenerate2DCoordinates()` (fast)
- For 3D coordinates: use Omega TK (separate toolkit)
- Before depiction: call `OESuppressHydrogens()` for cleaner images

### Atom/Bond Iteration
- For all atoms: use `mol.GetAtoms()` iterator
- For all bonds: use `mol.GetBonds()` iterator
- For atom's bonds: use `atom.GetBonds()` iterator
- For counting: use `OECount(mol, predicate)` instead of manual iteration

### Property Calculation
- For molecular weight: use `OECalculateMolecularWeight()`
- For formal charge: use `OENetCharge()`
- For molecular formula: use `OEMolecularFormula()`
- For atom counts: use `OECount()` with predicates like `OEIsHeavy()`, `OEIsCarbon()`

### SD Data (Tagged Data)
- To read field: use `OEGetSDData(mol, tag)`
- To write field: use `OESetSDData(mol, tag, value)`
- To check existence: use `OEHasSDData(mol, tag)` before reading
- To iterate all fields: use `OEGetSDDataPairs(mol)`

## Common Parameters & Types

**OEMolBase**: Base interface for all molecule types
  - Create with: `OEGraphMol()` for single conformer, `OEMol()` for multi-conformer
  - Common in: Nearly all OEChem functions that operate on molecules
  - Gotcha: Use `OEGraphMol` for most tasks; only use `OEMol` when explicitly working with conformers

**OEAtomBase**: Interface for atom objects
  - Create with: Obtained from `mol.GetAtoms()` iterator or `mol.GetAtom(idx)`
  - Common in: Atom property access, bond traversal, substructure matches
  - Gotcha: Atoms are invalidated if molecule structure changes; don't store long-term

**OEBondBase**: Interface for bond objects
  - Create with: Obtained from `mol.GetBonds()` or `atom.GetBonds()` iterators
  - Common in: Bond property access, molecular graph traversal
  - Typical values: Access via `bond.GetBgn()` and `bond.GetEnd()` for connected atoms

**OEQMolBase**: Query molecule for pattern matching
  - Create with: `OEQMol()` then `OEParseSmarts(qmol, smarts_string)`
  - Common in: `OESubSearch`, `OEHasSubstructMatch`, all substructure search functions
  - Gotcha: SMARTS syntax is different from SMILES; use SMARTS-specific features for queries

**OEMolStreamBase**: Base class for molecule I/O streams
  - Create with: `oemolistream(filename)` for input, `oemolostream(filename)` for output
  - Common in: `OEReadMolecule`, `OEWriteMolecule`, all file I/O operations
  - Gotcha: Always close streams with `close()` or use context managers; format auto-detected from extension

**Predicates (OEUnaryPredicate)**: Functors for filtering atoms/bonds
  - Create with: Built-in predicates like `OEIsHeavy()`, `OEIsCarbon()`, `OEIsAromaticAtom()`
  - Common in: `OECount()`, atom/bond filtering, custom traversal
  - Typical values: `OEIsHeavy()`, `OEIsCarbon()`, `OEIsNitrogen()`, `OEIsAromaticAtom()`, `OEAtomIsInRing()`

**Aromaticity Models (int constants)**: Control aromaticity perception
  - Create with: Use constants like `OEAroModel_OpenEye`, `OEAroModel_MDL`
  - Common in: `OEAssignAromaticFlags(mol, model)`
  - Typical values: `OEAroModel_OpenEye` (default), `OEAroModel_MDL`, `OEAroModel_Daylight`

**File Formats (int constants)**: Specify molecular file formats
  - Create with: Use constants like `OEFormat_SDF`, `OEFormat_MOL2`, `OEFormat_PDB`
  - Common in: `SetFormat()` on streams when explicit format needed
  - Gotcha: Usually auto-detected from filename extension; explicit setting rarely needed

## Return Types & Error Handling

```python
# Pattern 1: Boolean returns indicate success/failure
mol = oechem.OEGraphMol()
if not oechem.OESmilesToMol(mol, smiles_string):
    print(f"Failed to parse SMILES: {smiles_string}")
    # Handle error - mol may be in invalid state

# Pattern 2: Iterator returns for traversal
for atom in mol.GetAtoms():
    # Process each atom
    # Iterator is empty if no atoms
    pass

# Pattern 3: Stream operations with boolean checks
ifs = oechem.oemolistream()
if not ifs.open(filename):
    print(f"Unable to open file: {filename}")
    # Handle file open error
    
mol = oechem.OEGraphMol()
while oechem.OEReadMolecule(ifs, mol):
    # Process molecule
    # Returns False when no more molecules or read error
    pass
ifs.close()

# Pattern 4: Substructure search returns iterator of matches
ss = oechem.OESubSearch(pattern)
matches = list(ss.Match(mol))  # Convert to list if needed
if not matches:
    print("No matches found")
else:
    for match in matches:
        # Process each match
        pass

# Pattern 5: String returns (empty string on failure)
smiles = oechem.OECreateCanSmiString(mol)
if not smiles:
    print("Failed to generate SMILES")
    
# Pattern 6: Numeric returns (check documentation for special values)
mw = oechem.OECalculateMolecularWeight(mol)
# Returns 0.0 for empty molecule

# Pattern 7: SD Data returns (empty string if tag doesn't exist)
if oechem.OEHasSDData(mol, "IC50"):
    value = oechem.OEGetSDData(mol, "IC50")
else:
    # Tag doesn't exist, handle appropriately
    value = None