alterlab-bindingdb

$npx mdskill add AlterLab-IEU/AlterLab-Academic-Skills/alterlab-bindingdb

Queries BindingDB for protein-ligand binding affinities via REST API or TSV download.

  • Look up experimental binding constants (Ki, Kd, IC50, EC50) for drug discovery.
  • Depends on BindingDB's keyless REST API and full TSV download.
  • Searches by target (UniProt ID), compound (SMILES), or pathogen.
  • Returns binding data as JSON or TSV for analysis.

SKILL.md

.github/skills/alterlab-bindingdbView on GitHub ↗
---
name: alterlab-bindingdb
description: Query BindingDB for measured protein-ligand binding affinities (Ki, Kd, IC50, EC50) via its keyless REST API or the full TSV download, searching by target (UniProt ID), compound (SMILES), or pathogen. Use when looking up experimental binding constants, profiling inhibitors of a protein target, doing lead optimization, polypharmacology analysis, or structure-activity relationship (SAR) studies; for curated bioactivity mining or drug-like compound library screening at scale prefer alterlab-chembl instead. Part of the AlterLab Academic Skills suite.
license: CC-BY-3.0
allowed-tools: Read WebFetch Bash(curl:*) Bash(python:*)
compatibility: Keyless public BindingDB web services (no authentication required)
metadata:
    skill-author: AlterLab
    version: "1.0.0"
---

# BindingDB Database

## Overview

