# Szmap TK

> Solvent thermodynamics and water mapping for protein binding sites

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

## Core API - Function Quick Reference

### Energy Calculation Functions

**OECalcSzmapResults**(results: OESzmapResults, opts: OESzmapEngineOptions, protein: OEGraphMol, coords: list) -> bool
  Use for: Calculate all Szmap energy components at specified coordinates
  Example: `OECalcSzmapResults(results, opts, protein, [x, y, z])`
  See: https://docs.eyesopen.com/toolkits/python/szmaptk/OESzmapFunctions/OECalcSzmapResults.html

**OECalcSzmapValue**(component: int, opts: OESzmapEngineOptions, protein: OEGraphMol, coords: list) -> float
  Use for: Calculate a single energy component value at coordinates
  Example: `energy = OECalcSzmapValue(OEComponent_VDW, opts, protein, [x, y, z])`
  See: https://docs.eyesopen.com/toolkits/python/szmaptk/OESzmapFunctions/OECalcSzmapValue.html

**OEIsClashing**(opts: OESzmapEngineOptions, protein: OEGraphMol, coords: list) -> bool
  Use for: Check if probe position clashes with protein atoms
  Example: `if not OEIsClashing(opts, protein, [x, y, z]): # calculate energy`
  See: https://docs.eyesopen.com/toolkits/python/szmaptk/OESzmapFunctions/OEIsClashing.html

### Component and Ensemble Name Functions

**OEGetComponentName**(component: int) -> str
  Use for: Get human-readable name for energy component constant
  Example: `name = OEGetComponentName(OEComponent_VDW)  # returns "VDW"`
  See: https://docs.eyesopen.com/toolkits/python/szmaptk/OESzmapFunctions/OEGetComponentName.html

**OEGetEnsembleName**(ensemble: int) -> str
  Use for: Get human-readable name for ensemble type constant
  Example: `name = OEGetEnsembleName(OEEnsemble_Neutral)  # returns "Neutral"`
  See: https://docs.eyesopen.com/toolkits/python/szmaptk/OESzmapFunctions/OEGetEnsembleName.html

### Version and License Functions

**OESzmapGetVersion**() -> str
  Use for: Get Szmap TK version string
  Example: `version = OESzmapGetVersion()`
  See: https://docs.eyesopen.com/toolkits/python/szmaptk/OESzmapFunctions/OESzmapGetVersion.html

**OESzmapIsLicensed**() -> bool
  Use for: Check if Szmap TK is properly licensed
  Example: `if not OESzmapIsLicensed(): raise RuntimeError("No license")`
  See: https://docs.eyesopen.com/toolkits/python/szmaptk/OESzmapFunctions/OESzmapIsLicensed.html

**OESzmapGetRelease**() -> str
  Use for: Get Szmap TK release information
  Example: `release = OESzmapGetRelease()`
  See: https://docs.eyesopen.com/toolkits/python/szmaptk/OESzmapFunctions/OESzmapGetRelease.html

**OESzmapGetLicensee**() -> str
  Use for: Get licensee information
  Example: `licensee = OESzmapGetLicensee()`
  See: https://docs.eyesopen.com/toolkits/python/szmaptk/OESzmapFunctions/OESzmapGetLicensee.html

**OESzmapGetSite**() -> str
  Use for: Get site information from license
  Example: `site = OESzmapGetSite()`
  See: https://docs.eyesopen.com/toolkits/python/szmaptk/OESzmapFunctions/OESzmapGetSite.html

## Common Patterns - Complete Working Examples

### Pattern: Calculate Szmap Energies at Ligand Atom Positions

