# OEFF TK

> Force field calculations, molecular mechanics, and energy optimization

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

## Core API - Function Quick Reference

### Force Field Setup

**OEMMFF(mol: OEMol) -> OEMMFF**
  Use for: Creating MMFF94 force field for small molecules
  Example: `ff = OEMMFF(mol)`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEMolMMFFClasses/OEMMFF.html

**OESmirnoff(mol: OEMol, params: OESmirnoffParams) -> OESmirnoff**
  Use for: Creating SMIRNOFF force field (OpenFF) for small molecules
  Example: `ff = OESmirnoff(mol, OEParsleyParams())`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEMolSmirnoffClasses/OESmirnoff.html

**OEParsley(mol: OEMol) -> OEParsley**
  Use for: Creating OpenFF Parsley force field (convenience wrapper)
  Example: `ff = OEParsley(mol)`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEMolSmirnoffClasses/OEParsley.html

**OESage(mol: OEMol) -> OESage**
  Use for: Creating OpenFF Sage force field (latest version)
  Example: `ff = OESage(mol)`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEMolSmirnoffClasses/OESage.html

**OEFF14SBParsley(mol: OEMol) -> OEFF14SBParsley**
  Use for: Creating FF14SB+Parsley force field for protein-ligand complexes
  Example: `ff = OEFF14SBParsley(complex_mol)`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEFFClasses/OEFF14SBParsley.html

**OEFF14SBSage(mol: OEMol) -> OEFF14SBSage**
  Use for: Creating FF14SB+Sage force field for protein-ligand complexes
  Example: `ff = OEFF14SBSage(complex_mol)`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEFFClasses/OEFF14SBSage.html

**OEMMFFSheffield(mol: OEMol, options: OEMMFFSheffieldOptions) -> OEMMFFSheffield**
  Use for: Creating MMFF with Sheffield solvation model
  Example: `ff = OEMMFFSheffield(mol, OEMMFFSheffieldOptions())`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEFFClasses/OEMMFFSheffield.html

**OESheffield(mol: OEMol, options: OESheffieldOptions) -> OESheffield**
  Use for: Creating Sheffield solvation model for proteins
  Example: `sheff = OESheffield(protein, OESheffieldOptions())`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OESheffClasses/OESheffield.html

### Energy Calculation

**Energy() -> float**
  Use for: Getting total energy from a force field object
  Example: `energy = ff.Energy()`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEMolPotentialClasses/OEForceField.html

**CalcGradient(grad: OEDoubleArray) -> float**
  Use for: Computing energy and gradient simultaneously
  Example: `energy = ff.CalcGradient(gradient_array)`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEMolPotentialClasses/OEForceField.html

**GetEnergies() -> OEComplexEnergies**
  Use for: Getting detailed energy breakdown for protein-ligand complexes
  Example: `energies = complex_ff.GetEnergies()`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEFFClasses/OEComplexFF.html

### Optimization

**OEBFGSOpt(func: OEFunc1) -> OEBFGSOpt**
  Use for: Creating BFGS optimizer (recommended for most cases)
  Example: `opt = OEBFGSOpt(force_field)`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEOptClasses/OEBFGSOpt.html

**OEConjGradOpt(func: OEFunc1) -> OEConjGradOpt**
  Use for: Creating conjugate gradient optimizer
  Example: `opt = OEConjGradOpt(force_field)`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEOptClasses/OEConjGradOpt.html

**OESteepestDescentOpt(func: OEFunc1) -> OESteepestDescentOpt**
  Use for: Creating steepest descent optimizer (simple but slow)
  Example: `opt = OESteepestDescentOpt(force_field)`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEOptClasses/OESteepestDescentOpt.html

**Run() -> int**
  Use for: Running optimization to convergence
  Example: `status = optimizer.Run()`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEOptClasses/OEOptimizer1.html

### Adaptors (Coordinate Transformations)

**OEMolAdaptor(mol: OEMol, ff: OEForceField) -> OEMolAdaptor**
  Use for: Adapting Cartesian coordinates for optimization
  Example: `adaptor = OEMolAdaptor(mol, force_field)`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEMolPotentialClasses/OEMolAdaptor.html

**OETorAdaptor(mol: OEMol, ff: OEForceField) -> OETorAdaptor**
  Use for: Optimizing only torsion angles (rigid geometry)
  Example: `adaptor = OETorAdaptor(mol, force_field)`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEMolPotentialClasses/OETorAdaptor.html

