# MolProp TK

> Molecular property calculation and filtering toolkit for drug discovery

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

## Core API - Function Quick Reference

### Filtering Functions

OEFilter(filtertype: int)
  Use for: Creating a molecular filter with predefined or custom rules
  Example: filt = OEFilter(OEFilterType_Lead)
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropClasses/OEFilter.html

OEFilter.__call__(mol: OEMolBase) -> bool
  Use for: Testing if a molecule passes filter criteria
  Example: if filt(mol): print("Passed")
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropClasses/OEFilter.html

OEConfigureFilterType(filt: OEFilter, filtertype: int) -> bool
  Use for: Configuring filter with standard filter types (Blockbuster, Lead, Drug)
  Example: OEConfigureFilterType(filt, OEFilterType_Blockbuster)
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OEConfigureFilterType.html

OEConfigureFilterParams(filt: OEFilter, filename: str, setup: int = OEFilterParamSetup_Default) -> bool
  Use for: Loading custom filter rules from a file
  Example: OEConfigureFilterParams(filt, "custom.txt", OEFilterParamSetup_Default)
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OEConfigureFilterParams.html

OEGetFilterType(filt: OEFilter) -> int
  Use for: Retrieving the current filter type from a filter object
  Example: ftype = OEGetFilterType(filt)
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OEGetFilterType.html

### Molecular Property Calculation

OEGetXLogP(mol: OEMolBase) -> float
  Use for: Calculating XLogP (lipophilicity) for a molecule
  Example: logp = OEGetXLogP(mol)
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OEGetXLogP.html

OEGetXLogPResult(mol: OEMolBase) -> OEXLogPResult
  Use for: Getting detailed XLogP calculation results including atom contributions
  Example: result = OEGetXLogPResult(mol)
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OEGetXLogPResult.html

OEGet2dPSA(mol: OEMolBase) -> float
  Use for: Calculating 2D polar surface area (PSA)
  Example: psa = OEGet2dPSA(mol)
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OEGet2dPSA.html

OEGetRotatableBondCount(mol: OEMolBase) -> int
  Use for: Counting rotatable bonds in a molecule
  Example: rotbonds = OEGetRotatableBondCount(mol)
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OEGetRotatableBondCount.html

### Lipinski and Hydrogen Bond Properties

OEGetLipinskiDonorCount(mol: OEMolBase) -> int
  Use for: Counting Lipinski hydrogen bond donors
  Example: donors = OEGetLipinskiDonorCount(mol)
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OEGetLipinskiDonorCount.html

OEGetLipinskiAcceptorCount(mol: OEMolBase) -> int
  Use for: Counting Lipinski hydrogen bond acceptors
  Example: acceptors = OEGetLipinskiAcceptorCount(mol)
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OEGetLipinskiAcceptorCount.html

OEGetHBondDonorCount(mol: OEMolBase) -> int
  Use for: Counting general hydrogen bond donors (more inclusive than Lipinski)
  Example: hbond_donors = OEGetHBondDonorCount(mol)
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OEGetHBondDonorCount.html

OEGetHBondAcceptorCount(mol: OEMolBase) -> int
  Use for: Counting general hydrogen bond acceptors (more inclusive than Lipinski)
  Example: hbond_acceptors = OEGetHBondAcceptorCount(mol)
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OEGetHBondAcceptorCount.html

### Structural Features

OEGetAromaticRingCount(mol: OEMolBase) -> int
  Use for: Counting aromatic rings in a molecule
  Example: aromatic_rings = OEGetAromaticRingCount(mol)
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OEGetAromaticRingCount.html

OEGetFractionCsp3(mol: OEMolBase) -> float
  Use for: Calculating fraction of sp3 carbons (molecular complexity indicator)
  Example: fsp3 = OEGetFractionCsp3(mol)
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OEGetFractionCsp3.html

OEGetAnionicCarbonCount(mol: OEMolBase) -> int
  Use for: Counting anionic carbon atoms
  Example: anionic_c = OEGetAnionicCarbonCount(mol)
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OEGetAnionicCarbonCount.html

OEGetHalideFraction(mol: OEMolBase) -> float
  Use for: Calculating fraction of halide atoms
  Example: halide_frac = OEGetHalideFraction(mol)
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OEGetHalideFraction.html