```python
from openeye import oechem, oeszmap

# Read protein and ligand
protein = oechem.OEGraphMol()
ligand = oechem.OEGraphMol()
oechem.OEReadMolecule(oechem.oemolistream("protein.pdb"), protein)
oechem.OEReadMolecule(oechem.oemolistream("ligand.mol2"), ligand)

# Setup Szmap calculation
opts = oeszmap.OESzmapEngineOptions()
opts.SetProbeCount(100)  # Number of probe orientations
results = oeszmap.OESzmapResults()

# Calculate energies at each ligand heavy atom
for atom in ligand.GetAtoms():
    if atom.GetAtomicNum() > 1:  # Skip hydrogens
        coords = oechem.OEFloatArray(3)
        ligand.GetCoords(atom, coords)
        if oeszmap.OECalcSzmapResults(results, opts, protein, coords):
            print(f"Atom {atom.GetIdx()}: dG={results.GetDeltaG():.2f}")
```
Use when: Analyzing water thermodynamics at specific ligand binding positions

### Pattern: Generate Probe Orientations for Best Water Positions

```python
from openeye import oechem, oeszmap

# Read protein structure
protein = oechem.OEGraphMol()
oechem.OEReadMolecule(oechem.oemolistream("protein.pdb"), protein)

# Setup calculation with orientation generation
opts = oeszmap.OESzmapEngineOptions()
opts.SetProbeCount(500)  # More probes for better sampling
results = oeszmap.OESzmapResults()

# Calculate at binding site center
coords = [10.5, 15.2, 8.7]  # Binding site coordinates
if not oeszmap.OEIsClashing(opts, protein, coords):
    oeszmap.OECalcSzmapResults(results, opts, protein, coords)
    
    # Access best probe orientations
    for i in range(min(10, results.GetNumOrientations())):
        orient = results.GetOrientation(i)
        print(f"Orientation {i}: Energy={orient.GetEnergy():.2f}")
```
Use when: Finding optimal water molecule orientations in binding sites

### Pattern: Calculate Individual Energy Components

```python
from openeye import oechem, oeszmap

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

# Setup options
opts = oeszmap.OESzmapEngineOptions()
coords = [12.3, 8.5, 15.1]

# Calculate specific energy components
vdw = oeszmap.OECalcSzmapValue(oeszmap.OEComponent_VDW, opts, protein, coords)
elec = oeszmap.OECalcSzmapValue(oeszmap.OEComponent_Elec, opts, protein, coords)
order = oeszmap.OECalcSzmapValue(oeszmap.OEComponent_Order, opts, protein, coords)

print(f"VDW: {vdw:.2f}, Electrostatic: {elec:.2f}, Order: {order:.2f}")
print(f"Total dG: {vdw + elec + order:.2f}")
```
Use when: Decomposing total energy into individual physical contributions

### Pattern: Scan Binding Site Grid for Favorable Water Positions

```python
from openeye import oechem, oeszmap

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

# Setup calculation
opts = oeszmap.OESzmapEngineOptions()
opts.SetProbeCount(200)
results = oeszmap.OESzmapResults()

# Define grid around binding site
grid_spacing = 0.5
favorable_positions = []

for x in range(-5, 6):
    for y in range(-5, 6):
        for z in range(-5, 6):
            coords = [center_x + x*grid_spacing, 
                     center_y + y*grid_spacing,
                     center_z + z*grid_spacing]
            
            if not oeszmap.OEIsClashing(opts, protein, coords):
                if oeszmap.OECalcSzmapResults(results, opts, protein, coords):
                    if results.GetDeltaG() < -2.0:  # Favorable threshold
                        favorable_positions.append((coords, results.GetDeltaG()))
```
Use when: Identifying all favorable water binding positions in a region

### Pattern: Compare Neutral vs Charged Water Ensembles

