# Quacpac TK

> Charge assignment, tautomer enumeration, and protonation state prediction for small molecules

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

## Core API - Function Quick Reference

### Charge Assignment
```
OEAssignCharges(mol: OEMolBase, chargeEngine: OEChargeEngineBase) -> bool
  Use for: Assign partial charges to a molecule using specified charge model
  Example: OEAssignCharges(mol, OEAM1BCCCharges())
  See: https://docs.eyesopen.com/toolkits/python/quacpactk/OEProtonFunctions/OEAssignCharges.html

OEAssignPartialCharges(mol: OEMolBase, chargeType: int) -> bool
  Use for: Assign partial charges using predefined charge type constant
  Example: OEAssignPartialCharges(mol, OECharges_AM1BCCCharges)
  See: https://docs.eyesopen.com/toolkits/python/quacpactk/OEProtonFunctions/OEAssignPartialCharges.html

OEAM1BCCCharges() -> OEChargeEngineBase
  Use for: Create AM1-BCC charge engine (most common for drug-like molecules)
  Example: chargeEngine = OEAM1BCCCharges()
  See: https://docs.eyesopen.com/toolkits/python/quacpactk/OEProtonClasses/OEAM1BCCCharges.html

OEAM1BCCELF10Charges() -> OEChargeEngineBase
  Use for: Create AM1-BCC-ELF10 charge engine (improved for conjugated systems)
  Example: chargeEngine = OEAM1BCCELF10Charges()
  See: https://docs.eyesopen.com/toolkits/python/quacpactk/OEProtonClasses/OEAM1BCCELF10Charges.html

OEGasteigerCharges() -> OEChargeEngineBase
  Use for: Create fast Gasteiger charge engine (quick approximation)
  Example: chargeEngine = OEGasteigerCharges()
  See: https://docs.eyesopen.com/toolkits/python/quacpactk/OEProtonClasses/OEGasteigerCharges.html

OEMMFF94Charges() -> OEChargeEngineBase
  Use for: Create MMFF94 charge engine (force field charges)
  Example: chargeEngine = OEMMFF94Charges()
  See: https://docs.eyesopen.com/toolkits/python/quacpactk/OEProtonClasses/OEMMFF94Charges.html
```

### Tautomer Enumeration
```
OEGetReasonableTautomers(mol: OEMolBase) -> OEMolBaseIter
  Use for: Generate reasonable tautomers for a molecule at neutral pH
  Example: for taut in OEGetReasonableTautomers(mol): process(taut)
  See: https://docs.eyesopen.com/toolkits/python/quacpactk/OEProtonFunctions/OEGetReasonableTautomers.html

OEEnumerateTautomers(mol: OEMolBase, options: OETautomerOptions) -> OEMolBaseIter
  Use for: Generate tautomers with custom options (pH, max zone size, etc.)
  Example: for taut in OEEnumerateTautomers(mol, opts): process(taut)
  See: https://docs.eyesopen.com/toolkits/python/quacpactk/OEProtonFunctions/OEEnumerateTautomers.html

OETautomerOptions() -> OETautomerOptions
  Use for: Create options object to control tautomer enumeration
  Example: opts = OETautomerOptions(); opts.SetMaxTautomersGenerated(100)
  See: https://docs.eyesopen.com/toolkits/python/quacpactk/OEProtonClasses/OETautomerOptions.html
```

### Protonation State
```
OEGetReasonableProtomer(mol: OEMolBase) -> OEMolBase
  Use for: Get single most reasonable protonation state at neutral pH
  Example: protomer = OEGetReasonableProtomer(mol)
  See: https://docs.eyesopen.com/toolkits/python/quacpactk/OEProtonFunctions/OEGetReasonableProtomer.html

OEGetReasonableProtomers(mol: OEMolBase) -> OEMolBaseIter
  Use for: Generate all reasonable protonation states at neutral pH
  Example: for prot in OEGetReasonableProtomers(mol): process(prot)
  See: https://docs.eyesopen.com/toolkits/python/quacpactk/OEProtonFunctions/OEGetReasonableProtomers.html

OEEnumerateFormalCharges(mol: OEMolBase, options: OEFormalChargeOptions) -> OEMolBaseIter
  Use for: Enumerate formal charge states with custom pH and options
  Example: for state in OEEnumerateFormalCharges(mol, opts): process(state)
  See: https://docs.eyesopen.com/toolkits/python/quacpactk/OEProtonFunctions/OEEnumerateFormalCharges.html

OESetNeutralpHModel(mol: OEMolBase) -> bool
  Use for: Set molecule to neutral pH protonation state (pH 7.4)
  Example: OESetNeutralpHModel(mol)
  See: https://docs.eyesopen.com/toolkits/python/quacpactk/OEProtonFunctions/OESetNeutralpHModel.html

OERemoveFormalCharge(mol: OEMolBase) -> bool
  Use for: Remove formal charges to create neutral form
  Example: OERemoveFormalCharge(mol)
  See: https://docs.eyesopen.com/toolkits/python/quacpactk/OEProtonFunctions/OERemoveFormalCharge.html
```