OEGetLongestUnbranchedCarbonsChain(mol: OEMolBase) -> int
  Use for: Finding longest unbranched carbon chain length
  Example: chain_len = OEGetLongestUnbranchedCarbonsChain(mol)
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OEGetLongestUnbranchedCarbonsChain.html

OEGetLongestUnbranchedHeavyAtomsChain(mol: OEMolBase) -> int
  Use for: Finding longest unbranched heavy atom chain length
  Example: heavy_chain = OEGetLongestUnbranchedHeavyAtomsChain(mol)
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OEGetLongestUnbranchedHeavyAtomsChain.html

### Stereochemistry

OEGetNumUnspecifiedAtomStereos(mol: OEMolBase) -> int
  Use for: Counting atoms with unspecified stereochemistry
  Example: unspec_atoms = OEGetNumUnspecifiedAtomStereos(mol)
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OEGetNumUnspecifiedAtomStereos.html

OEGetNumUnspecifiedBondStereos(mol: OEMolBase) -> int
  Use for: Counting bonds with unspecified stereochemistry
  Example: unspec_bonds = OEGetNumUnspecifiedBondStereos(mol)
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OEGetNumUnspecifiedBondStereos.html

### XLogP Type Checking

OECheckXLogXType(mol: OEMolBase) -> bool
  Use for: Checking if molecule has valid XLogP atom types
  Example: if OECheckXLogXType(mol): logp = OEGetXLogP(mol)
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OECheckXLogXType.html

OECheckXLogXTypes(mol: OEMolBase, atomtypes: OEIntArray) -> bool
  Use for: Checking XLogP types and retrieving atom type assignments
  Example: types = oechem.OEIntArray(mol.NumAtoms()); OECheckXLogXTypes(mol, types)
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OECheckXLogXTypes.html

### Data Export

OEWritePropertyDataToCSV(filename: str, mol: OEMolBase, properties: list) -> bool
  Use for: Writing molecular properties to CSV file
  Example: OEWritePropertyDataToCSV("props.csv", mol, ["MW", "LogP"])
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OEWritePropertyDataToCSV.html

### Version Information

OEGetXLogPVersion() -> str
  Use for: Getting XLogP model version string
  Example: version = OEGetXLogPVersion()
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OEGetXLogPVersion.html

OEMolPropGetVersion() -> str
  Use for: Getting MolProp TK version
  Example: version = OEMolPropGetVersion()
  See: https://docs.eyesopen.com/toolkits/python/molproptk/OEMolPropFunctions/OEMolPropGetVersion.html

## Common Patterns - Complete Working Examples

### Pattern: Basic Molecule Filtering with Standard Filter

```python
from openeye import oechem
from openeye import oemolprop

ifs = oechem.oemolistream("input.sdf")
ofs = oechem.oemolostream("passed.sdf")
filt = oemolprop.OEFilter(oemolprop.OEFilterType_Lead)

for mol in ifs.GetOEMols():
    if filt(mol):
        oechem.OEWriteMolecule(ofs, mol)
    else:
        print(f"Molecule {mol.GetTitle()} failed filter")
```
Use when: You need to filter molecules using standard drug-like, lead-like, or blockbuster criteria

### Pattern: Custom Filter from File

```python
from openeye import oechem
from openeye import oemolprop

filt = oemolprop.OEFilter()
if not oemolprop.OEConfigureFilterParams(filt, "custom_rules.txt"):
    oechem.OEThrow.Fatal("Unable to configure filter")

ifs = oechem.oemolistream("compounds.sdf")
for mol in ifs.GetOEMols():
    if filt(mol):
        print(f"{mol.GetTitle()} passed custom filter")
```
Use when: You have custom filtering rules defined in a text file with property limits and functional group constraints

### Pattern: Calculate Multiple Properties for a Molecule

