# Spruce TK

> Biomolecular structure preparation and validation toolkit for protein-ligand complexes

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

## Core API - Function Quick Reference

### Design Unit Creation & Preparation

```
OEMakeDesignUnits(ifs: oemolistream, opts: OEMakeDesignUnitOptions) -> Iterator[OEDesignUnit]
  Use for: Creating design units from PDB/mmCIF files with automatic preparation
  Example: for du in OEMakeDesignUnits(ifs, opts): process(du)
  See: https://docs.eyesopen.com/toolkits/python/sprucetk/OESpruceFunctions/OEMakeDesignUnits.html

OEMakeDesignUnit(protein: OEGraphMol, ligand: OEGraphMol, opts: OEMakeDesignUnitOptions) -> OEDesignUnit
  Use for: Creating a single design unit from separate protein and ligand molecules
  Example: du = OEMakeDesignUnit(protein, ligand, opts)
  See: https://docs.eyesopen.com/toolkits/python/sprucetk/OESpruceFunctions/OEMakeDesignUnit.html

OEMakeBioDesignUnits(ifs: oemolistream, opts: OEDesignUnitBuildOptions) -> Iterator[OEDesignUnit]
  Use for: Creating biological design units (BioDUs) with biological assembly context
  Example: for biodu in OEMakeBioDesignUnits(ifs, opts): process(biodu)
  See: https://docs.eyesopen.com/toolkits/python/sprucetk/OESpruceFunctions/OEMakeBioDesignUnits.html

OEProtonateDesignUnit(du: OEDesignUnit, opts: OEProtonateDesignUnitOptions) -> bool
  Use for: Adding and optimizing hydrogen positions in a design unit
  Example: success = OEProtonateDesignUnit(du, opts)
  See: https://docs.eyesopen.com/toolkits/python/sprucetk/OESpruceFunctions/OEProtonateDesignUnit.html
```

### Biological Unit Extraction

```
OEExtractBioUnits(ifs: oemolistream, opts: OEBioUnitExtractionOptions) -> Iterator[OEGraphMol]
  Use for: Extracting biological assemblies from PDB/mmCIF files
  Example: for biounit in OEExtractBioUnits(ifs, opts): process(biounit)
  See: https://docs.eyesopen.com/toolkits/python/sprucetk/OESpruceFunctions/OEExtractBioUnits.html
```

### Pocket & Site Detection

```
OEFindPockets(protein: OEGraphMol, opts: OEPocketOptions) -> Iterator[OEPocket]
  Use for: Finding binding pockets in protein structures
  Example: for pocket in OEFindPockets(protein, opts): analyze(pocket)
  See: https://docs.eyesopen.com/toolkits/python/sprucetk/OESpruceFunctions/OEFindPockets.html

OEEnumerateSites(du: OEDesignUnit, opts: OEDesignUnitEnumerateSitesOptions) -> Iterator[OEDesignUnit]
  Use for: Enumerating all potential binding sites in a design unit
  Example: for site_du in OEEnumerateSites(du, opts): process(site_du)
  See: https://docs.eyesopen.com/toolkits/python/sprucetk/OESpruceFunctions/OEEnumerateSites.html

OEMakeDesignUnitFromPocket(protein: OEGraphMol, pocket: OEPocket, opts: OEMakeDesignUnitOptions) -> OEDesignUnit
  Use for: Creating a design unit focused on a specific pocket
  Example: du = OEMakeDesignUnitFromPocket(protein, pocket, opts)
  See: https://docs.eyesopen.com/toolkits/python/sprucetk/OESpruceFunctions/OEMakeDesignUnitFromPocket.html
```

### Structure Modeling & Building