```python
from openeye import oechem, oeszmap

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

# Setup for neutral ensemble
opts_neutral = oeszmap.OESzmapEngineOptions()
opts_neutral.SetEnsemble(oeszmap.OEEnsemble_Neutral)

# Setup for charged ensemble  
opts_charged = oeszmap.OESzmapEngineOptions()
opts_charged.SetEnsemble(oeszmap.OEEnsemble_Charged)

coords = [10.0, 12.0, 8.0]
results = oeszmap.OESzmapResults()

# Calculate with neutral water
oeszmap.OECalcSzmapResults(results, opts_neutral, protein, coords)
neutral_dg = results.GetDeltaG()

# Calculate with charged water
oeszmap.OECalcSzmapResults(results, opts_charged, protein, coords)
charged_dg = results.GetDeltaG()

print(f"Neutral: {neutral_dg:.2f}, Charged: {charged_dg:.2f}")
```
Use when: Analyzing electrostatic effects on water binding energetics

### Pattern: Validate Protein Preparation Before Calculation

```python
from openeye import oechem, oeszmap

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

# Check protein has coordinates
if protein.GetDimension() != 3:
    raise ValueError("Protein must have 3D coordinates")

# Check for hydrogens (required for Szmap)
has_hydrogens = False
for atom in protein.GetAtoms():
    if atom.GetAtomicNum() == 1:
        has_hydrogens = True
        break

if not has_hydrogens:
    oechem.OEAddExplicitHydrogens(protein)
    print("Added explicit hydrogens to protein")

# Assign partial charges if missing
if not oechem.OEHasPartialCharges(protein):
    oechem.OEAssignPartialCharges(protein, oechem.OECharges_AM1BCCSym)
    print("Assigned AM1BCC charges to protein")

# Now ready for Szmap calculation
opts = oeszmap.OESzmapEngineOptions()
```
Use when: Ensuring protein structure is properly prepared for Szmap calculations

### Pattern: Analyze Water Displacement Energy for Ligand Design

```python
from openeye import oechem, oeszmap

# Read protein and reference ligand
protein = oechem.OEGraphMol()
ref_ligand = oechem.OEGraphMol()
oechem.OEReadMolecule(oechem.oemolistream("protein.pdb"), protein)
oechem.OEReadMolecule(oechem.oemolistream("reference.mol2"), ref_ligand)

# Setup Szmap
opts = oeszmap.OESzmapEngineOptions()
opts.SetProbeCount(300)
results = oeszmap.OESzmapResults()

# Calculate displacement energy at each ligand atom
total_displacement = 0.0
for atom in ref_ligand.GetAtoms():
    if atom.GetAtomicNum() > 1:
        coords = oechem.OEFloatArray(3)
        ref_ligand.GetCoords(atom, coords)
        
        if oeszmap.OECalcSzmapResults(results, opts, protein, coords):
            dg = results.GetDeltaG()
            if dg < 0:  # Favorable water position
                total_displacement += abs(dg)
                print(f"Atom {atom.GetIdx()} displaces favorable water: {dg:.2f}")

print(f"Total displacement penalty: {total_displacement:.2f} kcal/mol")
```
Use when: Estimating energetic cost of displacing bound waters with ligand atoms

### Pattern: Export Szmap Results for Visualization

```python
from openeye import oechem, oeszmap

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

# Calculate Szmap at grid points
opts = oeszmap.OESzmapEngineOptions()
results = oeszmap.OESzmapResults()

# Create output molecule to store results
output = oechem.OEGraphMol()
output.SetTitle("Szmap_Results")

# Calculate and store as atoms with SD data
for x in range(-10, 11, 2):
    for y in range(-10, 11, 2):
        for z in range(-10, 11, 2):
            coords = [float(x), float(y), float(z)]
            
            if not oeszmap.OEIsClashing(opts, protein, coords):
                if oeszmap.OECalcSzmapResults(results, opts, protein, coords):
                    atom = output.NewAtom(oechem.OEElemNo_He)  # Dummy atom
                    output.SetCoords(atom, coords)
                    oechem.OESetSDData(atom, "dG", str(results.GetDeltaG()))
                    oechem.OESetSDData(atom, "VDW", str(results.GetVDW()))

oechem.OEWriteMolecule(oechem.oemolostream("szmap_grid.sdf"), output)
```
Use when: Creating files for visualization in molecular graphics programs

### Pattern: Calculate Stabilization Energy for Bound Water