BindingDB (https://www.bindingdb.org/) is the primary public database of measured drug-protein binding affinities. It contains roughly 3.2 million binding data records for ~1.4 million compounds tested against ~11,400 protein targets, curated from scientific literature and patent literature. BindingDB stores quantitative binding measurements (Ki, Kd, IC50, EC50) essential for drug discovery, pharmacology, and computational chemistry research.

**Key resources:**
- BindingDB website: https://www.bindingdb.org/
- REST API base: https://bindingdb.org/rest/ (no key; default response is XML, append `response=application/json`)
- Downloads page: https://www.bindingdb.org/rwd/bind/chemsearch/marvin/Download.jsp (the full TSV is the dated `BindingDB_All_<YYYYMM>_tsv.zip`, ~560 MB zipped, refreshed monthly)

## When to Use This Skill

Use BindingDB when:

- **Target-based drug discovery**: What known compounds bind to a target protein? What are their affinities?
- **SAR analysis**: How do structural modifications affect binding affinity for a series of analogs?
- **Lead compound profiling**: What targets does a compound bind (selectivity/polypharmacology)?
- **Benchmark datasets**: Obtain curated protein-ligand affinity data for ML model training
- **Repurposing analysis**: Does an approved drug bind to an unintended target?
- **Competitive analysis**: What is the best reported affinity for a target class?
- **Fragment screening**: Find validated binding data for fragments against a target

## Core Capabilities

### 1. BindingDB REST API

Base URL: `https://bindingdb.org/rest`

```python
import requests

BASE_URL = "https://bindingdb.org/rest"

def bindingdb_query(method, params):
    """Query the BindingDB REST API."""
    url = f"{BASE_URL}/{method}"
    response = requests.get(url, params=params, headers={"Accept": "application/json"})
    response.raise_for_status()
    return response.json()
```

### 2. Query by Target (UniProt ID)

The `getLigandsByUniprot` endpoint takes a single `uniprot` parameter formatted as
`<UniProt accession>;<cutoff in nM>`, e.g. `P00519;10000`.

```python
def get_ligands_for_target(uniprot_id, cutoff=10000):
    """
    Get all ligands with measured affinity for a UniProt target.

    Args:
        uniprot_id: UniProt accession (e.g., "P00519" for ABL1)
        cutoff: Maximum affinity value to return (in nM)
    """
    params = {
        "uniprot": f"{uniprot_id};{cutoff}",
        "response": "application/json",
    }
    return bindingdb_query("getLigandsByUniprot", params)

# Example: Get all compounds binding ABL1 (imatinib target) at <=100 nM
ligands = get_ligands_for_target("P00519", cutoff=100)
```

### 3. Query by SMILES (structural similarity)

```python
def search_by_smiles(smiles, cutoff=0.85):
    """
    Search BindingDB by SMILES string (structural-similarity search).

    Args:
        smiles: SMILES string of the compound
        cutoff: Tanimoto similarity threshold (0.0-1.0; e.g. 0.85)
    """
    params = {
        "smiles": smiles,
        "cutoff": cutoff,
        "response": "application/json",
    }
    return bindingdb_query("getTargetByCompound", params)

# Example: structural-similarity search for imatinib's binding targets
result = search_by_smiles("Cc1ccc(NC(=O)c2ccc(CN3CCN(C)CC3)cc2)cc1Nc1nccc(-c2cccnc2)n1")
```

To query by a PubChem CID, first convert the CID to a SMILES string via PubChem
PUG-REST, then pass it to `search_by_smiles`. There is no by-name or by-CID
BindingDB REST endpoint.

### 4. Download-Based Analysis (Recommended for Large Queries)

For comprehensive analyses, download BindingDB data directly:

```python
import pandas as pd

def load_bindingdb(filepath="BindingDB_All.tsv"):
    """
    Load BindingDB TSV file (the unzipped BindingDB_All_<YYYYMM>.tsv).
    Download the dated BindingDB_All_<YYYYMM>_tsv.zip from:
    https://www.bindingdb.org/rwd/bind/chemsearch/marvin/Download.jsp
    """
    # Key columns
    usecols = [
        "BindingDB Reactant_set_id",
        "Ligand SMILES",
        "Ligand InChI",
        "Ligand InChI Key",
        "BindingDB Target Chain  Sequence",
        "PDB ID(s) for Ligand-Target Complex",
        "UniProt (SwissProt) Entry Name of Target Chain",
        "UniProt (SwissProt) Primary ID of Target Chain",
        "UniProt (TrEMBL) Primary ID of Target Chain",
        "Ki (nM)",
        "IC50 (nM)",
        "Kd (nM)",
        "EC50 (nM)",
        "kon (M-1-s-1)",
        "koff (s-1)",
        "Target Name",
        "Target Source Organism According to Curator or DataSource",
        "Number of Protein Chains in Target (>1 implies a multichain complex)",
        "PubChem CID",
        "PubChem SID",
        "ChEMBL ID of Ligand",
        "DrugBank ID of Ligand",
    ]

    # Exact TSV headers drift between monthly releases (some contain double
    # spaces), so intersect with the actual header rather than hard-failing.
    header = pd.read_csv(filepath, sep="\t", nrows=0).columns
    keep = [c for c in usecols if c in header]
    df = pd.read_csv(filepath, sep="\t", usecols=keep,
                     low_memory=False, on_bad_lines='skip')

    # Convert affinity columns to numeric
    for col in ["Ki (nM)", "IC50 (nM)", "Kd (nM)", "EC50 (nM)"]:
        if col in df.columns:
            df[col] = pd.to_numeric(df[col], errors='coerce')

    return df

def query_target_affinity(df, uniprot_id, affinity_types=None, max_nm=10000):
    """Query loaded BindingDB for a specific target."""
    if affinity_types is None:
        affinity_types = ["Ki (nM)", "IC50 (nM)", "Kd (nM)"]

    # Filter by UniProt ID
    mask = df["UniProt (SwissProt) Primary ID of Target Chain"] == uniprot_id
    target_df = df[mask].copy()

    # Filter by affinity cutoff
    has_affinity = pd.Series(False, index=target_df.index)
    for col in affinity_types:
        if col in target_df.columns:
            has_affinity |= target_df[col] <= max_nm

    result = target_df[has_affinity][["Ligand SMILES"] + affinity_types +
                                      ["PubChem CID", "ChEMBL ID of Ligand"]].dropna(how='all')
    return result.sort_values(affinity_types[0])
```

### 5. SAR Analysis

```python
import pandas as pd

def sar_analysis(df, target_uniprot, affinity_col="IC50 (nM)"):
    """
    Structure-activity relationship analysis for a target.
    Retrieves all compounds with affinity data and ranks by potency.
    """
    target_data = query_target_affinity(df, target_uniprot, [affinity_col])

    if target_data.empty:
        return target_data

    # Add pIC50 (negative log of IC50 in molar)
    if affinity_col in target_data.columns:
        target_data = target_data[target_data[affinity_col].notna()].copy()
        target_data["pAffinity"] = -((target_data[affinity_col] * 1e-9).apply(
            lambda x: __import__('math').log10(x)
        ))
        target_data = target_data.sort_values("pAffinity", ascending=False)

    return target_data

# Most potent compounds against EGFR (P00533)
# sar = sar_analysis(df, "P00533", "IC50 (nM)")
# print(sar.head(20))
```

### 6. Polypharmacology Profile

```python
def polypharmacology_profile(df, ligand_smiles, affinity_cutoff_nM=1000):
    """
    Find all targets a compound binds to, by exact SMILES match.
    For tolerance to tautomers/salts/charge states, match on the InChIKey
    skeleton (first 14 chars of "Ligand InChI Key") instead of raw SMILES.
    """
    # Search by ligand SMILES (exact string match)
    mask = df["Ligand SMILES"] == ligand_smiles

    ligand_data = df[mask].copy()

    # Filter by affinity
    aff_cols = ["Ki (nM)", "IC50 (nM)", "Kd (nM)"]
    has_aff = pd.Series(False, index=ligand_data.index)
    for col in aff_cols:
        if col in ligand_data.columns:
            has_aff |= ligand_data[col] <= affinity_cutoff_nM

    result = ligand_data[has_aff][
        ["Target Name", "UniProt (SwissProt) Primary ID of Target Chain"] + aff_cols
    ].dropna(how='all')

    # Rank by the tightest measured constant per row (NaNs ignored)
    result = result.assign(best_nM=result[aff_cols].min(axis=1))
    return result.sort_values("best_nM")
```

## Query Workflows

### Workflow 1: Find Best Inhibitors for a Target

```python
import pandas as pd

def find_best_inhibitors(uniprot_id, affinity_type="IC50 (nM)", top_n=20):
    """Find the most potent inhibitors for a target in BindingDB."""
    df = load_bindingdb("BindingDB_All.tsv")  # Load once and reuse
    result = query_target_affinity(df, uniprot_id, [affinity_type])

    if result.empty:
        print(f"No data found for {uniprot_id}")
        return result

    result = result.sort_values(affinity_type).head(top_n)
    print(f"Top {top_n} inhibitors for {uniprot_id} by {affinity_type}:")
    for _, row in result.iterrows():
        print(f"  {row['PubChem CID']}: {row[affinity_type]:.1f} nM | SMILES: {row['Ligand SMILES'][:40]}...")
    return result
```

### Workflow 2: Selectivity Profiling

1. Get all affinity data for your compound across all targets
2. Compare affinity ratios between on-target and off-targets
3. Identify selectivity cliffs (structural changes that improve selectivity)
4. Cross-reference with ChEMBL for additional selectivity data

### Workflow 3: Machine Learning Dataset Preparation

```python
def prepare_ml_dataset(df, uniprot_ids, affinity_col="IC50 (nM)",
                        max_affinity_nM=100000, min_count=50):
    """Prepare BindingDB data for ML model training."""
    records = []
    for uid in uniprot_ids:
        target_df = query_target_affinity(df, uid, [affinity_col], max_affinity_nM)
        if len(target_df) >= min_count:
            target_df = target_df.copy()
            target_df["target"] = uid
            records.append(target_df)

    if not records:
        return pd.DataFrame()

    combined = pd.concat(records)
    # Add pAffinity (normalized)
    combined["pAffinity"] = -((combined[affinity_col] * 1e-9).apply(
        lambda x: __import__('math').log10(max(x, 1e-12))
    ))
    return combined[["Ligand SMILES", "target", "pAffinity", affinity_col]].dropna()
```

## Key Data Fields

| Field | Description |
|-------|-------------|
| `Ligand SMILES` | 2D structure of the compound |
| `Ligand InChI Key` | Unique chemical identifier |
| `Ki (nM)` | Inhibition constant (equilibrium, functional) |
| `Kd (nM)` | Dissociation constant (thermodynamic, binding) |
| `IC50 (nM)` | Half-maximal inhibitory concentration |
| `EC50 (nM)` | Half-maximal effective concentration |
| `kon (M-1-s-1)` | Association rate constant |
| `koff (s-1)` | Dissociation rate constant |
| `UniProt (SwissProt) Primary ID` | Target UniProt accession |
| `Target Name` | Protein name |
| `PDB ID(s) for Ligand-Target Complex` | Crystal structures |
| `PubChem CID` | PubChem compound ID |
| `ChEMBL ID of Ligand` | ChEMBL compound ID |

## Affinity Interpretation

| Affinity | Classification | Drug-likeness |
|----------|---------------|---------------|
| < 1 nM | Sub-nanomolar | Very potent (picomolar range) |
| 1–10 nM | Nanomolar | Potent, typical for approved drugs |
| 10–100 nM | Moderate | Common lead compounds |
| 100–1000 nM | Weak | Fragment/starting point |
| > 1000 nM | Very weak | Generally below drug-relevance threshold |

## Best Practices

- **Use Ki for direct binding**: Ki reflects true binding affinity independent of enzymatic mechanism
- **IC50 context-dependency**: IC50 values depend on substrate concentration (Cheng-Prusoff equation)
- **Watch for qualifier prefixes**: TSV affinity cells often carry `>`, `<`, or `>=` prefixes (e.g. `>10000`) for censored measurements. `pd.to_numeric(errors='coerce')` silently turns these into NaN — strip the prefix first (e.g. `df[col].astype(str).str.lstrip("<>= ")`) and decide explicitly whether to keep, drop, or treat censored values as inequalities before modeling
- **Normalize units**: BindingDB reports in nM; verify units when comparing across studies
- **Filter by target organism**: Use `Target Source Organism` to ensure human protein data
- **Handle missing values**: Not all compounds have all measurement types
- **Cross-reference with ChEMBL**: ChEMBL has more curated activity data for medicinal chemistry

## Additional Resources

- **BindingDB website**: https://www.bindingdb.org/
- **Data downloads**: https://www.bindingdb.org/rwd/bind/chemsearch/marvin/Download.jsp
- **REST API documentation**: https://www.bindingdb.org/rwd/bind/BindingDBRESTfulAPI.jsp (REST base: https://bindingdb.org/rest)
- **Citation**: Gilson MK et al. "BindingDB in 2015." Nucleic Acids Research 2016;44(D1):D1045-53. PMID: 26481362, doi:10.1093/nar/gkv1072
- **Related resources**: ChEMBL (https://www.ebi.ac.uk/chembl/), PubChem BioAssay

## Scripts

`scripts/query_bindingdb.py` — runnable helper for the BindingDB REST API (no key):

```bash
python scripts/query_bindingdb.py uniprot P00519 --cutoff 10000
python scripts/query_bindingdb.py pdb 1Q0L,3ANM --cutoff 100 --identity 92
python scripts/query_bindingdb.py compound "<SMILES>" --cutoff 0.85
```

More from AlterLab-IEU/AlterLab-Academic-Skills

SkillDescription
alterlab-abm-mesaBuilds agent-based models of social systems with Mesa 3 — the current AgentSet API (model.agents.shuffle_do('step'), auto-assigned unique_id, mandatory super().__init__(seed=...)), cell spaces (mesa.discrete_space OrthogonalMooreGrid / classic mesa.space grids), the DataCollector, batch_run parameter sweeps, and SolaraViz — for emergence, segregation, diffusion, opinion dynamics, and cooperation models. It uses the Mesa 3.x API (the old mesa.time schedulers like RandomActivation are removed) and treats the model as a generative theory to be validated, not just run. Use when the request mentions an agent-based model, Mesa, simulating interacting agents, or emergent macro behavior from micro rules. For discrete-event (queueing/process) simulation prefer alterlab-simpy; for reinforcement learning prefer alterlab-stable-baselines3. Part of the AlterLab Academic Skills suite.
alterlab-academic-careerPrepares academic career documents and professional-development materials for faculty and researchers. Use when drafting academic CVs, research statements, teaching philosophies, diversity statements, faculty-position cover letters, tenure dossiers, promotion narratives, academic portfolios, or mentorship statements, and when planning conference-networking strategy, building academic web presence, setting up ORCID profiles, or understanding impact metrics. Part of the AlterLab Academic Skills suite.
alterlab-accreditation-aolScaffolds program-level Assurance-of-Learning (AoL) documentation for AACSB (2020 Standard 5) and ABET (Criterion 3 Student Outcomes, Criterion 4 Continuous Improvement) accreditation — program learning outcomes / competency goals, curriculum-to-outcome mapping matrices, direct- and indirect-assessment plans, rubric design, and closing-the-loop continuous-improvement narratives — and validates the structure of an outcome-mapping matrix with scripts/aol_matrix.py. Use when the user needs AACSB or ABET assurance-of-learning material, a program-learning-outcomes set, a curriculum/outcome map or coverage matrix, a direct/indirect assessment plan, a closing-the-loop report, or accreditation self-study text. For single-course design or course rubrics prefer alterlab-teaching-design; for post-award grant reports prefer alterlab-grant-reporting. Part of the AlterLab Academic Skills suite.
alterlab-adaptyvSubmits and tracks protein-testing experiments on the Adaptyv Bio Foundry cloud lab (wet-lab validation), and optimizes protein sequences before submission with computational tools (NetSolP, SoluProt, SolubleMPNN, ESM). Use when designing proteins that need wet-lab validation - binding/affinity screening, expression testing, thermostability, or fluorescence assays - or when submitting experiments to the Foundry API, browsing the target catalog, tracking experiment status, retrieving results, or pre-screening sequences for solubility/expression. Triggers on "Adaptyv", "Foundry API", "cloud lab", "biolayer interferometry / BLI", "wet-lab validation". Part of the AlterLab Academic Skills suite.
alterlab-aeonRuns time series machine learning with the aeon library — classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search via scikit-learn compatible APIs. Use when working with temporal data, sequential patterns, or time-indexed observations (univariate or multivariate) that need specialized algorithms beyond standard ML approaches. Part of the AlterLab Academic Skills suite.
alterlab-akademik-tesvikComputes the annual Turkish academic-incentive (akademik teşvik) score for Devlet (state) university öğretim elemanı (academic staff) from a classified activity list, applying the verified Akademik Teşvik Ödeneği Yönetmeliği (2018/11834) Faaliyet Hesaplama Tablosu headline puanları (Proje 20, Araştırma 15, Yayın 30, Patent 30, Atıf 30, Tebliğ 20, Ödül 20) with the k (author-count), p (Q1 1/Q2 0.8/Q3 0.5/Q4 0.25), and r (project-role) coefficients via türü puanı = Σ(faaliyet oranları) × headline (MADDE 8/2), then enforcing the per-type headline ceilings, the 100 cap (MADDE 8/3), and the net-30 payment gate (MADDE 10/3) in a deterministic scripts/tesvik_score.py. Use when the user wants to calculate akademik teşvik puanı, check the en az 30 (net-30) threshold, apply TABLO 4 ceilings, or estimate teşvik eligibility; keeps its coefficients separate from doçentlik scoring. For doçentlik point eligibility prefer alterlab-docentlik-eligibility. Part of the AlterLab Academic Skills suite.
alterlab-alpha-vantageAccesses real-time and historical stock market data, forex rates, cryptocurrency prices, commodities, economic indicators, and 50+ technical indicators via the Alpha Vantage API (requires a free API key from alphavantage.co). Use when fetching stock prices (OHLCV), company fundamentals (income statement, balance sheet, cash flow), earnings, options data, market news/sentiment, insider transactions, GDP, CPI, treasury yields, gold/silver/oil prices, Bitcoin/crypto prices, forex exchange rates, or calculating technical indicators (SMA, EMA, MACD, RSI, Bollinger Bands). Part of the AlterLab Academic Skills suite.
alterlab-alphafoldPredict protein 3D structures with AlphaFold2 via ColabFold — MMseqs2-accelerated MSAs, monomer and AlphaFold2-Multimer complex folding, and confidence-based validation (pLDDT, pTM/ipTM, PAE). Use when folding a protein sequence or complex from FASTA, generating a predicted structure with confidence metrics, ranking models, or checking self-consistency of a design. For co-folding a protein WITH a small-molecule ligand or predicting binding affinity prefer alterlab-boltz; for antibody–antigen or one-FASTA multi-entity complexes prefer alterlab-chai; to LOOK UP an already-computed structure prefer alterlab-alphafold-db; for ESM embeddings or inverse folding prefer alterlab-esm. Part of the AlterLab Academic Skills suite.
alterlab-alphafold-dbAccess the AlphaFold DB of 200M+ AI-PREDICTED protein structures — retrieve models by UniProt accession, download PDB/mmCIF files, and analyze prediction confidence metrics (pLDDT, PAE). Use when a UniProt ID needs a computationally predicted 3D structure or when no experimental structure exists, for homology modeling, protein engineering, or structure-based drug discovery; for EXPERIMENTALLY determined structures (X-ray, cryo-EM, NMR) prefer alterlab-pdb, and for protein sequences, annotations, or accession ID mapping prefer alterlab-uniprot instead. Part of the AlterLab Academic Skills suite.
alterlab-anndataBuild, slice, concatenate, read, and write AnnData annotated data matrices (obs, var, X, layers, obsm, uns) — the scverse data STRUCTURE, not an analysis pipeline. Use when creating or wrangling .h5ad/zarr files, managing cell and gene annotations, concatenating batches, or handling layers/obsm/backed-mode; for the QC, normalization, clustering, UMAP, and differential-expression analysis pipeline prefer alterlab-scanpy instead, and for RNA velocity from spliced/unspliced layers prefer alterlab-scvelo instead. Part of the AlterLab Academic Skills suite.