```
OEBuildSidechains(protein: OEGraphMol, opts: OESidechainBuilderOptions) -> bool
  Use for: Building missing protein side chains
  Example: success = OEBuildSidechains(protein, opts)
  See: https://docs.eyesopen.com/toolkits/python/sprucetk/OESpruceFunctions/OEBuildSidechains.html

OEBuildLoops(protein: OEGraphMol, opts: OELoopBuilderOptions) -> bool
  Use for: Building missing protein loops
  Example: success = OEBuildLoops(protein, opts)
  See: https://docs.eyesopen.com/toolkits/python/sprucetk/OESpruceFunctions/OEBuildLoops.html

OEBuildSingleLoop(protein: OEGraphMol, chain_id: str, start_resnum: int, end_resnum: int, opts: OELoopBuilderOptions) -> bool
  Use for: Building a specific missing loop region
  Example: success = OEBuildSingleLoop(protein, 'A', 45, 52, opts)
  See: https://docs.eyesopen.com/toolkits/python/sprucetk/OESpruceFunctions/OEBuildSingleLoop.html

OECapTermini(protein: OEGraphMol, opts: OECapBuilderOptions) -> bool
  Use for: Adding capping groups to protein termini
  Example: success = OECapTermini(protein, opts)
  See: https://docs.eyesopen.com/toolkits/python/sprucetk/OESpruceFunctions/OECapTermini.html

OECapNTermini(protein: OEGraphMol, opts: OECapBuilderOptions) -> bool
  Use for: Adding capping groups to N-termini only
  Example: success = OECapNTermini(protein, opts)
  See: https://docs.eyesopen.com/toolkits/python/sprucetk/OESpruceFunctions/OECapNTermini.html

OECapCTermini(protein: OEGraphMol, opts: OECapBuilderOptions) -> bool
  Use for: Adding capping groups to C-termini only
  Example: success = OECapCTermini(protein, opts)
  See: https://docs.eyesopen.com/toolkits/python/sprucetk/OESpruceFunctions/OECapCTermini.html
```

### Mutations & Modifications

```
OEMutateResidue(protein: OEGraphMol, chain_id: str, resnum: int, target_aa: str, opts: OEDesignUnitMutationOptions) -> bool
  Use for: Mutating a single residue to a different amino acid
  Example: success = OEMutateResidue(protein, 'A', 123, 'ALA', opts)
  See: https://docs.eyesopen.com/toolkits/python/sprucetk/OESpruceFunctions/OEMutateResidue.html

OEMutateResidues(protein: OEGraphMol, mutations: dict, opts: OEDesignUnitMutationOptions) -> bool
  Use for: Applying multiple mutations simultaneously
  Example: success = OEMutateResidues(protein, {('A', 123): 'ALA', ('B', 45): 'GLY'}, opts)
  See: https://docs.eyesopen.com/toolkits/python/sprucetk/OESpruceFunctions/OEMutateResidues.html
```

### Superposition & Alignment

```
OESuperpose(ref_protein: OEGraphMol, fit_protein: OEGraphMol, opts: OESuperposeOptions) -> OESuperposeResults
  Use for: Superposing one protein structure onto another
  Example: results = OESuperpose(ref_protein, fit_protein, opts)
  See: https://docs.eyesopen.com/toolkits/python/sprucetk/OESpruceFunctions/OESuperpose.html
```

### Structure Validation & Quality

```
OEValidateDesignUnit(du: OEDesignUnit) -> OEValidateDesignUnit
  Use for: Validating design unit structure and identifying issues
  Example: validator = OEValidateDesignUnit(du); issues = validator.GetIssues()
  See: https://docs.eyesopen.com/toolkits/python/sprucetk/OESpruceClasses/OEValidateDesignUnit.html

OESpruceFilter(opts: OESpruceFilterOptions) -> OESpruceFilter
  Use for: Filtering structures based on quality criteria
  Example: filter = OESpruceFilter(opts); if filter(mol): process(mol)
  See: https://docs.eyesopen.com/toolkits/python/sprucetk/OESpruceClasses/OESpruceFilter.html
```

### Utility Functions

```
OEGetPartialResidues(protein: OEGraphMol) -> list
  Use for: Identifying residues with missing atoms
  Example: partial_residues = OEGetPartialResidues(protein)
  See: https://docs.eyesopen.com/toolkits/python/sprucetk/OESpruceFunctions/OEGetPartialResidues.html

OEFixBackbone(protein: OEGraphMol) -> bool
  Use for: Fixing backbone connectivity issues
  Example: success = OEFixBackbone(protein)
  See: https://docs.eyesopen.com/toolkits/python/sprucetk/OESpruceFunctions/OEFixBackbone.html
```

## Common Patterns - Complete Working Examples