### Canonical Forms
```
OEGetUniqueProtomer(mol: OEMolBase) -> OEMolBase
  Use for: Get canonical protonation state for deduplication
  Example: canonical = OEGetUniqueProtomer(mol)
  See: https://docs.eyesopen.com/toolkits/python/quacpactk/OEProtonFunctions/OEGetUniqueProtomer.html
```

### Advanced Charge Engines
```
OEDesignUnitCharges() -> OEChargeEngineBase
  Use for: Assign charges to ligand in protein context (OEDesignUnit)
  Example: chargeEngine = OEDesignUnitCharges()
  See: https://docs.eyesopen.com/toolkits/python/quacpactk/OEProtonClasses/OEDesignUnitCharges.html

OECombineChargeEngines(engine1: OEChargeEngineBase, engine2: OEChargeEngineBase) -> OEChargeEngineBase
  Use for: Chain charge engines (try first, fallback to second if fails)
  Example: combined = OECombineChargeEngines(OEAM1BCCCharges(), OEGasteigerCharges())
  See: https://docs.eyesopen.com/toolkits/python/quacpactk/OEProtonClasses/OECombineChargeEngines.html

OEELFCharges(options: OEELFOptions) -> OEChargeEngineBase
  Use for: Create ELF charge engine with custom options
  Example: chargeEngine = OEELFCharges(OEELFOptions())
  See: https://docs.eyesopen.com/toolkits/python/quacpactk/OEProtonClasses/OEELFCharges.html
```

### AM1 Calculations
```
OEAM1() -> OEAM1
  Use for: Perform AM1 semi-empirical quantum calculations
  Example: am1 = OEAM1(); results = OEAM1Results(); am1(results, mol)
  See: https://docs.eyesopen.com/toolkits/python/quacpactk/OEMolAM1Classes/OEAM1.html

OEAM1Results() -> OEAM1Results
  Use for: Store results from AM1 calculations (energy, charges, etc.)
  Example: results = OEAM1Results(); am1(results, mol); energy = results.GetEnergy()
  See: https://docs.eyesopen.com/toolkits/python/quacpactk/OEMolAM1Classes/OEAM1Results.html
```

### Utility Functions
```
OEHypervalentNormalization(mol: OEMolBase) -> bool
  Use for: Normalize hypervalent atoms (e.g., sulfones, phosphates)
  Example: OEHypervalentNormalization(mol)
  See: https://docs.eyesopen.com/toolkits/python/quacpactk/OEProtonFunctions/OEHypervalent.html

OESymmetrizePartialCharges(mol: OEMolBase) -> bool
  Use for: Average charges on symmetrically equivalent atoms
  Example: OESymmetrizePartialCharges(mol)
  See: https://docs.eyesopen.com/toolkits/python/quacpactk/OEAM1BCCFunctions/OESymmetrizePartialCharges.html
```

## Common Patterns - Complete Working Examples

### Pattern: Assign AM1-BCC Charges to Molecule
```python
from openeye import oechem, oequacpac

mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccccc1C(=O)O")
oechem.OEAddExplicitHydrogens(mol)

# Assign AM1-BCC charges (most common for drug-like molecules)
if not oequacpac.OEAssignCharges(mol, oequacpac.OEAM1BCCCharges()):
    print("Charge assignment failed")
    
# Access charges
for atom in mol.GetAtoms():
    print(f"Atom {atom.GetIdx()}: {atom.GetPartialCharge():.4f}")
```
Use when: You need accurate partial charges for docking, force field calculations, or electrostatic analysis of drug-like molecules.

