File size: 3,491 Bytes
1d27ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#!/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()