mcpField
P
pubchem-database

pubchem-database

github.com/jackspace数据与数据库1636 次安装12 周前更新
代码仓库

关于 pubchem-database

pubchem-database 是面向化学与药物研究的 PubChem 数据查询技能,可按名称、结构或标识符查找化合物并获取性质与生物活性。它还支持结构相似性和子结构搜索、标识符转换及批量分析。

主要功能

  1. 01按名称、CID、SMILES 等搜索化合物
  2. 02获取分子性质与注释
  3. 03进行相似性和子结构搜索
  4. 04查询生物活性与测定信息
  5. 05转换化学结构标识符
  6. 06批量检索并下载结构图

适用场景

  1. 01筛选具有特定结构基团的化合物
  2. 02比较候选化合物的分子性质
  3. 03查找与已知药物相似的化合物
  4. 04按靶标查询测定活性数据

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/jackspace/claudeskillz --skill pubchem-database

安装后在 Claude Code 中输入/pubchem-database确认已加载。

附带文件SKILL.json

详细介绍

PubChem 数据库

概述

PubChem 是全球最大的免费化学数据库,收录了超过 1.1 亿种化合物和超过 2.7 亿条生物活性数据。可按名称、CID 或 SMILES 查询化学结构、检索分子属性、执行相似性和子结构搜索,并通过 PUG-REST API 和 PubChemPy 访问生物活性数据。

何时使用此技能

在以下情况下使用此技能:

  • 按名称、结构(SMILES/InChI)或分子式搜索化合物
  • 检索分子属性(MW、LogP、TPSA、氢键描述符)
  • 执行相似性搜索,查找结构相关的化合物
  • 进行子结构搜索,查找特定的化学基团
  • 访问筛选实验中的生物活性数据
  • 在化学标识符格式(CID、SMILES、InChI)之间转换
  • 批量处理多个化合物,进行类药性筛选或属性分析

核心功能

1. 化学结构搜索

使用多种标识符类型搜索化合物:

按化学名称搜索:

import pubchempy as pcp
compounds = pcp.get_compounds('aspirin', 'name')
compound = compounds[0]

按 CID(化合物 ID)搜索:

compound = pcp.Compound.from_cid(2244)  # Aspirin

按 SMILES 搜索:

compound = pcp.get_compounds('CC(=O)OC1=CC=CC=C1C(=O)O', 'smiles')[0]

按 InChI 搜索:

compound = pcp.get_compounds('InChI=1S/C9H8O4/...', 'inchi')[0]

按分子式搜索:

compounds = pcp.get_compounds('C9H8O4', 'formula')
# Returns all compounds matching this formula
2. 属性检索

使用高层或底层方法检索化合物的分子属性:

使用 PubChemPy(推荐):

import pubchempy as pcp

# Get compound object with all properties
compound = pcp.get_compounds('caffeine', 'name')[0]

# Access individual properties
molecular_formula = compound.molecular_formula
molecular_weight = compound.molecular_weight
iupac_name = compound.iupac_name
smiles = compound.canonical_smiles
inchi = compound.inchi
xlogp = compound.xlogp  # Partition coefficient
tpsa = compound.tpsa    # Topological polar surface area

获取特定属性:

# Request only specific properties
properties = pcp.get_properties(
    ['MolecularFormula', 'MolecularWeight', 'CanonicalSMILES', 'XLogP'],
    'aspirin',
    'name'
)
# Returns list of dictionaries

批量检索属性:

import pandas as pd

compound_names = ['aspirin', 'ibuprofen', 'paracetamol']
all_properties = []

for name in compound_names:
    props = pcp.get_properties(
        ['MolecularFormula', 'MolecularWeight', 'XLogP'],
        name,
        'name'
    )
    all_properties.extend(props)

df = pd.DataFrame(all_properties)

可用属性:MolecularFormula、MolecularWeight、CanonicalSMILES、IsomericSMILES、InChI、InChIKey、IUPACName、XLogP、TPSA、HBondDonorCount、HBondAcceptorCount、RotatableBondCount、Complexity、Charge 等等(完整列表请参阅 references/api_reference.md)。