### Pattern: Create Design Units from PDB File

```python
from openeye import oechem, oespruce

ifs = oechem.oemolistream("input.pdb")
opts = oespruce.OEMakeDesignUnitOptions()
opts.SetStrictProtonationMode(False)

for du in oespruce.OEMakeDesignUnits(ifs, opts):
    protein = oechem.OEGraphMol()
    ligand = oechem.OEGraphMol()
    du.GetProtein(protein)
    du.GetLigand(ligand)
    print(f"Created DU with {protein.NumAtoms()} protein atoms, {ligand.NumAtoms()} ligand atoms")
```
Use when: You have a PDB/mmCIF file and want to automatically prepare protein-ligand complexes for docking or analysis.

### Pattern: Create Apo Design Units (No Ligand)

```python
from openeye import oechem, oespruce

ifs = oechem.oemolistream("apo_structure.pdb")
opts = oespruce.OEMakeDesignUnitOptions()
opts.SetAllowApoDesignUnit(True)

for du in oespruce.OEMakeDesignUnits(ifs, opts):
    protein = oechem.OEGraphMol()
    du.GetProtein(protein)
    ofs = oechem.oemolostream("prepared_apo.oedu")
    oechem.OEWriteDesignUnit(ofs, du)
```
Use when: Working with apo structures (no bound ligand) for pocket detection or virtual screening preparation.

### Pattern: Find and Analyze Binding Pockets

```python
from openeye import oechem, oespruce

ifs = oechem.oemolistream("protein.pdb")
protein = oechem.OEGraphMol()
oechem.OEReadMolecule(ifs, protein)

opts = oespruce.OEPocketOptions()
for pocket in oespruce.OEFindPockets(protein, opts):
    volume = pocket.GetVolume()
    surface_area = pocket.GetSurfaceArea()
    print(f"Pocket: volume={volume:.1f} Å³, surface={surface_area:.1f} Ų")
```
Use when: You need to identify potential binding sites in a protein structure without a known ligand.

### Pattern: Build Missing Loops and Side Chains

```python
from openeye import oechem, oespruce

ifs = oechem.oemolistream("incomplete_protein.pdb")
protein = oechem.OEGraphMol()
oechem.OEReadMolecule(ifs, protein)

loop_opts = oespruce.OELoopBuilderOptions()
oespruce.OEBuildLoops(protein, loop_opts)

sc_opts = oespruce.OESidechainBuilderOptions()
oespruce.OEBuildSidechains(protein, sc_opts)

ofs = oechem.oemolostream("complete_protein.pdb")
oechem.OEWriteMolecule(ofs, protein)
```
Use when: Your structure has missing loops or side chains that need to be modeled before further analysis.

### Pattern: Protonate Design Unit with Custom pH

```python
from openeye import oechem, oespruce

ifs = oechem.oemolistream("complex.pdb")
opts = oespruce.OEMakeDesignUnitOptions()

for du in oespruce.OEMakeDesignUnits(ifs, opts):
    prot_opts = oespruce.OEProtonateDesignUnitOptions()
    prot_opts.SetTargetPH(7.4)
    prot_opts.SetPlaceHydrogens(True)
    
    if oespruce.OEProtonateDesignUnit(du, prot_opts):
        ofs = oechem.oemolostream("protonated.oedu")
        oechem.OEWriteDesignUnit(ofs, du)
```
Use when: You need to add hydrogens and optimize protonation states at a specific pH for molecular modeling.

### Pattern: Extract Biological Assemblies

```python
from openeye import oechem, oespruce

ifs = oechem.oemolistream("asymmetric_unit.pdb")
opts = oespruce.OEBioUnitExtractionOptions()
opts.SetBioUnitID(1)

count = 0
for biounit in oespruce.OEExtractBioUnits(ifs, opts):
    ofs = oechem.oemolostream(f"biounit_{count}.pdb")
    oechem.OEWriteMolecule(ofs, biounit)
    count += 1
    print(f"Extracted biounit with {biounit.NumAtoms()} atoms")
```
Use when: You need to generate the biologically relevant assembly from a crystallographic asymmetric unit.

### Pattern: Mutate Residues in Protein