```python
from openeye import oechem
from openeye import oemolprop

mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccccc1O")

logp = oemolprop.OEGetXLogP(mol)
psa = oemolprop.OEGet2dPSA(mol)
rotbonds = oemolprop.OEGetRotatableBondCount(mol)
hbd = oemolprop.OEGetLipinskiDonorCount(mol)
hba = oemolprop.OEGetLipinskiAcceptorCount(mol)

print(f"LogP: {logp:.2f}, PSA: {psa:.2f}, RotBonds: {rotbonds}")
```
Use when: You need to calculate standard ADME properties for molecular characterization

### Pattern: Detailed XLogP Analysis with Atom Contributions

```python
from openeye import oechem
from openeye import oemolprop

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

result = oemolprop.OEGetXLogPResult(mol)
print(f"Total XLogP: {result.GetValue():.3f}")

for atom in mol.GetAtoms():
    contrib = result.GetAtomValue(atom.GetIdx())
    print(f"Atom {atom.GetIdx()} ({oechem.OEGetAtomicSymbol(atom.GetAtomicNum())}): {contrib:.3f}")
```
Use when: You need to understand which atoms contribute to lipophilicity for molecular design

### Pattern: Property Table Generation

```python
from openeye import oechem
from openeye import oemolprop

ifs = oechem.oemolistream("molecules.sdf")

print("Title\tMW\tLogP\tPSA\tHBD\tHBA\tRotBonds")
for mol in ifs.GetOEMols():
    mw = oechem.OECalculateMolecularWeight(mol)
    logp = oemolprop.OEGetXLogP(mol)
    psa = oemolprop.OEGet2dPSA(mol)
    hbd = oemolprop.OEGetLipinskiDonorCount(mol)
    hba = oemolprop.OEGetLipinskiAcceptorCount(mol)
    rotb = oemolprop.OEGetRotatableBondCount(mol)
    print(f"{mol.GetTitle()}\t{mw:.1f}\t{logp:.2f}\t{psa:.1f}\t{hbd}\t{hba}\t{rotb}")
```
Use when: You need to generate a property table for multiple molecules for analysis or reporting

### Pattern: Attach Properties as SD Data

```python
from openeye import oechem
from openeye import oemolprop

ifs = oechem.oemolistream("input.sdf")
ofs = oechem.oemolostream("output.sdf")

for mol in ifs.GetOEMols():
    oechem.OESetSDData(mol, "XLogP", f"{oemolprop.OEGetXLogP(mol):.2f}")
    oechem.OESetSDData(mol, "PSA", f"{oemolprop.OEGet2dPSA(mol):.2f}")
    oechem.OESetSDData(mol, "RotBonds", str(oemolprop.OEGetRotatableBondCount(mol)))
    oechem.OEWriteMolecule(ofs, mol)
```
Use when: You want to store calculated properties in SD file format for downstream processing

### Pattern: Write Properties to CSV File

```python
from openeye import oechem
from openeye import oemolprop

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

properties = ["MW", "XLogP", "TPSA", "NumRotBonds", "NumHBD", "NumHBA"]
oemolprop.OEWritePropertyDataToCSV("properties.csv", mol, properties)
```
Use when: You need to export molecular properties in CSV format for spreadsheet analysis

### Pattern: Validate XLogP Atom Types Before Calculation

```python
from openeye import oechem
from openeye import oemolprop

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

if oemolprop.OECheckXLogXType(mol):
    logp = oemolprop.OEGetXLogP(mol)
    print(f"XLogP: {logp:.2f}")
else:
    print("Warning: Molecule contains atoms with undefined XLogP types")
```
Use when: You need to ensure XLogP can be calculated before attempting calculation (important for unusual atom types)

### Pattern: Filter with Quiet Mode (No Output Messages)

```python
from openeye import oechem
from openeye import oemolprop

oechem.OEThrow.SetLevel(oechem.OEErrorLevel_Warning)

filt = oemolprop.OEFilter(oemolprop.OEFilterType_Drug)
ifs = oechem.oemolistream("compounds.sdf")

passed = 0
failed = 0
for mol in ifs.GetOEMols():
    if filt(mol):
        passed += 1
    else:
        failed += 1

print(f"Passed: {passed}, Failed: {failed}")
```
Use when: You want to suppress filter messages for batch processing

### Pattern: Calculate Molecular Complexity Indicators