**OEQuatAdaptor(mol: OEMol, ff: OEForceField) -> OEQuatAdaptor**
  Use for: Optimizing rigid body position/orientation
  Example: `adaptor = OEQuatAdaptor(mol, force_field)`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEMolPotentialClasses/OEQuatAdaptor.html

**OESubsetAdaptor(mol: OEMol, ff: OEForceField, atom_pred: OEAtomPred) -> OESubsetAdaptor**
  Use for: Optimizing only selected atoms (freeze others)
  Example: `adaptor = OESubsetAdaptor(mol, ff, OENotAtom(OEIsHydrogen()))`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEMolPotentialClasses/OESubsetAdaptor.html

### Validation & Utilities

**OEIsValidMMFFMolecule(mol: OEMol) -> bool**
  Use for: Checking if molecule can be parameterized with MMFF
  Example: `if OEIsValidMMFFMolecule(mol): ...`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEMolMMFFFunctions/OEIsValidMMFFMolecule.html

**OEIsForceFieldDummyAtom(atom: OEAtom) -> bool**
  Use for: Checking if atom is a dummy atom for force field
  Example: `if OEIsForceFieldDummyAtom(atom): ...`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEFFFunctions/OEIsForceFieldDummyAtom.html

**OESetForceFieldDummyAtom(atom: OEAtom, is_dummy: bool) -> None**
  Use for: Marking atoms as dummy (excluded from force field)
  Example: `OESetForceFieldDummyAtom(atom, True)`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEFFFunctions/OESetForceFieldDummyAtom.html

### Interaction Analysis

**GetInteraction(mol1: OEMol, mol2: OEMol) -> OEInteraction**
  Use for: Computing interaction energy between two molecules
  Example: `interaction = ff.GetInteraction(ligand, protein)`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEMolPotentialClasses/OEInteraction.html

**GetComponents() -> OEFComponent iterator**
  Use for: Iterating over individual force field energy terms
  Example: `for comp in ff.GetComponents(): print(comp.GetName(), comp.Energy())`
  See: https://docs.eyesopen.com/toolkits/python/oefftk/OEMolPotentialClasses/OEForceField.html

## Common Patterns - Complete Working Examples

### Pattern: Basic Ligand Energy Minimization (MMFF)
```python
from openeye import oechem, oeff

mol = oechem.OEMol()
oechem.OEReadMolecule(oechem.oemolistream("ligand.sdf"), mol)

ff = oeff.OEMMFF(mol)
adaptor = oeff.OEMolAdaptor(mol, ff)
opt = oeff.OEBFGSOpt(adaptor)
opt.Run()

adaptor.GetMol(mol)
oechem.OEWriteMolecule(oechem.oemolostream("minimized.sdf"), mol)
```
Use when: You need to minimize a small molecule in vacuum using MMFF94 force field

### Pattern: Ligand Optimization with OpenFF Sage
```python
from openeye import oechem, oeff

mol = oechem.OEMol()
oechem.OEReadMolecule(oechem.oemolistream("ligand.mol2"), mol)

ff = oeff.OESage(mol)
adaptor = oeff.OEMolAdaptor(mol, ff)
opt = oeff.OEBFGSOpt(adaptor)
status = opt.Run()

adaptor.GetMol(mol)
final_energy = ff.Energy()
print(f"Final energy: {final_energy} kcal/mol")
```
Use when: You want to use the latest OpenFF force field (Sage) for small molecules

### Pattern: Protein-Ligand Complex Optimization
```python
from openeye import oechem, oeff

complex_mol = oechem.OEMol()
oechem.OEReadMolecule(oechem.oemolistream("complex.pdb"), complex_mol)

ff = oeff.OEFF14SBSage(complex_mol)
adaptor = oeff.OEMolAdaptor(complex_mol, ff)
opt = oeff.OEBFGSOpt(adaptor)
opt.Run()

adaptor.GetMol(complex_mol)
energies = ff.GetEnergies()
print(f"Ligand energy: {energies.GetLigandEnergy()}")
print(f"Protein energy: {energies.GetProteinEnergy()}")
print(f"Interaction energy: {energies.GetInteractionEnergy()}")
```
Use when: Optimizing protein-ligand complexes with FF14SB for protein and Sage for ligand