```python
from openeye import oechem, oeszmap

# Read protein with crystallographic water
protein = oechem.OEGraphMol()
oechem.OEReadMolecule(oechem.oemolistream("protein_with_waters.pdb"), protein)

# Setup Szmap
opts = oeszmap.OESzmapEngineOptions()
results = oeszmap.OESzmapResults()

# Find and analyze crystallographic waters
for atom in protein.GetAtoms():
    if oechem.OEGetResidueIndex(atom) == oechem.OEResidueIndex_HOH:
        coords = oechem.OEFloatArray(3)
        protein.GetCoords(atom, coords)
        
        # Calculate stabilization at water position
        if oeszmap.OECalcSzmapResults(results, opts, protein, coords):
            dg = results.GetDeltaG()
            
            # Negative dG indicates favorable/stable water
            if dg < -1.0:
                print(f"Stable water at {coords[0]:.1f},{coords[1]:.1f},{coords[2]:.1f}")
                print(f"  Stabilization: {dg:.2f} kcal/mol")
            elif dg > 1.0:
                print(f"Unstable water - candidate for displacement")
```
Use when: Identifying which crystallographic waters are thermodynamically stable

### Pattern: Batch Process Multiple Protein Structures

```python
from openeye import oechem, oeszmap
import glob

# Setup Szmap options once
opts = oeszmap.OESzmapEngineOptions()
opts.SetProbeCount(200)
results = oeszmap.OESzmapResults()

# Process all PDB files in directory
for pdb_file in glob.glob("structures/*.pdb"):
    protein = oechem.OEGraphMol()
    
    if oechem.OEReadMolecule(oechem.oemolistream(pdb_file), protein):
        # Prepare protein
        oechem.OEAddExplicitHydrogens(protein)
        oechem.OEAssignPartialCharges(protein, oechem.OECharges_AM1BCCSym)
        
        # Calculate at active site (example coordinates)
        coords = [10.0, 12.0, 8.0]
        
        if oeszmap.OECalcSzmapResults(results, opts, protein, coords):
            print(f"{pdb_file}: dG = {results.GetDeltaG():.2f}")
        else:
            print(f"{pdb_file}: Calculation failed")
```
Use when: Analyzing water thermodynamics across multiple protein structures

## API Decision Guide

### Choosing Calculation Functions
- For **complete energy analysis**: use `OECalcSzmapResults()` (returns all components in OESzmapResults object)
- For **single energy component**: use `OECalcSzmapValue()` (faster when only one component needed)
- For **clash checking before calculation**: use `OEIsClashing()` (prevents wasted calculations at invalid positions)

### Choosing Ensemble Type
- For **neutral binding sites**: use `OEEnsemble_Neutral` (uncharged water model)
- For **charged/polar sites**: use `OEEnsemble_Charged` (includes electrostatic effects)
- **Default behavior**: Neutral ensemble unless explicitly set otherwise

### Choosing Probe Count
- For **quick screening**: use 50-100 probes (faster but less accurate)
- For **production calculations**: use 200-500 probes (recommended for publication)
- For **high-accuracy analysis**: use 500-1000 probes (slower but most thorough sampling)

### Energy Component Selection
- `OEComponent_VDW`: Van der Waals interactions (steric effects)
- `OEComponent_Elec`: Electrostatic interactions (charge-charge)
- `OEComponent_Order`: Entropic ordering penalty (water structure)
- `OEComponent_DeltaG`: Total free energy (sum of all components)

### When to Use Each Pattern
- **Ligand atom analysis**: When designing ligands and need to know water displacement costs
- **Grid scanning**: When identifying all favorable water sites in a binding pocket
- **Orientation generation**: When need to visualize or analyze specific water geometries
- **Component decomposition**: When understanding physical basis of water binding
- **Batch processing**: When comparing water thermodynamics across protein series

## Common Parameters & Types

