检查计算的咖啡因构象
离线预览 PubChem 三维构象,比较键长并审计重原子距离几何。
目标与运行方法
本课适合具备 Python 基础的本科生。先阅读每一步的方法与图注,再修改参数。AI 练习为可选部分,不需要 AI 账号即可完成核心课程。数据写在 notebook metadata 中,不需要另下载数据文件。请保持 notebook 已保存到当前工作文件夹。
学习任务是理解本课的研究问题、执行透明的计算、校验结果,并说明结论的边界。
环境与参数
from pathlib import Path
import base64, gzip, hashlib, json, platform
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import display, HTML
import py3Dmol
from scipy.spatial.distance import cdist
from IPython.display import display as _display
def display(value):
if isinstance(value,pd.DataFrame):
table=value.to_html(max_rows=12,escape=True)
style="<style>.vibeit-readable-table{max-width:100%;overflow-x:auto}.vibeit-readable-table table{width:max-content;max-width:none;border-collapse:collapse}.vibeit-readable-table td,.vibeit-readable-table th{white-space:nowrap!important;word-break:normal!important;overflow-wrap:normal!important}</style>"
return _display(HTML(style+'<div class="vibeit-readable-table">'+table+'</div>'))
return _display(value)
RECIPE_ID='ch03-caffeine-geometry'
OUTPUT_DIR=Path.cwd()/"results"/RECIPE_ID
plt.rcParams.update({"figure.dpi":120,"font.size":10,"axes.spines.top":False,"axes.spines.right":False,
"axes.prop_cycle":plt.cycler(color=["#18785f","#416aa6","#bc6541","#9974a5"])})
print("Python:",platform.python_version(),"; NumPy:",np.__version__,"; Pandas:",pd.__version__)
print("Working folder:",Path.cwd())
print("Core data mode: embedded snapshot; no network requests")
Python: 3.13.13 ; NumPy: 2.5.3 ; Pandas: 3.0.6 Working folder: /Users/zhiluo/Developer/vibeit-cookbook/cookbook/downloads Core data mode: embedded snapshot; no network requests
读取内嵌快照
def load_snapshot(recipe_id, expected_sha256, snapshot_key):
"""Read embedded data from this notebook, including a renamed copy."""
for path in sorted(Path.cwd().glob("*.ipynb")):
try:
notebook = json.loads(path.read_text(encoding="utf-8"))
metadata = notebook.get("metadata", {}).get("vibeit_cookbook", {})
blob = metadata.get("snapshots", {}).get(snapshot_key)
if metadata.get("recipe_id") != recipe_id or not blob:
continue
if blob.get("sha256") != expected_sha256:
continue
raw = gzip.decompress(base64.b64decode(blob["gzip_base64"], validate=True))
if hashlib.sha256(raw).hexdigest() != expected_sha256:
raise ValueError("Embedded snapshot checksum mismatch: " + snapshot_key)
return json.loads(raw)
except (OSError, json.JSONDecodeError):
continue
raise FileNotFoundError(
"Save/open the complete .ipynb in the active working folder. "
"The embedded snapshot could not be located for " + recipe_id)
SNAPSHOT_HASHES={'molecules': '780c5f98bb3b7261465f8330d4b31589d4224cdf21f916b4a1788f11bcc00aac'}
def snapshot(key):
return load_snapshot(RECIPE_ID,SNAPSHOT_HASHES[key],key)
print("Embedded snapshots:",list(SNAPSHOT_HASHES))
Embedded snapshots: ['molecules']
方法函数
def parse_molfile(text):
"""Read V2000 atoms/bonds and formal-charge annotations from one SDF record."""
lines=text.splitlines()
if len(lines)<4 or 'V2000' not in lines[3]:raise ValueError('Expected one V2000 molfile/SDF record')
atom_count=int(lines[3][:3]);bond_count=int(lines[3][3:6])
if atom_count<=0 or len(lines)<4+atom_count+bond_count:raise ValueError('Truncated molfile')
atoms=[];charge_codes={0:0,1:3,2:2,3:1,5:-1,6:-2,7:-3}
for j,line in enumerate(lines[4:4+atom_count]):
element=line[31:34].strip();position=[float(line[:10]),float(line[10:20]),float(line[20:30])]
if not element or not np.isfinite(position).all():raise ValueError('Invalid atom record')
charge_code=int(line[36:39].strip() or 0)
if charge_code not in charge_codes:raise ValueError('Unsupported atom charge/radical code')
atoms.append(dict(index=j,element=element,position=position,formal_charge=charge_codes[charge_code]))
bonds=[];seen=set()
for line in lines[4+atom_count:4+atom_count+bond_count]:
a=int(line[:3])-1;b=int(line[3:6])-1;order=int(line[6:9]);pair=tuple(sorted([a,b]))
if not 0<=a<atom_count or not 0<=b<atom_count or a==b or pair in seen or order not in [1,2,3,4]:
raise ValueError('Invalid or duplicate bond')
seen.add(pair);bonds.append(dict(a=a,b=b,order=order))
for line in lines[4+atom_count+bond_count:]:
if line.startswith('M CHG'):
fields=line.split();count=int(fields[2])
for j in range(count):
index=int(fields[3+2*j])-1;charge=int(fields[4+2*j])
if not 0<=index<atom_count:raise ValueError('Invalid formal-charge atom index')
atoms[index]['formal_charge']=charge
return dict(atoms=atoms,bonds=bonds,title=lines[0],atom_count=atom_count,bond_count=bond_count)
print("Method ready: parse_molfile")
Method ready: parse_molfile
数据与模型边界
PubChem 性质与构象是数据库计算字段,不是新实验测量。本课 V2000 解析范围明确限定为原子、来源键型与形式电荷。滴定及校准使用已声明的理想/模拟教学假设;水蒸气压使用署名的 IAPWS 参考关联式。描述符、距离和视觉邻近不能证明生物活性或结合强度。
分步分析
1. 区分计算构象与实验结构
来源是 PubChem 计算的咖啡因构象,坐标单位为埃并包含显式氢。它不是实验解析蛋白结构,也不是溶剂中的构象集合;来源键连接与几何邻近应分别处理。
molecules=snapshot("molecules");sdf=molecules["caffeine_3d_sdf"];record=parse_molfile(sdf)
positions=np.array([a["position"] for a in record["atoms"]]);elements=np.array([a["element"] for a in record["atoms"]])
heavy=elements!="H";print("Atoms:",len(positions),"; heavy atoms:",int(heavy.sum()),"; coordinate unit: Å; computed conformer")
viewer=py3Dmol.view(width="100%",height=420)
viewer.addModel(sdf,"sdf");viewer.setStyle({"stick":{"radius":.15},"sphere":{"scale":.25}});viewer.setBackgroundColor("white");viewer.zoomTo();viewer.zoom(.7)
display(HTML(viewer._make_html()))
Atoms: 24 ; heavy atoms: 14 ; coordinate unit: Å; computed conformer
3Dmol.js failed to load for some reason. Please check your browser console for error messages.
2. 构造静态几何核对图
静态图使用同一组坐标及来源键,轴单位为埃。它提供无需 WebGL 的离线视图,也不靠画出所有短距离推断键。
colors={"C":"gray","H":"lightgray","N":"royalblue","O":"red"}
fig=plt.figure(figsize=(7,6));ax=fig.add_subplot(projection="3d")
for element in sorted(set(elements)):
mask=elements==element;ax.scatter(*positions[mask].T,color=colors.get(element,"green"),s=35 if element!="H" else 12,label=element)
for bond in record["bonds"]:
pair=positions[[bond["a"],bond["b"]]];ax.plot(*pair.T,color="black",lw=1)
ax.set(xlabel="x (Å)",ylabel="y (Å)",zlabel="z (Å)",title="Calculated caffeine conformer; source bonds");ax.legend();plt.tight_layout();plt.show()
3. 测量来源键长
仅对声明的键端点计算欧氏距离。直方图来自计算构象的几何,不将键长当成键能、力常数或生物结合证据。
bond_lengths=np.array([np.linalg.norm(positions[b["a"]]-positions[b["b"]]) for b in record["bonds"]])
fig,ax=plt.subplots(figsize=(7,4));ax.hist(bond_lengths,bins=15,edgecolor="white")
ax.set(xlabel="Calculated source-bond length (Å)",ylabel="Bonds",title="Geometric lengths, not interaction energies");plt.tight_layout();plt.show()
4. 审计重原子距离矩阵
矩阵包含全部重原子对,对角线为零。距离矩阵描述几何,不编码键型、立体身份或结合实验,应结合声明结构记录解读。
heavy_positions=positions[heavy];distance=cdist(heavy_positions,heavy_positions)
fig,ax=plt.subplots(figsize=(6,5));im=ax.imshow(distance,cmap="viridis")
ax.set(xlabel="Heavy-atom order",ylabel="Heavy-atom order",title="Calculated heavy-atom distances");fig.colorbar(im,ax=ax,label="Distance (Å)");plt.tight_layout();plt.show()
5. 核对几何并导出构象
检查对称性及一个手工重算距离,并检查来源键长均为正。随派生表保留原始 SDF,便于追溯确切计算构象。
assert np.allclose(distance,distance.T) and np.allclose(np.diag(distance),0)
assert np.isclose(distance[0,1],np.sqrt(np.sum((heavy_positions[0]-heavy_positions[1])**2)))
assert np.all(bond_lengths>0) and heavy.sum()==14
OUTPUT_DIR.mkdir(parents=True,exist_ok=True);(OUTPUT_DIR/"caffeine-computed-conformer.sdf").write_text(sdf)
pd.DataFrame(distance).to_csv(OUTPUT_DIR/"heavy-atom-distances-Angstrom.csv",index=False)
pd.DataFrame({"a":[b["a"] for b in record["bonds"]],"b":[b["b"] for b in record["bonds"]],"reported_type":[b["order"] for b in record["bonds"]],"length_Angstrom":bond_lengths}).to_csv(OUTPUT_DIR/"reported-bond-lengths.csv",index=False)
print("Geometry checks passed; exports:",OUTPUT_DIR)
Geometry checks passed; exports: /Users/zhiluo/Developer/vibeit-cookbook/cookbook/downloads/results/ch03-caffeine-geometry
自主练习与参考答案
- 为何区分来源键与几何短距离对?
- 为何单一计算构象不代表溶液动态?
参考解释。 短距离本身不是声明的键。快照是计算模型,没有环境构象集合、动力学或实验。
先保留当前 notebook 副本,再修改参数。把新图与原图一起比较,并记录改变了哪些输入、哪些计算和哪些结论。
可选的 AI 编程练习
提示词 1
仅用 NumPy、SciPy、Matplotlib、py3Dmol 按元素着色并标原子索引,不暗示生物结合。
提示词 2
使用同样的包比较含氢和仅重原子的键长分布。
人工验收。 距离对称、对角为零,保留来源 SDF,单位保持埃。
检查修改后的源代码,再手动运行受影响单元及后续校验。要求助手解释修改的目的、使用的包和数据来源,并用实际输出核对解释。
可选联网扩展
RUN_ONLINE_UPDATE=False
if RUN_ONLINE_UPDATE:
import requests
try:
response=requests.get('https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/2519/property/MolecularFormula/JSON',timeout=20)
response.raise_for_status()
print("Source:",response.url)
print(response.text[:700])
except requests.RequestException as error:
print("Online extension unavailable:",type(error).__name__,str(error)[:160])
else:
print("Online extension skipped; embedded core data unchanged")
Online extension skipped; embedded core data unchanged
来源、快照与下一步
PubChem calculated molecular properties — NCBI public data; PubChem computed properties only; credit PubChem; no third-party narrative annotations included; retrieved 2026-10-09. SHA-256
b01b092cc8872e14fdab1fdc608c783669131a081c71d9ccee77c0bb9c6ff408. Keep the returned calculated fields for eight declared CIDs; molecular weight converted from API numeric string.PubChem 2D SDF 702 — NCBI public data; PubChem standardized structure; credit PubChem; retrieved 2026-10-09. SHA-256
5962afc9ee8115dee9d5e63cefeef89cdc47641420b34afe156062d263c9caa7. Preserve complete standardized SDF, including CID and explicit hydrogen/bond fields.PubChem 2D SDF 176 — NCBI public data; PubChem standardized structure; credit PubChem; retrieved 2026-10-09. SHA-256
f51353e1db0a0be8aa3aeb7bea28b6febb1e1f8afdf88fbf298405851f7ee092. Preserve complete standardized SDF, including CID and explicit hydrogen/bond fields.PubChem 2D SDF 241 — NCBI public data; PubChem standardized structure; credit PubChem; retrieved 2026-10-09. SHA-256
3f4698bd6773f5e709184759048c116d106ac392e874676444b64af254e9a189. Preserve complete standardized SDF, including CID and explicit hydrogen/bond fields.PubChem 2D SDF 887 — NCBI public data; PubChem standardized structure; credit PubChem; retrieved 2026-10-09. SHA-256
5cf6d180935f2fe77d20772a4bf2506711d4436762f6c6801157ac748f088530. Preserve complete standardized SDF, including CID and explicit hydrogen/bond fields.PubChem 2D SDF 180 — NCBI public data; PubChem standardized structure; credit PubChem; retrieved 2026-10-09. SHA-256
6ecceacce326b6ecc292dedd946f589e879c999f43242395d995b59a8c8eb128. Preserve complete standardized SDF, including CID and explicit hydrogen/bond fields.PubChem 2D SDF 2519 — NCBI public data; PubChem standardized structure; credit PubChem; retrieved 2026-10-09. SHA-256
47293391d630f44f2a32c3f7702d766744c8f4a4f16f6571d4ae09f04b3daaed. Preserve complete standardized SDF, including CID and explicit hydrogen/bond fields.PubChem 2D SDF 2244 — NCBI public data; PubChem standardized structure; credit PubChem; retrieved 2026-10-09. SHA-256
0dfd04496745032c06410241f91f10fcec77cbc6828cdbede75f4c08da418fbb. Preserve complete standardized SDF, including CID and explicit hydrogen/bond fields.PubChem 2D SDF 750 — NCBI public data; PubChem standardized structure; credit PubChem; retrieved 2026-10-09. SHA-256
e1c2ddd732cea1d052a9426c9a25fef86acd1309748bb2115cf2b56481ba288f. Preserve complete standardized SDF, including CID and explicit hydrogen/bond fields.PubChem caffeine 3D conformer — NCBI public data; PubChem computed conformer; credit PubChem; retrieved 2026-10-09. SHA-256
2a78d98d09d50768fe3f6e6114d7baf3dad9cf88e41835735f96abf5867f5092. Preserve calculated coordinates and conformer identifiers; not an experimental crystal structure.
下一步。 在保留本课的数据检查、参数记录和结果校验之后,将相同方法用于自己的公开或已获授权数据。记录研究设计与方法限制,不把示例结果当成新实验的验证。完整数据许可与生成说明见 cookbook 网页。