ChAFF / CHAFF_processing_scripts /st1_download_pubchem.py
haneulpark's picture
Upload 5 files
e623e49 verified
raw
history blame
4.17 kB
#!/usr/bin/env python3
"""
Download canonical SMILES and assay outcome for all compounds in a PubChem BioAssay (AID).
Uses ListKey interface to handle large assays (>10,000 compounds).
Usage:
python download_pubchem.py 584 --output smiles_with_outcome.csv
"""
import argparse
import csv
import sys
import time
import requests
from typing import Dict, Tuple
from io import StringIO
PUG_BASE = "https://pubchem.ncbi.nlm.nih.gov/rest/pug"
def get_listkey_for_aid(aid: str) -> Tuple[str, int]:
"""Get ListKey and size for a given AID (used to retrieve large CID sets)."""
url = f"{PUG_BASE}/assay/aid/{aid}/cids/JSON?list_return=listkey"
try:
resp = requests.get(url, timeout=20)
resp.raise_for_status()
data = resp.json()["IdentifierList"]
listkey = data["ListKey"]
size = data["Size"]
print(f"Retrieved ListKey: {listkey} with {size} CIDs.")
return listkey, size
except Exception as e:
print(f"Error retrieving ListKey for AID {aid}: {e}", file=sys.stderr)
sys.exit(1)
def fetch_smiles_from_listkey(listkey: str) -> Dict[int, str]:
"""Fetch SMILES in batches using ListKey."""
smiles_dict = {}
url = f"{PUG_BASE}/compound/listkey/{listkey}/property/SMILES/CSV"
try:
resp = requests.get(url, timeout=30)
resp.raise_for_status()
reader = csv.DictReader(StringIO(resp.text))
count = 0
for row in reader:
cid = int(row["CID"])
smiles = row["SMILES"]
smiles_dict[cid] = smiles
count += 1
print(f"Fetched {count} SMILES")
except Exception as e:
print(f"Error fetching SMILES: {e}", file=sys.stderr)
return smiles_dict
def fetch_outcomes_from_listkey(aid: int, listkey: str, size: int, batch_size: int, delay: float) -> Dict[int, str]:
"""Fetch outcomes in batches using ListKey."""
outcomes = {}
for start in range(0, size, batch_size):
url = f"{PUG_BASE}/assay/aid/{aid}/CSV?cid=listkey&listkey={listkey}&listkey_start={start}&listkey_count={batch_size}"
try:
resp = requests.get(url, timeout=30)
resp.raise_for_status()
reader = csv.DictReader(StringIO(resp.text))
for row in reader:
if "PUBCHEM_CID" in row and row["PUBCHEM_CID"].isdigit():
cid = int(row["PUBCHEM_CID"])
outcome = row.get("PUBCHEM_ACTIVITY_OUTCOME", "Unavailable")
outcomes[cid] = outcome
print(f"Fetched outcomes for {len(outcomes)} compounds.")
time.sleep(delay)
except Exception as e:
print(f"Error fetching assay outcomes: {e}", file=sys.stderr)
sys.exit(1)
return outcomes
def write_to_csv(smiles_dict: Dict[int, str], outcomes: Dict[int, str], output_file: str):
"""Write combined CID, SMILES, and outcome to CSV."""
with open(output_file, "w", newline='') as f:
writer = csv.writer(f)
writer.writerow(["CID", "CanonicalSMILES", "AssayOutcome"])
for cid, smiles in smiles_dict.items():
outcome = outcomes.get(cid, "Unavailable")
writer.writerow([cid, smiles, outcome])
print(f"Saved {len(smiles_dict)} entries to {output_file}")
def main():
parser = argparse.ArgumentParser(description="Download SMILES and outcome using ListKey for a PubChem assay")
parser.add_argument("aid", help="PubChem Assay ID (AID)")
parser.add_argument("--output", "-o", default="smiles_with_outcome.csv", help="Output CSV file")
parser.add_argument("--batch-size", type=int, default=10000, help="Batch size for ListKey download")
parser.add_argument("--delay", type=float, default=0.5, help="Delay between batches (in seconds)")
args = parser.parse_args()
listkey, size = get_listkey_for_aid(args.aid)
smiles_dict = fetch_smiles_from_listkey(listkey)
outcomes = fetch_outcomes_from_listkey(args.aid, listkey, size, batch_size=args.batch_size, delay=args.delay)
write_to_csv(smiles_dict, outcomes, args.output)
if __name__ == "__main__":
main()