```python
from openeye import oechem, oespruce

ifs = oechem.oemolistream("wildtype.pdb")
protein = oechem.OEGraphMol()
oechem.OEReadMolecule(ifs, protein)

opts = oespruce.OEDesignUnitMutationOptions()
mutations = {('A', 123): 'ALA', ('A', 456): 'GLY'}

if oespruce.OEMutateResidues(protein, mutations, opts):
    ofs = oechem.oemolostream("mutant.pdb")
    oechem.OEWriteMolecule(ofs, protein)
```
Use when: Creating mutant structures for computational mutagenesis studies or structure-activity relationship analysis.

### Pattern: Superpose Proteins and Get RMSD

```python
from openeye import oechem, oespruce

ref_ifs = oechem.oemolistream("reference.pdb")
fit_ifs = oechem.oemolistream("target.pdb")
ref_protein = oechem.OEGraphMol()
fit_protein = oechem.OEGraphMol()
oechem.OEReadMolecule(ref_ifs, ref_protein)
oechem.OEReadMolecule(fit_ifs, fit_protein)

opts = oespruce.OESuperposeOptions()
results = oespruce.OESuperpose(ref_protein, fit_protein, opts)
print(f"RMSD: {results.GetRMSD():.2f} Å")
```
Use when: Aligning protein structures for comparison or preparing multiple structures in a common reference frame.

### Pattern: Validate Design Unit Quality

```python
from openeye import oechem, oespruce

ifs = oechem.oemolistream("complex.oedu")
du = oechem.OEDesignUnit()
oechem.OEReadDesignUnit(ifs, du)

validator = oespruce.OEValidateDesignUnit(du)
if validator.HasIssues():
    for issue in validator.GetIssues():
        print(f"Issue: {issue.GetDescription()}")
else:
    print("Design unit passed validation")
```
Use when: Checking if a design unit meets quality criteria before using it for docking or other applications.

### Pattern: Filter Structures by Quality Criteria

```python
from openeye import oechem, oespruce

ifs = oechem.oemolistream("structures.pdb")
opts = oespruce.OESpruceFilterOptions()
opts.SetMinResolution(2.5)
opts.SetMaxBFactor(50.0)

filter = oespruce.OESpruceFilter(opts)
for mol in ifs.GetOEGraphMols():
    if filter(mol):
        print(f"Structure {mol.GetTitle()} passed filter")
    else:
        print(f"Structure {mol.GetTitle()} failed: {filter.GetFilterReason()}")
```
Use when: Pre-filtering a set of structures based on experimental quality metrics before preparation.

### Pattern: Enumerate All Binding Sites

```python
from openeye import oechem, oespruce

ifs = oechem.oemolistream("protein.pdb")
opts = oespruce.OEMakeDesignUnitOptions()

for du in oespruce.OEMakeDesignUnits(ifs, opts):
    site_opts = oespruce.OEDesignUnitEnumerateSitesOptions()
    site_opts.SetMaxSites(5)
    
    for site_du in oespruce.OEEnumerateSites(du, site_opts):
        ligand = oechem.OEGraphMol()
        site_du.GetLigand(ligand)
        print(f"Site with {ligand.NumAtoms()} atoms")
```
Use when: You want to identify and prepare multiple potential binding sites for virtual screening.

### Pattern: Create Design Unit with Metadata

```python
from openeye import oechem, oespruce
import json

with open("metadata.json") as f:
    metadata_dict = json.load(f)

metadata = oespruce.OEStructureMetadata()
metadata.SetPDBID(metadata_dict["pdb_id"])
metadata.SetResolution(metadata_dict["resolution"])

ifs = oechem.oemolistream("structure.pdb")
opts = oespruce.OEMakeDesignUnitOptions()
opts.SetStructureMetadata(metadata)

for du in oespruce.OEMakeDesignUnits(ifs, opts):
    print(f"Created DU for {metadata.GetPDBID()}")
```
Use when: You have external metadata (resolution, experimental conditions) to associate with your structures.

### Pattern: Cap Protein Termini