3. 相似性搜索

使用 Tanimoto 相似度查找结构相似的化合物:

import pubchempy as pcp

# Start with a query compound
query_compound = pcp.get_compounds('gefitinib', 'name')[0]
query_smiles = query_compound.canonical_smiles

# Perform similarity search
similar_compounds = pcp.get_compounds(
    query_smiles,
    'smiles',
    searchtype='similarity',
    Threshold=85,  # Similarity threshold (0-100)
    MaxRecords=50
)

# Process results
for compound in similar_compounds[:10]:
    print(f"CID {compound.cid}: {compound.iupac_name}")
    print(f"  MW: {compound.molecular_weight}")

注意:对于大型查询,相似性搜索采用异步方式,可能需要 15-30 秒才能完成。PubChemPy 会自动处理异步模式。

4. 子结构搜索

查找包含特定结构基团的化合物:

import pubchempy as pcp

# Search for compounds containing pyridine ring
pyridine_smiles = 'c1ccncc1'

matches = pcp.get_compounds(
    pyridine_smiles,
    'smiles',
    searchtype='substructure',
    MaxRecords=100
)

print(f"Found {len(matches)} compounds containing pyridine")

常见子结构:

  • 苯环:c1ccccc1
  • 吡啶:c1ccncc1
  • 苯酚:c1ccc(O)cc1
  • 羧酸:C(=O)O
5. 格式转换

在不同的化学结构格式之间转换:

import pubchempy as pcp

compound = pcp.get_compounds('aspirin', 'name')[0]

# Convert to different formats
smiles = compound.canonical_smiles
inchi = compound.inchi
inchikey = compound.inchikey
cid = compound.cid

# Download structure files
pcp.download('SDF', 'aspirin', 'name', 'aspirin.sdf', overwrite=True)
pcp.download('JSON', '2244', 'cid', 'aspirin.json', overwrite=True)
6. 结构可视化

生成 2D 结构图像:

import pubchempy as pcp

# Download compound structure as PNG
pcp.download('PNG', 'caffeine', 'name', 'caffeine.png', overwrite=True)

# Using direct URL (via requests)
import requests

cid = 2244  # Aspirin
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{cid}/PNG?image_size=large"
response = requests.get(url)

with open('structure.png', 'wb') as f:
    f.write(response.content)
7. 同义词检索

获取化合物的所有已知名称和同义词:

import pubchempy as pcp

synonyms_data = pcp.get_synonyms('aspirin', 'name')

if synonyms_data:
    cid = synonyms_data[0]['CID']
    synonyms = synonyms_data[0]['Synonym']

    print(f"CID {cid} has {len(synonyms)} synonyms:")
    for syn in synonyms[:10]:  # First 10
        print(f"  - {syn}")
8. 生物活性数据访问

从实验中检索生物活性数据:

import requests
import json

# Get bioassay summary for a compound
cid = 2244  # Aspirin
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{cid}/assaysummary/JSON"

response = requests.get(url)
if response.status_code == 200:
    data = response.json()
    # Process bioassay information
    table = data.get('Table', {})
    rows = table.get('Row', [])
    print(f"Found {len(rows)} bioassay records")

对于更复杂的生物活性查询,请使用辅助脚本 scripts/bioactivity_query.py,它提供:

  • 可按活性结果筛选的生物测定摘要
  • 测定靶标识别
  • 按生物靶标搜索化合物
  • 特定测定的活性化合物列表
9. 全面的化合物注释

通过 PUG-View 访问详细的化合物信息:

import requests

cid = 2244
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/data/compound/{cid}/JSON"

response = requests.get(url)
if response.status_code == 200:
    annotations = response.json()
    # Contains extensive data including:
    # - Chemical and Physical Properties
    # - Drug and Medication Information
    # - Pharmacology and Biochemistry
    # - Safety and Hazards
    # - Toxicity
    # - Literature references
    # - Patents

获取特定部分:

# Get only drug information
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/data/compound/{cid}/JSON?heading=Drug and Medication Information"

安装要求

安装 PubChemPy,以便通过 Python 访问:

pip install pubchempy

若要直接访问 API 并查询生物活性:

pip install requests

数据分析的可选项:

pip install pandas

辅助脚本

此技能包含用于常见 PubChem 任务的 Python 脚本:

scripts/compound_search.py

提供用于搜索和获取化合物信息的实用函数:

主要函数:

  • search_by_name(name, max_results=10):按名称搜索化合物
  • search_by_smiles(smiles):按 SMILES 字符串搜索
  • get_compound_by_cid(cid):按 CID 获取化合物
  • get_compound_properties(identifier, namespace, properties):获取指定属性
  • similarity_search(smiles, threshold, max_records):执行相似性搜索
  • substructure_search(smiles, max_records):执行子结构搜索
  • get_synonyms(identifier, namespace):获取所有同义词
  • batch_search(identifiers, namespace, properties):批量搜索多个化合物
  • download_structure(identifier, namespace, format, filename):下载结构
  • print_compound_info(compound):打印格式化的化合物信息

用法:

from scripts.compound_search import search_by_name, get_compound_properties

# Search for a compound
compounds = search_by_name('ibuprofen')

# Get specific properties
props = get_compound_properties('aspirin', 'name', ['MolecularWeight', 'XLogP'])
scripts/bioactivity_query.py

提供用于获取生物活性数据的函数:

主要函数:

  • get_bioassay_summary(cid):获取化合物的生物测定摘要
  • get_compound_bioactivities(cid, activity_outcome):获取筛选后的生物活性数据
  • get_assay_description(aid):获取详细的测定信息
  • get_assay_targets(aid):获取测定的生物靶点
  • search_assays_by_target(target_name, max_results):按靶点查找测定
  • get_active_compounds_in_assay(aid, max_results):获取活性化合物
  • get_compound_annotations(cid, section):获取 PUG-View 注释
  • summarize_bioactivities(cid):生成生物活性汇总统计数据
  • find_compounds_by_bioactivity(target, threshold, max_compounds):按靶点查找化合物

用法:

from scripts.bioactivity_query import get_bioassay_summary, summarize_bioactivities

# Get bioactivity summary
summary = summarize_bioactivities(2244)  # Aspirin
print(f"Total assays: {summary['total_assays']}")
print(f"Active: {summary['active']}, Inactive: {summary['inactive']}")

API 速率限制与最佳实践

速率限制:

  • 每秒最多 5 个请求
  • 每分钟最多 400 个请求
  • 每分钟运行时间最多 300 秒

最佳实践:

  1. 重复查询时使用 CID:CID 比名称或结构更高效
  2. 在本地缓存结果:存储经常访问的数据
  3. 批量请求:尽可能合并多个查询
  4. 添加延迟:在请求之间添加 0.2-0.3 秒的延迟
  5. 妥善处理错误:检查 HTTP 错误和缺失数据
  6. 使用 PubChemPy:更高层级的抽象可处理许多边缘情况
  7. 利用异步模式:适用于大型相似性/子结构搜索
  8. 指定 MaxRecords:限制结果数量,避免超时

错误处理:

from pubchempy import BadRequestError, NotFoundError, TimeoutError

try:
    compound = pcp.get_compounds('query', 'name')[0]
except NotFoundError:
    print("Compound not found")
except BadRequestError:
    print("Invalid request format")
except TimeoutError:
    print("Request timed out - try reducing scope")
except IndexError:
    print("No results returned")

常见工作流

工作流 1:化学标识符转换流程

在不同的化学标识符之间进行转换:

import pubchempy as pcp

# Start with any identifier type
compound = pcp.get_compounds('caffeine', 'name')[0]

# Extract all identifier formats
identifiers = {
    'CID': compound.cid,
    'Name': compound.iupac_name,
    'SMILES': compound.canonical_smiles,
    'InChI': compound.inchi,
    'InChIKey': compound.inchikey,
    'Formula': compound.molecular_formula
}
工作流 2:类药性属性筛选

使用 Lipinski 五规则筛选化合物:

import pubchempy as pcp