**OESzmapEngineOptions**: Configuration object for Szmap calculations
  - Create with: `opts = oeszmap.OESzmapEngineOptions()`
  - Common in: All calculation functions (OECalcSzmapResults, OECalcSzmapValue)
  - Key methods: `SetProbeCount(int)`, `SetEnsemble(int)`, `SetMaskCutoff(float)`
  - Gotcha: Must set probe count before calculation; default may be too low for accurate results

**OESzmapResults**: Container for calculated energy values and probe orientations
  - Create with: `results = oeszmap.OESzmapResults()`
  - Common in: OECalcSzmapResults (populated by calculation)
  - Key methods: `GetDeltaG()`, `GetVDW()`, `GetElec()`, `GetOrder()`, `GetNumOrientations()`
  - Gotcha: Results object is reused/overwritten on each calculation call

**coords (list or OEFloatArray)**: 3D coordinates for probe placement
  - Create with: `coords = [x, y, z]` or `coords = oechem.OEFloatArray(3)`
  - Common in: All calculation functions as position parameter
  - Typical values: Cartesian coordinates in Angstroms
  - Gotcha: Must be 3-element list/array; coordinates should be in protein reference frame

**protein (OEGraphMol)**: Protein structure for Szmap calculation
  - Create with: `protein = oechem.OEGraphMol()` then read from file
  - Common in: All calculation functions as context
  - Requirements: Must have 3D coordinates, explicit hydrogens, and partial charges
  - Gotcha: Missing hydrogens or charges will cause incorrect results; use OEAddExplicitHydrogens and OEAssignPartialCharges

**component (int constant)**: Energy component identifier
  - Create with: Use constants like `oeszmap.OEComponent_VDW`
  - Common in: OECalcSzmapValue, OEGetComponentName
  - Available values: OEComponent_VDW, OEComponent_Elec, OEComponent_Order, OEComponent_DeltaG
  - Gotcha: DeltaG is sum of other components; don't double-count

**ensemble (int constant)**: Water ensemble type
  - Create with: Use constants like `oeszmap.OEEnsemble_Neutral`
  - Common in: OESzmapEngineOptions.SetEnsemble()
  - Available values: OEEnsemble_Neutral, OEEnsemble_Charged
  - Typical values: Neutral for most binding sites; Charged for highly polar/charged regions

## Return Types & Error Handling

```python
# Boolean returns - most calculation functions return success/failure
results = oeszmap.OESzmapResults()
if oeszmap.OECalcSzmapResults(results, opts, protein, coords):
    # Success - results object now contains valid data
    dg = results.GetDeltaG()
else:
    # Failure - calculation could not complete
    # Common causes: clashing position, invalid protein, out of bounds
    print("Calculation failed at this position")

# Clash checking - returns boolean
if oeszmap.OEIsClashing(opts, protein, coords):
    print("Position clashes with protein atoms")
    # Skip calculation at this position
else:
    # Safe to calculate
    oeszmap.OECalcSzmapResults(results, opts, protein, coords)

# Direct value returns - OECalcSzmapValue returns float
energy = oeszmap.OECalcSzmapValue(oeszmap.OEComponent_VDW, opts, protein, coords)
# Returns 0.0 on failure; check with OEIsClashing first for validation

# String returns - version and name functions
version = oeszmap.OESzmapGetVersion()  # Always returns string
component_name = oeszmap.OEGetComponentName(oeszmap.OEComponent_VDW)  # Returns "VDW"

# License checking - validate before running calculations
if not oeszmap.OESzmapIsLicensed():
    raise RuntimeError("Szmap TK is not licensed")
    
# Results object access - check validity before accessing
if oeszmap.OECalcSzmapResults(results, opts, protein, coords):
    # Safe to access all result methods
    dg = results.GetDeltaG()
    vdw = results.GetVDW()
    num_orients = results.GetNumOrientations()
    
    # Iterate orientations safely
    for i in range(results.GetNumOrientations()):
        orient = results.GetOrientation(i)
        energy = orient.GetEnergy()