```python
from openeye import oechem
from openeye import oemolprop

mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "CC(C)CC1=CC=C(C=C1)C(C)C(O)=O")

fsp3 = oemolprop.OEGetFractionCsp3(mol)
aromatic_rings = oemolprop.OEGetAromaticRingCount(mol)
rotbonds = oemolprop.OEGetRotatableBondCount(mol)

print(f"Fsp3: {fsp3:.2f}, Aromatic Rings: {aromatic_rings}, RotBonds: {rotbonds}")
```
Use when: You need to assess molecular complexity for lead optimization or library design

### Pattern: Check Stereochemistry Completeness

```python
from openeye import oechem
from openeye import oemolprop

mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "C[C@H](O)CC")

unspec_atoms = oemolprop.OEGetNumUnspecifiedAtomStereos(mol)
unspec_bonds = oemolprop.OEGetNumUnspecifiedBondStereos(mol)

if unspec_atoms > 0 or unspec_bonds > 0:
    print(f"Warning: {unspec_atoms} unspecified atom stereos, {unspec_bonds} unspecified bond stereos")
else:
    print("All stereochemistry is specified")
```
Use when: You need to validate that stereochemistry is fully defined for chiral molecules

### Pattern: Analyze Structural Features for Drug-likeness

```python
from openeye import oechem
from openeye import oemolprop

mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "CC(=O)Oc1ccccc1C(=O)O")

halide_frac = oemolprop.OEGetHalideFraction(mol)
anionic_c = oemolprop.OEGetAnionicCarbonCount(mol)
longest_chain = oemolprop.OEGetLongestUnbranchedCarbonsChain(mol)

print(f"Halide fraction: {halide_frac:.2f}")
print(f"Anionic carbons: {anionic_c}")
print(f"Longest carbon chain: {longest_chain}")
```
Use when: You need to analyze specific structural features that may affect drug-likeness

### Pattern: Multi-Stage Filtering Pipeline

```python
from openeye import oechem
from openeye import oemolprop

lead_filter = oemolprop.OEFilter(oemolprop.OEFilterType_Lead)
drug_filter = oemolprop.OEFilter(oemolprop.OEFilterType_Drug)

ifs = oechem.oemolistream("compounds.sdf")
lead_ofs = oechem.oemolostream("lead_like.sdf")
drug_ofs = oechem.oemolostream("drug_like.sdf")

for mol in ifs.GetOEMols():
    if lead_filter(mol):
        oechem.OEWriteMolecule(lead_ofs, mol)
    if drug_filter(mol):
        oechem.OEWriteMolecule(drug_ofs, mol)
```
Use when: You need to categorize molecules into different drug-likeness categories

## API Decision Guide

- **For standard drug-likeness filtering**: use `OEFilter(OEFilterType_Drug)` (Lipinski-like rules)
- **For lead-like filtering**: use `OEFilter(OEFilterType_Lead)` (smaller, less complex molecules)
- **For blockbuster filtering**: use `OEFilter(OEFilterType_Blockbuster)` (oral bioavailability focus)
- **For custom filtering rules**: use `OEConfigureFilterParams(filt, filename)` with a custom filter file
- **For lipophilicity calculation**: use `OEGetXLogP(mol)` (returns single float value)
- **For detailed lipophilicity analysis**: use `OEGetXLogPResult(mol)` (returns atom contributions)
- **For polar surface area**: use `OEGet2dPSA(mol)` (2D PSA calculation)
- **For Lipinski hydrogen bond counts**: use `OEGetLipinskiDonorCount()` and `OEGetLipinskiAcceptorCount()` (strict Lipinski definition)
- **For general hydrogen bond counts**: use `OEGetHBondDonorCount()` and `OEGetHBondAcceptorCount()` (more inclusive)
- **For rotatable bonds**: use `OEGetRotatableBondCount(mol)` (flexibility indicator)
- **For molecular complexity**: use `OEGetFractionCsp3(mol)` (sp3 carbon fraction)
- **For aromatic content**: use `OEGetAromaticRingCount(mol)` (counts aromatic rings)
- **For stereochemistry validation**: use `OEGetNumUnspecifiedAtomStereos()` and `OEGetNumUnspecifiedBondStereos()`
- **Before XLogP calculation**: use `OECheckXLogXType(mol)` to validate atom types
- **For property export**: use `OEWritePropertyDataToCSV()` for CSV format
- **For SD file property storage**: use `oechem.OESetSDData()` with calculated properties

