[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M73K4PH5ANKFVJZTNQHMQWPD":3,"skill-same:01M73K4PH5ANKFVJZTNQHMQWPD":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M73K4PH5ANKFVJZTNQHMQWPD","unichem-database",null,"Cross-reference compound IDs across 20+ databases (ChEMBL, DrugBank, PubChem, ChEBI, PDB, SureChEMBL, HMDB, DrugCentral, BindingDB) via UniChem REST API. Resolve InChIKeys to source IDs, translate between source-specific IDs, find structurally related compounds by connectivity. POST with a JSON body for all cross-reference queries; only \u002Fsources is GET. No auth required.","bg-szy\u002FTOP-SKILLS","bg-szy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106576190?v=4","01M73A4E8KPV67SFXRY8XZGNBX","ShuZhiyong","01M73A4E96MQ294MHM74TZBVQD",6,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Funichem-database\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: \"unichem-database\"\ndescription: \"Cross-reference compound IDs across 20+ databases (ChEMBL, DrugBank, PubChem, ChEBI, PDB, SureChEMBL, HMDB, DrugCentral, BindingDB) via UniChem REST API. Resolve InChIKeys to source IDs, translate between source-specific IDs, find structurally related compounds by connectivity. POST with a JSON body for all cross-reference queries; only \u002Fsources is GET. No auth required.\"\nlicense: \"Apache-2.0\"\n---\n\n# UniChem Database\n\n## Overview\n\nUniChem is a chemical structure cross-referencing service from EMBL-EBI that links compound records across 20+ public chemistry databases using InChI-based identifiers.\nIt maps a single chemical entity to its corresponding IDs in ChEMBL, DrugBank, PubChem, ChEBI, PDB (RCSB and PDBe), SureChEMBL, HMDB, DrugCentral, BindingDB, and others.\nAccess is via a free REST API at https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\u002F - no API key required.\nImportant: every cross-reference query is sent as POST with a JSON body; only the catalogue endpoint GET \u002Fsources is implemented as a GET.\n\n## When to Use\n\n- Translating a ChEMBL compound ID to a PubChem CID, DrugBank accession, or ChEBI ID for cross-database analysis\n- Resolving an InChIKey to all database sources where a compound appears\n- Finding all structurally related compounds (same connectivity, different stereochemistry\u002Fsalts) across databases using connectivity search\n- Validating compound identity across sources before merging datasets from multiple databases\n- Building a compound cross-reference table for a drug discovery project (linking bioactivity data in ChEMBL to structural data in PDB)\n- Checking if a synthesized compound or a vendor compound exists in any public database by InChIKey\n- For full bioactivity profiles (IC50, Ki) use chembl-database-bioactivity; UniChem provides only ID cross-references, not experimental data\n- For compound property prediction or substructure searching use pubchem-compound-search; UniChem is for identifier translation only\n\n## Prerequisites\n\n- **Python packages**: requests, pandas, matplotlib\n- **Data requirements**: compound InChIKeys (standard 27-character XXXXXXXXXXXXXX-XXXXXXXXXX-X), source-specific IDs (e.g. CHEMBL25), or PubChem CIDs as starting points\n- **Environment**: internet connection; no API key required\n- **Rate limits**: ~10 requests\u002Fsecond; add time.sleep(0.1) between requests in batch loops; no daily quota\n\n```bash\npip install requests pandas matplotlib\n```\n\n## Quick Start\n\nThe UniChem \u002Fcompounds endpoint is POST-only - GET returns 405 Method Not Allowed. Submit a JSON body {type: inchikey, compound: KEY} and read per-database hits from compounds[0][sources]. Each source record carries an id (numeric database ID) and a compoundId (the ID in that database).\n\n```python\nimport requests\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\n\ndef unichem_post(endpoint: str, body: dict) -> dict:\n    \"\"\"POST request to UniChem API; raise on HTTP errors.\"\"\"\n    r = requests.post(f\"{UNICHEM_API}\u002F{endpoint}\", json=body, timeout=20)\n    r.raise_for_status()\n    return r.json()\n\n# Find all database sources for aspirin by InChIKey\ninchikey = \"BSYNRYMUTXBXSQ-UHFFFAOYSA-N\"  # aspirin\nresult = unichem_post(\"compounds\", {\"type\": \"inchikey\", \"compound\": inchikey})\ncompounds = result.get(\"compounds\", [])\nprint(f\"Found {len(compounds)} compound record(s) for {inchikey}\")\nif compounds:\n    sources = compounds[0].get(\"sources\", [])\n    print(f\"  Present in {len(sources)} database records\")\n    seen = set()\n    for src in sources:\n        if src[\"id\"] in seen:\n            continue\n        seen.add(src[\"id\"])\n        print(f\"  source id={src['id']:>3} ({src['shortName']:>12}): {src['compoundId']}\")\n        if len(seen) >= 5:\n            break\n# Found 1 compound record(s) for BSYNRYMUTXBXSQ-UHFFFAOYSA-N\n#   Present in many database records\n#   source id=  1 (      chembl): CHEMBL25\n#   source id=  2 (    drugbank): DB00945\n#   source id=  3 (    rcsb_pdb): AIN\n```\n\n## Core API\n\n### Query 1: InChIKey Lookup - All Sources\n\nSearch for a compound by its standard InChIKey and retrieve all database records. This is the primary cross-reference method. The endpoint is POST \u002Fcompounds; the response carries one entry in compounds (if found), each with a sources list whose records use id (source database) and compoundId (the ID in that database).\n\n```python\nimport requests, pandas as pd\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\n\n# Common source IDs (verify with the \u002Fsources endpoint - see Query 4)\nSOURCE_NAMES = {\n    1: \"ChEMBL\", 2: \"DrugBank\", 3: \"RCSB PDB\", 4: \"GtoPdb\", 5: \"PDBe\",\n    7: \"ChEBI\", 14: \"FDA SRS\", 15: \"SureChEMBL\", 18: \"HMDB\", 22: \"PubChem\",\n    31: \"BindingDB\", 32: \"CompTox\", 33: \"LIPID MAPS\", 34: \"DrugCentral\",\n    37: \"BRENDA\", 38: \"Rhea\", 41: \"SwissLipids\", 49: \"Probes-and-Drugs\",\n}\n\ndef lookup_by_inchikey(inchikey: str) -> pd.DataFrame:\n    \"\"\"Return all database cross-references for an InChIKey.\"\"\"\n    r = requests.post(f\"{UNICHEM_API}\u002Fcompounds\",\n                      json={\"type\": \"inchikey\", \"compound\": inchikey}, timeout=20)\n    r.raise_for_status()\n    compounds = r.json().get(\"compounds\", [])\n    if not compounds:\n        return pd.DataFrame()\n    rows = []\n    for src in compounds[0].get(\"sources\", []):\n        rows.append({\n            \"source_id\": src[\"id\"],\n            \"source_name\": SOURCE_NAMES.get(src[\"id\"], src.get(\"shortName\", \"\")),\n            \"compound_id\": src[\"compoundId\"],\n            \"url\": src.get(\"url\", \"\"),\n        })\n    return pd.DataFrame(rows).sort_values([\"source_id\", \"compound_id\"])\n\n# Triclosan cross-references\ndf = lookup_by_inchikey(\"XEFQLINVKFYRCS-UHFFFAOYSA-N\")\nprint(f\"Triclosan found in {df['source_id'].nunique()} distinct databases ({len(df)} records):\")\nprint(df[[\"source_name\", \"compound_id\"]].head(8).to_string(index=False))\n# Triclosan found in 16 distinct databases\n#   ChEMBL    CHEMBL849\n#   DrugBank  DB08604\n#   RCSB PDB  TCL\n#   ChEBI     CHEBI:164200\n```\n```python\n# Extract specific source IDs from cross-reference table\ndef get_id_for_source(inchikey: str, source_id: int) -> str | None:\n    \"\"\"Return the compound ID in a specific database, or None if not found.\"\"\"\n    r = requests.post(f\"{UNICHEM_API}\u002Fcompounds\",\n                      json={\"type\": \"inchikey\", \"compound\": inchikey}, timeout=20)\n    r.raise_for_status()\n    compounds = r.json().get(\"compounds\", [])\n    if not compounds:\n        return None\n    for src in compounds[0].get(\"sources\", []):\n        if src[\"id\"] == source_id:\n            return src[\"compoundId\"]\n    return None\n\ntriclosan = \"XEFQLINVKFYRCS-UHFFFAOYSA-N\"\nchembl_id   = get_id_for_source(triclosan, source_id=1)   # ChEMBL\npubchem_id  = get_id_for_source(triclosan, source_id=22)  # PubChem\ndrugbank_id = get_id_for_source(triclosan, source_id=2)   # DrugBank\nprint(f\"Triclosan: ChEMBL={chembl_id}, PubChem={pubchem_id}, DrugBank={drugbank_id}\")\n# Triclosan: ChEMBL=CHEMBL849, PubChem=5564, DrugBank=DB08604\n```\n\n### Query 2: Compound Lookup by Source-Specific ID\n\nGiven a known compound ID in a specific source database (e.g., a ChEMBL ID), retrieve all cross-references. Use type: sourceID with the compound s source ID alongside the numeric sourceID in the body. Returns the same data shape as the InChIKey lookup.\n\n```python\nimport requests\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\n\ndef get_sources_for_compound(compound_id: str, source_id: int) -> list:\n    \"\"\"Get all database cross-references for a compound identified in a specific source.\n\n    Args:\n        compound_id: The ID in the source database (e.g., CHEMBL192)\n        source_id: UniChem source ID (1=ChEMBL, 2=DrugBank, 22=PubChem, 7=ChEBI)\n    \"\"\"\n    body = {\"type\": \"sourceID\", \"compound\": compound_id, \"sourceID\": source_id}\n    r = requests.post(f\"{UNICHEM_API}\u002Fcompounds\", json=body, timeout=20)\n    r.raise_for_status()\n    compounds = r.json().get(\"compounds\", [])\n    if not compounds:\n        return []\n    return compounds[0].get(\"sources\", [])\n\n# Sildenafil (Viagra): look up starting from ChEMBL ID\nsources = get_sources_for_compound(\"CHEMBL192\", source_id=1)\ndistinct_dbs = {s[\"id\"] for s in sources}\nprint(f\"Sildenafil (CHEMBL192): {len(sources)} source records across {len(distinct_dbs)} databases\")\nseen = set()\nfor s in sources:\n    if s[\"id\"] in seen:\n        continue\n    seen.add(s[\"id\"])\n    print(f\"  [{s['id']:>3}] {s['shortName']:>15}: {s['compoundId']}\")\n    if len(seen) >= 8:\n        break\n# Sildenafil (CHEMBL192): 272 source records across 19 databases\n```\n\n### Query 3: Connectivity Search - Structural Relatives\n\nFind compounds with the same core structure but different stereochemistry, salt forms, isotopic labeling, or protonation. The endpoint is POST \u002Fconnectivity and accepts a full standard InChIKey (the API rejects 14-character fragments with 404 Not found). Internally UniChem uses the connectivity layer for matching but returns hits that may differ at the stereo\u002Fcharge\u002Fisotope layers.\n\nUnlike \u002Fcompounds, the connectivity response returns a flat sources list (one entry per database hit across all relatives) plus the queried searchedCompound and totalCompounds\u002FtotalSources summary fields. Each hit s comparison dict shows which InChI layers matched.\n\n```python\nimport requests, pandas as pd\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\n\ndef connectivity_search(inchikey: str) -> dict:\n    \"\"\"Find all compounds related by InChI connectivity (same skeleton, possibly different stereo\u002Fsalts).\n\n    Pass a FULL standard InChIKey (27 chars). The server rejects 14-char fragments.\n    \"\"\"\n    body = {\"type\": \"inchikey\", \"compound\": inchikey}\n    r = requests.post(f\"{UNICHEM_API}\u002Fconnectivity\", json=body, timeout=30)\n    r.raise_for_status()\n    return r.json()\n\n# Warfarin: find all stereoforms, racemates, and salt forms\nwarfarin_inchikey = \"PJVWKTKQMONHTI-UHFFFAOYSA-N\"\ndata = connectivity_search(warfarin_inchikey)\nprint(f\"Warfarin connectivity relatives: {data['totalCompounds']} unique compounds, \"\n      f\"{data['totalSources']} database records\")\nhits = data.get(\"sources\", [])\nby_source = {}\nfor h in hits:\n    by_source.setdefault(h[\"shortName\"], []).append(h[\"compoundId\"])\nfor name, ids in sorted(by_source.items(), key=lambda kv: -len(kv[1]))[:8]:\n    print(f\"  {name:>15}: {len(ids):>4} IDs (e.g. {ids[0]})\")\n# Warfarin connectivity relatives: 13 unique compounds, 353 database records\n```\n```python\n# Compare source coverage across connectivity relatives\ndef compare_coverage(inchikey: str) -> pd.DataFrame:\n    \"\"\"Show connectivity relatives split by their source-database coverage.\"\"\"\n    data = connectivity_search(inchikey)\n    rows = []\n    for src in data.get(\"sources\", []):\n        rows.append({\n            \"source_id\":    src[\"id\"],\n            \"source_name\":  src[\"shortName\"],\n            \"compound_id\":  src[\"compoundId\"],\n            \"stereo_match\": src[\"comparison\"].get(\"stereoSp3\", False),\n            \"salt_match\":   src[\"comparison\"].get(\"protonation\", False),\n        })\n    return pd.DataFrame(rows)\n\ndf = compare_coverage(\"PJVWKTKQMONHTI-UHFFFAOYSA-N\")\nprint(f\"Total records: {len(df)}\")\nprint(df.head(10).to_string(index=False))\nprint(f\"Records with stereo mismatch (skeleton matches, stereo differs): {(~df['stereo_match']).sum()}\")\n```\n\n### Query 4: List All Data Sources\n\nRetrieve the full list of UniChem data sources with their IDs, names, descriptions, and website URLs. This is the only endpoint served by GET. The response uses sourceID (capital ID) inside each source entry.\n\n```python\nimport requests, pandas as pd\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\n\ndef list_sources() -> pd.DataFrame:\n    \"\"\"Return all UniChem data sources as a DataFrame.\"\"\"\n    r = requests.get(f\"{UNICHEM_API}\u002Fsources\", timeout=15)\n    r.raise_for_status()\n    sources = r.json().get(\"sources\", [])\n    rows = []\n    for s in sources:\n        rows.append({\n            \"source_id\":  s[\"sourceID\"],\n            \"name\":       s.get(\"nameLong\") or s.get(\"nameLabel\", \"\"),\n            \"label\":      s.get(\"nameLabel\", \"\"),\n            \"short_name\": s.get(\"name\", \"\"),\n            \"uci_count\":  s.get(\"UCICount\"),\n            \"url\":        s.get(\"baseIdUrl\", \"\"),\n        })\n    return pd.DataFrame(rows).sort_values(\"source_id\")\n\nsources_df = list_sources()\nprint(f\"Total UniChem sources: {len(sources_df)}\")\nprint(sources_df[[\"source_id\", \"label\", \"uci_count\"]].to_string(index=False))\n# Total UniChem sources: 23\n#   1   ChEMBL          2854815\n#   2   DrugBank          14622\n#  22   PubChem      123392679\n```\n\n### Query 5: Per-Compound Loop (No Batch Endpoint)\n\nUniChem does not support a list-batch shape - the \u002Fcompounds POST accepts only a single compound per request. Submitting {compounds: [...]} or {inchikeys: [...]} returns 400 illegal_argument_exception. For multiple inputs, iterate with a small sleep to respect the ~10 req\u002Fs rate limit.\n\n```python\nimport requests, time, pandas as pd\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\n\ndef batch_translate(inchikeys: list[str],\n                    target_source_ids=(1, 2, 7, 22)) -> pd.DataFrame:\n    \"\"\"Translate a list of InChIKeys to IDs in multiple target databases.\n\n    Loops one POST per InChIKey (UniChem has no list-batch endpoint).\n    \"\"\"\n    SOURCE_NAMES = {1: \"chembl\", 2: \"drugbank\", 3: \"pdb\", 7: \"chebi\",\n                    14: \"fda_srs\", 22: \"pubchem\", 34: \"drugcentral\"}\n    rows = []\n    for ik in inchikeys:\n        row = {\"inchikey\": ik}\n        for sid in target_source_ids:\n            row[SOURCE_NAMES.get(sid, f\"src_{sid}\")] = None\n        try:\n            r = requests.post(f\"{UNICHEM_API}\u002Fcompounds\",\n                              json={\"type\": \"inchikey\", \"compound\": ik}, timeout=20)\n            r.raise_for_status()\n            compounds = r.json().get(\"compounds\", [])\n            if compounds:\n                for src in compounds[0].get(\"sources\", []):\n                    if src[\"id\"] in target_source_ids:\n                        col = SOURCE_NAMES.get(src[\"id\"], f\"src_{src['id']}\")\n                        if row[col] is None:\n                            row[col] = src[\"compoundId\"]\n        except requests.RequestException as e:\n            row[\"error\"] = str(e)\n        rows.append(row)\n        time.sleep(0.1)  # respect ~10 req\u002Fs rate limit\n    return pd.DataFrame(rows)\n\n# Translate a set of NSAIDs by InChIKey\nnsaid_inchikeys = [\n    \"BSYNRYMUTXBXSQ-UHFFFAOYSA-N\",  # aspirin\n    \"HEFNNWSXXWATRW-UHFFFAOYSA-N\",  # ibuprofen\n    \"CMWTZPSULFXXJA-VIFPVBQESA-N\",  # naproxen\n    \"DCOPUUMXTXDBNB-UHFFFAOYSA-N\",  # diclofenac (free acid)\n]\ndf = batch_translate(nsaid_inchikeys, target_source_ids=[1, 2, 7, 22])\nprint(df.to_string(index=False))\ndf.to_csv(\"nsaid_xrefs.csv\", index=False)\nprint(f\"Saved nsaid_xrefs.csv ({len(df)} compounds)\")\n```\n\n### Query 6: Per-Compound Loop with Source-ID Inputs\n\nWhen the starting identifiers are not InChIKeys but source-specific IDs (e.g., a list of ChEMBL IDs from a bioactivity table), use type=sourceID and loop, again one POST per ID.\n\n```python\nimport requests, time\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\n\ndef translate_source_ids(ids: list[str], from_source: int,\n                         to_sources=(2, 22, 34)) -> list[dict]:\n    \"\"\"Translate IDs in one source database to IDs in target databases.\n\n    Args:\n        ids: list of compound IDs in the from_source database\n        from_source: source ID of the input list (1=ChEMBL, 22=PubChem, ...)\n        to_sources: iterable of target source IDs to extract\n    \"\"\"\n    out = []\n    for cid in ids:\n        body = {\"type\": \"sourceID\", \"compound\": cid, \"sourceID\": from_source}\n        r = requests.post(f\"{UNICHEM_API}\u002Fcompounds\", json=body, timeout=20)\n        row = {\"input\": cid}\n        if r.ok:\n            compounds = r.json().get(\"compounds\", [])\n            if compounds:\n                row[\"inchikey\"] = compounds[0].get(\"standardInchiKey\")\n                hits = {s[\"id\"]: s[\"compoundId\"] for s in compounds[0].get(\"sources\", [])}\n                for tsid in to_sources:\n                    row[f\"src_{tsid}\"] = hits.get(tsid)\n        out.append(row)\n        time.sleep(0.1)\n    return out\n\n# Three kinase inhibitors known by ChEMBL ID\nchembl_inputs = [\"CHEMBL535\", \"CHEMBL553\", \"CHEMBL941\"]  # nilotinib, dasatinib, imatinib\nrows = translate_source_ids(chembl_inputs, from_source=1, to_sources=(2, 22, 34))\nfor row in rows:\n    ik = (row.get(\"inchikey\") or \"?\")[:14]\n    print(f\"{row['input']:>10}  ik={ik}...  \"\n          f\"DrugBank={row.get('src_2')}, PubChem={row.get('src_22')}, \"\n          f\"DrugCentral={row.get('src_34')}\")\n```\n\n## Key Concepts\n\n### InChI vs InChIKey\n\nUniChem uses the **InChI** (IUPAC International Chemical Identifier) and its hashed form the **InChIKey** as the canonical compound identity. The InChIKey is a 27-character string split into three blocks: the first 14 characters encode the connectivity layer (heavy atoms and bonds), the next 8 encode stereochemistry and charge, and the last character is a version flag. UniChem cross-references compounds by requiring identical standard InChIKeys, ensuring the same chemical entity across databases.\n\n### Source ID Reference Table (verified live against \u002Fsources)\n\n| Source ID | Database | Scope |\n|-----------|----------|-------|\n| 1  | ChEMBL          | Bioactive molecules, drug discovery |\n| 2  | DrugBank        | Approved drugs, pharmacology |\n| 3  | RCSB PDB        | Ligands in crystal structures (US) |\n| 4  | Guide to Pharmacology | Pharmacology targets\u002Fligands |\n| 5  | PDBe            | Ligands in crystal structures (Europe) |\n| 7  | ChEBI           | Chemical ontology, metabolites |\n| 14 | FDA SRS         | FDA Substance Registration System |\n| 15 | SureChEMBL      | Patent chemistry |\n| 18 | HMDB            | Human Metabolome Database |\n| 22 | PubChem         | General compound repository |\n| 31 | BindingDB       | Binding affinity data |\n| 32 | CompTox         | Environmental tox dashboard |\n| 33 | LIPID MAPS      | Lipid structures |\n| 34 | DrugCentral     | Approved drugs + pharmacology |\n| 37 | BRENDA          | Enzyme substrates\u002Fproducts |\n| 38 | Rhea            | Biochemical reactions |\n| 41 | SwissLipids     | Lipid structures |\n| 49 | Probes-and-Drugs| Chemical probes |\n\n### Field Naming: id vs sourceID\n\nThis is the single most common error when scripting UniChem. The two endpoints use different field names for the source database identifier:\n\n- **GET \u002Fsources** lists databases as objects with a **sourceID** field (capital ID).\n- **POST \u002Fcompounds** and **POST \u002Fconnectivity** return per-database hits inside sources lists, where the source identifier is a plain **id** field. There is no sourceID or sourceId key on these per-hit records.\n\nAlways use src[\"id\"] when iterating compound or connectivity responses, and use s[\"sourceID\"] when iterating the \u002Fsources catalogue.\n\n### Connectivity vs Standard InChIKey Matching\n\nPOST \u002Fcompounds returns exact InChIKey matches (same stereo, salt, isotopes). POST \u002Fconnectivity returns all compounds sharing the bond topology - useful for finding racemates, stereoisomers, free acids\u002Fbases, and co-crystal partners. The connectivity response includes a comparison dict per hit indicating which InChI layers matched (stereoSp3, protonation, isotope, etc.); use it to filter for same skeleton, different stereo only relatives.\n\n## Common Workflows\n\n### Workflow 1: Drug Compound Cross-Reference Report\n\n**Goal**: Given a list of drug names (or ChEMBL IDs), resolve each to all major database IDs and export to CSV.\n\n```python\nimport requests, time, pandas as pd\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\nCHEMBL_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Fchembl\u002Fapi\u002Fdata\"\n\nSOURCE_NAMES = {1: \"chembl\", 2: \"drugbank\", 3: \"rcsb_pdb\",\n                7: \"chebi\", 22: \"pubchem\", 14: \"fda_srs\", 34: \"drugcentral\"}\n\ndef chembl_to_inchikey(chembl_id: str) -> str | None:\n    \"\"\"Look up the standard InChIKey for a ChEMBL compound ID.\"\"\"\n    r = requests.get(f\"{CHEMBL_API}\u002Fmolecule\u002F{chembl_id}.json\", timeout=15)\n    if r.status_code == 404:\n        return None\n    r.raise_for_status()\n    return r.json().get(\"molecule_structures\", {}).get(\"standard_inchi_key\")\n\ndef inchikey_to_sources(inchikey: str) -> dict:\n    \"\"\"Return source_id -> compound_id dict for an InChIKey (first hit per source).\"\"\"\n    r = requests.post(f\"{UNICHEM_API}\u002Fcompounds\",\n                      json={\"type\": \"inchikey\", \"compound\": inchikey}, timeout=20)\n    r.raise_for_status()\n    compounds = r.json().get(\"compounds\", [])\n    if not compounds:\n        return {}\n    out = {}\n    for s in compounds[0].get(\"sources\", []):\n        out.setdefault(s[\"id\"], s[\"compoundId\"])\n    return out\n\n# Example: top cardiovascular drugs\ndrug_chembl_ids = {\n    \"atorvastatin\": \"CHEMBL1487\",\n    \"lisinopril\":   \"CHEMBL1237\",\n    \"metoprolol\":   \"CHEMBL13\",\n    \"amlodipine\":   \"CHEMBL1491\",\n    \"warfarin\":     \"CHEMBL1464\",\n}\n\nrows = []\nfor name, chembl_id in drug_chembl_ids.items():\n    ik = chembl_to_inchikey(chembl_id)\n    row = {\"drug\": name, \"chembl_id\": chembl_id, \"inchikey\": ik}\n    if ik:\n        srcs = inchikey_to_sources(ik)\n        for sid, col in SOURCE_NAMES.items():\n            row[col] = srcs.get(sid)\n    rows.append(row)\n    time.sleep(0.2)\n\ndf = pd.DataFrame(rows)\ndf.to_csv(\"drug_xrefs.csv\", index=False)\nprint(df[[\"drug\", \"chembl\", \"drugbank\", \"pubchem\", \"chebi\"]].to_string(index=False))\nprint(f\"Saved drug_xrefs.csv ({len(df)} drugs)\")\n```\n\n### Workflow 2: Structural Relatives Discovery and Visualization\n\n**Goal**: Find all structural relatives of a compound, summarize their database coverage, and plot a bar chart showing source distribution.\n\n```python\nimport requests, pandas as pd\nimport matplotlib.pyplot as plt\nfrom collections import Counter\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\n\nSOURCE_NAMES = {1: \"ChEMBL\", 2: \"DrugBank\", 3: \"RCSB PDB\", 5: \"PDBe\",\n                7: \"ChEBI\", 14: \"FDA SRS\", 15: \"SureChEMBL\",\n                22: \"PubChem\", 31: \"BindingDB\", 34: \"DrugCentral\"}\n\n# Aspirin connectivity relatives (covers acetylsalicylate salts)\nquery_inchikey = \"BSYNRYMUTXBXSQ-UHFFFAOYSA-N\"\n\nr = requests.post(f\"{UNICHEM_API}\u002Fconnectivity\",\n                  json={\"type\": \"inchikey\", \"compound\": query_inchikey}, timeout=30)\nr.raise_for_status()\ndata = r.json()\nhits = data.get(\"sources\", [])\nprint(f\"Aspirin connectivity relatives: {data['totalCompounds']} unique compounds, \"\n      f\"{len(hits)} database records\")\n\n# Count how often each named database appears\nsource_counter = Counter()\nfor h in hits:\n    if h[\"id\"] in SOURCE_NAMES:\n        source_counter[SOURCE_NAMES[h[\"id\"]]] += 1\n\nlabels = [k for k, _ in source_counter.most_common()]\ncounts = [v for _, v in source_counter.most_common()]\n\nfig, ax = plt.subplots(figsize=(9, 4))\nbars = ax.bar(labels, counts, color=\"#2E86AB\", edgecolor=\"white\")\nax.bar_label(bars, padding=2)\nax.set_xlabel(\"Database\")\nax.set_ylabel(\"Number of Source Records (relatives x hits)\")\nax.set_title(\"UniChem Connectivity Records - Aspirin Skeleton\")\nplt.xticks(rotation=30, ha=\"right\")\nplt.tight_layout()\nplt.savefig(\"unichem_connectivity_coverage.png\", dpi=150, bbox_inches=\"tight\")\nprint(\"Saved unichem_connectivity_coverage.png\")\nplt.close(fig)\n\n# DataFrame summary by source\ndf = pd.DataFrame(source_counter.most_common(), columns=[\"database\", \"records\"])\nprint(df.to_string(index=False))\n```\n\n### Workflow 3: Merge ChEMBL Bioactivity with PubChem CIDs\n\n**Goal**: Augment a ChEMBL bioactivity table with PubChem CIDs for downstream analysis in tools that use PubChem identifiers.\n\n```python\nimport requests, time, pandas as pd\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\n\ndef add_pubchem_cids(df: pd.DataFrame,\n                     inchikey_col: str = \"standard_inchi_key\") -> pd.DataFrame:\n    \"\"\"Add pubchem_cid column to a DataFrame that has an InChIKey column.\"\"\"\n    unique_keys = df[inchikey_col].dropna().unique()\n    mapping = {}\n    for ik in unique_keys:\n        try:\n            r = requests.post(f\"{UNICHEM_API}\u002Fcompounds\",\n                              json={\"type\": \"inchikey\", \"compound\": ik}, timeout=15)\n            r.raise_for_status()\n            compounds = r.json().get(\"compounds\", [])\n            if compounds:\n                for src in compounds[0].get(\"sources\", []):\n                    if src[\"id\"] == 22:  # PubChem\n                        mapping[ik] = src[\"compoundId\"]\n                        break\n        except requests.RequestException:\n            pass\n        time.sleep(0.1)\n    df = df.copy()\n    df[\"pubchem_cid\"] = df[inchikey_col].map(mapping)\n    return df\n\n# Simulate a small ChEMBL activity table\nchembl_data = pd.DataFrame({\n    \"compound_name\": [\"aspirin\", \"ibuprofen\", \"naproxen\"],\n    \"standard_inchi_key\": [\n        \"BSYNRYMUTXBXSQ-UHFFFAOYSA-N\",\n        \"HEFNNWSXXWATRW-UHFFFAOYSA-N\",\n        \"CMWTZPSULFXXJA-VIFPVBQESA-N\",\n    ],\n    \"ic50_nm\": [2500.0, 13000.0, 1600.0],\n})\n\nenriched = add_pubchem_cids(chembl_data)\nprint(enriched[[\"compound_name\", \"ic50_nm\", \"pubchem_cid\"]].to_string(index=False))\nenriched.to_csv(\"chembl_with_pubchem.csv\", index=False)\nprint(\"Saved chembl_with_pubchem.csv\")\n```\n\n## Key Parameters\n\n| Parameter | Endpoint | Default | Range \u002F Options | Effect |\n|-----------|----------|---------|-----------------|--------|\n| type (body) | POST \u002Fcompounds, POST \u002Fconnectivity | - | inchikey, sourceID | Selects the kind of identifier in compound. inchikey requires a 27-char standard InChIKey; sourceID also requires the numeric sourceID field. |\n| compound (body) | POST \u002Fcompounds, POST \u002Fconnectivity | - | One string (no list) | The identifier to look up. UniChem does NOT support a list-batch shape; loop one POST per compound. |\n| sourceID (body) | POST \u002Fcompounds (with type=sourceID) | - | Integer DB id from \u002Fsources | The source database the input compound belongs to (1=ChEMBL, 2=DrugBank, 22=PubChem, ...). |\n| Per-hit id (response) | POST \u002Fcompounds, POST \u002Fconnectivity | - | Integer | Source database id of each hit in sources. **Use src[\"id\"], NOT src[\"sourceID\"]** for these per-hit records. |\n| sourceID (response) | GET \u002Fsources | - | Integer | Numeric ID of each database entry in the catalogue (capital ID). |\n| timeout | All requests | 20s | Any positive integer | Seconds before request fails; raise to 30s for \u002Fconnectivity on common skeletons. |\n\n## Best Practices\n\n1. **Use POST everywhere except \u002Fsources**: GET \u002Fcompounds returns 405 Method Not Allowed; GET \u002Fcompounds\u002F{src}\u002F{id} and GET \u002Fconnectivity\u002F{key} return 404. The only GET endpoint is \u002Fsources. Always POST with a JSON body.\n\n2. **Use the correct field - id on hits, sourceID on \u002Fsources**: Inside the sources list returned by POST \u002Fcompounds and POST \u002Fconnectivity, each record s source database is in the id key. Reading src[\"sourceID\"] raises KeyError. The capital-ID sourceID field only appears in the catalogue returned by GET \u002Fsources.\n\n3. **Use standard (not non-standard) InChIKeys**: UniChem indexes standard InChIKeys. Non-standard InChIKeys will return no results. Verify with: from rdkit.Chem.inchi import MolToInchiKey; MolToInchiKey(mol).\n\n4. **Fall back to connectivity search when exact match fails**: If a compound is in DrugBank as a salt (e.g., hydrochloride) but you have the free base InChIKey, the standard lookup will miss it. Run a connectivity search as a fallback for drug cross-referencing.\n\n5. **Pass the full InChIKey to \u002Fconnectivity**: The endpoint expects a complete 27-character standard InChIKey. Submitting only the 14-char connectivity fragment returns {response: Not found}. UniChem strips the stereo\u002Fcharge layers internally.\n\n6. **Cache the source list on startup**: Call \u002Fsources once and build a {sourceID: nameLabel} dict rather than hard-coding IDs.\n\n```python\ndef load_source_map() -> dict:\n    r = requests.get(f\"{UNICHEM_API}\u002Fsources\", timeout=15)\n    r.raise_for_status()\n    return {s[\"sourceID\"]: s.get(\"nameLabel\", str(s[\"sourceID\"]))\n            for s in r.json().get(\"sources\", [])}\n```\n\n7. **No batch endpoint exists - loop with sleep**: Submitting {compounds: [...]} or {inchikeys: [...]} returns 400 illegal_argument_exception. Iterate POSTs with time.sleep(0.1) between calls (~10 req\u002Fs).\n\n## Common Recipes\n\n### Recipe: Resolve Any Compound ID to InChIKey\n\nWhen to use: You have a PubChem CID or ChEBI ID and need the InChIKey to query UniChem or other services.\n\n```python\nimport requests\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\nPUBCHEM_API = \"https:\u002F\u002Fpubchem.ncbi.nlm.nih.gov\u002Frest\u002Fpug\"\n\ndef pubchem_cid_to_inchikey(cid) -> str | None:\n    \"\"\"Resolve a PubChem CID to a standard InChIKey via PubChem.\"\"\"\n    r = requests.get(f\"{PUBCHEM_API}\u002Fcompound\u002Fcid\u002F{cid}\u002Fproperty\u002FInChIKey\u002FJSON\", timeout=10)\n    if r.status_code == 404:\n        return None\n    r.raise_for_status()\n    props = r.json()[\"PropertyTable\"][\"Properties\"]\n    return props[0][\"InChIKey\"] if props else None\n\ndef cid_to_all_sources(cid) -> list:\n    \"\"\"PubChem CID -> InChIKey -> UniChem cross-references.\"\"\"\n    ik = pubchem_cid_to_inchikey(cid)\n    if not ik:\n        return []\n    r = requests.post(f\"{UNICHEM_API}\u002Fcompounds\",\n                      json={\"type\": \"inchikey\", \"compound\": ik}, timeout=20)\n    r.raise_for_status()\n    compounds = r.json().get(\"compounds\", [])\n    return compounds[0].get(\"sources\", []) if compounds else []\n\nsources = cid_to_all_sources(2244)  # PubChem CID for aspirin\ndistinct = {s[\"id\"] for s in sources}\nprint(f\"Aspirin (CID=2244) is in {len(distinct)} UniChem databases ({len(sources)} records)\")\nseen = set()\nfor s in sources:\n    if s[\"id\"] in seen:\n        continue\n    seen.add(s[\"id\"])\n    print(f\"  [{s['id']:>3}] {s['shortName']:>15}: {s['compoundId']}\")\n    if len(seen) >= 6:\n        break\n```\n\n### Recipe: Check If a Compound Is an Approved Drug\n\nWhen to use: Quickly flag whether a compound appears in DrugBank (source 2) using its InChIKey.\n\n```python\nimport requests\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\n\ndef is_approved_drug(inchikey: str) -> tuple[bool, str | None]:\n    \"\"\"Check if compound appears in DrugBank (id=2). Returns (is_drug, DrugBank_ID).\"\"\"\n    r = requests.post(f\"{UNICHEM_API}\u002Fcompounds\",\n                      json={\"type\": \"inchikey\", \"compound\": inchikey}, timeout=20)\n    r.raise_for_status()\n    compounds = r.json().get(\"compounds\", [])\n    if not compounds:\n        return False, None\n    for src in compounds[0].get(\"sources\", []):\n        if src[\"id\"] == 2:  # DrugBank\n            return True, src[\"compoundId\"]\n    return False, None\n\n# Test a few compounds\ntest_compounds = {\n    \"aspirin\":      \"BSYNRYMUTXBXSQ-UHFFFAOYSA-N\",\n    \"triclosan\":    \"XEFQLINVKFYRCS-UHFFFAOYSA-N\",\n    \"sildenafil\":   \"BNRNXUUZRGQAQC-UHFFFAOYSA-N\",\n}\nfor name, ik in test_compounds.items():\n    is_drug, db_id = is_approved_drug(ik)\n    status = f\"DrugBank:{db_id}\" if is_drug else \"not in DrugBank\"\n    print(f\"{name:>12}: {status}\")\n```\n\n### Recipe: Source Coverage Summary for a Compound Set\n\nWhen to use: Audit which databases cover your compound list - useful before choosing which database to use for downstream analysis.\n\n```python\nimport requests, time, pandas as pd\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\nSOURCE_NAMES = {1: \"ChEMBL\", 2: \"DrugBank\", 3: \"RCSB PDB\", 7: \"ChEBI\",\n                14: \"FDA SRS\", 22: \"PubChem\", 34: \"DrugCentral\"}\n\ndef source_coverage_matrix(inchikeys: list[str]) -> pd.DataFrame:\n    \"\"\"Return a boolean matrix: rows=compounds, columns=databases.\"\"\"\n    rows = []\n    for ik in inchikeys:\n        r = requests.post(f\"{UNICHEM_API}\u002Fcompounds\",\n                          json={\"type\": \"inchikey\", \"compound\": ik}, timeout=15)\n        row = {\"inchikey\": ik}\n        for sid, name in SOURCE_NAMES.items():\n            row[name] = False\n        if r.ok:\n            compounds = r.json().get(\"compounds\", [])\n            if compounds:\n                ids_present = {s[\"id\"] for s in compounds[0].get(\"sources\", [])}\n                for sid, name in SOURCE_NAMES.items():\n                    row[name] = sid in ids_present\n        rows.append(row)\n        time.sleep(0.1)\n    return pd.DataFrame(rows)\n\nsample_keys = [\n    \"BSYNRYMUTXBXSQ-UHFFFAOYSA-N\",  # aspirin\n    \"HEFNNWSXXWATRW-UHFFFAOYSA-N\",  # ibuprofen\n    \"XEFQLINVKFYRCS-UHFFFAOYSA-N\",  # triclosan\n]\ncoverage = source_coverage_matrix(sample_keys)\nprint(coverage.to_string(index=False))\nprint(\"Coverage per database:\")\nfor col in list(SOURCE_NAMES.values()):\n    print(f\"  {col}: {coverage[col].sum()}\u002F{len(coverage)}\")\n```\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| 405 Method Not Allowed on \u002Fcompounds | Hitting the endpoint with GET | UniChem \u002Fcompounds is POST-only. Send requests.post(url, json={type:inchikey, compound:ik}). |\n| KeyError: sourceID (or sourceId) on per-hit records | Reading the wrong field name | Use src[\"id\"] for hits inside compounds[0][sources] and the sources list from \u002Fconnectivity. sourceID only exists in the \u002Fsources catalogue. |\n| 400 illegal_argument_exception field name is null or empty | Tried {compounds: [...]} or {inchikeys: [...]} batch | No batch endpoint exists. Loop with time.sleep(0.1) between POSTs. |\n| {response: Not found} from \u002Fconnectivity | Passed only the 14-char fragment | Send the full 27-char standard InChIKey; UniChem strips the stereo layers internally. |\n| Empty compounds list for a known compound | Non-standard InChIKey, salt-form mismatch, or compound missing | Verify the InChIKey with RDKit; try POST \u002Fconnectivity to catch salt\u002Fstereo variants. |\n| Too many records from connectivity | Same skeleton matches many SureChEMBL patent IDs | Filter by src[\"id\"] to drop source 15 (SureChEMBL) or by comparison.stereoSp3 == True. |\n| requests.exceptions.Timeout | Slow API response under load | Increase timeout to 30s for \u002Fconnectivity; retry once with exponential backoff. |\n| Source URL field is empty | Not all sources provide URL templates | Use baseIdUrl from the \u002Fsources endpoint combined with compoundId to construct links manually. |\n\n## Related Skills\n\n- chembl-database-bioactivity - Query ChEMBL for bioactivity data (IC50, Ki) using the compound IDs resolved via UniChem\n- pubchem-compound-search - Full compound property and bioassay queries using PubChem CIDs from UniChem\n- pdb-database - Look up 3D ligand structures using PDB ligand codes (source 3 or 5) resolved via UniChem\n- drugbank-database-access - Detailed pharmacology, ADMET, and drug interaction data using DrugBank IDs from UniChem\n\n## References\n\n- [UniChem API documentation](https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Finfo\u002Fwebservices) - Official REST API reference with all endpoint descriptions\n- [UniChem home page](https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002F) - Interactive search interface and database listing\n- [Chambers et al., J Cheminform 2013](https:\u002F\u002Fdoi.org\u002F10.1186\u002F1758-2946-5-3) - Original UniChem publication describing the InChI-based cross-referencing methodology\n- [InChI Trust](https:\u002F\u002Fwww.inchi-trust.org\u002F) - InChI standard specification and algorithm documentation\n","# UniChem Database\n\n## Overview\n\nUniChem is a chemical structure cross-referencing service from EMBL-EBI that links compound records across 20+ public chemistry databases using InChI-based identifiers.\nIt maps a single chemical entity to its corresponding IDs in ChEMBL, DrugBank, PubChem, ChEBI, PDB (RCSB and PDBe), SureChEMBL, HMDB, DrugCentral, BindingDB, and others.\nAccess is via a free REST API at https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\u002F - no API key required.\nImportant: every cross-reference query is sent as POST with a JSON body; only the catalogue endpoint GET \u002Fsources is implemented as a GET.\n\n## When to Use\n\n- Translating a ChEMBL compound ID to a PubChem CID, DrugBank accession, or ChEBI ID for cross-database analysis\n- Resolving an InChIKey to all database sources where a compound appears\n- Finding all structurally related compounds (same connectivity, different stereochemistry\u002Fsalts) across databases using connectivity search\n- Validating compound identity across sources before merging datasets from multiple databases\n- Building a compound cross-reference table for a drug discovery project (linking bioactivity data in ChEMBL to structural data in PDB)\n- Checking if a synthesized compound or a vendor compound exists in any public database by InChIKey\n- For full bioactivity profiles (IC50, Ki) use chembl-database-bioactivity; UniChem provides only ID cross-references, not experimental data\n- For compound property prediction or substructure searching use pubchem-compound-search; UniChem is for identifier translation only\n\n## Prerequisites\n\n- **Python packages**: requests, pandas, matplotlib\n- **Data requirements**: compound InChIKeys (standard 27-character XXXXXXXXXXXXXX-XXXXXXXXXX-X), source-specific IDs (e.g. CHEMBL25), or PubChem CIDs as starting points\n- **Environment**: internet connection; no API key required\n- **Rate limits**: ~10 requests\u002Fsecond; add time.sleep(0.1) between requests in batch loops; no daily quota\n\n```bash\npip install requests pandas matplotlib\n```\n\n## Quick Start\n\nThe UniChem \u002Fcompounds endpoint is POST-only - GET returns 405 Method Not Allowed. Submit a JSON body {type: inchikey, compound: KEY} and read per-database hits from compounds[0][sources]. Each source record carries an id (numeric database ID) and a compoundId (the ID in that database).\n\n```python\nimport requests\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\n\ndef unichem_post(endpoint: str, body: dict) -> dict:\n    \"\"\"POST request to UniChem API; raise on HTTP errors.\"\"\"\n    r = requests.post(f\"{UNICHEM_API}\u002F{endpoint}\", json=body, timeout=20)\n    r.raise_for_status()\n    return r.json()\n\n# Find all database sources for aspirin by InChIKey\ninchikey = \"BSYNRYMUTXBXSQ-UHFFFAOYSA-N\"  # aspirin\nresult = unichem_post(\"compounds\", {\"type\": \"inchikey\", \"compound\": inchikey})\ncompounds = result.get(\"compounds\", [])\nprint(f\"Found {len(compounds)} compound record(s) for {inchikey}\")\nif compounds:\n    sources = compounds[0].get(\"sources\", [])\n    print(f\"  Present in {len(sources)} database records\")\n    seen = set()\n    for src in sources:\n        if src[\"id\"] in seen:\n            continue\n        seen.add(src[\"id\"])\n        print(f\"  source id={src['id']:>3} ({src['shortName']:>12}): {src['compoundId']}\")\n        if len(seen) >= 5:\n            break\n# Found 1 compound record(s) for BSYNRYMUTXBXSQ-UHFFFAOYSA-N\n#   Present in many database records\n#   source id=  1 (      chembl): CHEMBL25\n#   source id=  2 (    drugbank): DB00945\n#   source id=  3 (    rcsb_pdb): AIN\n```\n\n## Core API\n\n### Query 1: InChIKey Lookup - All Sources\n\nSearch for a compound by its standard InChIKey and retrieve all database records. This is the primary cross-reference method. The endpoint is POST \u002Fcompounds; the response carries one entry in compounds (if found), each with a sources list whose records use id (source database) and compoundId (the ID in that database).\n\n```python\nimport requests, pandas as pd\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\n\n# Common source IDs (verify with the \u002Fsources endpoint - see Query 4)\nSOURCE_NAMES = {\n    1: \"ChEMBL\", 2: \"DrugBank\", 3: \"RCSB PDB\", 4: \"GtoPdb\", 5: \"PDBe\",\n    7: \"ChEBI\", 14: \"FDA SRS\", 15: \"SureChEMBL\", 18: \"HMDB\", 22: \"PubChem\",\n    31: \"BindingDB\", 32: \"CompTox\", 33: \"LIPID MAPS\", 34: \"DrugCentral\",\n    37: \"BRENDA\", 38: \"Rhea\", 41: \"SwissLipids\", 49: \"Probes-and-Drugs\",\n}\n\ndef lookup_by_inchikey(inchikey: str) -> pd.DataFrame:\n    \"\"\"Return all database cross-references for an InChIKey.\"\"\"\n    r = requests.post(f\"{UNICHEM_API}\u002Fcompounds\",\n                      json={\"type\": \"inchikey\", \"compound\": inchikey}, timeout=20)\n    r.raise_for_status()\n    compounds = r.json().get(\"compounds\", [])\n    if not compounds:\n        return pd.DataFrame()\n    rows = []\n    for src in compounds[0].get(\"sources\", []):\n        rows.append({\n            \"source_id\": src[\"id\"],\n            \"source_name\": SOURCE_NAMES.get(src[\"id\"], src.get(\"shortName\", \"\")),\n            \"compound_id\": src[\"compoundId\"],\n            \"url\": src.get(\"url\", \"\"),\n        })\n    return pd.DataFrame(rows).sort_values([\"source_id\", \"compound_id\"])\n\n# Triclosan cross-references\ndf = lookup_by_inchikey(\"XEFQLINVKFYRCS-UHFFFAOYSA-N\")\nprint(f\"Triclosan found in {df['source_id'].nunique()} distinct databases ({len(df)} records):\")\nprint(df[[\"source_name\", \"compound_id\"]].head(8).to_string(index=False))\n# Triclosan found in 16 distinct databases\n#   ChEMBL    CHEMBL849\n#   DrugBank  DB08604\n#   RCSB PDB  TCL\n#   ChEBI     CHEBI:164200\n```\n```python\n# Extract specific source IDs from cross-reference table\ndef get_id_for_source(inchikey: str, source_id: int) -> str | None:\n    \"\"\"Return the compound ID in a specific database, or None if not found.\"\"\"\n    r = requests.post(f\"{UNICHEM_API}\u002Fcompounds\",\n                      json={\"type\": \"inchikey\", \"compound\": inchikey}, timeout=20)\n    r.raise_for_status()\n    compounds = r.json().get(\"compounds\", [])\n    if not compounds:\n        return None\n    for src in compounds[0].get(\"sources\", []):\n        if src[\"id\"] == source_id:\n            return src[\"compoundId\"]\n    return None\n\ntriclosan = \"XEFQLINVKFYRCS-UHFFFAOYSA-N\"\nchembl_id   = get_id_for_source(triclosan, source_id=1)   # ChEMBL\npubchem_id  = get_id_for_source(triclosan, source_id=22)  # PubChem\ndrugbank_id = get_id_for_source(triclosan, source_id=2)   # DrugBank\nprint(f\"Triclosan: ChEMBL={chembl_id}, PubChem={pubchem_id}, DrugBank={drugbank_id}\")\n# Triclosan: ChEMBL=CHEMBL849, PubChem=5564, DrugBank=DB08604\n```\n\n### Query 2: Compound Lookup by Source-Specific ID\n\nGiven a known compound ID in a specific source database (e.g., a ChEMBL ID), retrieve all cross-references. Use type: sourceID with the compound s source ID alongside the numeric sourceID in the body. Returns the same data shape as the InChIKey lookup.\n\n```python\nimport requests\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\n\ndef get_sources_for_compound(compound_id: str, source_id: int) -> list:\n    \"\"\"Get all database cross-references for a compound identified in a specific source.\n\n    Args:\n        compound_id: The ID in the source database (e.g., CHEMBL192)\n        source_id: UniChem source ID (1=ChEMBL, 2=DrugBank, 22=PubChem, 7=ChEBI)\n    \"\"\"\n    body = {\"type\": \"sourceID\", \"compound\": compound_id, \"sourceID\": source_id}\n    r = requests.post(f\"{UNICHEM_API}\u002Fcompounds\", json=body, timeout=20)\n    r.raise_for_status()\n    compounds = r.json().get(\"compounds\", [])\n    if not compounds:\n        return []\n    return compounds[0].get(\"sources\", [])\n\n# Sildenafil (Viagra): look up starting from ChEMBL ID\nsources = get_sources_for_compound(\"CHEMBL192\", source_id=1)\ndistinct_dbs = {s[\"id\"] for s in sources}\nprint(f\"Sildenafil (CHEMBL192): {len(sources)} source records across {len(distinct_dbs)} databases\")\nseen = set()\nfor s in sources:\n    if s[\"id\"] in seen:\n        continue\n    seen.add(s[\"id\"])\n    print(f\"  [{s['id']:>3}] {s['shortName']:>15}: {s['compoundId']}\")\n    if len(seen) >= 8:\n        break\n# Sildenafil (CHEMBL192): 272 source records across 19 databases\n```\n\n### Query 3: Connectivity Search - Structural Relatives\n\nFind compounds with the same core structure but different stereochemistry, salt forms, isotopic labeling, or protonation. The endpoint is POST \u002Fconnectivity and accepts a full standard InChIKey (the API rejects 14-character fragments with 404 Not found). Internally UniChem uses the connectivity layer for matching but returns hits that may differ at the stereo\u002Fcharge\u002Fisotope layers.\n\nUnlike \u002Fcompounds, the connectivity response returns a flat sources list (one entry per database hit across all relatives) plus the queried searchedCompound and totalCompounds\u002FtotalSources summary fields. Each hit s comparison dict shows which InChI layers matched.\n\n```python\nimport requests, pandas as pd\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\n\ndef connectivity_search(inchikey: str) -> dict:\n    \"\"\"Find all compounds related by InChI connectivity (same skeleton, possibly different stereo\u002Fsalts).\n\n    Pass a FULL standard InChIKey (27 chars). The server rejects 14-char fragments.\n    \"\"\"\n    body = {\"type\": \"inchikey\", \"compound\": inchikey}\n    r = requests.post(f\"{UNICHEM_API}\u002Fconnectivity\", json=body, timeout=30)\n    r.raise_for_status()\n    return r.json()\n\n# Warfarin: find all stereoforms, racemates, and salt forms\nwarfarin_inchikey = \"PJVWKTKQMONHTI-UHFFFAOYSA-N\"\ndata = connectivity_search(warfarin_inchikey)\nprint(f\"Warfarin connectivity relatives: {data['totalCompounds']} unique compounds, \"\n      f\"{data['totalSources']} database records\")\nhits = data.get(\"sources\", [])\nby_source = {}\nfor h in hits:\n    by_source.setdefault(h[\"shortName\"], []).append(h[\"compoundId\"])\nfor name, ids in sorted(by_source.items(), key=lambda kv: -len(kv[1]))[:8]:\n    print(f\"  {name:>15}: {len(ids):>4} IDs (e.g. {ids[0]})\")\n# Warfarin connectivity relatives: 13 unique compounds, 353 database records\n```\n```python\n# Compare source coverage across connectivity relatives\ndef compare_coverage(inchikey: str) -> pd.DataFrame:\n    \"\"\"Show connectivity relatives split by their source-database coverage.\"\"\"\n    data = connectivity_search(inchikey)\n    rows = []\n    for src in data.get(\"sources\", []):\n        rows.append({\n            \"source_id\":    src[\"id\"],\n            \"source_name\":  src[\"shortName\"],\n            \"compound_id\":  src[\"compoundId\"],\n            \"stereo_match\": src[\"comparison\"].get(\"stereoSp3\", False),\n            \"salt_match\":   src[\"comparison\"].get(\"protonation\", False),\n        })\n    return pd.DataFrame(rows)\n\ndf = compare_coverage(\"PJVWKTKQMONHTI-UHFFFAOYSA-N\")\nprint(f\"Total records: {len(df)}\")\nprint(df.head(10).to_string(index=False))\nprint(f\"Records with stereo mismatch (skeleton matches, stereo differs): {(~df['stereo_match']).sum()}\")\n```\n\n### Query 4: List All Data Sources\n\nRetrieve the full list of UniChem data sources with their IDs, names, descriptions, and website URLs. This is the only endpoint served by GET. The response uses sourceID (capital ID) inside each source entry.\n\n```python\nimport requests, pandas as pd\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\n\ndef list_sources() -> pd.DataFrame:\n    \"\"\"Return all UniChem data sources as a DataFrame.\"\"\"\n    r = requests.get(f\"{UNICHEM_API}\u002Fsources\", timeout=15)\n    r.raise_for_status()\n    sources = r.json().get(\"sources\", [])\n    rows = []\n    for s in sources:\n        rows.append({\n            \"source_id\":  s[\"sourceID\"],\n            \"name\":       s.get(\"nameLong\") or s.get(\"nameLabel\", \"\"),\n            \"label\":      s.get(\"nameLabel\", \"\"),\n            \"short_name\": s.get(\"name\", \"\"),\n            \"uci_count\":  s.get(\"UCICount\"),\n            \"url\":        s.get(\"baseIdUrl\", \"\"),\n        })\n    return pd.DataFrame(rows).sort_values(\"source_id\")\n\nsources_df = list_sources()\nprint(f\"Total UniChem sources: {len(sources_df)}\")\nprint(sources_df[[\"source_id\", \"label\", \"uci_count\"]].to_string(index=False))\n# Total UniChem sources: 23\n#   1   ChEMBL          2854815\n#   2   DrugBank          14622\n#  22   PubChem      123392679\n```\n\n### Query 5: Per-Compound Loop (No Batch Endpoint)\n\nUniChem does not support a list-batch shape - the \u002Fcompounds POST accepts only a single compound per request. Submitting {compounds: [...]} or {inchikeys: [...]} returns 400 illegal_argument_exception. For multiple inputs, iterate with a small sleep to respect the ~10 req\u002Fs rate limit.\n\n```python\nimport requests, time, pandas as pd\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\n\ndef batch_translate(inchikeys: list[str],\n                    target_source_ids=(1, 2, 7, 22)) -> pd.DataFrame:\n    \"\"\"Translate a list of InChIKeys to IDs in multiple target databases.\n\n    Loops one POST per InChIKey (UniChem has no list-batch endpoint).\n    \"\"\"\n    SOURCE_NAMES = {1: \"chembl\", 2: \"drugbank\", 3: \"pdb\", 7: \"chebi\",\n                    14: \"fda_srs\", 22: \"pubchem\", 34: \"drugcentral\"}\n    rows = []\n    for ik in inchikeys:\n        row = {\"inchikey\": ik}\n        for sid in target_source_ids:\n            row[SOURCE_NAMES.get(sid, f\"src_{sid}\")] = None\n        try:\n            r = requests.post(f\"{UNICHEM_API}\u002Fcompounds\",\n                              json={\"type\": \"inchikey\", \"compound\": ik}, timeout=20)\n            r.raise_for_status()\n            compounds = r.json().get(\"compounds\", [])\n            if compounds:\n                for src in compounds[0].get(\"sources\", []):\n                    if src[\"id\"] in target_source_ids:\n                        col = SOURCE_NAMES.get(src[\"id\"], f\"src_{src['id']}\")\n                        if row[col] is None:\n                            row[col] = src[\"compoundId\"]\n        except requests.RequestException as e:\n            row[\"error\"] = str(e)\n        rows.append(row)\n        time.sleep(0.1)  # respect ~10 req\u002Fs rate limit\n    return pd.DataFrame(rows)\n\n# Translate a set of NSAIDs by InChIKey\nnsaid_inchikeys = [\n    \"BSYNRYMUTXBXSQ-UHFFFAOYSA-N\",  # aspirin\n    \"HEFNNWSXXWATRW-UHFFFAOYSA-N\",  # ibuprofen\n    \"CMWTZPSULFXXJA-VIFPVBQESA-N\",  # naproxen\n    \"DCOPUUMXTXDBNB-UHFFFAOYSA-N\",  # diclofenac (free acid)\n]\ndf = batch_translate(nsaid_inchikeys, target_source_ids=[1, 2, 7, 22])\nprint(df.to_string(index=False))\ndf.to_csv(\"nsaid_xrefs.csv\", index=False)\nprint(f\"Saved nsaid_xrefs.csv ({len(df)} compounds)\")\n```\n\n### Query 6: Per-Compound Loop with Source-ID Inputs\n\nWhen the starting identifiers are not InChIKeys but source-specific IDs (e.g., a list of ChEMBL IDs from a bioactivity table), use type=sourceID and loop, again one POST per ID.\n\n```python\nimport requests, time\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\n\ndef translate_source_ids(ids: list[str], from_source: int,\n                         to_sources=(2, 22, 34)) -> list[dict]:\n    \"\"\"Translate IDs in one source database to IDs in target databases.\n\n    Args:\n        ids: list of compound IDs in the from_source database\n        from_source: source ID of the input list (1=ChEMBL, 22=PubChem, ...)\n        to_sources: iterable of target source IDs to extract\n    \"\"\"\n    out = []\n    for cid in ids:\n        body = {\"type\": \"sourceID\", \"compound\": cid, \"sourceID\": from_source}\n        r = requests.post(f\"{UNICHEM_API}\u002Fcompounds\", json=body, timeout=20)\n        row = {\"input\": cid}\n        if r.ok:\n            compounds = r.json().get(\"compounds\", [])\n            if compounds:\n                row[\"inchikey\"] = compounds[0].get(\"standardInchiKey\")\n                hits = {s[\"id\"]: s[\"compoundId\"] for s in compounds[0].get(\"sources\", [])}\n                for tsid in to_sources:\n                    row[f\"src_{tsid}\"] = hits.get(tsid)\n        out.append(row)\n        time.sleep(0.1)\n    return out\n\n# Three kinase inhibitors known by ChEMBL ID\nchembl_inputs = [\"CHEMBL535\", \"CHEMBL553\", \"CHEMBL941\"]  # nilotinib, dasatinib, imatinib\nrows = translate_source_ids(chembl_inputs, from_source=1, to_sources=(2, 22, 34))\nfor row in rows:\n    ik = (row.get(\"inchikey\") or \"?\")[:14]\n    print(f\"{row['input']:>10}  ik={ik}...  \"\n          f\"DrugBank={row.get('src_2')}, PubChem={row.get('src_22')}, \"\n          f\"DrugCentral={row.get('src_34')}\")\n```\n\n## Key Concepts\n\n### InChI vs InChIKey\n\nUniChem uses the **InChI** (IUPAC International Chemical Identifier) and its hashed form the **InChIKey** as the canonical compound identity. The InChIKey is a 27-character string split into three blocks: the first 14 characters encode the connectivity layer (heavy atoms and bonds), the next 8 encode stereochemistry and charge, and the last character is a version flag. UniChem cross-references compounds by requiring identical standard InChIKeys, ensuring the same chemical entity across databases.\n\n### Source ID Reference Table (verified live against \u002Fsources)\n\n| Source ID | Database | Scope |\n|-----------|----------|-------|\n| 1  | ChEMBL          | Bioactive molecules, drug discovery |\n| 2  | DrugBank        | Approved drugs, pharmacology |\n| 3  | RCSB PDB        | Ligands in crystal structures (US) |\n| 4  | Guide to Pharmacology | Pharmacology targets\u002Fligands |\n| 5  | PDBe            | Ligands in crystal structures (Europe) |\n| 7  | ChEBI           | Chemical ontology, metabolites |\n| 14 | FDA SRS         | FDA Substance Registration System |\n| 15 | SureChEMBL      | Patent chemistry |\n| 18 | HMDB            | Human Metabolome Database |\n| 22 | PubChem         | General compound repository |\n| 31 | BindingDB       | Binding affinity data |\n| 32 | CompTox         | Environmental tox dashboard |\n| 33 | LIPID MAPS      | Lipid structures |\n| 34 | DrugCentral     | Approved drugs + pharmacology |\n| 37 | BRENDA          | Enzyme substrates\u002Fproducts |\n| 38 | Rhea            | Biochemical reactions |\n| 41 | SwissLipids     | Lipid structures |\n| 49 | Probes-and-Drugs| Chemical probes |\n\n### Field Naming: id vs sourceID\n\nThis is the single most common error when scripting UniChem. The two endpoints use different field names for the source database identifier:\n\n- **GET \u002Fsources** lists databases as objects with a **sourceID** field (capital ID).\n- **POST \u002Fcompounds** and **POST \u002Fconnectivity** return per-database hits inside sources lists, where the source identifier is a plain **id** field. There is no sourceID or sourceId key on these per-hit records.\n\nAlways use src[\"id\"] when iterating compound or connectivity responses, and use s[\"sourceID\"] when iterating the \u002Fsources catalogue.\n\n### Connectivity vs Standard InChIKey Matching\n\nPOST \u002Fcompounds returns exact InChIKey matches (same stereo, salt, isotopes). POST \u002Fconnectivity returns all compounds sharing the bond topology - useful for finding racemates, stereoisomers, free acids\u002Fbases, and co-crystal partners. The connectivity response includes a comparison dict per hit indicating which InChI layers matched (stereoSp3, protonation, isotope, etc.); use it to filter for same skeleton, different stereo only relatives.\n\n## Common Workflows\n\n### Workflow 1: Drug Compound Cross-Reference Report\n\n**Goal**: Given a list of drug names (or ChEMBL IDs), resolve each to all major database IDs and export to CSV.\n\n```python\nimport requests, time, pandas as pd\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\nCHEMBL_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Fchembl\u002Fapi\u002Fdata\"\n\nSOURCE_NAMES = {1: \"chembl\", 2: \"drugbank\", 3: \"rcsb_pdb\",\n                7: \"chebi\", 22: \"pubchem\", 14: \"fda_srs\", 34: \"drugcentral\"}\n\ndef chembl_to_inchikey(chembl_id: str) -> str | None:\n    \"\"\"Look up the standard InChIKey for a ChEMBL compound ID.\"\"\"\n    r = requests.get(f\"{CHEMBL_API}\u002Fmolecule\u002F{chembl_id}.json\", timeout=15)\n    if r.status_code == 404:\n        return None\n    r.raise_for_status()\n    return r.json().get(\"molecule_structures\", {}).get(\"standard_inchi_key\")\n\ndef inchikey_to_sources(inchikey: str) -> dict:\n    \"\"\"Return source_id -> compound_id dict for an InChIKey (first hit per source).\"\"\"\n    r = requests.post(f\"{UNICHEM_API}\u002Fcompounds\",\n                      json={\"type\": \"inchikey\", \"compound\": inchikey}, timeout=20)\n    r.raise_for_status()\n    compounds = r.json().get(\"compounds\", [])\n    if not compounds:\n        return {}\n    out = {}\n    for s in compounds[0].get(\"sources\", []):\n        out.setdefault(s[\"id\"], s[\"compoundId\"])\n    return out\n\n# Example: top cardiovascular drugs\ndrug_chembl_ids = {\n    \"atorvastatin\": \"CHEMBL1487\",\n    \"lisinopril\":   \"CHEMBL1237\",\n    \"metoprolol\":   \"CHEMBL13\",\n    \"amlodipine\":   \"CHEMBL1491\",\n    \"warfarin\":     \"CHEMBL1464\",\n}\n\nrows = []\nfor name, chembl_id in drug_chembl_ids.items():\n    ik = chembl_to_inchikey(chembl_id)\n    row = {\"drug\": name, \"chembl_id\": chembl_id, \"inchikey\": ik}\n    if ik:\n        srcs = inchikey_to_sources(ik)\n        for sid, col in SOURCE_NAMES.items():\n            row[col] = srcs.get(sid)\n    rows.append(row)\n    time.sleep(0.2)\n\ndf = pd.DataFrame(rows)\ndf.to_csv(\"drug_xrefs.csv\", index=False)\nprint(df[[\"drug\", \"chembl\", \"drugbank\", \"pubchem\", \"chebi\"]].to_string(index=False))\nprint(f\"Saved drug_xrefs.csv ({len(df)} drugs)\")\n```\n\n### Workflow 2: Structural Relatives Discovery and Visualization\n\n**Goal**: Find all structural relatives of a compound, summarize their database coverage, and plot a bar chart showing source distribution.\n\n```python\nimport requests, pandas as pd\nimport matplotlib.pyplot as plt\nfrom collections import Counter\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\n\nSOURCE_NAMES = {1: \"ChEMBL\", 2: \"DrugBank\", 3: \"RCSB PDB\", 5: \"PDBe\",\n                7: \"ChEBI\", 14: \"FDA SRS\", 15: \"SureChEMBL\",\n                22: \"PubChem\", 31: \"BindingDB\", 34: \"DrugCentral\"}\n\n# Aspirin connectivity relatives (covers acetylsalicylate salts)\nquery_inchikey = \"BSYNRYMUTXBXSQ-UHFFFAOYSA-N\"\n\nr = requests.post(f\"{UNICHEM_API}\u002Fconnectivity\",\n                  json={\"type\": \"inchikey\", \"compound\": query_inchikey}, timeout=30)\nr.raise_for_status()\ndata = r.json()\nhits = data.get(\"sources\", [])\nprint(f\"Aspirin connectivity relatives: {data['totalCompounds']} unique compounds, \"\n      f\"{len(hits)} database records\")\n\n# Count how often each named database appears\nsource_counter = Counter()\nfor h in hits:\n    if h[\"id\"] in SOURCE_NAMES:\n        source_counter[SOURCE_NAMES[h[\"id\"]]] += 1\n\nlabels = [k for k, _ in source_counter.most_common()]\ncounts = [v for _, v in source_counter.most_common()]\n\nfig, ax = plt.subplots(figsize=(9, 4))\nbars = ax.bar(labels, counts, color=\"#2E86AB\", edgecolor=\"white\")\nax.bar_label(bars, padding=2)\nax.set_xlabel(\"Database\")\nax.set_ylabel(\"Number of Source Records (relatives x hits)\")\nax.set_title(\"UniChem Connectivity Records - Aspirin Skeleton\")\nplt.xticks(rotation=30, ha=\"right\")\nplt.tight_layout()\nplt.savefig(\"unichem_connectivity_coverage.png\", dpi=150, bbox_inches=\"tight\")\nprint(\"Saved unichem_connectivity_coverage.png\")\nplt.close(fig)\n\n# DataFrame summary by source\ndf = pd.DataFrame(source_counter.most_common(), columns=[\"database\", \"records\"])\nprint(df.to_string(index=False))\n```\n\n### Workflow 3: Merge ChEMBL Bioactivity with PubChem CIDs\n\n**Goal**: Augment a ChEMBL bioactivity table with PubChem CIDs for downstream analysis in tools that use PubChem identifiers.\n\n```python\nimport requests, time, pandas as pd\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\n\ndef add_pubchem_cids(df: pd.DataFrame,\n                     inchikey_col: str = \"standard_inchi_key\") -> pd.DataFrame:\n    \"\"\"Add pubchem_cid column to a DataFrame that has an InChIKey column.\"\"\"\n    unique_keys = df[inchikey_col].dropna().unique()\n    mapping = {}\n    for ik in unique_keys:\n        try:\n            r = requests.post(f\"{UNICHEM_API}\u002Fcompounds\",\n                              json={\"type\": \"inchikey\", \"compound\": ik}, timeout=15)\n            r.raise_for_status()\n            compounds = r.json().get(\"compounds\", [])\n            if compounds:\n                for src in compounds[0].get(\"sources\", []):\n                    if src[\"id\"] == 22:  # PubChem\n                        mapping[ik] = src[\"compoundId\"]\n                        break\n        except requests.RequestException:\n            pass\n        time.sleep(0.1)\n    df = df.copy()\n    df[\"pubchem_cid\"] = df[inchikey_col].map(mapping)\n    return df\n\n# Simulate a small ChEMBL activity table\nchembl_data = pd.DataFrame({\n    \"compound_name\": [\"aspirin\", \"ibuprofen\", \"naproxen\"],\n    \"standard_inchi_key\": [\n        \"BSYNRYMUTXBXSQ-UHFFFAOYSA-N\",\n        \"HEFNNWSXXWATRW-UHFFFAOYSA-N\",\n        \"CMWTZPSULFXXJA-VIFPVBQESA-N\",\n    ],\n    \"ic50_nm\": [2500.0, 13000.0, 1600.0],\n})\n\nenriched = add_pubchem_cids(chembl_data)\nprint(enriched[[\"compound_name\", \"ic50_nm\", \"pubchem_cid\"]].to_string(index=False))\nenriched.to_csv(\"chembl_with_pubchem.csv\", index=False)\nprint(\"Saved chembl_with_pubchem.csv\")\n```\n\n## Key Parameters\n\n| Parameter | Endpoint | Default | Range \u002F Options | Effect |\n|-----------|----------|---------|-----------------|--------|\n| type (body) | POST \u002Fcompounds, POST \u002Fconnectivity | - | inchikey, sourceID | Selects the kind of identifier in compound. inchikey requires a 27-char standard InChIKey; sourceID also requires the numeric sourceID field. |\n| compound (body) | POST \u002Fcompounds, POST \u002Fconnectivity | - | One string (no list) | The identifier to look up. UniChem does NOT support a list-batch shape; loop one POST per compound. |\n| sourceID (body) | POST \u002Fcompounds (with type=sourceID) | - | Integer DB id from \u002Fsources | The source database the input compound belongs to (1=ChEMBL, 2=DrugBank, 22=PubChem, ...). |\n| Per-hit id (response) | POST \u002Fcompounds, POST \u002Fconnectivity | - | Integer | Source database id of each hit in sources. **Use src[\"id\"], NOT src[\"sourceID\"]** for these per-hit records. |\n| sourceID (response) | GET \u002Fsources | - | Integer | Numeric ID of each database entry in the catalogue (capital ID). |\n| timeout | All requests | 20s | Any positive integer | Seconds before request fails; raise to 30s for \u002Fconnectivity on common skeletons. |\n\n## Best Practices\n\n1. **Use POST everywhere except \u002Fsources**: GET \u002Fcompounds returns 405 Method Not Allowed; GET \u002Fcompounds\u002F{src}\u002F{id} and GET \u002Fconnectivity\u002F{key} return 404. The only GET endpoint is \u002Fsources. Always POST with a JSON body.\n\n2. **Use the correct field - id on hits, sourceID on \u002Fsources**: Inside the sources list returned by POST \u002Fcompounds and POST \u002Fconnectivity, each record s source database is in the id key. Reading src[\"sourceID\"] raises KeyError. The capital-ID sourceID field only appears in the catalogue returned by GET \u002Fsources.\n\n3. **Use standard (not non-standard) InChIKeys**: UniChem indexes standard InChIKeys. Non-standard InChIKeys will return no results. Verify with: from rdkit.Chem.inchi import MolToInchiKey; MolToInchiKey(mol).\n\n4. **Fall back to connectivity search when exact match fails**: If a compound is in DrugBank as a salt (e.g., hydrochloride) but you have the free base InChIKey, the standard lookup will miss it. Run a connectivity search as a fallback for drug cross-referencing.\n\n5. **Pass the full InChIKey to \u002Fconnectivity**: The endpoint expects a complete 27-character standard InChIKey. Submitting only the 14-char connectivity fragment returns {response: Not found}. UniChem strips the stereo\u002Fcharge layers internally.\n\n6. **Cache the source list on startup**: Call \u002Fsources once and build a {sourceID: nameLabel} dict rather than hard-coding IDs.\n\n```python\ndef load_source_map() -> dict:\n    r = requests.get(f\"{UNICHEM_API}\u002Fsources\", timeout=15)\n    r.raise_for_status()\n    return {s[\"sourceID\"]: s.get(\"nameLabel\", str(s[\"sourceID\"]))\n            for s in r.json().get(\"sources\", [])}\n```\n\n7. **No batch endpoint exists - loop with sleep**: Submitting {compounds: [...]} or {inchikeys: [...]} returns 400 illegal_argument_exception. Iterate POSTs with time.sleep(0.1) between calls (~10 req\u002Fs).\n\n## Common Recipes\n\n### Recipe: Resolve Any Compound ID to InChIKey\n\nWhen to use: You have a PubChem CID or ChEBI ID and need the InChIKey to query UniChem or other services.\n\n```python\nimport requests\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\nPUBCHEM_API = \"https:\u002F\u002Fpubchem.ncbi.nlm.nih.gov\u002Frest\u002Fpug\"\n\ndef pubchem_cid_to_inchikey(cid) -> str | None:\n    \"\"\"Resolve a PubChem CID to a standard InChIKey via PubChem.\"\"\"\n    r = requests.get(f\"{PUBCHEM_API}\u002Fcompound\u002Fcid\u002F{cid}\u002Fproperty\u002FInChIKey\u002FJSON\", timeout=10)\n    if r.status_code == 404:\n        return None\n    r.raise_for_status()\n    props = r.json()[\"PropertyTable\"][\"Properties\"]\n    return props[0][\"InChIKey\"] if props else None\n\ndef cid_to_all_sources(cid) -> list:\n    \"\"\"PubChem CID -> InChIKey -> UniChem cross-references.\"\"\"\n    ik = pubchem_cid_to_inchikey(cid)\n    if not ik:\n        return []\n    r = requests.post(f\"{UNICHEM_API}\u002Fcompounds\",\n                      json={\"type\": \"inchikey\", \"compound\": ik}, timeout=20)\n    r.raise_for_status()\n    compounds = r.json().get(\"compounds\", [])\n    return compounds[0].get(\"sources\", []) if compounds else []\n\nsources = cid_to_all_sources(2244)  # PubChem CID for aspirin\ndistinct = {s[\"id\"] for s in sources}\nprint(f\"Aspirin (CID=2244) is in {len(distinct)} UniChem databases ({len(sources)} records)\")\nseen = set()\nfor s in sources:\n    if s[\"id\"] in seen:\n        continue\n    seen.add(s[\"id\"])\n    print(f\"  [{s['id']:>3}] {s['shortName']:>15}: {s['compoundId']}\")\n    if len(seen) >= 6:\n        break\n```\n\n### Recipe: Check If a Compound Is an Approved Drug\n\nWhen to use: Quickly flag whether a compound appears in DrugBank (source 2) using its InChIKey.\n\n```python\nimport requests\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\n\ndef is_approved_drug(inchikey: str) -> tuple[bool, str | None]:\n    \"\"\"Check if compound appears in DrugBank (id=2). Returns (is_drug, DrugBank_ID).\"\"\"\n    r = requests.post(f\"{UNICHEM_API}\u002Fcompounds\",\n                      json={\"type\": \"inchikey\", \"compound\": inchikey}, timeout=20)\n    r.raise_for_status()\n    compounds = r.json().get(\"compounds\", [])\n    if not compounds:\n        return False, None\n    for src in compounds[0].get(\"sources\", []):\n        if src[\"id\"] == 2:  # DrugBank\n            return True, src[\"compoundId\"]\n    return False, None\n\n# Test a few compounds\ntest_compounds = {\n    \"aspirin\":      \"BSYNRYMUTXBXSQ-UHFFFAOYSA-N\",\n    \"triclosan\":    \"XEFQLINVKFYRCS-UHFFFAOYSA-N\",\n    \"sildenafil\":   \"BNRNXUUZRGQAQC-UHFFFAOYSA-N\",\n}\nfor name, ik in test_compounds.items():\n    is_drug, db_id = is_approved_drug(ik)\n    status = f\"DrugBank:{db_id}\" if is_drug else \"not in DrugBank\"\n    print(f\"{name:>12}: {status}\")\n```\n\n### Recipe: Source Coverage Summary for a Compound Set\n\nWhen to use: Audit which databases cover your compound list - useful before choosing which database to use for downstream analysis.\n\n```python\nimport requests, time, pandas as pd\n\nUNICHEM_API = \"https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Fapi\u002Fv1\"\nSOURCE_NAMES = {1: \"ChEMBL\", 2: \"DrugBank\", 3: \"RCSB PDB\", 7: \"ChEBI\",\n                14: \"FDA SRS\", 22: \"PubChem\", 34: \"DrugCentral\"}\n\ndef source_coverage_matrix(inchikeys: list[str]) -> pd.DataFrame:\n    \"\"\"Return a boolean matrix: rows=compounds, columns=databases.\"\"\"\n    rows = []\n    for ik in inchikeys:\n        r = requests.post(f\"{UNICHEM_API}\u002Fcompounds\",\n                          json={\"type\": \"inchikey\", \"compound\": ik}, timeout=15)\n        row = {\"inchikey\": ik}\n        for sid, name in SOURCE_NAMES.items():\n            row[name] = False\n        if r.ok:\n            compounds = r.json().get(\"compounds\", [])\n            if compounds:\n                ids_present = {s[\"id\"] for s in compounds[0].get(\"sources\", [])}\n                for sid, name in SOURCE_NAMES.items():\n                    row[name] = sid in ids_present\n        rows.append(row)\n        time.sleep(0.1)\n    return pd.DataFrame(rows)\n\nsample_keys = [\n    \"BSYNRYMUTXBXSQ-UHFFFAOYSA-N\",  # aspirin\n    \"HEFNNWSXXWATRW-UHFFFAOYSA-N\",  # ibuprofen\n    \"XEFQLINVKFYRCS-UHFFFAOYSA-N\",  # triclosan\n]\ncoverage = source_coverage_matrix(sample_keys)\nprint(coverage.to_string(index=False))\nprint(\"Coverage per database:\")\nfor col in list(SOURCE_NAMES.values()):\n    print(f\"  {col}: {coverage[col].sum()}\u002F{len(coverage)}\")\n```\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| 405 Method Not Allowed on \u002Fcompounds | Hitting the endpoint with GET | UniChem \u002Fcompounds is POST-only. Send requests.post(url, json={type:inchikey, compound:ik}). |\n| KeyError: sourceID (or sourceId) on per-hit records | Reading the wrong field name | Use src[\"id\"] for hits inside compounds[0][sources] and the sources list from \u002Fconnectivity. sourceID only exists in the \u002Fsources catalogue. |\n| 400 illegal_argument_exception field name is null or empty | Tried {compounds: [...]} or {inchikeys: [...]} batch | No batch endpoint exists. Loop with time.sleep(0.1) between POSTs. |\n| {response: Not found} from \u002Fconnectivity | Passed only the 14-char fragment | Send the full 27-char standard InChIKey; UniChem strips the stereo layers internally. |\n| Empty compounds list for a known compound | Non-standard InChIKey, salt-form mismatch, or compound missing | Verify the InChIKey with RDKit; try POST \u002Fconnectivity to catch salt\u002Fstereo variants. |\n| Too many records from connectivity | Same skeleton matches many SureChEMBL patent IDs | Filter by src[\"id\"] to drop source 15 (SureChEMBL) or by comparison.stereoSp3 == True. |\n| requests.exceptions.Timeout | Slow API response under load | Increase timeout to 30s for \u002Fconnectivity; retry once with exponential backoff. |\n| Source URL field is empty | Not all sources provide URL templates | Use baseIdUrl from the \u002Fsources endpoint combined with compoundId to construct links manually. |\n\n## Related Skills\n\n- chembl-database-bioactivity - Query ChEMBL for bioactivity data (IC50, Ki) using the compound IDs resolved via UniChem\n- pubchem-compound-search - Full compound property and bioassay queries using PubChem CIDs from UniChem\n- pdb-database - Look up 3D ligand structures using PDB ligand codes (source 3 or 5) resolved via UniChem\n- drugbank-database-access - Detailed pharmacology, ADMET, and drug interaction data using DrugBank IDs from UniChem\n\n## References\n\n- [UniChem API documentation](https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002Finfo\u002Fwebservices) - Official REST API reference with all endpoint descriptions\n- [UniChem home page](https:\u002F\u002Fwww.ebi.ac.uk\u002Funichem\u002F) - Interactive search interface and database listing\n- [Chambers et al., J Cheminform 2013](https:\u002F\u002Fdoi.org\u002F10.1186\u002F1758-2946-5-3) - Original UniChem publication describing the InChI-based cross-referencing methodology\n- [InChI Trust](https:\u002F\u002Fwww.inchi-trust.org\u002F) - InChI standard specification and algorithm documentation\n",{"name":5,"license":15,"description":7},"master","63f17866001c5ca854bf2fa0b678ce277133de5b","skills\u002Fawesome-skills\u002Funichem-database",0,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS","https:\u002F\u002Fbg-szy.github.io\u002FTOP-SKILLS\u002F","https:\u002F\u002Fgithub.com\u002Fbg-szy","https:\u002F\u002Fwww.ecust.edu.cn\u002F","a student of East China University of Science and Technology","2026-11-15 03:38:02",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add bg-szy\u002FTOP-SKILLS --skill unichem-database",{"tool":40,"command":41},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill unichem-database",{"tool":43,"command":44},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill unichem-database","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Funichem-database\u002FSKILL.md",true,[],[49,58,65,72,79,86],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":54,"categories":55,"keywords":56,"publishedAt":57},"01M7DXW9N826PKXK174PVW3038","serpmaven","Scrape Google search results (SERP) to JSON with SERP Maven (serpmaven) - a real Chrome browser on a residential proxy with sticky sessions. Run it as a CLI, a Python library, a local HTTP search API (`serve`), an MCP server or a Docker image; set the proxy login, workers, pages and cost tracking. Use when the user wants Google results, rank tracking, a self-hosted SERP API, or live Google search for an AI agent.","MIT","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fserpmaven\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":57},"01M7DXVHSTWDV65475QEQ915M7","revnu-landing-page-audit","Find out why a landing page isn't turning visitors into signups, demos or sales. Audits one page against what the ad, post or search that sends people there promised, then checks the first screen, proof, call to action, friction and mobile. Returns at most 7 prioritized fixes, plus what is fine and what could not be checked; rewrites specific lines and fixes the page in the repo when asked. Never promises a conversion lift. Works without a Revnu account. Use when the user says or asks: \"audit my landing page\", \"why isn't this page converting\", \"review my homepage\", \"my ads get clicks but no signups\", \"people bounce from the pricing page\", \"CRO review\", \"improve conversion rate\", \"is my hero section clear\", \"roast my landing page\", \"rewrite my headline\", \"what's wrong with this page\", \"landing page feedback\", \"make the signup page convert better\". Not for SEO or AI-search audits, page speed engineering on its own, or building a new page from scratch.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-landing-page-audit\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":57},"01M7DXV8X2D7B3VTD4HHYYHTGR","revnu-growth-context","Write down once who buys, what they're stuck on, what it costs, what proof you have and what you've already tried, so every growth task starts from facts instead of a questionnaire. Creates or updates .agents\u002Frevnu-growth.md from the repo, the live site and the user, and imports an existing product-marketing.md. Use when the user says \"set up our marketing context\", \"who is our ideal customer\", \"write our ICP\", \"describe the product for marketing\", \"positioning doc\", \"what's our brand voice\", \"remember this about our customers\", \"log what we tried\", \"what have we learned from marketing\", \"we changed pricing, update the context\", \"update our growth notes\", \"summarize the business for the agent\", \"import my product-marketing.md\", \"start a growth doc\", or before a first marketing, SEO, outreach or launch task when no context file exists. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-growth-context\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":57},"01M7DXV0DGJ1G0A60PAHC6J3C5","revnu-get-listed","Get onto the third-party pages AI answers and search cite when buyers ask for the best tool in your category: \"best X\" roundups, directories, review sites, GitHub awesome lists, community threads and comparison pages. Finds which ones are cited, ranks them by fit and effort, and drafts each submission, PR or pitch by the target's own rules. Use when the user says \"get us listed\", \"which directories should we submit to\", \"how do we get into best-of lists\", \"why does ChatGPT recommend competitors and not us\", \"get mentioned in AI answers\", \"submit to awesome lists\", \"get on G2\", \"where are our competitors listed\", \"pitch listicle authors\", \"find backlink opportunities\", \"launch directories\", \"get into roundups\", \"Product Hunt alternatives\", \"where should we be listed\", \"get cited by Perplexity\". Never submits, pays or posts without a yes. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-get-listed\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":57},"01M7DXTSPMGT9D6DSS0HP9BSTA","revnu-ai-readiness-audit","Audit whether your website gives ChatGPT, Perplexity, Claude, Gemini and Google's AI Overviews something worth quoting, and fix the pages that don't. Use when the user says or asks \"is my site ready for AI search\", \"audit my site for AI answers\", \"AEO audit\", \"GEO audit\", \"why doesn't ChatGPT quote our pricing\", \"make our pages citable by AI\", \"do I need llms.txt\", \"does schema help with ChatGPT\", \"check our structured data\", \"is our content visible without JavaScript\", \"AI SEO audit\", \"optimize our homepage for AI answers\", \"LLM SEO check\", \"why does AI get our product wrong\", \"fix our site for AI Overviews\". Checks fetchability and indexability, answers in the raw HTML, entity facts, schema (including JS-injected markup), headings, dates and llms.txt, then gives at most 10 prioritised fixes and edits the repo when asked. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-ai-readiness-audit\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":57},"01M7DXSZHCVTRS620GC3S97JZV","proxy-troubleshooting","Diagnose residential proxy failures, with NodeMaven's gateway as the reference - 407 with correct credentials, 406, 410, 500, a connection that hangs, ERR_TUNNEL_CONNECTION_FAILED in a browser, Playwright or Puppeteer ignoring proxy credentials, a sticky session that changes IP, geo-targeting that is silently ignored, passwords with special characters, and unexpected traffic from headless Chrome. Use when a proxy connection fails, returns the wrong location, or costs more traffic than expected.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fproxy-troubleshooting\u002FSKILL.md",[],[]]