### Pattern: Enumerate Reasonable Tautomers
```python
from openeye import oechem, oequacpac

mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccc2c(c1)nc[nH]2")  # Benzimidazole

# Generate reasonable tautomers at neutral pH
tautomers = []
for tautomer in oequacpac.OEGetReasonableTautomers(mol):
    taut_copy = oechem.OEGraphMol(tautomer)
    tautomers.append(taut_copy)
    
print(f"Generated {len(tautomers)} tautomers")
```
Use when: You need to explore tautomeric forms for virtual screening, database searching, or understanding chemical behavior at physiological pH.

### Pattern: Set Neutral pH Protonation State
```python
from openeye import oechem, oequacpac

mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccccc1C(=O)O")  # Benzoic acid

# Set to neutral pH protonation state (pH 7.4)
if oequacpac.OESetNeutralpHModel(mol):
    print(f"Formal charge: {oechem.OENetCharge(mol)}")
    smi = oechem.OEMolToSmiles(mol)
    print(f"Protonated SMILES: {smi}")
else:
    print("Failed to set neutral pH state")
```
Use when: Preparing molecules for docking or simulation at physiological pH - automatically handles acids, bases, and zwitterions.

### Pattern: Get Canonical Protomer for Deduplication
```python
from openeye import oechem, oequacpac

# Two molecules that are the same compound in different protomers
mol1 = oechem.OEGraphMol()
mol2 = oechem.OEGraphMol()
oechem.OESmilesToMol(mol1, "c1ccccc1C(=O)O")   # Neutral benzoic acid
oechem.OESmilesToMol(mol2, "c1ccccc1C(=O)[O-]") # Benzoate anion

# Get canonical forms for comparison
canon1 = oequacpac.OEGetUniqueProtomer(mol1)
canon2 = oequacpac.OEGetUniqueProtomer(mol2)

# Compare canonical SMILES
smi1 = oechem.OEMolToSmiles(canon1)
smi2 = oechem.OEMolToSmiles(canon2)
print(f"Same compound: {smi1 == smi2}")  # True
```
Use when: Deduplicating compound libraries where same molecule may appear in different protonation states.

### Pattern: Enumerate Tautomers with Custom Options
```python
from openeye import oechem, oequacpac

mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "CC(=O)CC(=O)C")  # Acetylacetone

# Configure tautomer enumeration
opts = oequacpac.OETautomerOptions()
opts.SetMaxTautomersGenerated(50)
opts.SetMaxTautomersToReturn(10)
opts.SetSaveStereo(True)

# Generate tautomers
tautomers = [oechem.OEGraphMol(t) for t in oequacpac.OEEnumerateTautomers(mol, opts)]
print(f"Generated {len(tautomers)} tautomers")
```
Use when: You need fine control over tautomer generation (limit count, preserve stereochemistry, adjust pH range).

### Pattern: Assign Charges with Fallback
```python
from openeye import oechem, oequacpac

mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccccc1")
oechem.OEAddExplicitHydrogens(mol)

# Try AM1-BCC first, fallback to Gasteiger if it fails
combined = oequacpac.OECombineChargeEngines(
    oequacpac.OEAM1BCCCharges(),
    oequacpac.OEGasteigerCharges()
)

if oequacpac.OEAssignCharges(mol, combined):
    print("Charges assigned successfully")
```
Use when: Processing diverse compound sets where some molecules may fail with AM1-BCC (e.g., unusual elements, large systems).

### Pattern: Enumerate Ionization States at Specific pH
```python
from openeye import oechem, oequacpac

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

# Configure pH-dependent ionization
opts = oequacpac.OEFormalChargeOptions()
opts.SetPH(7.4)

# Generate ionization states
states = []
for state in oequacpac.OEEnumerateFormalCharges(mol, opts):
    state_copy = oechem.OEGraphMol(state)
    states.append(state_copy)
    print(f"Charge: {oechem.OENetCharge(state_copy)}")
```
Use when: You need to explore ionization states at a specific pH for pKa analysis or pH-dependent property prediction.

### Pattern: Assign Charges to Ligand in Protein Context
```python
from openeye import oechem, oequacpac, oedocking

# Load design unit with protein and ligand
du = oechem.OEDesignUnit()
oedocking.OEReadDesignUnit("complex.oedu", du)

ligand = oechem.OEGraphMol()
du.GetLigand(ligand)

# Assign charges considering protein environment
chargeEngine = oequacpac.OEDesignUnitCharges()
if oequacpac.OEAssignCharges(ligand, chargeEngine):
    du.SetLigand(ligand)
    oedocking.OEWriteDesignUnit("charged.oedu", du)
```
Use when: Assigning charges to a ligand in a protein binding site where protein environment affects charge distribution.