def check_drug_likeness(compound_name):
    compound = pcp.get_compounds(compound_name, 'name')[0]

    # Lipinski's Rule of Five
    rules = {
        'MW <= 500': compound.molecular_weight <= 500,
        'LogP <= 5': compound.xlogp <= 5 if compound.xlogp else None,
        'HBD <= 5': compound.h_bond_donor_count <= 5,
        'HBA <= 10': compound.h_bond_acceptor_count <= 10
    }

    violations = sum(1 for v in rules.values() if v is False)
    return rules, violations

rules, violations = check_drug_likeness('aspirin')
print(f"Lipinski violations: {violations}")
工作流 3:查找相似的候选药物

查找与已知药物结构相似的化合物:

import pubchempy as pcp

# Start with known drug
reference_drug = pcp.get_compounds('imatinib', 'name')[0]
reference_smiles = reference_drug.canonical_smiles

# Find similar compounds
similar = pcp.get_compounds(
    reference_smiles,
    'smiles',
    searchtype='similarity',
    Threshold=85,
    MaxRecords=20
)

# Filter by drug-like properties
candidates = []
for comp in similar:
    if comp.molecular_weight and 200 <= comp.molecular_weight <= 600:
        if comp.xlogp and -1 <= comp.xlogp <= 5:
            candidates.append(comp)

print(f"Found {len(candidates)} drug-like candidates")
工作流 4:批量比较化合物属性

比较多个化合物的属性:

import pubchempy as pcp
import pandas as pd

compound_list = ['aspirin', 'ibuprofen', 'naproxen', 'celecoxib']

properties_list = []
for name in compound_list:
    try:
        compound = pcp.get_compounds(name, 'name')[0]
        properties_list.append({
            'Name': name,
            'CID': compound.cid,
            'Formula': compound.molecular_formula,
            'MW': compound.molecular_weight,
            'LogP': compound.xlogp,
            'TPSA': compound.tpsa,
            'HBD': compound.h_bond_donor_count,
            'HBA': compound.h_bond_acceptor_count
        })
    except Exception as e:
        print(f"Error processing {name}: {e}")

df = pd.DataFrame(properties_list)
print(df.to_string(index=False))
工作流 5:基于子结构的虚拟筛选

筛选包含特定药效团的化合物:

import pubchempy as pcp

# Define pharmacophore (e.g., sulfonamide group)
pharmacophore_smiles = 'S(=O)(=O)N'

# Search for compounds containing this substructure
hits = pcp.get_compounds(
    pharmacophore_smiles,
    'smiles',
    searchtype='substructure',
    MaxRecords=100
)

# Further filter by properties
filtered_hits = [
    comp for comp in hits
    if comp.molecular_weight and comp.molecular_weight < 500
]

print(f"Found {len(filtered_hits)} compounds with desired substructure")

参考文档

如需详细的 API 文档,包括完整的属性列表、URL 模式、高级查询选项和更多示例,请参阅 references/api_reference.md。这份全面的参考文档包括:

  • 完整的 PUG-REST API 端点文档
  • 所有可用分子属性的完整列表
  • 异步请求处理模式
  • PubChemPy API 参考
  • 用于注释的 PUG-View API
  • 常见工作流和用例
  • PubChem 官方文档链接

故障排除

未找到化合物:

  • 尝试其他名称或同义词
  • 如果知道 CID,请使用 CID
  • 检查拼写和化学名称格式

超时错误:

  • 减小 MaxRecords 参数
  • 在请求之间添加延迟
  • 使用 CID 而非名称,以加快查询速度

属性值为空:

  • 并非所有化合物都具备所有属性
  • 访问前请检查属性是否存在:if compound.xlogp:
  • 某些属性仅适用于特定类型的化合物

超出速率限制:

  • 在请求之间添加延迟(0.2-0.3 秒)
  • 尽可能使用批量操作
  • 考虑在本地缓存结果

相似性/子结构搜索挂起:

  • 这些是异步操作,可能需要 15-30 秒
  • PubChemPy 会自动处理轮询
  • 如果发生超时,请减小 MaxRecords

更多资源

评论

支持 Markdown