QQCM / COM /inchikey.py
JX-Lab's picture
Add files using upload-large-folder tool
1d27ec0 verified
Raw History Blame Contribute Delete
3.49 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations
import os
from pathlib import Path
import pandas as pd
from rdkit import Chem
from tqdm import tqdm
SDF_DIR = Path("/mnt/disk1/yanganqi/QQCM/COM/pubchem_clean_sdf")
MOL2_DIR = Path("/mnt/disk1/yanganqi/QQCM/COM/tcmsp_mol2")
ALT_SDF_ROOT = Path("/mnt/disk1/yanganqi/QQCM/清窍聪明汤结构-mol2-sdf")
OUT_CSV = Path("/mnt/disk1/yanganqi/QQCM/COM/compound_inchikey.csv")
def sdf_to_inchikey(file_path: Path) -> str | None:
try:
supplier = Chem.SDMolSupplier(str(file_path))
mol = supplier[0] if supplier and len(supplier) > 0 else None
if mol is not None:
return Chem.MolToInchiKey(mol)
except Exception:
return None
return None
def mol2_to_inchikey(file_path: Path) -> str | None:
try:
mol = Chem.MolFromMol2File(str(file_path))
if mol is not None:
return Chem.MolToInchiKey(mol)
except Exception:
pass
try:
mol = Chem.MolFromMol2File(
str(file_path),
sanitize=False,
removeHs=False,
cleanupSubstructures=False,
)
if mol is not None:
return Chem.MolToInchiKey(mol)
except Exception:
return None
return None
def build_alt_sdf_lookup(root: Path) -> dict[str, Path]:
lookup: dict[str, Path] = {}
for path in root.rglob("*.sdf"):
lookup.setdefault(path.stem, path)
return lookup
def main() -> None:
results: list[dict[str, str | None]] = []
alt_sdf_lookup = build_alt_sdf_lookup(ALT_SDF_ROOT)
print("=== Processing SDF files ===")
sdf_files = sorted(f for f in os.listdir(SDF_DIR) if f.endswith(".sdf"))
for filename in tqdm(sdf_files):
path = SDF_DIR / filename
inchikey = sdf_to_inchikey(path)
results.append(
{
"file_name": filename,
"source": "pubchem_sdf",
"parse_source": "pubchem_sdf",
"fallback_path": "",
"inchikey": inchikey,
}
)
print("=== Processing MOL2 files ===")
mol2_files = sorted(f for f in os.listdir(MOL2_DIR) if f.endswith(".mol2"))
for filename in tqdm(mol2_files):
path = MOL2_DIR / filename
stem = path.stem
inchikey = mol2_to_inchikey(path)
parse_source = "tcmsp_mol2"
fallback_path = ""
if inchikey is None and stem in alt_sdf_lookup:
fallback = alt_sdf_lookup[stem]
inchikey = sdf_to_inchikey(fallback)
if inchikey is not None:
parse_source = "fallback_sdf"
fallback_path = str(fallback)
results.append(
{
"file_name": filename,
"source": "tcmsp_mol2",
"parse_source": parse_source,
"fallback_path": fallback_path,
"inchikey": inchikey,
}
)
df = pd.DataFrame(results)
df["status"] = df["inchikey"].apply(lambda value: "success" if pd.notna(value) else "fail")
df_clean = df.dropna(subset=["inchikey"]).copy()
OUT_CSV.parent.mkdir(parents=True, exist_ok=True)
df_clean.to_csv(OUT_CSV, index=False)
print("=== Done ===")
print(f"Total: {len(df)}")
print(f"Success: {len(df_clean)}")
print(f"Failed: {len(df) - len(df_clean)}")
print(f"Saved to: {OUT_CSV}")
if __name__ == "__main__":
main()