```python
from openeye import oechem, oespruce

ifs = oechem.oemolistream("protein_fragment.pdb")
protein = oechem.OEGraphMol()
oechem.OEReadMolecule(ifs, protein)

opts = oespruce.OECapBuilderOptions()
opts.SetNTerminusCap("ACE")
opts.SetCTerminusCap("NME")

if oespruce.OECapTermini(protein, opts):
    ofs = oechem.oemolostream("capped_protein.pdb")
    oechem.OEWriteMolecule(ofs, protein)
```
Use when: Working with protein fragments that need capping groups to prevent artificial charge artifacts.

## API Decision Guide

### Design Unit Creation
- For automatic preparation from PDB/mmCIF: use **OEMakeDesignUnits** (handles multiple structures, alternate locations)
- For single protein-ligand pair: use **OEMakeDesignUnit** (when you already have separated components)
- For biological assemblies: use **OEMakeBioDesignUnits** (creates BioDUs with biological context)
- For apo structures: use **OEMakeDesignUnits** with `SetAllowApoDesignUnit(True)`

### Pocket Detection
- For finding all pockets: use **OEFindPockets** (returns iterator of OEPocket objects)
- For enumerating binding sites in DU: use **OEEnumerateSites** (creates separate DU for each site)
- For creating DU from known pocket: use **OEMakeDesignUnitFromPocket** (when you already identified the pocket)

### Structure Building
- For missing side chains: use **OEBuildSidechains** (rebuilds all missing side chains)
- For missing loops: use **OEBuildLoops** (rebuilds all missing loops automatically)
- For specific loop region: use **OEBuildSingleLoop** (when you know exact residue range)
- For terminal caps: use **OECapTermini** (both termini), **OECapNTermini** (N-term only), or **OECapCTermini** (C-term only)

### Protonation
- For full protonation workflow: use **OEProtonateDesignUnit** (adds hydrogens and optimizes H-bond network)
- Set pH with: `OEProtonateDesignUnitOptions.SetTargetPH(pH_value)`
- For strict protonation: use `OEMakeDesignUnitOptions.SetStrictProtonationMode(True)` (fails if protonation uncertain)

### Mutations
- For single mutation: use **OEMutateResidue** (chain_id, resnum, target_aa)
- For multiple mutations: use **OEMutateResidues** (dict of mutations)

### Superposition
- For protein alignment: use **OESuperpose** (returns OESuperposeResults with RMSD)
- For secondary structure-based: use **OESecondaryStructureSuperposition** class
- For structural superposition: use **OEStructuralSuperposition** class

### Validation & Filtering
- For design unit validation: use **OEValidateDesignUnit** (checks structure quality, identifies issues)
- For pre-filtering structures: use **OESpruceFilter** (filter by resolution, B-factor, etc.)
- For checking partial residues: use **OEGetPartialResidues** (identifies incomplete residues)

### Biological Units
- For extracting from PDB remarks: use **OEExtractBioUnits** with default options
- For specific biounit ID: use `OEBioUnitExtractionOptions.SetBioUnitID(id)`
- For alignment-based extraction: use **OEExtractBioUnits** with reference protein set

## Common Parameters & Types

**OEMakeDesignUnitOptions**: Controls design unit creation workflow
  - Create with: `opts = oespruce.OEMakeDesignUnitOptions()`
  - Common in: OEMakeDesignUnits, OEMakeDesignUnit, OEMakeDesignUnitFromPocket
  - Key settings: `SetStrictProtonationMode(bool)`, `SetAllowApoDesignUnit(bool)`, `SetStructureMetadata(metadata)`
  - Gotcha: Strict protonation mode will fail if protonation states are uncertain

**OEDesignUnit**: Container for protein-ligand complex with preparation metadata
  - Create with: Returned by OEMakeDesignUnits or constructed manually
  - Common in: All design unit manipulation functions
  - Access components: `GetProtein(mol)`, `GetLigand(mol)`, `GetSolvent(mol)`
  - Gotcha: Must use Get methods to extract components, not direct access

**OEProtonateDesignUnitOptions**: Controls hydrogen placement and optimization
  - Create with: `opts = oespruce.OEProtonateDesignUnitOptions()`
  - Common in: OEProtonateDesignUnit
  - Key settings: `SetTargetPH(float)`, `SetPlaceHydrogens(bool)`, `SetOptimizeHydrogens(bool)`
  - Typical values: pH 7.4 for physiological conditions