**OEFilter vs custom rules**: Use predefined `OEFilterType` constants for standard filtering; use `OEConfigureFilterParams()` when you need custom property ranges or functional group rules

**Lipinski vs general H-bond counts**: Lipinski functions use strict Lipinski definitions (N,O for acceptors; N,O with H for donors); general functions are more inclusive and may count additional atoms

## Common Parameters & Types

**OEFilter**: Molecular filter object for testing molecules against criteria
  - Create with: `OEFilter()` (empty) or `OEFilter(OEFilterType_Lead)` (predefined)
  - Common in: All filtering operations
  - Configure with: `OEConfigureFilterType()` or `OEConfigureFilterParams()`
  - Gotcha: Must configure before use; call as function `filt(mol)` to test molecules

**OEFilterType constants**: Predefined filter types
  - Values: `OEFilterType_Lead`, `OEFilterType_Drug`, `OEFilterType_Blockbuster`
  - Common in: `OEFilter()` constructor, `OEConfigureFilterType()`
  - Use: Specify standard drug-likeness criteria sets

**OEFilterParamSetup constants**: Filter parameter setup modes
  - Values: `OEFilterParamSetup_Default`, `OEFilterParamSetup_Append`
  - Common in: `OEConfigureFilterParams()`
  - Use: Control how custom filter rules are loaded (replace vs append)

**OEXLogPResult**: Detailed XLogP calculation result object
  - Create with: `OEGetXLogPResult(mol)`
  - Common in: Detailed lipophilicity analysis
  - Methods: `GetValue()` (total XLogP), `GetAtomValue(idx)` (atom contribution)
  - Use when: You need atom-level contributions to understand lipophilicity

**OEMolBase**: Base molecule object (from OEChem)
  - Create with: `oechem.OEGraphMol()` or read from file
  - Common in: All MolProp functions as input parameter
  - Gotcha: Must be a valid molecule with proper atom types for property calculations

**Property name strings**: String identifiers for properties
  - Values: "MW", "XLogP", "TPSA", "NumRotBonds", "NumHBD", "NumHBA", etc.
  - Common in: `OEWritePropertyDataToCSV()`, SD data tags
  - Use: Specify which properties to calculate or export

**Filter rule files**: Text files with custom filter definitions
  - Format: Property limits and functional group rules
  - Common in: `OEConfigureFilterParams()`
  - Structure: Lines with property ranges (e.g., "MW 150 500") and SMARTS patterns
  - Gotcha: Must follow specific syntax; see filter file documentation for format

## Return Types & Error Handling

```python
# Boolean returns - filtering and validation
filt = oemolprop.OEFilter(oemolprop.OEFilterType_Lead)
if filt(mol):  # Returns True if molecule passes filter
    print("Passed")
else:
    print("Failed")

# Boolean returns - configuration success
if not oemolprop.OEConfigureFilterParams(filt, "rules.txt"):
    oechem.OEThrow.Fatal("Failed to load filter rules")

# Float returns - property calculations
logp = oemolprop.OEGetXLogP(mol)  # Returns float, no error checking needed
psa = oemolprop.OEGet2dPSA(mol)   # Returns float

# Integer returns - counts
rotbonds = oemolprop.OEGetRotatableBondCount(mol)  # Returns int
hbd = oemolprop.OEGetLipinskiDonorCount(mol)       # Returns int

# Object returns - detailed results
result = oemolprop.OEGetXLogPResult(mol)  # Returns OEXLogPResult object
total_logp = result.GetValue()
atom_contrib = result.GetAtomValue(0)

# XLogP type validation before calculation
if not oemolprop.OECheckXLogXType(mol):
    print("Warning: Undefined XLogP atom types present")
    # XLogP calculation may be unreliable
else:
    logp = oemolprop.OEGetXLogP(mol)

# Suppress filter messages for batch processing
oechem.OEThrow.SetLevel(oechem.OEErrorLevel_Warning)
# Now filter operations won't print messages for each molecule