1.1 课程结构的整体连贯性
这份 AIDD 课程从基础到高级,逐步引导学习者从 Python 编程基础到复杂的人工智能药物设计任务,整体结构具有较好的连贯性。具体分析如下:
循序渐进的知识构建:
Day 1-3:从 Python 基础(变量、数据类型、控制流)开始,快速建立编程基础,适合初学者。这些内容为后续处理化学数据(如分子量、毒性评分)奠定了基础。
Day 4-5:引入函数和高级数据结构(如列表、字典),并结合 AIDD 场景(如 SMILES 字符串解析、分子属性计算),逐步过渡到药物发现的实际应用。
Day 6-7:引入数据科学库(NumPy、Pandas、Matplotlib)和机器学习基础(如线性回归、深度学习),为处理大规模化学数据和分子属性预测提供了工具。
Day 27-32:深入到高级主题,如强化学习(RL)、多目标优化(MOO)、迁移学习和分子模拟,逐步引导学习者处理复杂的药物设计问题。
这种从基础到高级、从简单编程到复杂算法的结构符合学习曲线的设计,确保了知识点的递进性。
AIDD 场景的贯穿性:
每个阶段都以 AIDD 为背景,结合具体的药物发现任务(如毒性预测、结合亲和力优化、合成路径预测),使学习内容与实际应用紧密相关。
课程通过反复使用 SMILES 字符串、分子量、IC50/pIC50 等核心概念,强化了 AIDD 领域的核心知识点,确保学习者在不同阶段都能围绕药物发现的核心问题展开学习。
实践导向:
每一天的课程都包含实践练习,涵盖从简单的数据处理到复杂的模型训练任务。这种“学-练-用”的模式有助于学习者将理论知识转化为实际能力。
练习任务与 AIDD 的实际问题高度相关,如计算分子量、筛选化合物、预测毒性等,增强了课程的实用性。
1.2 存在的潜在问题
尽管整体连贯性较好,但课程在某些方面仍存在改进空间:
基础与高级内容的衔接:
Day 1-5 的基础内容到 Day 6-7 的机器学习和深度学习之间存在一定跳跃性。对于没有机器学习背景的学习者,可能会感到从基础编程到复杂模型的过渡较为陡峭。
例如,Day 6 直接引入 NumPy、Pandas 和机器学习模型(如线性回归),但缺乏对机器学习基本概念(如特征工程、模型评估)的详细介绍。
化学知识的融入不足:
课程中虽然提到了 SMILES 字符串、分子量、IC50 等化学概念,但对化学背景知识(如分子结构、化学键、药物代谢动力学)的解释较为有限。这可能导致非化学专业背景的学习者在理解 AIDD 任务时遇到困难。
工具与库的介绍深度不足:
课程中使用的库(如 RDKit、TensorFlow、ChemBERTa)虽然在 AIDD 中非常重要,但对这些工具的安装、配置和使用场景的介绍较为简略。初学者可能需要更多指导来上手这些专业工具。
高级主题的覆盖范围:
Day 27-32 涵盖了强化学习、多目标优化和迁移学习等高级主题,但这些内容较为集中,可能导致学习者在短时间内难以深入掌握。例如,强化学习(RL)的 Q-learning 实现较为简化,缺乏对更复杂 RL 算法(如 DQN、PPO)的介绍。
数据集的获取与处理:
课程中提到了一些数据集(如毒性数据、SMILES 数据),但没有详细说明如何获取真实化学数据集(如 PubChem、ChEMBL)或如何处理数据中的噪声和缺失值。这在实际 AIDD 项目中是关键问题。
二、如何插入更多知识以优化课程
为了提升课程的连贯性和实用性,可以在以下几个方面插入更多知识点,确保内容更加全面且适合不同背景的学习者。
2.1 加强基础与高级内容的衔接
为了平滑从基础编程到高级机器学习和 AIDD 应用的过渡,可以在 Day 5-6 之间插入以下内容:
Day 5.5:机器学习基础与 AIDD 应用入门:
内容:
介绍机器学习的基本概念:监督学习、无监督学习、回归与分类。
解释特征工程在 AIDD 中的作用,如分子描述符(分子量、LogP、可旋转键数等)的提取。
介绍模型评估指标(如均方误差 MSE、准确率、F1 分数)及其在 AIDD 中的意义。
示例:
from sklearn.metrics import mean_squared_error, r2_score
# 示例:评估分子量预测模型的性能
y_true = [180.2, 206.3, 151.2] # 真实分子量
y_pred = [182.0, 204.5, 150.0] # 预测分子量
mse = mean_squared_error(y_true, y_pred)
r2 = r2_score(y_true, y_pred)
print(f"均方误差 (MSE): {mse:.2f}")
print(f"R² 分数: {r2:.2f}")练习:
编写代码,基于分子量和 IC50 数据,使用线性回归模型预测毒性评分,并计算 MSE 和 R² 分数。
AIDD 相关性:
通过分子描述符和简单的机器学习模型,学习者可以更平滑地过渡到 Day 6 的复杂模型,理解机器学习在药物发现中的实际应用。
Day 6.5:化学信息学工具与数据集处理:
内容:
详细介绍 RDKit 的安装、配置和核心功能(如 SMILES 解析、分子描述符计算)。
讲解如何从 PubChem、ChEMBL 等数据库获取化学数据,并处理数据中的缺失值、异常值和格式问题。
介绍数据预处理技术,如归一化、标准化和特征选择。
示例:
from rdkit import Chem
from rdkit.Chem import Descriptors
import pandas as pd
# 从 CSV 文件加载 SMILES 数据
data = pd.read_csv("compounds.csv")
smiles_list = data["smiles"]
# 计算分子描述符
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
if mol:
mw = Descriptors.MolWt(mol)
logp = Descriptors.MolLogP(mol)
descriptors.append([mw, logp])
# 创建 DataFrame
df = pd.DataFrame(descriptors, columns=["Molecular_Weight", "LogP"])
print(df)练习:
从 ChEMBL 下载一个小型数据集,提取 SMILES 字符串并计算分子量和 LogP。
清洗数据,处理缺失的 SMILES 字符串,并对分子量进行归一化。
AIDD 相关性:
帮助学习者掌握化学信息学工具的使用,并理解如何处理真实的化学数据集,为后续的机器学习任务做好准备。
2.2 补充化学与药物设计背景知识
为了让非化学背景的学习者更好地理解 AIDD 任务,可以在 Day 2 或 Day 3 插入一节基础化学知识模块:
Day 2.5:AIDD 中的化学基础:
内容:
介绍分子结构的基本概念:原子、化学键、官能团。
讲解 SMILES 字符串的语法和表示方法。
介绍药物发现中的核心指标:分子量、LogP、IC50/pIC50、结合亲和力、ADMET 属性(吸收、分布、代谢、排泄、毒性)。
简述 Lipinski 五规则(Rule of Five)及其在药物筛选中的作用。
示例:
from rdkit import Chem
from rdkit.Chem import Lipinski
# 检查化合物的 Lipinski 规则
def check_lipinski(smiles):
mol = Chem.MolFromSmiles(smiles)
if mol:
mw = Descriptors.MolWt(mol)
logp = Descriptors.MolLogP(mol)
h_donors = Lipinski.NumHDonors(mol)
h_acceptors = Lipinski.NumHAcceptors(mol)
return mw <= 500 and logp <= 5 and h_donors <= 5 and h_acceptors <= 10
return False
# 示例:检查阿司匹林是否符合 Lipinski 规则
aspirin_smiles = "CC(=O)OC1=CC=CC=C1C(=O)O"
is_drug_like = check_lipinski(aspirin_smiles)
print(f"阿司匹林是否符合 Lipinski 规则:{is_drug_like}")练习:
编写代码,检查一组化合物的 SMILES 字符串是否符合 Lipinski 规则。
研究 LogP 和 IC50 在药物设计中的意义,并尝试解释其与毒性的关系。
AIDD 相关性:
通过介绍化学基础,帮助学习者理解药物设计的背景知识,从而更好地应用 Python 代码处理 AIDD 任务。
2.3 增强高级主题的深度
在 Day 27-32 的高级主题中,可以增加以下内容以提升课程深度:
Day 27.5:强化学习的进阶算法:
内容:
介绍更复杂的 RL 算法,如深度 Q 网络(DQN)、近端策略优化(PPO)或 Actor-Critic 方法。
讲解 RL 在 AIDD 中的具体应用场景,如分子生成(生成新化合物的 SMILES 字符串)或药物优化中的多目标奖励函数。
示例:
import gym
from stable_baselines3 import PPO
import numpy as np
# 自定义分子优化环境
class MoleculeOptimizationEnv(gym.Env):
def __init__(self):
super().__init__()
self.action_space = gym.spaces.Discrete(10) # 10 种分子修改操作
self.observation_space = gym.spaces.Box(low=0, high=1, shape=(50,)) # 分子特征向量
self.state = np.random.rand(50) # 初始分子状态
def step(self, action):
# 执行分子修改操作
reward = self.calculate_reward(self.state, action)
self.state = self.modify_molecule(self.state, action)
done = self.is_done(self.state)
return self.state, reward, done, {}
def reset(self):
self.state = np.random.rand(50)
return self.state
def calculate_reward(self, state, action):
# 模拟奖励函数(基于结合亲和力)
return np.random.rand() # 简化示例
def modify_molecule(self, state, action):
# 修改分子(简化示例)
return state + np.random.rand(50) * 0.1
def is_done(self, state):
return False # 简化示例
# 使用 PPO 算法优化分子
env = MoleculeOptimizationEnv()
model = PPO("MlpPolicy", env, verbose=1)
model.learn(total_timesteps=10000)练习:
实现一个自定义的分子优化环境,定义奖励函数基于结合亲和力和毒性。
使用 PPO 算法训练 RL 模型,优化一个虚拟化合物的分子结构。
AIDD 相关性:
提供更实际的 RL 算法示例,帮助学习者理解如何在药物设计中实现动态优化。
Day 28.5:多目标优化的可视化与分析:
内容:
深入讲解 Pareto 前沿的计算和可视化方法。
介绍 NSGA-II 的具体实现细节,如非支配排序和拥挤距离的计算。
提供 Pareto 前沿的分析工具,帮助学习者选择最佳候选药物。
示例:
import matplotlib.pyplot as plt
import numpy as np
from deap import base, creator, tools, algorithms
# 定义多目标优化问题
creator.create("FitnessMulti", base.Fitness, weights=(1.0, -1.0)) # 最大化结合亲和力,最小化毒性
creator.create("Individual", list, fitness=creator.FitnessMulti)
def evaluate_individual(individual):
binding_affinity = sum(individual[:5]) # 简化示例:结合亲和力
toxicity = sum(individual[5:]) # 简化示例:毒性
return binding_affinity, toxicity
# 配置 NSGA-II
toolbox = base.Toolbox()
toolbox.register("attr_float", np.random.rand)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_float, n=10)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
toolbox.register("evaluate", evaluate_individual)
toolbox.register("mate", tools.cxBlend, alpha=0.5)
toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=0.2, indpb=0.2)
toolbox.register("select", tools.selNSGA2)
# 运行 NSGA-II
pop = toolbox.population(n=100)
algorithms.eaMuPlusLambda(pop, toolbox, mu=100, lambda_=100, cxpb=0.7, mutpb=0.3, ngen=50, verbose=False)
# 可视化 Pareto 前沿
fronts = tools.sortNondominated(pop, len(pop), first_front_only=True)
binding_affinities = [ind.fitness.values[0] for ind in fronts[0]]
toxicities = [ind.fitness.values[1] for ind in fronts[0]]
plt.scatter(binding_affinities, toxicities)
plt.xlabel("Binding Affinity")
plt.ylabel("Toxicity")
plt.title("Pareto Front: Binding Affinity vs Toxicity")
plt.show()练习:
使用 NSGA-II 优化一个包含结合亲和力、毒性和生物利用度的多目标问题。
可视化 Pareto 前沿,并分析候选化合物的权衡关系。
AIDD 相关性:
通过可视化和分析 Pareto 前沿,学习者可以更直观地理解多目标优化在药物设计中的应用。
2.4 增加真实项目案例
为了增强课程的实践性和真实性,可以在 Day 30-32 后插入一个综合案例模块:
Day 32.5:AIDD 综合项目:从数据到药物候选:
内容:
提供一个完整的 AIDD 项目案例,从数据获取到药物候选筛选。
包括以下步骤:
从 ChEMBL 下载化合物数据集,包含 SMILES 字符串和 IC50 值。
使用 RDKit 提取分子描述符(如分子量、LogP)。
构建一个简单的深度学习模型预测 IC50。
使用强化学习优化候选化合物的结构。
可视化模型预测结果和 Pareto 前沿。
示例:
import pandas as pd
from rdkit import Chem
from rdkit.Chem import Descriptors
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import matplotlib.pyplot as plt
# 1. 加载 ChEMBL 数据
data = pd.read_csv("chembl_data.csv")
smiles_list = data["smiles"]
ic50_values = data["ic50"]
# 2. 提取分子描述符
features = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
if mol:
features.append([Descriptors.MolWt(mol), Descriptors.MolLogP(mol)])
# 3. 训练深度学习模型
X = np.array(features)
y = np.array(ic50_values)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = Sequential([
Dense(64, activation='relu', input_shape=(2,)),
Dense(32, activation='relu'),
Dense(1)
])
model.compile(optimizer='adam', loss='mean_squared_error')
history = model.fit(X_train, y_train, epochs=50, validation_data=(X_test, y_test))
# 4. 可视化训练过程
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.title('Model Training Loss')
plt.legend()
plt.show()练习:
完成一个完整的 AIDD 项目,从数据获取到模型训练和优化。
使用强化学习进一步优化候选化合物的 IC50。
AIDD 相关性:
通过真实案例,学习者可以整合前 32 天的知识,完成一个从头到尾的药物发现流程,增强实践能力。
三、优化后的课程结构建议
以下是优化后的课程结构,插入了新的模块以增强连贯性和内容深度:
Day 1-2:Python 基础(变量、数据类型、输入输出)。
Day 2.5:AIDD 中的化学基础(分子结构、SMILES、Lipinski 规则)。
Day 3-4:控制流和函数(条件语句、循环、函数定义)。
Day 5:高级数据结构(列表、字典、集合)。
Day 5.5:机器学习基础与 AIDD 应用入门(特征工程、模型评估)。
Day 6:数据科学库(NumPy、Pandas、Matplotlib)。
Day 6.5:化学信息学工具与数据集处理(RDKit、ChEMBL 数据处理)。
Day 7-27:机器学习、深度学习、强化学习等高级主题。
Day 27.5:强化学习的进阶算法(DQN、PPO)。
Day 28:多目标优化(Pareto 前沿、NSGA-II)。
Day 28.5:多目标优化的可视化与分析。
Day 29-31:迁移学习、分子模拟与强化学习结合。
Day 32:合成路径预测与反应机制预测。
Day 32.5:AIDD 综合项目:从数据到药物候选。
四、总结
4.1 课程连贯性总结
现有课程结构从 Python 基础到高级 AIDD 应用,整体具有较好的连贯性,通过循序渐进的方式引导学习者掌握编程和药物发现技能。然而,在基础到高级内容的衔接、化学背景知识、工具使用深度和高级主题的覆盖范围方面存在改进空间。
4.2 插入知识的建议
通过插入以下模块,课程可以更全面、连贯:
机器学习基础与化学信息学:平滑过渡到高级内容,帮助学习者理解特征工程和数据处理。
化学背景知识:补充分子结构、SMILES 和药物设计指标的解释,降低非化学背景学习者的门槛。
进阶 RL 和多目标优化:增加复杂 RL 算法和 Pareto 前沿分析,深化高级主题。
综合项目:通过真实案例整合知识,提升实践能力。
4.3 实施建议
提供补充资源:为每个新模块提供在线资源链接(如 RDKit 文档、ChEMBL 数据下载教程)。
分层教学:为初学者和有经验的学习者设计不同的练习难度。例如,初学者可以完成简单的分子量计算,高级学习者可以实现复杂的 RL 优化任务。
社区支持:建议建立学习社区或论坛,让学习者交流代码、数据集和项目经验,增强互动性。
通过这些优化,课程将更具连贯性和实用性,能够更好地满足 AIDD 领域学习者的需求,从初学者到专业人士都能从中受益。
Day 2.5: AIDD 中的化学基础(分子结构、SMILES、Lipinski 规则)
Day 2.5: Chemical Foundations in AIDD (Molecular Structure, SMILES, Lipinski's Rule of Five)
目标 / Objectives
通过本课程的学习,您将能够: By the end of this session, you will be able to:
理解分子结构的基本概念,包括原子、化学键和官能团。 Understand the basic concepts of molecular structure, including atoms, chemical bonds, and functional groups.
掌握 SMILES(简化分子输入线性系统)表示法的语法和用途。 Master the syntax and applications of SMILES (Simplified Molecular Input Line Entry System) notation.
熟悉 Lipinski 五规则及其在药物筛选中的作用。 Become familiar with Lipinski's Rule of Five and its role in drug candidate screening.
使用 Python 和 RDKit 库进行分子结构分析,计算关键理化性质(如分子量、LogP)。 Use Python and the RDKit library to analyze molecular structures and calculate key physicochemical properties (e.g., molecular weight, LogP).
将化学基础知识与 AIDD 任务结合,为后续的分子属性预测和药物优化奠定基础。 Integrate chemical knowledge with AIDD tasks to lay the foundation for subsequent molecular property prediction and drug optimization.
内容 / Content
1. 分子结构基础 / Fundamentals of Molecular Structure
1.1 原子与化学键 / Atoms and Chemical Bonds
原子 (Atoms):化学分子的基本组成单元,由质子、中子和电子构成。原子通过化学键连接形成分子。 Atoms are the fundamental building blocks of chemical molecules, composed of protons, neutrons, and electrons. Atoms are connected via chemical bonds to form molecules.
化学键 (Chemical Bonds):包括共价键(单键、双键、三键)、离子键和氢键。在药物设计中,共价键决定了分子的骨架结构。 Chemical bonds include covalent bonds (single, double, triple), ionic bonds, and hydrogen bonds. In drug design, covalent bonds define the molecular scaffold.
分子结构 (Molecular Structure):分子的三维排列,影响其理化性质(如溶解度、稳定性)和生物活性。 Molecular structure refers to the three-dimensional arrangement of atoms, influencing physicochemical properties (e.g., solubility, stability) and biological activity.
1.2 官能团 / Functional Groups
定义 (Definition):官能团是分子中决定其化学性质的特定原子团,如羟基 (-OH)、羧基 (-COOH)、氨基 (-NH2)。 Functional groups are specific groups of atoms within a molecule that determine its chemical properties, such as hydroxyl (-OH), carboxyl (-COOH), and amino (-NH2).
AIDD 中的作用 (Role in AIDD):官能团影响分子的反应性、结合亲和力和药物代谢动力学(ADMET)。例如,羧基通常提高水溶性,而芳香环增加疏水性。 Functional groups influence a molecule’s reactivity, binding affinity, and ADMET (absorption, distribution, metabolism, excretion, toxicity) properties. For example, carboxyl groups enhance water solubility, while aromatic rings increase hydrophobicity.
示例 / Example:
以下为阿司匹林(Aspirin)的分子结构及其官能团: Below is the molecular structure of Aspirin and its functional groups:
化学式 / Chemical Formula: C9H8O4
官能团 / Functional Groups: 羧基 (-COOH)、酯基 (-COO-)、芳香环 (benzene ring)
结构示意图 / Structural Diagram
:
O=C(O)c1ccccc1OC(=O)C
2. SMILES 表示法 / SMILES Notation
2.1 SMILES 的定义与语法 / Definition and Syntax of SMILES
SMILES 定义 (SMILES Definition):SMILES(Simplified Molecular Input Line Entry System)是一种基于文本的化学分子表示方法,使用 ASCII 字符描述分子的原子连接和化学键。 SMILES (Simplified Molecular Input Line Entry System) is a text-based representation of chemical molecules, using ASCII characters to describe atomic connectivity and chemical bonds.
基本语法 / Basic Syntax
:
原子 / Atoms: 用元素符号表示,如 C(碳)、O(氧)、N(氮)。 Atoms are represented by their element symbols, e.g., C (carbon), O (oxygen), N (nitrogen).
化学键 / Bonds: 单键默认不写,双键用
=,三键用#。 Single bonds are implied, double bonds use=, and triple bonds use#.分支 / Branches: 用括号
()表示分支结构。 Branches are indicated using parentheses().环 / Rings: 用数字标记环的开闭,如
c1ccccc1表示苯环。 Rings are denoted by numbers to indicate ring closure, e.g.,c1ccccc1for a benzene ring.
示例 / Example
:
阿司匹林的 SMILES:
CC(=O)OC1=CC=CC=C1C(=O)OSMILES for Aspirin:CC(=O)OC1=CC=CC=C1C(=O)O解析 / Interpretation:
CC(=O)O:乙酰基(acetyl group)。C1=CC=CC=C1:苯环(benzene ring)。C(=O)O:羧基(carboxyl group)。
2.2 SMILES 在 AIDD 中的应用 / Applications of SMILES in AIDD
分子表示 / Molecular Representation: SMILES 提供了一种紧凑的方式表示分子结构,便于存储和处理大规模化学数据。 SMILES provides a compact representation of molecular structures, facilitating storage and processing of large-scale chemical data.
分子描述符计算 / Molecular Descriptor Calculation: SMILES 可用于计算分子量、LogP、可旋转键数等理化性质。 SMILES can be used to compute physicochemical properties such as molecular weight, LogP, and the number of rotatable bonds.
机器学习输入 / Input for Machine Learning: SMILES 字符串可作为机器学习模型的输入,用于预测药物性质(如毒性、结合亲和力)。 SMILES strings serve as input for machine learning models to predict drug properties (e.g., toxicity, binding affinity).
3. Lipinski 五规则 / Lipinski's Rule of Five
3.1 定义 / Definition
Lipinski 五规则 (Lipinski's Rule of Five)
:由 Christopher Lipinski 提出,用于评估化合物的类药性(drug-likeness),即其作为口服药物候选的可能性。规则包括:
Lipinski's Rule of Five, proposed by Christopher Lipinski, evaluates a compound’s drug-likeness, i.e., its potential as an orally bioavailable drug candidate. The rules are:
分子量 / Molecular Weight: ≤ 500 Da(道尔顿)。 Molecular weight ≤ 500 Da (Daltons).
疏水性 / Lipophilicity: LogP(分配系数)≤ 5。 LogP (partition coefficient) ≤ 5.
氢键给体 / Hydrogen Bond Donors: ≤ 5(通常为 -OH 或 -NH 的数量)。 Number of hydrogen bond donors ≤ 5 (typically -OH or -NH groups).
氢键受体 / Hydrogen Bond Acceptors: ≤ 10(通常为 O 或 N 原子)。 Number of hydrogen bond acceptors ≤ 10 (typically O or N atoms).
可旋转键 / Rotatable Bonds(扩展规则):≤ 10,影响分子的灵活性。 Number of rotatable bonds ≤ 10 (an extended rule, affecting molecular flexibility).
3.2 在 AIDD 中的作用 / Role in AIDD
筛选候选药物 / Screening Drug Candidates: Lipinski 规则用于过滤具有较高口服生物利用度潜力的化合物,减少后续实验的成本和时间。 Lipinski’s rules are used to filter compounds with high oral bioavailability potential, reducing the cost and time of subsequent experiments.
优化分子设计 / Optimizing Molecular Design: 在药物优化过程中,调整分子结构以满足 Lipinski 规则,提高类药性。 During drug optimization, molecular structures are adjusted to meet Lipinski’s rules, enhancing drug-likeness.
机器学习中的特征 / Features in Machine Learning: Lipinski 规则的指标(如分子量、LogP)常作为机器学习模型的输入特征,用于预测化合物的生物活性。 Metrics from Lipinski’s rules (e.g., molecular weight, LogP) are often used as input features in machine learning models to predict biological activity.
示例代码 / Example Code
以下示例使用 RDKit 库解析 SMILES 字符串,计算分子量、LogP 和 Lipinski 规则相关指标,并评估化合物的类药性。 The following example uses the RDKit library to parse SMILES strings, calculate molecular weight, LogP, and Lipinski-related metrics, and evaluate a compound’s drug-likeness.
import matplotlib.pyplot as plt
import numpy as np
from rdkit import Chem
from rdkit.Chem import Descriptors, Lipinski
import seaborn as sns
import pandas as pd
# 函数:检查 Lipinski 五规则 / Function: Check Lipinski's Rule of Five
def check_lipinski(smiles):
"""
检查化合物是否符合 Lipinski 五规则。
Check if a compound complies with Lipinski's Rule of Five.
参数 / Parameters:
smiles (str): 化合物的 SMILES 字符串 / SMILES string of the compound
返回 / Returns:
dict: 包含分子量、LogP、氢键给体、氢键受体和类药性评估结果
dict: Contains molecular weight, LogP, H-bond donors, H-bond acceptors, and drug-likeness evaluation
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return {"error": "Invalid SMILES string"}
# 计算分子描述符 / Calculate molecular descriptors
mw = Descriptors.MolWt(mol) # 分子量 / Molecular weight
logp = Descriptors.MolLogP(mol) # LogP
h_donors = Lipinski.NumHDonors(mol) # 氢键给体 / Hydrogen bond donors
h_acceptors = Lipinski.NumHAcceptors(mol) # 氢键受体 / Hydrogen bond acceptors
rotatable_bonds = Lipinski.NumRotatableBonds(mol) # 可旋转键 / Rotatable bonds
# 检查 Lipinski 规则 / Check Lipinski's rules
is_drug_like = (mw <= 500) and (logp <= 5) and (h_donors <= 5) and (h_acceptors <= 10)
return {
"Molecular Weight": mw,
"LogP": logp,
"H-bond Donors": h_donors,
"H-bond Acceptors": h_acceptors,
"Rotatable Bonds": rotatable_bonds,
"Complies with Lipinski's Rule": is_drug_like
}
# 示例:检查阿司匹林和布洛芬的类药性 / Example: Check drug-likeness of Aspirin and Ibuprofen
compounds = {
"Aspirin": "CC(=O)OC1=CC=CC=C1C(=O)O",
"Ibuprofen": "CC(C)CC1=CC=CC=C1C(C)C(=O)O"
}
# 初始化结果存储
results = []
# 进行分析并生成结果
for name, smiles in compounds.items():
result = check_lipinski(smiles)
if "error" not in result:
results.append(result)
print(f"\nCompound: {name}")
for key, value in result.items():
print(f"{key}: {value}")
# 将结果转换为 DataFrame 以便进一步分析和绘图
df = pd.DataFrame(results, index=compounds.keys())
# 可视化分析
def plot_lipinski(df):
"""
根据计算的分子描述符值生成图表,并对每个指标进行分析
Generate plots based on calculated molecular descriptors and provide analysis for each metric.
"""
# 设置图表风格 / Set plot style
sns.set(style="whitegrid")
# 创建子图 / Create subplots
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
# 分子量 / Molecular Weight
sns.barplot(x=df.index, y="Molecular Weight", data=df, ax=axes[0, 0])
axes[0, 0].set_title("Molecular Weight")
# LogP
sns.barplot(x=df.index, y="LogP", data=df, ax=axes[0, 1])
axes[0, 1].set_title("LogP")
# 氢键给体 / H-bond Donors
sns.barplot(x=df.index, y="H-bond Donors", data=df, ax=axes[0, 2])
axes[0, 2].set_title("H-bond Donors")
# 氢键受体 / H-bond Acceptors
sns.barplot(x=df.index, y="H-bond Acceptors", data=df, ax=axes[1, 0])
axes[1, 0].set_title("H-bond Acceptors")
# 可旋转键 / Rotatable Bonds
sns.barplot(x=df.index, y="Rotatable Bonds", data=df, ax=axes[1, 1])
axes[1, 1].set_title("Rotatable Bonds")
# 类药性 / Drug-likeness (布尔值)
# 将布尔值转换为数字类型 / Convert Boolean values to numeric
drug_like = df["Complies with Lipinski's Rule"].map({True: 1, False: 0})
sns.barplot(x=df.index, y=drug_like, ax=axes[1, 2])
axes[1, 2].set_title("Drug-likeness")
plt.tight_layout()
plt.show()
# 绘制并展示图表
plot_lipinski(df)
# 自动生成图表解读
def generate_plot_explanation(df):
"""
自动生成图表的分析解读 / Automatically generate explanations for the charts.
"""
explanations = {}
# 分子量解释 / Explanation for Molecular Weight
mw_comparison = df["Molecular Weight"]
explanations["Molecular Weight"] = f"Larger molecular weight compounds generally have higher biological volume and lower permeability. This chart compares the molecular weight of Aspirin and Ibuprofen, both of which comply with Lipinski's rule."
# LogP 解释
logp_comparison = df["LogP"]
explanations["LogP"] = f"LogP reflects the lipophilicity of a compound; higher values suggest better membrane permeability. In this chart, Ibuprofen has a slightly higher LogP, suggesting better lipophilicity."
# 氢键给体解释 / H-bond Donors Explanation
hdonors_comparison = df["H-bond Donors"]
explanations["H-bond Donors"] = f"The number of hydrogen bond donors influences the affinity of a molecule to biological targets. Both Aspirin and Ibuprofen have low numbers of H-bond donors, which comply with Lipinski's rule."
# 氢键受体解释 / H-bond Acceptors Explanation
hacceptors_comparison = df["H-bond Acceptors"]
explanations["H-bond Acceptors"] = f"A higher number of hydrogen bond acceptors generally indicates stronger interaction with targets. Both Aspirin and Ibuprofen meet this criterion."
# 可旋转键解释 / Rotatable Bonds Explanation
rot_bonds_comparison = df["Rotatable Bonds"]
explanations["Rotatable Bonds"] = f"The number of rotatable bonds influences molecular flexibility. Too many rotatable bonds can impact stability. Both Aspirin and Ibuprofen have moderate numbers of rotatable bonds."
# 类药性总结 / Drug-likeness Summary
drug_like_comparison = df["Complies with Lipinski's Rule"]
explanations["Drug-likeness"] = f"Based on Lipinski's Rule of Five, both compounds are classified as drug-like."
return explanations
# 获取并打印图表的解释
explanations = generate_plot_explanation(df)
for key, explanation in explanations.items():
print(f"\n{key} Explanation:\n{explanation}")
输出 / Output:
化合物 / Compound: 阿司匹林 / Aspirin
分子量 / Molecular Weight: 180.158
LogP: 1.3101
氢键给体 / H-bond Donors: 1
氢键受体 / H-bond Acceptors: 4
可旋转键 / Rotatable Bonds: 4
是否符合 Lipinski 规则 / Complies with Lipinski's Rule: True
化合物 / Compound: 布洛芬 / Ibuprofen
分子量 / Molecular Weight: 206.285
LogP: 3.0724
氢键给体 / H-bond Donors: 1
氢键受体 / H-bond Acceptors: 2
可旋转键 / Rotatable Bonds: 4
是否符合 Lipinski 规则 / Complies with Lipinski's Rule: True
代码解析 / Code Explanation:
RDKit 库 / RDKit Library: 使用
Chem.MolFromSmiles解析 SMILES 字符串,生成分子对象。 UsesChem.MolFromSmilesto parse SMILES strings and generate molecular objects.描述符计算 / Descriptor Calculation: 使用
Descriptors模块计算分子量、LogP 等理化性质;使用Lipinski模块计算氢键给体、受体和可旋转键数。 Uses theDescriptorsmodule to calculate physicochemical properties like molecular weight and LogP; uses theLipinskimodule to calculate hydrogen bond donors, acceptors, and rotatable bonds.Lipinski 规则检查 / Lipinski Rule Check: 通过条件判断评估化合物是否符合 Lipinski 五规则。 Evaluates whether the compound complies with Lipinski’s Rule of Five using conditional checks.
实践练习 / Practice Exercises
解析 SMILES 字符串 / Parse SMILES Strings:
编写一个 Python 函数,输入化合物的 SMILES 字符串,返回其官能团信息(如羧基、羟基的数量)。 Write a Python function that takes a compound’s SMILES string as input and returns information about its functional groups (e.g., number of carboxyl or hydroxyl groups).
示例化合物 / Example Compounds: 对乙酰氨基酚(Paracetamol)
CC(=O)Nc1ccc(O)cc1Example compound: ParacetamolCC(=O)Nc1ccc(O)cc1
计算分子描述符 / Calculate Molecular Descriptors:
使用 RDKit 编写代码,计算一组化合物的分子量、LogP、氢键给体和受体,并将结果存储在 Pandas DataFrame 中。 Write code using RDKit to calculate molecular weight, LogP, hydrogen bond donors, and acceptors for a set of compounds, and store the results in a Pandas DataFrame.
示例数据集 / Example Dataset: 使用以下化合物:阿司匹林、布洛芬、对乙酰氨基酚。 Example dataset: Use compounds Aspirin, Ibuprofen, and Paracetamol.
Lipinski 规则筛选 / Lipinski Rule Screening:
编写一个程序,输入一组化合物的 SMILES 字符串,筛选出符合 Lipinski 五规则的化合物,并输出它们的理化性质。 Write a program that takes a list of SMILES strings, filters compounds that comply with Lipinski’s Rule of Five, and outputs their physicochemical properties.
提示 / Hint: 使用
check_lipinski函数,并扩展为处理多个化合物的批量操作。 Hint: Use thecheck_lipinskifunction and extend it for batch processing of multiple compounds.
探索化学性质与类药性的关系 / Explore Relationships Between Chemical Properties and Drug-Likeness:
编写代码,分析一组化合物的分子量和 LogP 之间的关系(例如,通过散点图可视化),并讨论其对类药性的影响。 Write code to analyze the relationship between molecular weight and LogP for a set of compounds (e.g., via scatter plot visualization) and discuss its impact on drug-likeness.
工具 / Tools: 使用 Matplotlib 或 Seaborn 进行可视化。 Tools: Use Matplotlib or Seaborn for visualization.
总结 / Conclusion
学习成果 / Learning Outcomes:
掌握了分子结构的基本概念,包括原子、化学键和官能团,为理解药物分子行为奠定了基础。 Mastered the basic concepts of molecular structure, including atoms, chemical bonds, and functional groups, laying the foundation for understanding drug molecule behavior.
理解了 SMILES 表示法的语法和应用,能够使用 SMILES 描述分子并进行计算。 Understood the syntax and applications of SMILES notation, enabling the representation and computation of molecular structures.
熟悉了 Lipinski 五规则及其在 AIDD 中的作用,能够通过代码评估化合物的类药性。 Became familiar with Lipinski’s Rule of Five and its role in AIDD, and learned to evaluate drug-likeness using code.
使用 RDKit 库实现了分子描述符的计算和类药性筛选,为后续的 AIDD 任务(如毒性预测、分子优化)做好准备。 Used the RDKit library to compute molecular descriptors and screen for drug-likeness, preparing for subsequent AIDD tasks (e.g., toxicity prediction, molecular optimization).
AIDD 相关性 / Relevance to AIDD:
本课程为非化学背景的学习者提供了化学基础知识,帮助他们理解 AIDD 中的核心概念(如分子结构、理化性质)。 This session provides non-chemistry-background learners with foundational chemical knowledge, helping them understand core AIDD concepts (e.g., molecular structure, physicochemical properties).
通过 SMILES 和 Lipinski 规则的应用,学习者能够将化学知识与 Python 编程结合,为药物设计中的数据处理和机器学习任务奠定基础。 Through the application of SMILES and Lipinski’s rules, learners can integrate chemical knowledge with Python programming, laying the groundwork for data processing and machine learning tasks in drug design.
Day 2: 分子结构(Molecular Structure)
目标 / Objectives
通过本课程的学习,您将能够: By the end of this session, you will be able to:
理解分子结构的基本概念,包括原子、化学键和官能团。 Understand the basic concepts of molecular structure, including atoms, chemical bonds, and functional groups.
认识 AIDD 中常见的分子结构类型,如烷烃、芳香环和杂环。 Recognize common molecular structure types in AIDD, such as alkanes, aromatic rings, and heterocycles.
使用 SMILES 表示法描述简单分子结构,并理解其在 AIDD 中的作用。 Use SMILES notation to describe simple molecular structures and understand its role in AIDD.
使用 Python 和 RDKit 库解析分子结构并提取基本信息(如原子数、化学键类型)。 Use Python and the RDKit library to parse molecular structures and extract basic information (e.g., number of atoms, types of bonds).
通过综合项目示例,将分子结构知识应用于 AIDD 任务,如化合物筛选。 Apply molecular structure knowledge to AIDD tasks, such as compound screening, through a comprehensive project example.
内容 / Content
1. 分子结构基础 / Fundamentals of Molecular Structure
1.1 什么是分子? / What is a Molecule?
定义 / Definition: 分子是由两个或多个原子通过化学键连接形成的化学实体。 A molecule is a chemical entity formed by two or more atoms connected through chemical bonds.
初学者理解 / For Beginners: 想象分子是一个由“积木”(原子)通过“绳子”(化学键)连接起来的结构。不同的积木组合形成不同的分子,就像乐高玩具可以拼出各种形状。 Think of a molecule as a structure where “building blocks” (atoms) are connected by “strings” (chemical bonds). Different combinations of blocks create different molecules, like building various shapes with LEGO.
AIDD 中的重要性 / Importance in AIDD: 分子结构决定了化合物的性质(如溶解度、毒性、生物活性),是药物设计的核心。 Molecular structure determines a compound’s properties (e.g., solubility, toxicity, bioactivity), making it central to drug design.
1.2 原子与化学键 / Atoms and Chemical Bonds
原子 / Atoms
: 化学分子的基本单元,如碳 (C)、氢 (H)、氧 (O)、氮 (N)。
Atoms are the basic units of molecules, such as carbon (C), hydrogen (H), oxygen (O), and nitrogen (N).
初学者理解 / For Beginners: 原子就像字母表中的字母,分子是这些字母拼成的单词。例如,水分子 (H₂O) 由两个氢原子和一个氧原子组成。 Atoms are like letters in the alphabet, and molecules are words formed by these letters. For example, water (H₂O) is made of two hydrogen atoms and one oxygen atom.
化学键 / Chemical Bonds
: 原子之间的连接方式,主要包括:
Chemical bonds are the ways atoms are connected, primarily including:
单键 / Single Bond: 一个电子对共享,记为
-(在 SMILES 中通常省略)。如 C-C。 A single bond involves one shared electron pair, denoted as-(often omitted in SMILES). E.g., C-C.双键 / Double Bond: 两个电子对共享,记为
=。如 C=O。 A double bond involves two shared electron pairs, denoted as=. E.g., C=O.三键 / Triple Bond: 三个电子对共享,记为
#。如 C#N。 A triple bond involves three shared electron pairs, denoted as#. E.g., C#N.
AIDD 中的作用 / Role in AIDD: 化学键类型影响分子的稳定性和反应性。例如,双键可能使分子更易发生化学反应。 The type of chemical bond affects a molecule’s stability and reactivity. For example, double bonds may make a molecule more reactive.
1.3 官能团 / Functional Groups
定义 / Definition: 官能团是分子中决定其化学性质的特定原子团。 Functional groups are specific groups of atoms in a molecule that determine its chemical properties.
初学者理解 / For Beginners: 官能团就像分子的“功能按钮”,决定了分子能做什么。例如,羟基 (-OH) 让分子更容易溶于水。 Functional groups are like a molecule’s “function buttons,” determining what it can do. For example, a hydroxyl group (-OH) makes a molecule more water-soluble.
常见的官能团 / Common Functional Groups
:
羟基 / Hydroxyl (-OH): 常见于醇类,增加水溶性。 Found in alcohols, enhances water solubility.
羧基 / Carboxyl (-COOH): 常见于酸类,影响酸性和药物代谢。 Found in acids, affects acidity and drug metabolism.
氨基 / Amino (-NH₂): 常见于胺类,影响碱性和生物活性。 Found in amines, affects basicity and bioactivity.
羰基 / Carbonyl (C=O): 常见于酮类和醛类,影响反应性。 Found in ketones and aldehydes, affects reactivity.
2. AIDD 中常见的分子结构类型 / Common Molecular Structure Types in AIDD
以下是 AIDD 中常见的分子结构类型,特别针对药物设计中频繁出现的结构,适合初学者理解: Below are common molecular structure types in AIDD, particularly those frequently encountered in drug design, explained for beginners:
2.1 烷烃 / Alkanes
定义 / Definition: 由碳和氢原子组成,仅含单键的饱和烃。 Alkanes are saturated hydrocarbons composed of carbon and hydrogen atoms with only single bonds.
初学者理解 / For Beginners: 烷烃是“简单”的分子,像一条直链或分叉的碳链。例如,甲烷 (CH₄) 是最简单的烷烃。 Alkanes are “simple” molecules, like a straight or branched chain of carbon atoms. For example, methane (CH₄) is the simplest alkane.
SMILES 示例 / SMILES Example
:
甲烷 / Methane:
C乙烷 / Ethane:
CC丙烷 / Propane:
CCC
AIDD 中的作用 / Role in AIDD: 烷烃常作为药物分子的疏水部分,影响其脂溶性(lipophilicity)。 Alkanes often serve as the hydrophobic portion of drug molecules, affecting their lipophilicity.
2.2 芳香环 / Aromatic Rings
定义 / Definition: 含有共轭 π 电子系统的环状结构,通常是苯环(6 个碳原子的环)。 Aromatic rings are cyclic structures with conjugated π-electron systems, typically benzene rings (6 carbon atoms).
初学者理解 / For Beginners: 芳香环像一个稳定的“圆形积木”,常见于许多药物分子中。例如,阿司匹林的苯环让它更稳定。 Aromatic rings are like stable “circular building blocks,” common in many drug molecules. For example, the benzene ring in Aspirin makes it more stable.
SMILES 示例 / SMILES Example :
苯 / Benzene:
c1ccccc1(小写c表示芳香碳)。 Benzene:c1ccccc1(lowercasecdenotes aromatic carbon).甲苯 / Toluene:
c1ccccc1C(苯环连一个甲基)。 Toluene:c1ccccc1C(benzene ring with a methyl group).
AIDD 中的作用 / Role in AIDD: 芳香环增加分子的刚性和疏水性,常用于增强与靶蛋白的结合亲和力。 Aromatic rings increase molecular rigidity and hydrophobicity, often used to enhance binding affinity with target proteins.
2.3 杂环 / Heterocycles
定义 / Definition: 含有除碳以外其他原子(如氮、氧、硫)的环状结构。 Heterocycles are cyclic structures containing atoms other than carbon, such as nitrogen, oxygen, or sulfur.
初学者理解 / For Beginners: 杂环像芳香环,但“圆形积木”中混杂了不同的元素(如氮),使分子功能更丰富。例如,吡啶是一个含氮的杂环。 Heterocycles are like aromatic rings but include different elements (e.g., nitrogen) in the “circular building block,” making the molecule more versatile. For example, pyridine is a nitrogen-containing heterocycle.
SMILES 示例 / SMILES Example :
吡啶 / Pyridine:
c1ccncc1(含一个氮原子的六元环)。 Pyridine:c1ccncc1(a six-membered ring with one nitrogen atom).呋喃 / Furan:
c1ccoc1(含一个氧原子的五元环)。 Furan:c1ccoc1(a five-membered ring with one oxygen atom).
AIDD 中的作用 / Role in AIDD: 杂环广泛存在于药物分子中,调节分子的极性和生物活性。例如,许多抗癌药物含有杂环结构。 Heterocycles are prevalent in drug molecules, modulating polarity and bioactivity. For example, many anticancer drugs contain heterocyclic structures.
2.4 其他常见结构 / Other Common Structures
酰胺 / Amides
: 含 C(=O)N 结构,常见于蛋白质结合的药物。
Amides contain the C(=O)N structure, common in drugs that bind to proteins.
SMILES 示例 / Example: 乙酰胺 / Acetamide:
CC(=O)N
酯 / Esters
: 含 C(=O)O 结构,常见于药物代谢研究。
Esters contain the C(=O)O structure, often studied in drug metabolism.
SMILES 示例 / Example: 乙酸乙酯 / Ethyl acetate:
CC(=O)OCC
AIDD 中的作用 / Role in AIDD: 这些结构影响分子的代谢稳定性和与靶点的相互作用,是药物设计中的关键模块。 These structures affect metabolic stability and target interactions, serving as key modules in drug design.
示例代码 / Example Code
以下代码使用 RDKit 库解析 SMILES 字符串,提取分子结构的原子数、化学键类型和官能团信息,针对初学者设计,包含详细注释和直观输出。 The following code uses the RDKit library to parse SMILES strings, extract the number of atoms, bond types, and functional group information, designed for beginners with detailed comments and clear output.
from rdkit import Chem
from rdkit.Chem import AllChem, Draw
import pandas as pd
from IPython.display import Image as IPImage # Import the IPython display for images
# 函数:筛选候选药物并分析分子结构 / Function: Screen Drug Candidates and Analyze Molecular Structure
def screen_drug_candidates(compounds):
"""
筛选含有羟基或羧基的化合物,并分析其分子结构。
Screen compounds containing hydroxyl or carboxyl groups and analyze their molecular structures.
参数 / Parameters:
compounds (dict): 化合物名称和 SMILES 字符串的字典
compounds (dict): Dictionary of compound names and SMILES strings
返回 / Returns:
pandas.DataFrame: 包含筛选结果和分子结构信息的表格
pandas.DataFrame: Table containing screening results and molecular structure information
"""
results = []
# 定义官能团模式 / Define functional group patterns
hydroxyl_pattern = Chem.MolFromSmarts('[OH]') # 羟基 / Hydroxyl group
carboxyl_pattern = Chem.MolFromSmarts('C(=O)[OH]') # 羧基 / Carboxyl group
for name, smiles in compounds.items():
# 解析 SMILES / Parse SMILES
mol = Chem.MolFromSmiles(smiles)
if mol is None:
continue
# 获取原子数和化学键信息 / Get atom and bond information
num_atoms = mol.GetNumAtoms()
single_bonds = sum(1 for bond in mol.GetBonds() if bond.GetBondType() == Chem.BondType.SINGLE)
double_bonds = sum(1 for bond in mol.GetBonds() if bond.GetBondType() == Chem.BondType.DOUBLE)
triple_bonds = sum(1 for bond in mol.GetBonds() if bond.GetBondType() == Chem.BondType.TRIPLE)
# 检查官能团 / Check functional groups
has_hydroxyl = len(mol.GetSubstructMatches(hydroxyl_pattern)) > 0
has_carboxyl = len(mol.GetSubstructMatches(carboxyl_pattern)) > 0
is_candidate = has_hydroxyl or has_carboxyl # 候选药物需含羟基或羧基
# Candidate must contain hydroxyl or carboxyl
# 保存结果 / Save results
results.append({
"化合物 / Compound": name,
"SMILES": smiles,
"原子数 / Number of Atoms": num_atoms,
"单键数 / Single Bonds": single_bonds,
"双键数 / Double Bonds": double_bonds,
"三键数 / Triple Bonds": triple_bonds,
"含羟基 / Has Hydroxyl": has_hydroxyl,
"含羧基 / Has Carboxyl": has_carboxyl,
"是否候选药物 / Is Candidate": is_candidate
})
# 转换为 DataFrame / Convert to DataFrame
df = pd.DataFrame(results)
# 可视化候选药物的分子结构 / Visualize molecular structures of candidates
candidate_mols = [Chem.MolFromSmiles(row["SMILES"]) for _, row in df.iterrows() if row["是否候选药物 / Is Candidate"]]
if candidate_mols:
img = Draw.MolsToGridImage(candidate_mols, molsPerRow=3, subImgSize=(200, 200),
legends=[row["化合物 / Compound"] for _, row in df.iterrows() if row["是否候选药物 / Is Candidate"]])
# Save the image as a PNG to display using IPython
# img_path = "/tmp/molecular_structure.png"
# img.save(img_path)
# IPImage(img_path) # Display the image using IPython display
return df
# 示例化合物数据集 / Example Compound Dataset
compounds = {
"甲烷 / Methane": "C",
"乙醇 / Ethanol": "CCO",
"阿司匹林 / Aspirin": "CC(=O)OC1=CC=CC=C1C(=O)O",
"吡啶 / Pyridine": "c1ccncc1",
"对乙酰氨基酚 / Paracetamol": "CC(=O)Nc1ccc(O)cc1",
"布洛芬 / Ibuprofen": "CC(C)CC1=CC=CC=C1C(C)C(=O)O"
}
# 运行筛选 / Run screening
result_df = screen_drug_candidates(compounds)
print(result_df[["化合物 / Compound", "SMILES", "原子数 / Number of Atoms",
"单键数 / Single Bonds", "双键数 / Double Bonds", "三键数 / Triple Bonds",
"含羟基 / Has Hydroxyl", "含羧基 / Has Carboxyl", "是否候选药物 / Is Candidate"]])
输出 / Output:
| 化合物 / Compound | SMILES | 原子数 / Number of Atoms | 单键数 / Single Bonds | 双键数 / Double Bonds | 三键数 / Triple Bonds | 含羟基 / Has Hydroxyl | 含羧基 / Has Carboxyl | 是否候选药物 / Is Candidate | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | 甲烷 / Methane | C | 1 | 0 | 0 | 0 | False | False | False |
| 1 | 乙醇 / Ethanol | CCO | 3 | 2 | 0 | 0 | True | False | True |
| 2 | 阿司匹林 / Aspirin | CC(=O)OC1=CC=CC=C1C(=O)O | 13 | 5 | 2 | 0 | True | True | True |
| 3 | 吡啶 / Pyridine | c1ccncc1 | 6 | 0 | 0 | 0 | False | False | False |
| 4 | 对乙酰氨基酚 / Paracetamol | CC(=O)Nc1ccc(O)cc1 | 11 | 4 | 1 | 0 | True | False | True |
| 5 | 布洛芬 / Ibuprofen | CC(C)CC1=CC=CC=C1C(C)C(=O)O | 15 | 8 | 1 | 0 | True | True | True |
代码解析 / Code Explanation:
SMILES 解析 / SMILES Parsing: 使用
Chem.MolFromSmiles将 SMILES 字符串转换为分子对象,便于分析。 UsesChem.MolFromSmilesto convert SMILES strings into molecular objects for analysis.原子与化学键 / Atoms and Bonds: 通过
GetNumAtoms和GetBonds获取原子数和化学键类型(单键、双键、三键)。 UsesGetNumAtomsandGetBondsto retrieve the number of atoms and bond types (single, double, triple).官能团检测 / Functional Group Detection: 使用
Chem.MolFromSmarts定义官能团的化学模式(SMARTS),并通过GetSubstructMatches检测是否存在羟基、羧基或氨基。 UsesChem.MolFromSmartsto define functional group patterns (SMARTS) andGetSubstructMatchesto detect hydroxyl, carboxyl, or amino groups.输出格式 / Output Format: 使用 Pandas DataFrame 整理结果,呈现清晰的表格,便于初学者理解。 Uses a Pandas DataFrame to organize results in a clear table, beginner-friendly.
实践练习 / Practice Exercises
解析 SMILES 字符串 / Parse SMILES Strings:
编写一个 Python 函数,输入化合物的 SMILES 字符串,返回其原子数和化学键总数。 Write a Python function that takes a SMILES string and returns the number of atoms and total bonds.
示例化合物 / Example Compound: 乙醇 / Ethanol:
CCO
识别官能团 / Identify Functional Groups:
修改
analyze_molecule
函数,添加对羰基 (C=O) 的检测,并分析以下化合物:
Modify the
analyze_molecule
function to detect carbonyl groups (C=O) and analyze the following compounds:
丙酮 / Acetone:
CC(=O)C乙酸 / Acetic acid:
CC(=O)O
比较分子结构 / Compare Molecular Structures:
编写代码,比较两组化合物的原子数和官能团数量,输出差异。 Write code to compare the number of atoms and functional groups between two sets of compounds and output the differences.
示例化合物 / Example Compounds
:
组 1 / Group 1: 甲烷 (C), 乙烷 (CC)
组 2 / Group 2: 阿司匹林, 对乙酰氨基酚
可视化分子结构 / Visualize Molecular Structures:
使用 RDKit 的
Draw.MolToImage将化合物的 SMILES 字符串转换为分子结构图。 Use RDKit’sDraw.MolToImageto convert SMILES strings into molecular structure diagrams.示例化合物 / Example Compound: 吡啶 / Pyridine:
c1ccncc1
综合项目示例代码 / Comprehensive Project Example Code
以下综合项目示例展示如何将分子结构知识应用于 AIDD 任务:从一组化合物中筛选出含有特定官能团(如羟基或羧基)的候选药物,并计算其原子数和化学键信息。项目适合初学者,代码注释详细,输出直观。 The following comprehensive project example demonstrates how to apply molecular structure knowledge to an AIDD task: screening a set of compounds for specific functional groups (e.g., hydroxyl or carboxyl) and calculating their atom and bond information. The project is beginner-friendly with detailed comments and clear output.
from rdkit import Chem
from rdkit.Chem import AllChem, Draw
import pandas as pd
from PIL import Image
# 函数:筛选候选药物并分析分子结构 / Function: Screen Drug Candidates and Analyze Molecular Structure
def screen_drug_candidates(compounds):
"""
筛选含有羟基或羧基的化合物,并分析其分子结构。
Screen compounds containing hydroxyl or carboxyl groups and analyze their molecular structures.
参数 / Parameters:
compounds (dict): 化合物名称和 SMILES 字符串的字典
compounds (dict): Dictionary of compound names and SMILES strings
返回 / Returns:
pandas.DataFrame: 包含筛选结果和分子结构信息的表格
pandas.DataFrame: Table containing screening results and molecular structure information
"""
results = []
# 定义官能团模式 / Define functional group patterns
hydroxyl_pattern = Chem.MolFromSmarts('[OH]') # 羟基 / Hydroxyl group
carboxyl_pattern = Chem.MolFromSmarts('C(=O)[OH]') # 羧基 / Carboxyl group
for name, smiles in compounds.items():
# 解析 SMILES / Parse SMILES
mol = Chem.MolFromSmiles(smiles)
if mol is None:
continue
# 获取原子数和化学键信息 / Get atom and bond information
num_atoms = mol.GetNumAtoms()
single_bonds = sum(1 for bond in mol.GetBonds() if bond.GetBondType() == Chem.BondType.SINGLE)
double_bonds = sum(1 for bond in mol.GetBonds() if bond.GetBondType() == Chem.BondType.DOUBLE)
triple_bonds = sum(1 for bond in mol.GetBonds() if bond.GetBondType() == Chem.BondType.TRIPLE)
# 检查官能团 / Check functional groups
has_hydroxyl = len(mol.GetSubstructMatches(hydroxyl_pattern)) > 0
has_carboxyl = len(mol.GetSubstructMatches(carboxyl_pattern)) > 0
is_candidate = has_hydroxyl or has_carboxyl # 候选药物需含羟基或羧基
# Candidate must contain hydroxyl or carboxyl
# 保存结果 / Save results
results.append({
"化合物 / Compound": name,
"SMILES": smiles,
"原子数 / Number of Atoms": num_atoms,
"单键数 / Single Bonds": single_bonds,
"双键数 / Double Bonds": double_bonds,
"三键数 / Triple Bonds": triple_bonds,
"含羟基 / Has Hydroxyl": has_hydroxyl,
"含羧基 / Has Carboxyl": has_carboxyl,
"是否候选药物 / Is Candidate": is_candidate
})
# 转换为 DataFrame / Convert to DataFrame
df = pd.DataFrame(results)
# 可视化候选药物的分子结构 / Visualize molecular structures of candidates
candidate_mols = [Chem.MolFromSmiles(row["SMILES"]) for _, row in df.iterrows() if row["是否候选药物 / Is Candidate"]]
if candidate_mols:
img = Draw.MolsToGridImage(candidate_mols, molsPerRow=3, subImgSize=(200, 200),
legends=[row["化合物 / Compound"] for _, row in df.iterrows() if row["是否候选药物 / Is Candidate"]])
img.show() # 显示分子结构图 / Display molecular structure diagram
return df
# 示例化合物数据集 / Example Compound Dataset
compounds = {
"甲烷 / Methane": "C",
"乙醇 / Ethanol": "CCO",
"阿司匹林 / Aspirin": "CC(=O)OC1=CC=CC=C1C(=O)O",
"吡啶 / Pyridine": "c1ccncc1",
"对乙酰氨基酚 / Paracetamol": "CC(=O)Nc1ccc(O)cc1",
"布洛芬 / Ibuprofen": "CC(C)CC1=CC=CC=C1C(C)C(=O)O"
}
# 运行筛选 / Run screening
result_df = screen_drug_candidates(compounds)
print(result_df[["化合物 / Compound", "SMILES", "原子数 / Number of Atoms",
"单键数 / Single Bonds", "双键数 / Double Bonds", "三键数 / Triple Bonds",
"含羟基 / Has Hydroxyl", "含羧基 / Has Carboxyl", "是否候选药物 / Is Candidate"]])输出 / Output:
| 原子数 / Number of Atoms | 单键数 / Single Bonds | 双键数 / Double Bonds | 三键数 / Triple Bonds | 羟基数 / Hydroxyl Groups | 羧基数 / Carboxyl Groups | 氨基数 / Amino Groups | 化合物 / Compound | SMILES | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 甲烷 / Methane | C |
| 1 | 13 | 5 | 2 | 0 | 1 | 1 | 0 | 阿司匹林 / Aspirin | CC(=O)OC1=CC=CC=C1C(=O)O |
| 2 | 6 | 0 | 0 | 0 | 0 | 0 | 0 | 吡啶 / Pyridine | c1ccncc1 |
| 3 | 11 | 4 | 1 | 0 | 1 | 0 | 0 | 对乙酰氨基酚 / Paracetamol | CC(=O)Nc1ccc(O)cc1 |
项目解析 / Project Explanation:
任务目标 / Task Objective: 筛选出含有羟基 (-OH) 或羧基 (-COOH) 的化合物作为潜在药物候选,模拟 AIDD 中的初步筛选流程。 Screen compounds containing hydroxyl (-OH) or carboxyl (-COOH) groups as potential drug candidates, simulating an initial AIDD screening process.
SMILES 解析 / SMILES Parsing: 使用 RDKit 将 SMILES 转换为分子对象,分析原子和化学键。 Uses RDKit to convert SMILES into molecular objects for atom and bond analysis.
官能团筛选 / Functional Group Screening: 使用 SMARTS 模式检测羟基和羧基,判断化合物是否为候选药物。 Uses SMARTS patterns to detect hydroxyl and carboxyl groups, determining if a compound is a candidate.
可视化 / Visualization: 使用
Draw.MolsToGridImage显示候选化合物的分子结构图,直观展示分子骨架。 UsesDraw.MolsToGridImageto display molecular structure diagrams of candidate compounds, visually showing their scaffolds.输出 / Output: 使用 Pandas DataFrame 整理结果,清晰呈现化合物的结构信息和筛选结果。 Uses a Pandas DataFrame to organize results, clearly presenting structural information and screening outcomes.
初学者友好 / Beginner-Friendly: 代码注释详细,逻辑简单,输出表格直观,适合零基础学习者理解。 Detailed comments, simple logic, and clear table output make it beginner-friendly.
总结 / Conclusion
学习成果 / Learning Outcomes:
掌握了分子结构的基本概念,包括原子、化学键和官能团。 Mastered the basic concepts of molecular structure, including atoms, chemical bonds, and functional groups.
认识了 AIDD 中常见的分子结构类型(烷烃、芳香环、杂环等)及其在药物设计中的作用。 Learned common molecular structure types in AIDD (alkanes, aromatic rings, heterocycles) and their roles in drug design.
学会了使用 SMILES 表示分子,并通过 RDKit 解析和分析分子结构。 Learned to represent molecules using SMILES and analyze structures with RDKit.
通过综合项目,应用分子结构知识完成 AIDD 中的化合物筛选任务。 Applied molecular structure knowledge to a compound screening task in AIDD through a comprehensive project.
AIDD 相关性 / Relevance to AIDD:
分子结构是 AIDD 的核心,决定了化合物的理化性质和生物活性。 Molecular structure is central to AIDD, determining a compound’s physicochemical properties and bioactivity.
本课程通过简单的 SMILES 和官能团分析,帮助初学者理解如何将化学知识与编程结合,为后续的分子属性预测和药物优化任务奠定基础。 This session helps beginners understand how to combine chemical knowledge with programming through simple SMILES and functional group analysis, laying the foundation for molecular property prediction and drug optimization.
后续学习 / Next Steps:
在 Day 2.5 中,学习者将深入了解 SMILES 表示法的语法和 Lipinski 五规则,学习如何评估化合物的类药性。 In Day 2.5, learners will explore SMILES notation syntax and Lipinski’s Rule of Five, learning to evaluate drug-likeness.
在 Day 3 及之后,学习者将使用 Python 控制流处理化学数据,并逐步引入更复杂的 AIDD 任务。 In Day 3 and beyond, learners will use Python control flow to process chemical data and gradually tackle more complex AIDD tasks.
评论
发表评论