**OEPocketOptions**: Controls pocket detection algorithm
  - Create with: `opts = oespruce.OEPocketOptions()`
  - Common in: OEFindPockets
  - Key settings: `SetMinVolume(float)`, `SetProbeRadius(float)`
  - Gotcha: Smaller probe radius finds smaller pockets but may be less relevant

**OEPocket**: Represents a detected binding pocket
  - Create with: Returned by OEFindPockets
  - Common in: OEMakeDesignUnitFromPocket, pocket analysis
  - Access properties: `GetVolume()`, `GetSurfaceArea()`, `GetCenter()`
  - Use for: Analyzing pocket characteristics before creating design units

**OELoopBuilderOptions**: Controls loop modeling algorithm
  - Create with: `opts = oespruce.OELoopBuilderOptions()`
  - Common in: OEBuildLoops, OEBuildSingleLoop
  - Key settings: `SetMaxLoopLength(int)`, `SetNumModels(int)`
  - Gotcha: Longer loops are harder to model accurately; consider limiting max length

**OESidechainBuilderOptions**: Controls side chain modeling
  - Create with: `opts = oespruce.OESidechainBuilderOptions()`
  - Common in: OEBuildSidechains
  - Key settings: `SetRotamerLibrary(lib)`, `SetClashTolerance(float)`
  - Typical values: Default rotamer library usually sufficient

**OEBioUnitExtractionOptions**: Controls biological assembly extraction
  - Create with: `opts = oespruce.OEBioUnitExtractionOptions()`
  - Common in: OEExtractBioUnits
  - Key settings: `SetBioUnitID(int)`, `SetReferenceProtein(mol)`
  - Gotcha: BioUnitID 0 means extract all biological units

**OESuperposeOptions**: Controls protein superposition algorithm
  - Create with: `opts = oespruce.OESuperposeOptions()`
  - Common in: OESuperpose
  - Key settings: `SetMethod(OESuperposeMethod)`, `SetIncludeHydrogens(bool)`
  - Methods: OESuperposeMethod_CAlpha (backbone only), OESuperposeMethod_Heavy (all heavy atoms)

**OEStructureMetadata**: Stores experimental metadata about structures
  - Create with: `metadata = oespruce.OEStructureMetadata()`
  - Common in: OEMakeDesignUnitOptions, structure filtering
  - Key settings: `SetPDBID(str)`, `SetResolution(float)`, `SetExperimentType(type)`
  - Use for: Associating experimental conditions with prepared structures

## Return Types & Error Handling

```python
# Pattern 1: Iterator returns (most common for structure generation)
for du in oespruce.OEMakeDesignUnits(ifs, opts):
    if du.IsValid():  # Check validity
        process(du)
    else:
        print(f"Invalid design unit: {du.GetTitle()}")

# Pattern 2: Boolean returns with side effects (modeling functions)
success = oespruce.OEBuildLoops(protein, opts)
if not success:
    print("Loop building failed - check for unresolvable gaps")
    # Protein is modified in-place even on partial success

# Pattern 3: Object returns with validation (superposition, validation)
results = oespruce.OESuperpose(ref_protein, fit_protein, opts)
if results.IsValid():
    rmsd = results.GetRMSD()
    print(f"Superposition RMSD: {rmsd:.2f} Å")
else:
    print("Superposition failed - insufficient overlap")

# Pattern 4: Validator pattern (checking quality)
validator = oespruce.OEValidateDesignUnit(du)
if validator.HasIssues():
    for issue in validator.GetIssues():
        severity = issue.GetSeverity()
        description = issue.GetDescription()
        print(f"{severity}: {description}")

# Pattern 5: Filter pattern (pre-screening structures)
filter = oespruce.OESpruceFilter(opts)
for mol in ifs.GetOEGraphMols():
    if filter(mol):
        process(mol)
    else:
        reason = filter.GetFilterReason()
        print(f"Filtered out: {reason}")

# Common error checking: File I/O
ifs = oechem.oemolistream("input.pdb")
if not ifs.IsValid():
    raise IOError("Cannot open input file")

# Common error checking: Empty results
pockets = list(oespruce.OEFindPockets(protein, opts))
if not pockets:
    print("No pockets found - try adjusting OEPocketOptions")