# Sitehopper TK

> Protein binding site comparison and analysis toolkit for rapid GPU-accelerated similarity searching

## Links
- [Full Documentation](https://docs.eyesopen.com/toolkits/python/sitehoppertk/index.html)
- [Code Examples](https://docs.eyesopen.com/toolkits/python/sitehoppertk/examples.html)
- [API Reference](https://docs.eyesopen.com/toolkits/python/sitehoppertk/api.html)
- [GPU Requirements](https://docs.eyesopen.com/toolkits/python/sitehoppertk/gpu_prereq.html)

## Core API - Function Quick Reference

### Database Operations
```
OESiteHopperDatabase(filename: str, mode: OESiteHopperDatabaseMode = OESiteHopperDatabaseMode_Read)
  Use for: Creating or opening a SiteHopper database for storing/searching protein binding sites
  Example: db = OESiteHopperDatabase("sites.shdb", OESiteHopperDatabaseMode_Write)
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperClasses/OESiteHopperDatabase.html

OESiteHopperDatabase.AddDesignUnit(du: OEDesignUnit) -> bool
  Use for: Adding a prepared protein binding site (OEDesignUnit) to the database
  Example: success = db.AddDesignUnit(design_unit)
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperClasses/OESiteHopperDatabase.html

OESiteHopperDatabase.GetDesignUnit(idx: int) -> OEDesignUnit
  Use for: Retrieving a specific design unit from database by index
  Example: du = db.GetDesignUnit(0)
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperClasses/OESiteHopperDatabase.html

OESiteHopperDatabase.NumDesignUnits() -> int
  Use for: Getting the total number of binding sites stored in the database
  Example: count = db.NumDesignUnits()
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperClasses/OESiteHopperDatabase.html

OESiteHopperDatabase.GetTitle(idx: int) -> str
  Use for: Getting the title/identifier of a design unit without loading the full structure
  Example: title = db.GetTitle(0)
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperClasses/OESiteHopperDatabase.html
```

### Search Operations
```
OESiteHopperSearch(db: OESiteHopperDatabase, opts: OESiteHopperSearchOptions = OESiteHopperSearchOptions())
  Use for: Creating a search object to find similar binding sites in a database
  Example: search = OESiteHopperSearch(database, search_options)
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperClasses/OESiteHopperSearch.html

OESiteHopperSearch.Search(query: OEDesignUnit) -> OESiteHopperResults
  Use for: Performing similarity search with a query binding site against database
  Example: results = search.Search(query_du)
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperClasses/OESiteHopperSearch.html

OESiteHopperResults.GetScores() -> iterator of OESiteHopperScore
  Use for: Iterating through search results to get similarity scores
  Example: for score in results.GetScores(): print(score.GetTanimoto())
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperClasses/OESiteHopperResults.html

OESiteHopperScore.GetTanimoto() -> float
  Use for: Getting the Tanimoto similarity score (0-1) for a search hit
  Example: similarity = score.GetTanimoto()
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperClasses/OESiteHopperScore.html

OESiteHopperScore.GetIndex() -> int
  Use for: Getting the database index of a hit to retrieve the full design unit
  Example: idx = score.GetIndex(); hit_du = db.GetDesignUnit(idx)
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperClasses/OESiteHopperScore.html
```

### Configuration & Options
```
OESiteHopperSearchOptions()
  Use for: Creating search configuration object to control search behavior
  Example: opts = OESiteHopperSearchOptions(); opts.SetNumBestHits(100)
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperClasses/OESiteHopperSearchOptions.html

OESiteHopperSearchOptions.SetNumBestHits(n: int)
  Use for: Limiting the number of top hits returned from a search
  Example: opts.SetNumBestHits(50)
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperClasses/OESiteHopperSearchOptions.html

OESiteHopperDatabaseOptions()
  Use for: Creating database configuration object for database creation
  Example: db_opts = OESiteHopperDatabaseOptions()
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperClasses/OESiteHopperDatabaseOptions.html

OESiteHopperPatchOptions()
  Use for: Configuring how binding site patches are generated from design units
  Example: patch_opts = OESiteHopperPatchOptions()
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperClasses/OESiteHopperPatchOptions.html
```

### Patch Surface Operations
```
OEMakePatchFromDesignUnit(du: OEDesignUnit, opts: OESiteHopperPatchOptions = OESiteHopperPatchOptions()) -> OEMolBase
  Use for: Generating a binding site patch surface from a design unit for searching
  Example: patch = OEMakePatchFromDesignUnit(design_unit)
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperFunctions/OEMakePatchFromDesignUnit.html

OEAddPatchSurface(du: OEDesignUnit, patch: OEMolBase) -> bool
  Use for: Attaching a patch surface to a design unit for storage/searching
  Example: OEAddPatchSurface(design_unit, patch_surface)
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperFunctions/OEAddPatchSurface.html

OEGetPatchSurface(du: OEDesignUnit) -> OEMolBase
  Use for: Retrieving the patch surface from a design unit
  Example: patch = OEGetPatchSurface(design_unit)
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperFunctions/OEGetPatchSurface.html

OEHasPatchSurface(du: OEDesignUnit) -> bool
  Use for: Checking if a design unit has a patch surface attached
  Example: if OEHasPatchSurface(du): patch = OEGetPatchSurface(du)
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperFunctions/OEHasPatchSurface.html

OESetPatchSurface(du: OEDesignUnit, patch: OEMolBase) -> bool
  Use for: Replacing the patch surface on a design unit
  Example: OESetPatchSurface(design_unit, new_patch)
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperFunctions/OESetPatchSurface.html
```

### Utility Functions
```
OESiteHopperIsGPUReady() -> bool
  Use for: Checking if GPU acceleration is available for searches
  Example: if OESiteHopperIsGPUReady(): print("GPU available")
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperFunctions/OESiteHopperIsGPUReady.html

OESiteHopperIsLicensed() -> bool
  Use for: Verifying that SiteHopper TK is properly licensed
  Example: if not OESiteHopperIsLicensed(): raise Exception("No license")
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperFunctions/OESiteHopperIsLicensed.html

OESiteHopperGetVersion() -> str
  Use for: Getting the version string of SiteHopper TK
  Example: version = OESiteHopperGetVersion()
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperFunctions/OESiteHopperGetVersion.html

OESetProteinSDData(mol: OEMolBase, du: OEDesignUnit) -> bool
  Use for: Adding protein metadata from design unit to molecule SD data
  Example: OESetProteinSDData(ligand, design_unit)
  See: https://docs.eyesopen.com/toolkits/python/sitehoppertk/OESiteHopperFunctions/OESetProteinSDData.html
```

## Common Patterns - Complete Working Examples

### Pattern: Create and Populate a SiteHopper Database
```python
from openeye import oechem, oesitehopper

# Create new database for writing
db = oesitehopper.OESiteHopperDatabase("sites.shdb", 
                                       oesitehopper.OESiteHopperDatabaseMode_Write)

# Read design units from file and add to database
ifs = oechem.oeifstream("prepared_sites.oedu")
for du in oechem.OEDesignUnits(ifs):
    if not db.AddDesignUnit(du):
        oechem.OEThrow.Warning(f"Failed to add {du.GetTitle()}")
        
ifs.close()
print(f"Added {db.NumDesignUnits()} sites to database")
```
Use when: Building a searchable database of protein binding sites from prepared structures

### Pattern: Search Database for Similar Binding Sites
```python
from openeye import oechem, oesitehopper

# Open existing database
db = oesitehopper.OESiteHopperDatabase("sites.shdb")

# Configure search to return top 50 hits
opts = oesitehopper.OESiteHopperSearchOptions()
opts.SetNumBestHits(50)

# Create search object and run query
search = oesitehopper.OESiteHopperSearch(db, opts)
query_du = oechem.OEDesignUnit()
oechem.OEReadDesignUnit(oechem.oeifstream("query.oedu"), query_du)
results = search.Search(query_du)

# Process results
for score in results.GetScores():
    print(f"Hit: {db.GetTitle(score.GetIndex())} Similarity: {score.GetTanimoto():.3f}")
```
Use when: Finding binding sites similar to a query site from a pre-built database

### Pattern: Generate Patch Surface from Design Unit
```python
from openeye import oechem, oesitehopper

# Read design unit
du = oechem.OEDesignUnit()
oechem.OEReadDesignUnit(oechem.oeifstream("protein_site.oedu"), du)

# Configure patch generation options
patch_opts = oesitehopper.OESiteHopperPatchOptions()

# Generate patch surface
patch = oesitehopper.OEMakePatchFromDesignUnit(du, patch_opts)

# Attach patch to design unit for searching
oesitehopper.OEAddPatchSurface(du, patch)

# Save design unit with patch
oechem.OEWriteDesignUnit(oechem.oeofstream("site_with_patch.oedu"), du)
```
Use when: Preparing a design unit for SiteHopper searching by generating its patch surface

### Pattern: Retrieve and Analyze Top Search Hits
```python
from openeye import oechem, oesitehopper

db = oesitehopper.OESiteHopperDatabase("sites.shdb")
search = oesitehopper.OESiteHopperSearch(db)
results = search.Search(query_du)

# Get top 10 hits above similarity threshold
top_hits = []
for score in results.GetScores():
    if score.GetTanimoto() >= 0.7 and len(top_hits) < 10:
        hit_du = db.GetDesignUnit(score.GetIndex())
        top_hits.append((score.GetTanimoto(), hit_du))
        
# Write hits to file
ofs = oechem.oeofstream("top_hits.oedu")
for similarity, du in top_hits:
    oechem.OEWriteDesignUnit(ofs, du)
```
Use when: Filtering search results by similarity threshold and retrieving full structures

### Pattern: Query Database Information
```python
from openeye import oechem, oesitehopper

# Open database in read mode
db = oesitehopper.OESiteHopperDatabase("sites.shdb")

# Get database statistics
num_sites = db.NumDesignUnits()
print(f"Database contains {num_sites} binding sites")

# List all site titles without loading full structures
print("\nSites in database:")
for i in range(num_sites):
    title = db.GetTitle(i)
    print(f"  {i}: {title}")
    
# Check if specific site exists
target_title = "1ABC_site1"
for i in range(num_sites):
    if db.GetTitle(i) == target_title:
        print(f"\nFound {target_title} at index {i}")
        break
```
Use when: Inspecting database contents without loading all design units into memory

### Pattern: Batch Process Multiple Queries
```python
from openeye import oechem, oesitehopper

db = oesitehopper.OESiteHopperDatabase("sites.shdb")
search = oesitehopper.OESiteHopperSearch(db)

# Process multiple query files
query_files = ["query1.oedu", "query2.oedu", "query3.oedu"]
all_results = {}

for query_file in query_files:
    query_du = oechem.OEDesignUnit()
    oechem.OEReadDesignUnit(oechem.oeifstream(query_file), query_du)
    
    results = search.Search(query_du)
    all_results[query_du.GetTitle()] = list(results.GetScores())
    
# Analyze results across queries
for query_name, scores in all_results.items():
    print(f"{query_name}: {len(scores)} hits, best={scores[0].GetTanimoto():.3f}")
```
Use when: Running multiple binding site searches and comparing results

### Pattern: Check GPU Availability and License
```python
from openeye import oesitehopper

# Verify license before running searches
if not oesitehopper.OESiteHopperIsLicensed():
    raise RuntimeError("SiteHopper TK is not licensed")

# Check GPU availability for acceleration
if oesitehopper.OESiteHopperIsGPUReady():
    print("GPU acceleration available")
    print(f"SiteHopper version: {oesitehopper.OESiteHopperGetVersion()}")
else:
    print("Running on CPU (GPU not available)")
    
# Proceed with database operations
db = oesitehopper.OESiteHopperDatabase("sites.shdb")
```
Use when: Validating environment before running SiteHopper operations

### Pattern: Create Database with Custom Options
```python
from openeye import oechem, oesitehopper

# Configure database creation options
db_opts = oesitehopper.OESiteHopperDatabaseOptions()

# Create database with options
db = oesitehopper.OESiteHopperDatabase("custom_sites.shdb",
                                       oesitehopper.OESiteHopperDatabaseMode_Write,
                                       db_opts)

# Configure patch generation
patch_opts = oesitehopper.OESiteHopperPatchOptions()

# Add design units with custom patches
for du in oechem.OEDesignUnits(oechem.oeifstream("sites.oedu")):
    patch = oesitehopper.OEMakePatchFromDesignUnit(du, patch_opts)
    oesitehopper.OEAddPatchSurface(du, patch)
    db.AddDesignUnit(du)
```
Use when: Creating a database with specific configuration for patch generation or storage

### Pattern: Extract Patch Surface for Visualization
```python
from openeye import oechem, oesitehopper

# Read design unit with patch
du = oechem.OEDesignUnit()
oechem.OEReadDesignUnit(oechem.oeifstream("site.oedu"), du)

# Check if patch exists and extract it
if oesitehopper.OEHasPatchSurface(du):
    patch = oesitehopper.OEGetPatchSurface(du)
    
    # Write patch surface to separate file for visualization
    oechem.OEWriteMolecule(oechem.oeofstream("patch_surface.oeb"), patch)
    print(f"Extracted patch with {patch.NumAtoms()} atoms")
else:
    print("No patch surface found - generating new one")
    patch = oesitehopper.OEMakePatchFromDesignUnit(du)
    oesitehopper.OESetPatchSurface(du, patch)
```
Use when: Extracting or regenerating patch surfaces for analysis or visualization

### Pattern: Filter Search Results by Protein Properties
```python
from openeye import oechem, oesitehopper

db = oesitehopper.OESiteHopperDatabase("sites.shdb")
search = oesitehopper.OESiteHopperSearch(db)
results = search.Search(query_du)

# Filter hits by retrieving and checking design units
filtered_hits = []
for score in results.GetScores():
    if score.GetTanimoto() < 0.6:
        continue
        
    hit_du = db.GetDesignUnit(score.GetIndex())
    protein = hit_du.GetProtein()
    
    # Filter by protein properties (e.g., resolution, organism)
    if protein.NumAtoms() > 1000:  # Example filter
        filtered_hits.append((score.GetTanimoto(), hit_du))
        
print(f"Found {len(filtered_hits)} hits passing filters")
```
Use when: Applying additional filters to search results based on protein structure properties

## API Decision Guide

- **For creating a new database**: use `OESiteHopperDatabase(filename, OESiteHopperDatabaseMode_Write)` to create writable database
- **For searching existing database**: use `OESiteHopperDatabase(filename)` or `OESiteHopperDatabase(filename, OESiteHopperDatabaseMode_Read)` for read-only access
- **For adding sites to database**: use `OESiteHopperDatabase.AddDesignUnit(du)` after creating database in write mode
- **For running similarity searches**: use `OESiteHopperSearch.Search(query_du)` after creating search object with database
- **For limiting search results**: use `OESiteHopperSearchOptions.SetNumBestHits(n)` before creating search object
- **For generating binding site patches**: use `OEMakePatchFromDesignUnit(du)` to create patch surface from design unit
- **For checking patch existence**: use `OEHasPatchSurface(du)` before calling `OEGetPatchSurface(du)`
- **For attaching patches**: use `OEAddPatchSurface(du, patch)` for new patches, `OESetPatchSurface(du, patch)` to replace existing
- **For retrieving search hits**: use `OESiteHopperScore.GetIndex()` to get database index, then `OESiteHopperDatabase.GetDesignUnit(idx)` to get full structure
- **For getting similarity scores**: use `OESiteHopperScore.GetTanimoto()` which returns value between 0 (dissimilar) and 1 (identical)
- **For database inspection**: use `OESiteHopperDatabase.GetTitle(idx)` to get site names without loading full structures
- **For GPU acceleration**: check `OESiteHopperIsGPUReady()` before running large searches - GPU provides significant speedup
- **For license validation**: call `OESiteHopperIsLicensed()` at startup to verify toolkit is properly licensed

## Common Parameters & Types

**OEDesignUnit**: Represents a prepared protein binding site with ligand, protein, and metadata
  - Create with: `oechem.OEDesignUnit()` then populate with `oechem.OEReadDesignUnit(ifs, du)`
  - Common in: `AddDesignUnit()`, `Search()`, `OEMakePatchFromDesignUnit()`, `GetDesignUnit()`
  - Gotcha: Must have patch surface attached (via `OEAddPatchSurface()`) before adding to database or searching

**OESiteHopperDatabase**: Database object for storing and searching binding sites
  - Create with: `OESiteHopperDatabase(filename, mode)` where mode is Read or Write
  - Common in: All database operations, search object creation
  - Gotcha: Cannot add design units to database opened in read mode; must close and reopen to switch modes

**OESiteHopperSearchOptions**: Configuration object controlling search behavior
  - Create with: `OESiteHopperSearchOptions()` then configure with setter methods
  - Common in: `OESiteHopperSearch()` constructor
  - Typical values: `SetNumBestHits(50)` for top 50 hits, `SetNumBestHits(0)` for all hits above threshold

**OESiteHopperResults**: Container for search results with similarity scores
  - Create with: Returned by `OESiteHopperSearch.Search(query)`
  - Common in: Iterating search results via `GetScores()`
  - Gotcha: Results are sorted by similarity (highest first); use `GetScores()` iterator, not direct indexing

**OESiteHopperScore**: Individual search hit with similarity score and database index
  - Create with: Obtained from `OESiteHopperResults.GetScores()` iterator
  - Common in: Accessing hit information via `GetTanimoto()` and `GetIndex()`
  - Typical values: Tanimoto scores range 0.0-1.0; scores >0.7 indicate high similarity

**OESiteHopperDatabaseMode**: Enum controlling database access mode
  - Create with: Use constants `OESiteHopperDatabaseMode_Read` or `OESiteHopperDatabaseMode_Write`
  - Common in: `OESiteHopperDatabase()` constructor
  - Gotcha: Write mode required for `AddDesignUnit()`; read mode is default and more efficient for searching

**OEMolBase**: Molecule object representing patch surface or ligand
  - Create with: Returned by `OEMakePatchFromDesignUnit()` or `OEGetPatchSurface()`
  - Common in: `OEAddPatchSurface()`, `OESetPatchSurface()`, `OEGetPatchSurface()`
  - Gotcha: Patch surfaces are special molecule objects representing binding site shape; don't modify directly

**OESiteHopperPatchOptions**: Configuration for patch surface generation
  - Create with: `OESiteHopperPatchOptions()` then configure with setter methods
  - Common in: `OEMakePatchFromDesignUnit()` optional parameter
  - Typical values: Default options work for most cases; customize for specific binding site types

## Return Types & Error Handling

```python
# Boolean returns - most add/set operations return success status
success = db.AddDesignUnit(du)
if not success:
    oechem.OEThrow.Warning(f"Failed to add design unit {du.GetTitle()}")

# Iterator returns - results provide iterator over scores
results = search.Search(query_du)
for score in results.GetScores():  # Iterator pattern
    if score.GetTanimoto() >= threshold:
        process_hit(score)

# Object returns - functions return objects or None on failure
patch = oesitehopper.OEGetPatchSurface(du)
if patch is None:  # Check for None when patch might not exist
    patch = oesitehopper.OEMakePatchFromDesignUnit(du)

# Integer returns - counts and indices
num_sites = db.NumDesignUnits()
for i in range(num_sites):  # Use count for iteration
    title = db.GetTitle(i)

# Float returns - similarity scores
tanimoto = score.GetTanimoto()  # Returns 0.0-1.0
if tanimoto >= 0.7:  # Apply threshold
    print(f"High similarity: {tanimoto:.3f}")

# License/GPU checks - verify before operations
if not oesitehopper.OESiteHopperIsLicensed():
    raise RuntimeError("SiteHopper not licensed")
if not oesitehopper.OESiteHopperIsGPUReady():
    oechem.OEThrow.Warning("GPU not available, using CPU")

# Database mode errors - catch mode mismatches
try:
    db = oesitehopper.OESiteHopperDatabase("sites.shdb", 
                                           oesitehopper.OESiteHopperDatabaseMode_Read)
    db.AddDesignUnit(du)  # Will fail - wrong mode
except RuntimeError as e:
    print(f"Database error: {e}")