### Pattern: Perform AM1 Calculation and Extract Results
```python
from openeye import oechem, oequacpac

mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "CC(=O)O")  # Acetic acid
oechem.OEAddExplicitHydrogens(mol)

# Run AM1 calculation
am1 = oequacpac.OEAM1()
results = oequacpac.OEAM1Results()

if am1(results, mol):
    print(f"Heat of formation: {results.GetEnergy():.2f} kcal/mol")
    print(f"Dipole moment: {results.GetDipoleMoment():.2f} Debye")
    # Charges are stored in results
```
Use when: You need quantum mechanical properties (energy, dipole, orbital energies) for small molecules.

### Pattern: Normalize Hypervalent Atoms
```python
from openeye import oechem, oequacpac

mol = oechem.OEGraphMol()
# Sulfone with hypervalent sulfur
oechem.OESmilesToMol(mol, "CS(=O)(=O)C")

# Normalize hypervalent representation
if oequacpac.OEHypervalentNormalization(mol):
    smi = oechem.OEMolToSmiles(mol)
    print(f"Normalized: {smi}")
```
Use when: Standardizing molecules with hypervalent atoms (sulfones, phosphates, nitro groups) before charge assignment or comparison.

### Pattern: Fast Charge Assignment with Gasteiger
```python
from openeye import oechem, oequacpac

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

# Fast Gasteiger charges (no quantum calculation)
if oequacpac.OEAssignCharges(mol, oequacpac.OEGasteigerCharges()):
    for atom in mol.GetAtoms():
        print(f"{atom.GetName()}: {atom.GetPartialCharge():.3f}")
```
Use when: You need quick approximate charges for large-scale screening or when AM1-BCC is too slow.

### Pattern: Symmetrize Charges on Equivalent Atoms
```python
from openeye import oechem, oequacpac

mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccccc1")  # Benzene
oechem.OEAddExplicitHydrogens(mol)

# Assign charges
oequacpac.OEAssignCharges(mol, oequacpac.OEAM1BCCCharges())

# Symmetrize charges on equivalent atoms
oequacpac.OESymmetrizePartialCharges(mol)

# All carbons now have identical charges
for atom in mol.GetAtoms(oechem.OEIsCarbon()):
    print(f"C charge: {atom.GetPartialCharge():.6f}")
```
Use when: You want to enforce symmetry in charge distribution for symmetric molecules (improves consistency).

### Pattern: Remove Formal Charges to Get Neutral Form
```python
from openeye import oechem, oequacpac

mol = oechem.OEGraphMol()
# Charged molecule (quaternary ammonium)
oechem.OESmilesToMol(mol, "C[N+](C)(C)C")

print(f"Initial charge: {oechem.OENetCharge(mol)}")

# Remove formal charges
if oequacpac.OERemoveFormalCharge(mol):
    print(f"Final charge: {oechem.OENetCharge(mol)}")
    print(f"Neutral SMILES: {oechem.OEMolToSmiles(mol)}")
```
Use when: Converting charged molecules to neutral forms for certain applications (e.g., lipophilicity calculations).

## API Decision Guide

### Charge Assignment
- **For drug-like molecules**: use `OEAM1BCCCharges()` (most accurate, industry standard)
- **For conjugated systems**: use `OEAM1BCCELF10Charges()` (improved for extended conjugation)
- **For fast screening**: use `OEGasteigerCharges()` (quick approximation, no QM calculation)
- **For force field work**: use `OEMMFF94Charges()` (consistent with MMFF94 force field)
- **For ligands in proteins**: use `OEDesignUnitCharges()` (considers protein environment)
- **For robust pipelines**: use `OECombineChargeEngines()` (try accurate method, fallback to fast)

### Tautomer Enumeration
- **For reasonable tautomers at pH 7.4**: use `OEGetReasonableTautomers()` (default, most common)
- **For custom pH or options**: use `OEEnumerateTautomers()` with `OETautomerOptions()`
- **For canonical form**: use `OEGetUniqueProtomer()` (deduplication, database storage)

### Protonation State
- **For single best state at pH 7.4**: use `OEGetReasonableProtomer()` (fastest)
- **For all reasonable states**: use `OEGetReasonableProtomers()` (multiple states)
- **For specific pH**: use `OEEnumerateFormalCharges()` with `OEFormalChargeOptions()`
- **For neutral pH adjustment**: use `OESetNeutralpHModel()` (automatic pH 7.4)
- **For neutral form**: use `OERemoveFormalCharge()` (strip all charges)

