rdkit について
rdkitスキルは、化学情報学、創薬、計算化学の研究向けに、RDKitによる分子処理のPythonガイドを提供します。構造解析、スクリーニング、反応、配座生成、可視化を扱います。
主な機能
- 01分子構造の読み込みと書き出し
- 02記述子とフィンガープリントの計算
- 03部分構造検索と類似性分析
- 04化学反応の定義と実行
- 052D・3D配座の生成
- 06分子構造の描画
活用シーン
- 01目的の構造を持つ分子のスクリーニング
- 02分子フィンガープリントの類似性比較
- 03薬物様分子の特性分析
- 04配座と構造画像の生成
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ jackspace/ claudeskillz --skill rdkitインストール後、Claude Code で/rdkitを入力して読み込まれたか確認します。
同梱ファイルSKILL.json
詳細
RDKit ケモインフォマティクスツールキット
概要
RDKit は、分子解析と操作のための Python API を提供する包括的なケモインフォマティクスライブラリです。このスキルは、分子構造の読み書き、記述子の計算、フィンガープリント作成、部分構造検索、化学反応、2D/3D 座標生成、分子の可視化に関する指針を提供します。創薬、計算化学、ケモインフォマティクス研究のタスクにこのスキルを使用してください。
中核機能
1. 分子の入出力と作成
分子の読み込み:
さまざまな形式から分子構造を読み込みます:
from rdkit import Chem
# From SMILES strings
mol = Chem.MolFromSmiles('Cc1ccccc1') # Returns Mol object or None
# From MOL files
mol = Chem.MolFromMolFile('path/to/file.mol')
# From MOL blocks (string data)
mol = Chem.MolFromMolBlock(mol_block_string)
# From InChI
mol = Chem.MolFromInchi('InChI=1S/C6H6/c1-2-4-6-5-3-1/h1-6H')
分子の書き出し:
分子をテキスト表現に変換します:
# To canonical SMILES
smiles = Chem.MolToSmiles(mol)
# To MOL block
mol_block = Chem.MolToMolBlock(mol)
# To InChI
inchi = Chem.MolToInchi(mol)
バッチ処理:
複数の分子を処理するには、Supplier/Writer オブジェクトを使用します:
# Read SDF files
suppl = Chem.SDMolSupplier('molecules.sdf')
for mol in suppl:
if mol is not None: # Check for parsing errors
# Process molecule
pass
# Read SMILES files
suppl = Chem.SmilesMolSupplier('molecules.smi', titleLine=False)
# For large files or compressed data
with gzip.open('molecules.sdf.gz') as f:
suppl = Chem.ForwardSDMolSupplier(f)
for mol in suppl:
# Process molecule
pass
# Multithreaded processing for large datasets
suppl = Chem.MultithreadedSDMolSupplier('molecules.sdf')
# Write molecules to SDF
writer = Chem.SDWriter('output.sdf')
for mol in molecules:
writer.write(mol)
writer.close()
重要な注意事項:
- すべての
MolFrom*関数は、失敗時にエラーメッセージとともにNoneを返します - 分子を処理する前に、必ず
Noneでないことを確認してください - 分子は読み込み時に自動的にサニタイズされます(原子価の検証、芳香族性の判定)
2. 分子のサニタイズと検証
RDKit は解析中に分子を自動的にサニタイズし、原子価の検査、芳香族性の判定、キラリティの割り当てを含む 13 のステップを実行します。
サニタイズの制御:
# Disable automatic sanitization
mol = Chem.MolFromSmiles('C1=CC=CC=C1', sanitize=False)
# Manual sanitization
Chem.SanitizeMol(mol)
# Detect problems before sanitization
problems = Chem.DetectChemistryProblems(mol)
for problem in problems:
print(problem.GetType(), problem.Message())
# Partial sanitization (skip specific steps)
from rdkit.Chem import rdMolStandardize
Chem.SanitizeMol(mol, sanitizeOps=Chem.SANITIZE_ALL ^ Chem.SANITIZE_PROPERTIES)
よくあるサニタイズの問題:
- 明示的な原子価が許容最大値を超える原子は、例外を発生させます
- 不正な芳香環はケクレ化エラーの原因になります
- ラジカル電子は、明示的に指定しないと正しく割り当てられない場合があります
3. 分子解析と特性
分子構造へのアクセス:
# Iterate atoms and bonds
for atom in mol.GetAtoms():
print(atom.GetSymbol(), atom.GetIdx(), atom.GetDegree())
for bond in mol.GetBonds():
print(bond.GetBeginAtomIdx(), bond.GetEndAtomIdx(), bond.GetBondType())
# Ring information
ring_info = mol.GetRingInfo()
ring_info.NumRings()
ring_info.AtomRings() # Returns tuples of atom indices
# Check if atom is in ring
atom = mol.GetAtomWithIdx(0)
atom.IsInRing()
atom.IsInRingSize(6) # Check for 6-membered rings
# Find smallest set of smallest rings (SSSR)
from rdkit.Chem import GetSymmSSSR
rings = GetSymmSSSR(mol)
立体化学:
# Find chiral centers
from rdkit.Chem import FindMolChiralCenters
chiral_centers = FindMolChiralCenters(mol, includeUnassigned=True)
# Returns list of (atom_idx, chirality) tuples
# Assign stereochemistry from 3D coordinates
from rdkit.Chem import AssignStereochemistryFrom3D
AssignStereochemistryFrom3D(mol)
# Check bond stereochemistry
bond = mol.GetBondWithIdx(0)
stereo = bond.GetStereo() # STEREONONE, STEREOZ, STEREOE, etc.
フラグメント解析:
# Get disconnected fragments
frags = Chem.GetMolFrags(mol, asMols=True)
# Fragment on specific bonds
from rdkit.Chem import FragmentOnBonds
frag_mol = FragmentOnBonds(mol, [bond_idx1, bond_idx2])
# Count ring systems
from rdkit.Chem.Scaffolds import MurckoScaffold
scaffold = MurckoScaffold.GetScaffoldForMol(mol)
4. 分子記述子と特性
基本的な記述子:
from rdkit.Chem import Descriptors
# Molecular weight
mw = Descriptors.MolWt(mol)
exact_mw = Descriptors.ExactMolWt(mol)
# LogP (lipophilicity)
logp = Descriptors.MolLogP(mol)
# Topological polar surface area
tpsa = Descriptors.TPSA(mol)
# Number of hydrogen bond donors/acceptors
hbd = Descriptors.NumHDonors(mol)
hba = Descriptors.NumHAcceptors(mol)
# Number of rotatable bonds
rot_bonds = Descriptors.NumRotatableBonds(mol)
# Number of aromatic rings
aromatic_rings = Descriptors.NumAromaticRings(mol)
記述子のバッチ計算:
# Calculate all descriptors at once
all_descriptors = Descriptors.CalcMolDescriptors(mol)
# Returns dictionary: {'MolWt': 180.16, 'MolLogP': 1.23, ...}
# Get list of available descriptor names
descriptor_names = [desc[0] for desc in Descriptors._descList]
Lipinski の Rule of Five:
# Check drug-likeness
mw = Descriptors.MolWt(mol) <= 500
logp = Descriptors.MolLogP(mol) <= 5
hbd = Descriptors.NumHDonors(mol) <= 5
hba = Descriptors.NumHAcceptors(mol) <= 10
is_drug_like = mw and logp and hbd and hba
5. フィンガープリントと分子類似性
フィンガープリントの種類:
from rdkit.Chem import AllChem, RDKFingerprint
from rdkit.Chem.AtomPairs import Pairs, Torsions
from rdkit.Chem import MACCSkeys
# RDKit topological fingerprint
fp = Chem.RDKFingerprint(mol)
# Morgan fingerprints (circular fingerprints, similar to ECFP)
fp = AllChem.GetMorganFingerprint(mol, radius=2)
fp_bits = AllChem.GetMorganFingerprintAsBitVect(mol, radius=2, nBits=2048)
# MACCS keys (166-bit structural key)
fp = MACCSkeys.GenMACCSKeys(mol)
# Atom pair fingerprints
fp = Pairs.GetAtomPairFingerprint(mol)
# Topological torsion fingerprints
fp = Torsions.GetTopologicalTorsionFingerprint(mol)
# Avalon fingerprints (if available)
from rdkit.Avalon import pyAvalonTools
fp = pyAvalonTools.GetAvalonFP(mol)
類似度の計算:
from rdkit import DataStructs
# Calculate Tanimoto similarity
fp1 = AllChem.GetMorganFingerprintAsBitVect(mol1, radius=2)
fp2 = AllChem.GetMorganFingerprintAsBitVect(mol2, radius=2)
similarity = DataStructs.TanimotoSimilarity(fp1, fp2)
# Calculate similarity for multiple molecules
similarities = DataStructs.BulkTanimotoSimilarity(fp1, [fp2, fp3, fp4])
# Other similarity metrics
dice = DataStructs.DiceSimilarity(fp1, fp2)
cosine = DataStructs.CosineSimilarity(fp1, fp2)
クラスタリングと多様性:
# Butina clustering based on fingerprint similarity
from rdkit.ML.Cluster import Butina
# Calculate distance matrix
dists = []
fps = [AllChem.GetMorganFingerprintAsBitVect(mol, 2) for mol in mols]
for i in range(len(fps)):
sims = DataStructs.BulkTanimotoSimilarity(fps[i], fps[:i])
dists.extend([1-sim for sim in sims])
# Cluster with distance cutoff
clusters = Butina.ClusterData(dists, len(fps), distThresh=0.3, isDistData=True)
6. 部分構造検索と SMARTS
基本的な部分構造マッチング:
# Define query using SMARTS
query = Chem.MolFromSmarts('[#6]1:[#6]:[#6]:[#6]:[#6]:[#6]:1') # Benzene ring
# Check if molecule contains substructure
has_match = mol.HasSubstructMatch(query)
# Get all matches (returns tuple of tuples with atom indices)
matches = mol.GetSubstructMatches(query)
# Get only first match
match = mol.GetSubstructMatch(query)
よく使われる SMARTS パターン:
# Primary alcohols
primary_alcohol = Chem.MolFromSmarts('[CH2][OH1]')
# Carboxylic acids
carboxylic_acid = Chem.MolFromSmarts('C(=O)[OH]')
# Amides
amide = Chem.MolFromSmarts('C(=O)N')
# Aromatic heterocycles
aromatic_n = Chem.MolFromSmarts('[nR]') # Aromatic nitrogen in ring
# Macrocycles (rings > 12 atoms)
macrocycle = Chem.MolFromSmarts('[r{12-}]')
マッチングのルール:
- 指定されていない特性は、ターゲット内の任意の値にマッチします
- 水素は、明示的に指定されない限り無視されます
- 電荷を持つクエリ原子は、電荷を持たないターゲット原子にはマッチしません
- 芳香族のクエリ原子は、脂肪族のターゲット原子にはマッチしません(クエリが汎用の場合を除く)
7. 化学反応
反応 SMARTS:
from rdkit.Chem import AllChem
# Define reaction using SMARTS: reactants >> products
rxn = AllChem.ReactionFromSmarts('[C:1]=[O:2]>>[C:1][O:2]') # Ketone reduction
# Apply reaction to molecules
reactants = (mol1,)
products = rxn.RunReactants(reactants)
# Products is tuple of tuples (one tuple per product set)
for product_set in products:
for product in product_set:
# Sanitize product
Chem.SanitizeMol(product)
反応の特徴:
- 原子マッピングにより、反応物と生成物の間で特定の原子が保持されます
- 生成物内のダミー原子は、対応する反応物の原子に置き換えられます
- 「任意」の結合は、反応物の結合次数を引き継ぎます
- 明示的に変更されない限り、キラリティは保持されます
反応の類似性:
# Generate reaction fingerprints
fp = AllChem.CreateDifferenceFingerprintForReaction(rxn)
# Compare reactions
similarity = DataStructs.TanimotoSimilarity(fp1, fp2)
8. 2D および 3D 座標生成
2D 座標の生成:
from rdkit.Chem import AllChem
# Generate 2D coordinates for depiction
AllChem.Compute2DCoords(mol)
# Align molecule to template structure
template = Chem.MolFromSmiles('c1ccccc1')
AllChem.Compute2DCoords(template)
AllChem.GenerateDepictionMatching2DStructure(mol, template)
3D 座標とコンフォーマーの生成:
# Generate single 3D conformer using ETKDG
AllChem.EmbedMolecule(mol, randomSeed=42)
# Generate multiple conformers
conf_ids = AllChem.EmbedMultipleConfs(mol, numConfs=10, randomSeed=42)
# Optimize geometry with force field
AllChem.UFFOptimizeMolecule(mol) # UFF force field
AllChem.MMFFOptimizeMolecule(mol) # MMFF94 force field
# Optimize all conformers
for conf_id in conf_ids:
AllChem.MMFFOptimizeMolecule(mol, confId=conf_id)
# Calculate RMSD between conformers
from rdkit.Chem import AllChem
rms = AllChem.GetConformerRMS(mol, conf_id1, conf_id2)
# Align molecules
AllChem.AlignMol(probe_mol, ref_mol)
拘束付き埋め込み:
# Embed with part of molecule constrained to specific coordinates
AllChem.ConstrainedEmbed(mol, core_mol)
9. 分子の可視化
基本的な描画:
from rdkit.Chem import Draw
# Draw single molecule to PIL image
img = Draw.MolToImage(mol, size=(300, 300))
img.save('molecule.png')
# Draw to file directly
Draw.MolToFile(mol, 'molecule.png')
# Draw multiple molecules in grid
mols = [mol1, mol2, mol3, mol4]
img = Draw.MolsToGridImage(mols, molsPerRow=2, subImgSize=(200, 200))
部分構造のハイライト:
# Highlight substructure match
query = Chem.MolFromSmarts('c1ccccc1')
match = mol.GetSubstructMatch(query)
img = Draw.MolToImage(mol, highlightAtoms=match)
# Custom highlight colors
highlight_colors = {atom_idx: (1, 0, 0) for atom_idx in match} # Red
img = Draw.MolToImage(mol, highlightAtoms=match,
highlightAtomColors=highlight_colors)
可視化のカスタマイズ:
from rdkit.Chem.Draw import rdMolDraw2D
# Create drawer with custom options
drawer = rdMolDraw2D.MolDraw2DCairo(300, 300)
opts = drawer.drawOptions()
# Customize options
opts.addAtomIndices = True
opts.addStereoAnnotation = True
opts.bondLineWidth = 2
# Draw molecule
drawer.DrawMolecule(mol)
drawer.FinishDrawing()
# Save to file
with open('molecule.png', 'wb') as f:
f.write(drawer.GetDrawingText())
Jupyter Notebook との統合:
# Enable inline display in Jupyter
from rdkit.Chem.Draw import IPythonConsole
# Customize default display
IPythonConsole.ipython_useSVG = True # Use SVG instead of PNG
IPythonConsole.molSize = (300, 300) # Default size
# Molecules now display automatically
mol # Shows molecule image
フィンガープリントビットの可視化:
# Show what molecular features a fingerprint bit represents
from rdkit.Chem import Draw
# For Morgan fingerprints
bit_info = {}
fp = AllChem.GetMorganFingerprintAsBitVect(mol, radius=2, bitInfo=bit_info)
# Draw environment for specific bit
img = Draw.DrawMorganBit(mol, bit_id, bit_info)
10. 分子の修飾
水素の追加と削除:
# Add explicit hydrogens
mol_h = Chem.AddHs(mol)
# Remove explicit hydrogens
mol = Chem.RemoveHs(mol_h)
ケクレ化と芳香族性:
# Convert aromatic bonds to alternating single/double
Chem.Kekulize(mol)
# Set aromaticity
Chem.SetAromaticity(mol)
部分構造の置換:
# Replace substructure with another structure
query = Chem.MolFromSmarts('c1ccccc1') # Benzene
replacement = Chem.MolFromSmiles('C1CCCCC1') # Cyclohexane
new_mol = Chem.ReplaceSubstructs(mol, query, replacement)[0]
電荷の中和:
# Remove formal charges by adding/removing hydrogens
from rdkit.Chem.MolStandardize import rdMolStandardize
# Using Uncharger
uncharger = rdMolStandardize.Uncharger()
mol_neutral = uncharger.uncharge(mol)
11. 分子ハッシュと標準化
分子ハッシュ:
from rdkit.Chem import rdMolHash
# Generate Murcko scaffold hash
scaffold_hash = rdMolHash.MolHash(mol, rdMolHash.HashFunction.MurckoScaffold)
# Canonical SMILES hash
canonical_hash = rdMolHash.MolHash(mol, rdMolHash.HashFunction.CanonicalSmiles)
# Regioisomer hash (ignores stereochemistry)
regio_hash = rdMolHash.MolHash(mol, rdMolHash.HashFunction.Regioisomer)
ランダム化 SMILES:
# Generate random SMILES representations (for data augmentation)
from rdkit.Chem import MolToRandomSmilesVect
random_smiles = MolToRandomSmilesVect(mol, numSmiles=10, randomSeed=42)
12. ファーマコフォアと 3D 特徴
ファーマコフォアの特徴:
from rdkit.Chem import ChemicalFeatures
from rdkit import RDConfig
import os
# Load feature factory
fdef_path = os.path.join(RDConfig.RDDataDir, 'BaseFeatures.fdef')
factory = ChemicalFeatures.BuildFeatureFactory(fdef_path)
# Get pharmacophore features
features = factory.GetFeaturesForMol(mol)
for feat in features:
print(feat.GetFamily(), feat.GetType(), feat.GetAtomIds())
一般的なワークフロー
薬らしさの解析
from rdkit import Chem
from rdkit.Chem import Descriptors
def analyze_druglikeness(smiles):
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
# Calculate Lipinski descriptors
results = {
'MW': Descriptors.MolWt(mol),
'LogP': Descriptors.MolLogP(mol),
'HBD': Descriptors.NumHDonors(mol),
'HBA': Descriptors.NumHAcceptors(mol),
'TPSA': Descriptors.TPSA(mol),
'RotBonds': Descriptors.NumRotatableBonds(mol)
}
# Check Lipinski's Rule of Five
results['Lipinski'] = (
results['MW'] <= 500 and
results['LogP'] <= 5 and
results['HBD'] <= 5 and
results['HBA'] <= 10
)
return results
類似性スクリーニング
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit import DataStructs
def similarity_screen(query_smiles, database_smiles, threshold=0.7):
query_mol = Chem.MolFromSmiles(query_smiles)
query_fp = AllChem.GetMorganFingerprintAsBitVect(query_mol, 2)
hits = []
for idx, smiles in enumerate(database_smiles):
mol = Chem.MolFromSmiles(smiles)
if mol:
fp = AllChem.GetMorganFingerprintAsBitVect(mol, 2)
sim = DataStructs.TanimotoSimilarity(query_fp, fp)
if sim >= threshold:
hits.append((idx, smiles, sim))
return sorted(hits, key=lambda x: x[2], reverse=True)
部分構造によるフィルタリング
from rdkit import Chem
def filter_by_substructure(smiles_list, pattern_smarts):
query = Chem.MolFromSmarts(pattern_smarts)
hits = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
if mol and mol.HasSubstructMatch(query):
hits.append(smiles)
return hits
ベストプラクティス
エラー処理
分子を解析するときは、必ず None を確認してください:
mol = Chem.MolFromSmiles(smiles)
if mol is None:
print(f"Failed to parse: {smiles}")
continue
パフォーマンスの最適化
保存にはバイナリ形式を使用する:
import pickle
# Pickle molecules for fast loading
with open('molecules.pkl', 'wb') as f:
pickle.dump(mols, f)
# Load pickled molecules (much faster than reparsing)
with open('molecules.pkl', 'rb') as f:
mols = pickle.load(f)
バルク操作を使用する:
# Calculate fingerprints for all molecules at once
fps = [AllChem.GetMorganFingerprintAsBitVect(mol, 2) for mol in mols]
# Use bulk similarity calculations
similarities = DataStructs.BulkTanimotoSimilarity(fps[0], fps[1:])
スレッドセーフティ
RDKit の操作は、一般に次の処理についてスレッドセーフです:
- 分子の入出力(SMILES、mol ブロック)
- 座標生成
- フィンガープリントと記述子の計算
- サブ構造検索
- 反応
- 描画
スレッドセーフではない: 同時にアクセスされる場合の MolSuppliers
メモリ管理
大規模なデータセットの場合:
# Use ForwardSDMolSupplier to avoid loading entire file
with open('large.sdf') as f:
suppl = Chem.ForwardSDMolSupplier(f)
for mol in suppl:
# Process one molecule at a time
pass
# Use MultithreadedSDMolSupplier for parallel processing
suppl = Chem.MultithreadedSDMolSupplier('large.sdf', numWriterThreads=4)
よくある落とし穴
- None のチェックを忘れる: パース後は必ず分子を検証してください
- サニタイズの失敗: デバッグには
DetectChemistryProblems()を使用してください - 水素の欠落: 水素に依存する特性を計算する場合は
AddHs()を使用してください - 2D と 3D: 可視化や 3D 解析の前に、適切な座標を生成してください
- SMARTS マッチングのルール: 指定されていない特性は任意の値に一致する点に注意してください
- MolSuppliers とのスレッドセーフティ: サプライヤーオブジェクトを複数のスレッドで共有しないでください
リソース
references/
このスキルには、詳細な API リファレンスドキュメントが含まれています:
api_reference.md- 機能別に整理された RDKit のモジュール、関数、クラスの包括的な一覧descriptors_reference.md- 利用可能な分子記述子の完全な一覧と説明smarts_patterns.md- 官能基や構造的特徴に対する一般的な SMARTS パターン
特定の API の詳細、パラメーター情報、パターンの例が必要な場合は、これらのリファレンスを読み込んでください。
scripts/
一般的な RDKit のワークフロー向けのサンプルスクリプト:
molecular_properties.py- 包括的な分子特性と記述子を計算しますsimilarity_search.py- フィンガープリントに基づく類似性スクリーニングを実行しますsubstructure_filter.py- サブ構造パターンによって分子をフィルタリングします
これらのスクリプトは直接実行することも、カスタムワークフローのテンプレートとして使用することもできます。