# OEMedChem TK

> Medicinal chemistry analysis, matched molecular pairs, and molecule fragmentation

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

## Core API - Function Quick Reference

### Matched Molecular Pair Analysis

**OEMedChemMMPIndex()**
  Use for: Creating an index for matched molecular pair analysis
  Example: `mmpindex = OEMedChemMMPIndex()`
  See: [API Reference](https://docs.eyesopen.com/toolkits/python/medchemtk/OEMedChemClasses/OEMedChemMMPIndex.html)

**OEMedChemMMPIndex.AddMol(mol: OEMolBase) -> bool**
  Use for: Adding molecules to the MMP index for analysis
  Example: `mmpindex.AddMol(mol)`
  See: [API Reference](https://docs.eyesopen.com/toolkits/python/medchemtk/OEMedChemClasses/OEMedChemMMPIndex.html)

**OEMedChemMMPIndex.GetTransforms(mol: OEMolBase) -> OEMedChemTransformIter**
  Use for: Retrieving all transformations applicable to a molecule
  Example: `for transform in mmpindex.GetTransforms(mol): process(transform)`
  See: [API Reference](https://docs.eyesopen.com/toolkits/python/medchemtk/OEMedChemClasses/OEMedChemMMPIndex.html)

**OEMedChemMMPIndex.GetTransformsBySmarts(smarts: str) -> OEMedChemTransformIter**
  Use for: Getting transformations matching a specific SMARTS pattern
  Example: `transforms = mmpindex.GetTransformsBySmarts("[#6]>>[#7]")`
  See: [API Reference](https://docs.eyesopen.com/toolkits/python/medchemtk/OEMedChemClasses/OEMedChemMMPIndex.html)

**OEMedChemTransform.GetFromSmarts() -> str**
  Use for: Getting the SMARTS pattern of the original fragment in a transformation
  Example: `from_smarts = transform.GetFromSmarts()`
  See: [API Reference](https://docs.eyesopen.com/toolkits/python/medchemtk/OEMedChemClasses/OEMedChemTransform.html)

**OEMedChemTransform.GetToSmarts() -> str**
  Use for: Getting the SMARTS pattern of the replacement fragment in a transformation
  Example: `to_smarts = transform.GetToSmarts()`
  See: [API Reference](https://docs.eyesopen.com/toolkits/python/medchemtk/OEMedChemClasses/OEMedChemTransform.html)

**OEMedChemTransform.GetContextSmarts() -> str**
  Use for: Getting the context (unchanged portion) SMARTS pattern
  Example: `context = transform.GetContextSmarts()`
  See: [API Reference](https://docs.eyesopen.com/toolkits/python/medchemtk/OEMedChemClasses/OEMedChemTransform.html)

**OEApplyMedChemTransformations(mol: OEMolBase, transforms: OEMedChemTransformIter) -> OEMolBase iterator**
  Use for: Applying transformations to generate new molecules
  Example: `for newmol in OEApplyMedChemTransformations(mol, transforms): process(newmol)`
  See: [API Reference](https://docs.eyesopen.com/toolkits/python/medchemtk/OEMedChemFunctions/OEApplyMedChemTransformations.html)

### Molecule Fragmentation

**OEGetBemisMurckoFragments(mol: OEMolBase) -> OEMolBase iterator**
  Use for: Generating Bemis-Murcko framework and scaffold fragments
  Example: `for frag in OEGetBemisMurckoFragments(mol): process(frag)`
  See: [API Reference](https://docs.eyesopen.com/toolkits/python/medchemtk/OEMedChemFunctions/OEGetBemisMurckoFragments.html)

**OEGetRingChainFragments(mol: OEMolBase) -> OEMolBase iterator**
  Use for: Fragmenting molecule into ring systems and chains
  Example: `for frag in OEGetRingChainFragments(mol): process(frag)`
  See: [API Reference](https://docs.eyesopen.com/toolkits/python/medchemtk/OEMedChemFunctions/OEGetRingChainFragments.html)

**OEGetFunctionalGroupFragments(mol: OEMolBase) -> OEMolBase iterator**
  Use for: Extracting functional group fragments from a molecule
  Example: `for frag in OEGetFunctionalGroupFragments(mol): process(frag)`
  See: [API Reference](https://docs.eyesopen.com/toolkits/python/medchemtk/OEMedChemFunctions/OEGetFunctionalGroupFragments.html)

**OEGetRingSystems(mol: OEMolBase) -> OEMolBase iterator**
  Use for: Extracting individual ring systems from a molecule
  Example: `for ring in OEGetRingSystems(mol): process(ring)`
  See: [API Reference](https://docs.eyesopen.com/toolkits/python/medchemtk/OEMedChemFunctions/OEGetRingSystems.html)

### MCS Fragment Database

**OEMCSFragDatabase()**
  Use for: Creating a database for MCS-based fragment similarity searching
  Example: `fragdb = OEMCSFragDatabase()`
  See: [API Reference](https://docs.eyesopen.com/toolkits/python/medchemtk/OEMedChemClasses/OEMCSFragDatabase.html)

**OEMCSFragDatabase.AddMol(mol: OEMolBase) -> bool**
  Use for: Adding molecules to the MCS fragment database
  Example: `fragdb.AddMol(mol)`
  See: [API Reference](https://docs.eyesopen.com/toolkits/python/medchemtk/OEMedChemClasses/OEMCSFragDatabase.html)

**OEMCSFragDatabase.GetSortedScores(mol: OEMolBase) -> OEMCSFragScore iterator**
  Use for: Getting similarity scores for a query molecule against database
  Example: `for score in fragdb.GetSortedScores(query): print(score.GetScore())`
  See: [API Reference](https://docs.eyesopen.com/toolkits/python/medchemtk/OEMedChemClasses/OEMCSFragDatabase.html)

**OEMCSFragScore.GetScore() -> float**
  Use for: Retrieving the similarity score from an MCS fragment match
  Example: `similarity = score.GetScore()`
  See: [API Reference](https://docs.eyesopen.com/toolkits/python/medchemtk/OEMedChemClasses/OEMCSFragScore.html)

**OEMCSFragScore.GetMol() -> OEMolBase**
  Use for: Getting the molecule associated with an MCS fragment score
  Example: `matched_mol = score.GetMol()`
  See: [API Reference](https://docs.eyesopen.com/toolkits/python/medchemtk/OEMedChemClasses/OEMCSFragScore.html)

### Fragmentation Options

**OEMedChemFragmentOptions()**
  Use for: Configuring fragmentation behavior for matched pair analysis
  Example: `opts = OEMedChemFragmentOptions()`
  See: [API Reference](https://docs.eyesopen.com/toolkits/python/medchemtk/OEMedChemClasses/OEMedChemFragmentOptions.html)

**OEMedChemFragmentOptions.SetMaxHeavyAtoms(maxatoms: int)**
  Use for: Setting maximum heavy atoms allowed in fragments
  Example: `opts.SetMaxHeavyAtoms(10)`
  See: [API Reference](https://docs.eyesopen.com/toolkits/python/medchemtk/OEMedChemClasses/OEMedChemFragmentOptions.html)

**OEMedChemFragmentOptions.SetMinHeavyAtoms(minatoms: int)**
  Use for: Setting minimum heavy atoms required in fragments
  Example: `opts.SetMinHeavyAtoms(3)`
  See: [API Reference](https://docs.eyesopen.com/toolkits/python/medchemtk/OEMedChemClasses/OEMedChemFragmentOptions.html)

## Common Patterns - Complete Working Examples

### Pattern: Building a Matched Molecular Pair Index

```python
from openeye import oechem
from openeye import oemedchem

# Create MMP index and configure options
mmpindex = oemedchem.OEMedChemMMPIndex()
opts = oemedchem.OEMedChemFragmentOptions()
opts.SetMaxHeavyAtoms(10)

# Read molecules and add to index
ifs = oechem.oemolistream("molecules.sdf")
for mol in ifs.GetOEGraphMols():
    mmpindex.AddMol(mol)
ifs.close()

# Index is now ready for transformation queries
print(f"Indexed {mmpindex.NumMols()} molecules")
```
Use when: Building a database of molecules for matched pair analysis and transformation discovery

### Pattern: Finding and Applying Transformations

```python
from openeye import oechem
from openeye import oemedchem

# Load pre-built MMP index
mmpindex = oemedchem.OEMedChemMMPIndex()
# ... populate index ...

# Get transformations for a query molecule
query = oechem.OEGraphMol()
oechem.OESmilesToMol(query, "c1ccccc1C(=O)O")

# Apply transformations to generate analogs
ofs = oechem.oemolostream("analogs.sdf")
for transform in mmpindex.GetTransforms(query):
    for newmol in oemedchem.OEApplyMedChemTransformations(query, [transform]):
        oechem.OEWriteMolecule(ofs, newmol)
ofs.close()
```
Use when: Generating structural analogs based on transformations learned from a molecule database

### Pattern: Extracting Specific Transformations by SMARTS

```python
from openeye import oechem
from openeye import oemedchem

# Create and populate MMP index
mmpindex = oemedchem.OEMedChemMMPIndex()
# ... add molecules ...

# Find all transformations involving halogen substitution
halogen_pattern = "[F,Cl,Br,I]>>[F,Cl,Br,I]"
transforms = mmpindex.GetTransformsBySmarts(halogen_pattern)

# Examine each transformation
for transform in transforms:
    from_smarts = transform.GetFromSmarts()
    to_smarts = transform.GetToSmarts()
    context = transform.GetContextSmarts()
    print(f"{from_smarts} -> {to_smarts} in context {context}")
```
Use when: Finding specific chemical transformations (e.g., halogen swaps, functional group changes) in your dataset

### Pattern: Bemis-Murcko Framework Analysis

```python
from openeye import oechem
from openeye import oemedchem

# Read input molecules
ifs = oechem.oemolistream("compounds.sdf")
mol = oechem.OEGraphMol()

# Extract frameworks and scaffolds
ofs = oechem.oemolostream("frameworks.sdf")
while oechem.OEReadMolecule(ifs, mol):
    for frag in oemedchem.OEGetBemisMurckoFragments(mol):
        frag.SetTitle(f"{mol.GetTitle()}_framework")
        oechem.OEWriteMolecule(ofs, frag)

ifs.close()
ofs.close()
```
Use when: Analyzing molecular scaffolds and frameworks for diversity assessment or clustering

### Pattern: Ring System Extraction

```python
from openeye import oechem
from openeye import oemedchem

# Process molecule to extract ring systems
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccc2c(c1)ccc1ccccc12")  # Anthracene

# Get individual ring systems
ring_systems = []
for ring in oemedchem.OEGetRingSystems(mol):
    ring_systems.append(oechem.OEGraphMol(ring))
    print(f"Ring system: {oechem.OEMolToSmiles(ring)}")

# Each ring system is now a separate molecule
print(f"Found {len(ring_systems)} ring systems")
```
Use when: Decomposing molecules into constituent ring systems for fragment analysis

### Pattern: Building MCS Fragment Database

```python
from openeye import oechem
from openeye import oemedchem

# Create MCS fragment database
fragdb = oemedchem.OEMCSFragDatabase()

# Add reference molecules
ifs = oechem.oemolistream("reference.sdf")
for mol in ifs.GetOEGraphMols():
    fragdb.AddMol(mol)
ifs.close()

# Database ready for similarity searching
print(f"Database contains {fragdb.NumMols()} molecules")
```
Use when: Building a reference database for MCS-based similarity searching

### Pattern: MCS Similarity Searching

```python
from openeye import oechem
from openeye import oemedchem

# Load pre-built fragment database
fragdb = oemedchem.OEMCSFragDatabase()
# ... populate database ...

# Query with a molecule
query = oechem.OEGraphMol()
oechem.OESmilesToMol(query, "c1ccccc1CCN")

# Get sorted similarity scores
results = []
for score in fragdb.GetSortedScores(query):
    similarity = score.GetScore()
    matched_mol = score.GetMol()
    results.append((similarity, matched_mol.GetTitle()))
    if len(results) >= 10:  # Top 10 hits
        break

for sim, title in results:
    print(f"{title}: {sim:.3f}")
```
Use when: Finding similar molecules based on MCS fragment overlap

### Pattern: Functional Group Fragment Analysis

```python
from openeye import oechem
from openeye import oemedchem

# Read molecule
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "CC(=O)Oc1ccccc1C(=O)O")  # Aspirin

# Extract functional groups
functional_groups = []
for frag in oemedchem.OEGetFunctionalGroupFragments(mol):
    smiles = oechem.OEMolToSmiles(frag)
    functional_groups.append(smiles)
    print(f"Functional group: {smiles}")

print(f"Total functional groups: {len(functional_groups)}")
```
Use when: Identifying and cataloging functional groups present in molecules

### Pattern: Ring-Chain Fragmentation

```python
from openeye import oechem
from openeye import oemedchem

# Process molecule
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccc(cc1)CCCC(=O)O")

# Separate rings and chains
rings = []
chains = []
for frag in oemedchem.OEGetRingChainFragments(mol):
    smiles = oechem.OEMolToSmiles(frag)
    if oechem.OECount(frag, oechem.OEIsInRing()):
        rings.append(smiles)
    else:
        chains.append(smiles)

print(f"Rings: {rings}")
print(f"Chains: {chains}")
```
Use when: Decomposing molecules into cyclic and acyclic components

### Pattern: Parallel MMP Index Building

```python
from openeye import oechem
from openeye import oemedchem
import multiprocessing

def build_index_chunk(mol_chunk):
    index = oemedchem.OEMedChemMMPIndex()
    for mol in mol_chunk:
        index.AddMol(mol)
    return index

# Read all molecules
ifs = oechem.oemolistream("large_dataset.sdf")
all_mols = [oechem.OEGraphMol(mol) for mol in ifs.GetOEGraphMols()]
ifs.close()

# Split into chunks for parallel processing
num_processes = multiprocessing.cpu_count()
chunk_size = len(all_mols) // num_processes
chunks = [all_mols[i:i+chunk_size] for i in range(0, len(all_mols), chunk_size)]

# Build indices in parallel (conceptual - actual merging requires additional logic)
with multiprocessing.Pool(num_processes) as pool:
    partial_indices = pool.map(build_index_chunk, chunks)
```
Use when: Processing large molecule datasets efficiently using multiple CPU cores

### Pattern: Filtering Transformations by Property Change

```python
from openeye import oechem
from openeye import oemedchem

# Build MMP index with property data
mmpindex = oemedchem.OEMedChemMMPIndex()
# ... add molecules with SD data properties ...

# Get transformations for query
query = oechem.OEGraphMol()
oechem.OESmilesToMol(query, "c1ccccc1C")

# Filter transformations by property improvement
good_transforms = []
for transform in mmpindex.GetTransforms(query):
    # Check if transformation improves desired property
    # (requires custom logic based on stored SD data)
    from_smarts = transform.GetFromSmarts()
    to_smarts = transform.GetToSmarts()
    good_transforms.append((from_smarts, to_smarts))

print(f"Found {len(good_transforms)} beneficial transformations")
```
Use when: Identifying transformations that improve specific molecular properties (solubility, potency, etc.)

### Pattern: Custom Fragmentation Options

```python
from openeye import oechem
from openeye import oemedchem

# Configure fragmentation behavior
opts = oemedchem.OEMedChemFragmentOptions()
opts.SetMaxHeavyAtoms(8)
opts.SetMinHeavyAtoms(3)

# Create index with custom options
mmpindex = oemedchem.OEMedChemMMPIndex(opts)

# Add molecules - fragmentation follows custom rules
ifs = oechem.oemolistream("molecules.sdf")
for mol in ifs.GetOEGraphMols():
    mmpindex.AddMol(mol)
ifs.close()

print(f"Indexed with custom fragmentation rules")
```
Use when: Controlling fragment size and complexity for matched pair analysis

## API Decision Guide

- **For matched pair analysis**: use `OEMedChemMMPIndex` (learns transformations from molecule sets)
- **For generating analogs**: use `OEApplyMedChemTransformations` (applies learned transformations to new molecules)
- **For scaffold analysis**: use `OEGetBemisMurckoFragments` (extracts frameworks and scaffolds)
- **For similarity searching**: use `OEMCSFragDatabase` (MCS-based fragment similarity)
- **For ring extraction**: use `OEGetRingSystems` (individual ring systems) or `OEGetRingChainFragments` (rings vs chains)
- **For functional groups**: use `OEGetFunctionalGroupFragments` (identifies functional groups)

- **OEMedChemMMPIndex vs OEMCSFragDatabase**: use MMPIndex for transformation discovery and analog generation; use MCSFragDatabase for similarity searching and clustering
- **OEGetBemisMurckoFragments vs OEGetRingSystems**: use BemisMurcko for scaffold/framework analysis; use RingSystems for individual ring extraction
- **GetTransforms vs GetTransformsBySmarts**: use GetTransforms for all applicable transformations; use GetTransformsBySmarts to filter by specific chemical patterns

- **For large datasets**: use parallel processing with multiple `OEMedChemMMPIndex` instances (see parallel example)
- **For specific transformations**: use `GetTransformsBySmarts` with SMARTS patterns (e.g., "[#6]>>[#7]" for C to N)
- **For property-driven design**: combine MMP transformations with SD data filtering (see property filtering example)

## Common Parameters & Types

**OEMolBase**: Molecule object from OEChem
  - Create with: `mol = oechem.OEGraphMol()` or `oechem.OESmilesToMol(mol, smiles)`
  - Common in: All fragmentation and MMP functions
  - Gotcha: Must be a valid molecule with explicit hydrogens for some operations

**OEMedChemFragmentOptions**: Configuration for fragmentation behavior
  - Create with: `opts = oemedchem.OEMedChemFragmentOptions()`
  - Common in: `OEMedChemMMPIndex` constructor
  - Typical values: `SetMaxHeavyAtoms(10)`, `SetMinHeavyAtoms(3)` for balanced fragment sizes

**OEMedChemTransform**: Represents a chemical transformation (from → to)
  - Create with: Returned by `GetTransforms()` or `GetTransformsBySmarts()`
  - Common in: Transformation iteration and application
  - Key methods: `GetFromSmarts()`, `GetToSmarts()`, `GetContextSmarts()`

**OEMedChemTransformIter**: Iterator over transformations
  - Create with: Returned by `GetTransforms()` methods
  - Common in: Looping over transformations
  - Usage: `for transform in transforms: ...`

**OEMCSFragScore**: Similarity score from MCS fragment matching
  - Create with: Returned by `GetSortedScores()`
  - Common in: Similarity searching results
  - Key methods: `GetScore()` (float 0-1), `GetMol()` (matched molecule)

**SMARTS pattern (str)**: Chemical pattern for substructure matching
  - Create with: String like `"[#6]>>[#7]"` for transformations
  - Common in: `GetTransformsBySmarts()`, transformation filtering
  - Gotcha: Must be valid SMARTS syntax; use `>>` to separate from/to patterns

## Return Types & Error Handling

```python
# Pattern 1: Iterator returns (most fragmentation functions)
for fragment in oemedchem.OEGetBemisMurckoFragments(mol):
    # Each fragment is an OEMolBase
    smiles = oechem.OEMolToSmiles(fragment)
    # Process fragment...

# Pattern 2: Boolean returns (adding to databases)
success = mmpindex.AddMol(mol)
if not success:
    print(f"Failed to add molecule: {mol.GetTitle()}")

# Pattern 3: Object returns (database queries)
scores = fragdb.GetSortedScores(query)
for score in scores:
    similarity = score.GetScore()  # float
    matched_mol = score.GetMol()   # OEMolBase
    if similarity > 0.7:
        # Process high-similarity match...
        pass

# Pattern 4: Checking valid molecules before processing
if mol.NumAtoms() == 0:
    print("Empty molecule, skipping")
    continue

# Pattern 5: Handling empty results
transforms = list(mmpindex.GetTransforms(mol))
if not transforms:
    print("No transformations found for this molecule")
else:
    print(f"Found {len(transforms)} transformations")