### Pattern: Torsion-Only Optimization (Rigid Geometry)
```python
from openeye import oechem, oeff

mol = oechem.OEMol()
oechem.OEReadMolecule(oechem.oemolistream("ligand.sdf"), mol)

ff = oeff.OEMMFF(mol)
tor_adaptor = oeff.OETorAdaptor(mol, ff)
opt = oeff.OEBFGSOpt(tor_adaptor)
opt.Run()

tor_adaptor.GetMol(mol)
oechem.OEWriteMolecule(oechem.oemolostream("torsion_opt.sdf"), mol)
```
Use when: You want to optimize only torsion angles while keeping bond lengths and angles fixed

### Pattern: Freeze Heavy Atoms, Optimize Hydrogens
```python
from openeye import oechem, oeff

mol = oechem.OEMol()
oechem.OEReadMolecule(oechem.oemolistream("ligand.mol2"), mol)

ff = oeff.OEMMFF(mol)
subset_adaptor = oeff.OESubsetAdaptor(mol, ff, oechem.OEIsHydrogen())
opt = oeff.OEBFGSOpt(subset_adaptor)
opt.Run()

subset_adaptor.GetMol(mol)
oechem.OEWriteMolecule(oechem.oemolostream("h_optimized.mol2"), mol)
```
Use when: You want to optimize only hydrogen positions while keeping heavy atoms fixed

### Pattern: Rigid Ligand Docking Pose Optimization
```python
from openeye import oechem, oeff

protein = oechem.OEMol()
ligand = oechem.OEMol()
oechem.OEReadMolecule(oechem.oemolistream("protein.pdb"), protein)
oechem.OEReadMolecule(oechem.oemolistream("ligand_pose.sdf"), ligand)

complex_mol = oechem.OEMol(protein)
oechem.OEAddMols(complex_mol, ligand)

ff = oeff.OEFF14SBParsley(complex_mol)
quat_adaptor = oeff.OEQuatAdaptor(ligand, ff)
opt = oeff.OEBFGSOpt(quat_adaptor)
opt.Run()

quat_adaptor.GetMol(ligand)
```
Use when: Optimizing rigid ligand position/orientation in protein binding site

### Pattern: Energy Calculation with Component Breakdown
```python
from openeye import oechem, oeff

mol = oechem.OEMol()
oechem.OEReadMolecule(oechem.oemolistream("molecule.sdf"), mol)

ff = oeff.OEMMFF(mol)
total_energy = ff.Energy()

print(f"Total energy: {total_energy:.2f} kcal/mol")
for component in ff.GetComponents():
    comp_name = component.GetName()
    comp_energy = component.Energy()
    print(f"  {comp_name}: {comp_energy:.2f} kcal/mol")
```
Use when: You need detailed breakdown of energy contributions (bonds, angles, torsions, VDW, electrostatics)

### Pattern: MMFF with Sheffield Solvation Model
```python
from openeye import oechem, oeff

mol = oechem.OEMol()
oechem.OEReadMolecule(oechem.oemolistream("ligand.sdf"), mol)

options = oeff.OEMMFFSheffieldOptions()
ff = oeff.OEMMFFSheffield(mol, options)
adaptor = oeff.OEMolAdaptor(mol, ff)
opt = oeff.OEBFGSOpt(adaptor)
opt.Run()

adaptor.GetMol(mol)
solvation_energy = ff.Energy()
print(f"Energy with solvation: {solvation_energy:.2f} kcal/mol")
```
Use when: You need implicit solvation effects for small molecules using Sheffield model

### Pattern: Protein Sheffield Solvation
```python
from openeye import oechem, oeff

protein = oechem.OEMol()
oechem.OEReadMolecule(oechem.oemolistream("protein.pdb"), protein)

sheff_options = oeff.OESheffieldOptions()
sheff = oeff.OESheffield(protein, sheff_options)

solvation_energy = sheff.Energy()
print(f"Protein solvation energy: {solvation_energy:.2f} kcal/mol")
```
Use when: Calculating Sheffield solvation energy for proteins

### Pattern: Custom SMIRNOFF Force Field
```python
from openeye import oechem, oeff

mol = oechem.OEMol()
oechem.OEReadMolecule(oechem.oemolistream("ligand.sdf"), mol)

params = oeff.OESmirnoffParams()
params.SetFFXMLFile("custom_forcefield.offxml")

ff = oeff.OESmirnoff(mol, params)
adaptor = oeff.OEMolAdaptor(mol, ff)
opt = oeff.OEBFGSOpt(adaptor)
opt.Run()

adaptor.GetMol(mol)
```
Use when: You have a custom SMIRNOFF force field XML file to use instead of built-in Parsley/Sage