### Charge Assignment Methods
- `OEAssignCharges()` vs `OEAssignPartialCharges()`: use `OEAssignCharges()` with engine object for flexibility, use `OEAssignPartialCharges()` with constant for simplicity
- AM1-BCC vs Gasteiger: use AM1-BCC for accuracy (docking, binding affinity), use Gasteiger for speed (large-scale filtering)
- AM1-BCC vs AM1-BCC-ELF10: use ELF10 for molecules with extended conjugation, use standard for typical drug-like molecules

### Normalization
- **Before charge assignment**: use `OEHypervalentNormalization()` (standardize hypervalent atoms)
- **After charge assignment**: use `OESymmetrizePartialCharges()` (enforce symmetry)

## Common Parameters & Types

**OEChargeEngineBase**: Abstract base class for charge assignment methods
  - Create with: `OEAM1BCCCharges()`, `OEGasteigerCharges()`, `OEMMFF94Charges()`, etc.
  - Common in: `OEAssignCharges(mol, chargeEngine)`
  - Gotcha: Must add explicit hydrogens before charge assignment or it will fail

**OETautomerOptions**: Configuration for tautomer enumeration
  - Create with: `opts = OETautomerOptions()`
  - Common in: `OEEnumerateTautomers(mol, opts)`
  - Key methods: `SetMaxTautomersGenerated()`, `SetMaxTautomersToReturn()`, `SetSaveStereo()`, `SetMaxZoneSize()`
  - Typical values: MaxTautomers=128 (default), MaxZoneSize=5 (default)

**OEFormalChargeOptions**: Configuration for ionization state enumeration
  - Create with: `opts = OEFormalChargeOptions()`
  - Common in: `OEEnumerateFormalCharges(mol, opts)`
  - Key methods: `SetPH()`, `SetMaxCount()`
  - Typical values: pH=7.4 (physiological), MaxCount=128

**OEAM1Results**: Container for AM1 calculation results
  - Create with: `results = OEAM1Results()`
  - Common in: `am1(results, mol)`
  - Key methods: `GetEnergy()`, `GetDipoleMoment()`, `GetPartialCharges()`
  - Gotcha: Results object must be created before calling AM1 calculation

**OEMolBaseIter**: Iterator over molecules (tautomers, protomers, etc.)
  - Returned by: `OEGetReasonableTautomers()`, `OEEnumerateTautomers()`, `OEGetReasonableProtomers()`
  - Usage: `for mol in OEGetReasonableTautomers(input_mol): process(mol)`
  - Gotcha: Iterator yields temporary molecules - copy with `OEGraphMol(mol)` if storing

**OECharges constants**: Predefined charge type identifiers
  - Values: `OECharges_AM1BCCCharges`, `OECharges_Gasteiger`, `OECharges_MMFF94`, etc.
  - Common in: `OEAssignPartialCharges(mol, OECharges_AM1BCCCharges)`
  - Use when: You want simple constant-based API instead of engine objects

## Return Types & Error Handling

```python
# Pattern 1: Boolean returns for success/failure
from openeye import oechem, oequacpac

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

# Most charge/protomer functions return bool
if not oequacpac.OEAssignCharges(mol, oequacpac.OEAM1BCCCharges()):
    print("ERROR: Charge assignment failed")
    # Common causes: missing hydrogens, unsupported atoms, invalid structure
else:
    print("SUCCESS: Charges assigned")

# Pattern 2: Iterator returns for enumeration
# Iterators may be empty if no tautomers/protomers found
tautomers = list(oequacpac.OEGetReasonableTautomers(mol))
if not tautomers:
    print("WARNING: No tautomers generated")
else:
    print(f"Generated {len(tautomers)} tautomers")

# Pattern 3: Object returns (may be invalid)
protomer = oequacpac.OEGetReasonableProtomer(mol)
if protomer.NumAtoms() == 0:
    print("ERROR: Failed to generate protomer")
else:
    print(f"Protomer has {protomer.NumAtoms()} atoms")

# Pattern 4: Common pre-check before charge assignment
if mol.NumAtoms() == 0:
    print("ERROR: Empty molecule")
elif not oechem.OEHasExplicitHydrogens(mol):
    print("ERROR: Missing explicit hydrogens - add with OEAddExplicitHydrogens()")
elif not oequacpac.OEAssignCharges(mol, oequacpac.OEAM1BCCCharges()):
    print("ERROR: Charge assignment failed - check for unusual atoms or invalid structure")