### Pattern: Monitoring Optimization Progress
```python
from openeye import oechem, oeff

mol = oechem.OEMol()
oechem.OEReadMolecule(oechem.oemolistream("ligand.sdf"), mol)

ff = oeff.OEMMFF(mol)
adaptor = oeff.OEMolAdaptor(mol, ff)

class ProgressCheckpoint(oeff.OECheckpoint1):
    def __call__(self, x, fx, gx):
        print(f"Energy: {fx:.4f} kcal/mol")
        return True

opt = oeff.OEBFGSOpt(adaptor)
opt.SetCheckpoint(ProgressCheckpoint())
opt.Run()
```
Use when: You need to monitor or log optimization progress at each iteration

### Pattern: Interaction Energy Between Molecules
```python
from openeye import oechem, oeff

ligand = oechem.OEMol()
protein = oechem.OEMol()
oechem.OEReadMolecule(oechem.oemolistream("ligand.sdf"), ligand)
oechem.OEReadMolecule(oechem.oemolistream("protein.pdb"), protein)

complex_mol = oechem.OEMol(protein)
oechem.OEAddMols(complex_mol, ligand)

ff = oeff.OEFF14SBParsley(complex_mol)
interaction = ff.GetInteraction(ligand, protein)
interaction_energy = interaction.Energy()

print(f"Protein-ligand interaction: {interaction_energy:.2f} kcal/mol")
```
Use when: Calculating interaction energy between two molecular components

### Pattern: Validating MMFF Parameterization
```python
from openeye import oechem, oeff

mol = oechem.OEMol()
oechem.OEReadMolecule(oechem.oemolistream("molecule.sdf"), mol)

if not oeff.OEIsValidMMFFMolecule(mol):
    print("Warning: Molecule cannot be fully parameterized with MMFF")
    print("Some atom types may be missing or unusual")
else:
    ff = oeff.OEMMFF(mol)
    energy = ff.Energy()
    print(f"MMFF energy: {energy:.2f} kcal/mol")
```
Use when: Checking if a molecule can be properly parameterized before running calculations

## API Decision Guide

### Force Field Selection
- For **small molecules in vacuum**: use `OEMMFF` (MMFF94) or `OESage` (OpenFF Sage, latest)
- For **small molecules with solvation**: use `OEMMFFSheffield` (MMFF + Sheffield implicit solvent)
- For **protein-ligand complexes**: use `OEFF14SBSage` (FF14SB protein + Sage ligand) or `OEFF14SBParsley`
- For **proteins only with solvation**: use `OESheffield` (Sheffield protein solvation model)
- For **custom OpenFF parameters**: use `OESmirnoff` with `OESmirnoffParams`
- **MMFF vs OpenFF**: MMFF is faster and well-tested; OpenFF (Sage/Parsley) is more modern and accurate for drug-like molecules

### Optimizer Selection
- For **general optimization**: use `OEBFGSOpt` (BFGS - recommended, fast convergence)
- For **large systems**: use `OEConjGradOpt` (conjugate gradient - lower memory)
- For **simple/debugging**: use `OESteepestDescentOpt` (steepest descent - slow but robust)
- For **second derivatives available**: use `OENewtonOpt` (Newton - fastest but needs Hessian)

### Adaptor Selection
- For **full Cartesian optimization**: use `OEMolAdaptor` (all atoms move freely)
- For **torsion-only optimization**: use `OETorAdaptor` (rigid geometry, only dihedrals change)
- For **rigid body positioning**: use `OEQuatAdaptor` (optimize position/orientation, no internal changes)
- For **partial optimization**: use `OESubsetAdaptor` with atom predicate (freeze selected atoms)
- For **torsion + rigid body**: use `OETorQuatAdaptor` (combine torsion and rigid body)

### Energy Calculation
- For **total energy only**: call `ff.Energy()`
- For **energy + gradient**: call `ff.CalcGradient(grad_array)` (more efficient than separate calls)
- For **energy breakdown**: iterate over `ff.GetComponents()` (bonds, angles, torsions, VDW, electrostatics)
- For **protein-ligand details**: use `complex_ff.GetEnergies()` to get `OEComplexEnergies` object with ligand/protein/interaction energies
- For **interaction between molecules**: use `ff.GetInteraction(mol1, mol2)`

### Common Workflows
- **Minimize ligand**: `OEMMFF` or `OESage` → `OEMolAdaptor` → `OEBFGSOpt`
- **Minimize complex**: `OEFF14SBSage` → `OEMolAdaptor` → `OEBFGSOpt`
- **Optimize H-bonds only**: `OEMMFF` → `OESubsetAdaptor(OEIsHydrogen())` → `OEBFGSOpt`
- **Dock pose refinement**: `OEFF14SBParsley` → `OEQuatAdaptor` → `OEBFGSOpt`
- **Conformer search**: `OEMMFF` → `OETorAdaptor` → `OEBFGSOpt` (multiple starting torsions)

## Common Parameters & Types

**OEMol**: Molecule object from OEChem
  - Create with: `mol = oechem.OEMol()` then read from file or build programmatically
  - Common in: All force field constructors, adaptors
  - Gotcha: Must have 3D coordinates for force field calculations; use `oechem.OEAddExplicitHydrogens()` if hydrogens missing

**OEForceField**: Base class for all force fields (OEMMFF, OESmirnoff, etc.)
  - Create with: Specific force field constructor like `OEMMFF(mol)` or `OESage(mol)`
  - Common in: Adaptor constructors, energy calculations
  - Methods: `Energy()`, `CalcGradient()`, `GetComponents()`

**OEAdaptor**: Coordinate transformation for optimization
  - Create with: `OEMolAdaptor(mol, ff)`, `OETorAdaptor(mol, ff)`, `OEQuatAdaptor(mol, ff)`, etc.
  - Common in: Optimizer constructors
  - Methods: `GetMol(mol)` to retrieve optimized coordinates back into molecule

**OEOptimizer**: Optimization algorithm
  - Create with: `OEBFGSOpt(adaptor)`, `OEConjGradOpt(adaptor)`, etc.
  - Common in: Optimization workflows
  - Methods: `Run()` returns status code, `SetCheckpoint()` for monitoring

**OEComplexEnergies**: Energy breakdown for protein-ligand complexes
  - Create with: Returned by `complex_ff.GetEnergies()`
  - Methods: `GetLigandEnergy()`, `GetProteinEnergy()`, `GetInteractionEnergy()`, `GetTotalEnergy()`
  - Gotcha: Only available for complex force fields (OEFF14SBSage, OEFF14SBParsley, etc.)

**OESmirnoffParams**: Parameters for SMIRNOFF force fields
  - Create with: `params = OESmirnoffParams()` or specific versions like `OEParsleyParams()`, `OESageParams()`
  - Common in: `OESmirnoff` constructor for custom force fields
  - Methods: `SetFFXMLFile(filename)` to load custom OFFXML file

**OESheffieldOptions**: Options for Sheffield solvation model
  - Create with: `options = OESheffieldOptions()` or `OEMMFFSheffieldOptions()`
  - Common in: Sheffield solvation constructors
  - Typical values: Default constructor usually sufficient; can customize solvation parameters

**OECheckpoint**: Callback for monitoring optimization
  - Create with: Subclass `OECheckpoint1` and implement `__call__(x, fx, gx)`
  - Common in: `optimizer.SetCheckpoint(checkpoint_obj)`
  - Gotcha: Return `True` to continue optimization, `False` to stop early

## Return Types & Error Handling

```python
# Pattern 1: Optimization status codes
opt = oeff.OEBFGSOpt(adaptor)
status = opt.Run()
# status is integer: 0 = success, non-zero = failure/max iterations
if status == 0:
    print("Optimization converged")
else:
    print(f"Optimization did not converge (status: {status})")

# Pattern 2: Force field validation before use
if not oeff.OEIsValidMMFFMolecule(mol):
    print("Warning: Incomplete MMFF parameterization")
    # Decide whether to proceed or use different force field

# Pattern 3: Energy calculations return floats
energy = ff.Energy()  # Returns float in kcal/mol
if energy > 1000.0:
    print("Warning: Very high energy, check structure")

# Pattern 4: Adaptor coordinate retrieval
adaptor = oeff.OEMolAdaptor(mol, ff)
opt = oeff.OEBFGSOpt(adaptor)
opt.Run()
adaptor.GetMol(mol)  # Updates mol in-place with optimized coordinates
# No return value - mol is modified directly

# Pattern 5: Component iteration
for component in ff.GetComponents():
    name = component.GetName()  # Returns string
    comp_energy = component.Energy()  # Returns float
    print(f"{name}: {comp_energy:.2f}")

# Pattern 6: Complex energies object
energies = complex_ff.GetEnergies()  # Returns OEComplexEnergies object
lig_e = energies.GetLigandEnergy()  # Returns float
prot_e = energies.GetProteinEnergy()  # Returns float
inter_e = energies.GetInteractionEnergy()  # Returns float