#!/usr/bin/env python3 from __future__ import annotations import csv import io import json import os import re import unicodedata from collections import Counter, defaultdict from pathlib import Path MS_CSV = Path("/mnt/disk1/yanganqi/QQCM/MS/三者并集完整输出.csv") OUTPUT_CSV = Path("/mnt/disk1/yanganqi/QQCM/MS/三者并集完整输出_结构标注.csv") YAO_CSV = Path("/mnt/disk1/yanganqi/YJT/药典中药汇总.csv") AGG_ROOT = Path("/mnt/disk1/yanganqi/YJT/data/原始数据汇总") HERB2_SOURCE_BACKFILL_CSV = AGG_ROOT / "HERB2" / "HERB2_source_backfill_rows.csv" QQCM_NAME_MAP = Path("/mnt/disk1/yanganqi/QQCM/id_trans/qqcm_pubchem_drugbank_mapping.tsv") QQCM_SMILES = Path("/mnt/disk1/yanganqi/QQCM/COM/compound_smiles.csv") QQCM_INCHIKEY = Path("/mnt/disk1/yanganqi/QQCM/COM/compound_inchikey.csv") QQCM_HELPER_DIR = Path("/mnt/disk1/yanganqi/QQCM/KG/qqcm_compound_subgraph/helper_tables") QQCM_MOL_GROUPS = QQCM_HELPER_DIR / "qqcm_compound_multi_mol_id_groups.tsv" QQCM_CID_LOOKUP_DIR = Path("/mnt/disk1/yanganqi/QQCM/LLM/pubchem_cache/cid_lookup") QQCM_TCMSP_CACHE_JSON = Path("/mnt/disk1/yanganqi/QQCM/COM/tcmsp_molecule_cache.json") READ_ENCODINGS = ("utf-8-sig", "utf-8", "gb18030", "latin1") FORMULA_COLUMNS = ("Molecular Formula", "MolecularFormula", "molecularformula", "Formula") NAME_COLUMNS = ("Name", "name", "Queried Name", "Queried Identifier", "compound_name") IUPAC_COLUMNS = ("IUPAC Name", "IUPACName", "iupacname") SMILES_COLUMNS = ("SMILES", "CanonicalSMILES", "smiles", "SMILES.1") INCHI_COLUMNS = ("InChI", "inchi") INCHIKEY_COLUMNS = ("InChKey", "InChIKey", "inchikey") CID_COLUMNS = ("PubChem CID", "pubchemcid", "CID", "cid", "mol_id") CAS_COLUMNS = ("CAS", "cas") SHORT_AMBIGUOUS = { "ado", "ann", "beo", "bzf", "cam", "cnh", "cpi", "cyt", "dbh", "dfv", "dhnq", "dle", "dmr", "dmt", "dob", "dtr", "dty", "dur", "eb", "ehbn", "eld", "esen", "fer", "foa", "fpr", "gbl", "gco", "gr", "gre", "gun", "hba", "hmf", "hmo", "iea", "ies", "ipmc", "l-", "ldp", "lof", "ltan", "mboa", "mhp", "mipk", "mlt", "mnn", "myf", "nfp", "nk", "noj", "ohp", "oxl", "pac", "pea", "pha", "phb", "pip", "ppy", "prz", "ptl", "pyc", "pyg", "rco", "rmn", "rng", "ron", "scg", "thz", "tml", "unal", "urc", "vca", "wv", "py", } def pick(row: dict[str, str], columns: tuple[str, ...]) -> str: for column in columns: value = row.get(column) if value is None: continue text = str(value).strip() if text and text.lower() != "nan": return text return "" def norm_formula(value: str) -> str: return re.sub(r"\s+", "", value or "").upper() def normalize_cid(value: str) -> str: text = (value or "").strip() if not text: return "" if text.upper().startswith("CID_") and text[4:].isdigit(): return text[4:] if re.fullmatch(r"\d+\.0", text): return text[:-2] return text def strip_accents(value: str) -> str: return "".join( ch for ch in unicodedata.normalize("NFKD", value) if not unicodedata.combining(ch) ) def normalize_name(value: str) -> str: text = (value or "").strip() if not text: return "" text = ( text.replace("\u2019", "'") .replace("\u2018", "'") .replace("\u201c", '"') .replace("\u201d", '"') .replace("β", "beta") .replace("Β", "beta") .replace("α", "alpha") .replace("Α", "alpha") .replace("γ", "gamma") .replace("Γ", "gamma") .replace("δ", "delta") .replace("Δ", "delta") .replace("\u3000", " ") ) text = strip_accents(text) text = re.sub(r"[_ ]+qt(?:\s*\d+)?$", "", text, flags=re.IGNORECASE) text = re.sub(r"\s+\d+$", "", text) text = text.strip(" ;,") text = re.sub(r"\s+", " ", text) return text.lower() def clean_reference_name(value: str) -> str: text = (value or "").strip() if not text: return "" lowered = text.lower() for prefix in ("name:", "compound_name:", "compound name:"): if lowered.startswith(prefix): return text[len(prefix) :].strip() if lowered.startswith(("cid:", "smiles:", "inchikey:", "inchi:")): return "" return text def alnum_name(value: str) -> str: return re.sub(r"[^a-z0-9]+", "", normalize_name(value)) def is_cas_name(value: str) -> bool: return bool(re.fullmatch(r"\d{2,7}-\d{2}-\d", value.strip())) def is_inchi_literal(value: str) -> bool: return value.strip().startswith("InChI=") def is_unresolved_noise(name: str) -> bool: n = normalize_name(name) if not n: return True if n in SHORT_AMBIGUOUS: return True if len(n) <= 2: return True if "_" in name: return True if re.fullmatch(r"[A-Z0-9\-]+", name) and len(name) <= 12: return True if "wln:" in n: return True if "pubchem cid" in n: return True return False def open_csv_with_fallback(path: Path, delimiter: str = ","): raw = path.read_bytes() last_error = None for encoding in READ_ENCODINGS: try: text = raw.decode(encoding) handle = io.StringIO(text) reader = csv.DictReader(handle, delimiter=delimiter) if not reader.fieldnames: handle.close() continue return handle, reader except Exception as exc: # pragma: no cover - filesystem/runtime dependent last_error = exc raise RuntimeError(f"Unable to read {path}") from last_error def split_aliases(value: str) -> list[str]: aliases: list[str] = [] for item in re.split(r"[;|]+", value or ""): cleaned = clean_reference_name(item) if cleaned: aliases.append(cleaned) return aliases def load_group_cid_map() -> dict[str, str]: if not QQCM_MOL_GROUPS.exists(): return {} mapping: dict[str, str] = {} with QQCM_MOL_GROUPS.open("r", encoding="utf-8-sig", newline="") as handle: reader = csv.DictReader(handle, delimiter="\t") for row in reader: mol_ids = [item.strip() for item in (row.get("mol_ids") or "").split("|") if item.strip()] cid_candidates = [item.removeprefix("CID_") for item in mol_ids if item.startswith("CID_")] if not cid_candidates: continue for mol_id in mol_ids: if mol_id.startswith("MOL") and mol_id not in mapping: mapping[mol_id] = cid_candidates[0] return mapping def load_lookup_cid_map() -> dict[str, str]: if not QQCM_CID_LOOKUP_DIR.exists(): return {} mapping: dict[str, str] = {} for json_path in sorted(QQCM_CID_LOOKUP_DIR.glob("MOL*.json")): try: payload = json.loads(json_path.read_text(encoding="utf-8")) except Exception: continue candidates = payload.get("cid_candidates") or [] if not candidates: continue cid_text = normalize_cid(str(candidates[0])) if cid_text and cid_text != "0": mapping[json_path.stem] = cid_text return mapping def load_tcmsp_cache() -> dict[str, dict[str, object]]: if not QQCM_TCMSP_CACHE_JSON.exists(): return {} try: return json.loads(QQCM_TCMSP_CACHE_JSON.read_text(encoding="utf-8")) except Exception: return {} def resolve_qqcm_pubchem_cid( file_name: str, lookup_cids: dict[str, str], group_cids: dict[str, str], tcmsp_cache: dict[str, dict[str, object]], ) -> str: stem = file_name.rsplit(".", 1)[0] if "." in file_name else file_name if stem.startswith("CID_"): return normalize_cid(stem) if stem.startswith("MOL"): if stem in lookup_cids: return lookup_cids[stem] cached = tcmsp_cache.get(stem) or {} cached_cid = normalize_cid(str(cached.get("pubchem_cid") or "")) if cached_cid and cached_cid != "0": return cached_cid if stem in group_cids: return group_cids[stem] return normalize_cid(stem) def structure_key(record: dict[str, str]) -> tuple[str, str]: for key in ("inchikey", "inchi", "smiles", "cid"): value = normalize_cid(record.get(key, "")) if key == "cid" else record.get(key, "").strip() if value: return key, value return "name_formula", f"{record.get('name', '')}|{record.get('formula', '')}" def dedup_records(records: list[dict[str, str]]) -> list[dict[str, str]]: unique: list[dict[str, str]] = [] for record in records: record = dict(record) record["cid"] = normalize_cid(record.get("cid", "")) merged = False for existing in unique: same_inchikey = ( record.get("inchikey") and existing.get("inchikey") and record["inchikey"] == existing["inchikey"] ) same_inchi = ( record.get("inchi") and existing.get("inchi") and record["inchi"] == existing["inchi"] ) same_smiles = ( record.get("smiles") and existing.get("smiles") and record["smiles"] == existing["smiles"] ) same_cid = record.get("cid") and existing.get("cid") and record["cid"] == existing["cid"] if same_inchikey or same_inchi or same_smiles or same_cid: for key, value in record.items(): if value and not existing.get(key): existing[key] = value merged = True break if not merged: unique.append(record) return unique def add_record(index: dict[str, defaultdict[str, list]], record: dict[str, str]) -> None: raw_names = {record.get("name", ""), record.get("iupac", "")} raw_names.update(record.get("aliases", [])) for raw_name in raw_names: if not raw_name: continue cleaned_name = clean_reference_name(raw_name) if not cleaned_name: continue normalized = normalize_name(cleaned_name) if normalized: index["norm"][normalized].append(record) compact = alnum_name(cleaned_name) if compact: index["alnum"][compact].append(record) cas = record.get("cas", "").strip() if cas: index["cas"][cas].append(record) def put_file_lookup(mapping: dict[str, str], file_name: str, value: str) -> None: if not file_name or not value: return mapping[file_name] = value stem = file_name if "." in file_name: stem = file_name.rsplit(".", 1)[0] mapping[stem] = value def get_file_lookup(mapping: dict[str, str], file_name: str) -> str: if not file_name: return "" if file_name in mapping: return mapping[file_name] for suffix in (".sdf", ".mol2"): candidate = f"{file_name}{suffix}" if candidate in mapping: return mapping[candidate] stem = file_name.rsplit(".", 1)[0] if "." in file_name else file_name return mapping.get(stem, "") def build_reference_index() -> dict[str, defaultdict[str, list]]: index: dict[str, defaultdict[str, list]] = { "norm": defaultdict(list), "alnum": defaultdict(list), "cas": defaultdict(list), } handle, reader = open_csv_with_fallback(YAO_CSV) try: for row in reader: record = { "source": "药典中药汇总", "name": clean_reference_name(pick(row, ("name",))), "iupac": pick(row, ("iupacname",)), "formula": pick(row, ("molecularformula",)), "smiles": pick(row, ("smiles",)), "inchi": pick(row, ("inchi",)), "inchikey": pick(row, ("inchikey",)), "cas": pick(row, ("cas",)), "cid": pick(row, ("pubchemcid",)), "aliases": [], } if record["name"] or record["iupac"]: add_record(index, record) finally: handle.close() for dirpath, _dirnames, filenames in os.walk(AGG_ROOT): for filename in filenames: if not filename.endswith("_Info_汇总.csv"): continue path = Path(dirpath) / filename handle, reader = open_csv_with_fallback(path) try: for row in reader: record = { "source": filename, "name": clean_reference_name(pick(row, NAME_COLUMNS)), "iupac": pick(row, IUPAC_COLUMNS), "formula": pick(row, FORMULA_COLUMNS), "smiles": pick(row, SMILES_COLUMNS), "inchi": pick(row, INCHI_COLUMNS), "inchikey": pick(row, INCHIKEY_COLUMNS), "cas": pick(row, CAS_COLUMNS), "cid": pick(row, CID_COLUMNS), "aliases": [], } if record["name"] or record["iupac"]: add_record(index, record) finally: handle.close() if HERB2_SOURCE_BACKFILL_CSV.exists(): handle, reader = open_csv_with_fallback(HERB2_SOURCE_BACKFILL_CSV) try: for row in reader: if pick(row, ("sourcebackfillstatus",)) != "filled_ingredient_detail": continue if not any( pick(row, columns) for columns in ( ("pubchemcid",), ("smiles",), ("inchi",), ("inchkey",), ("cas",), ) ): continue queried_name = clean_reference_name(pick(row, ("queriedname",))) record = { "source": "HERB2_source_backfill_rows", "name": clean_reference_name(pick(row, ("sourceingredientname", "sourcepubchemname"))), "iupac": pick(row, ("iupacname", "sourcepubchemname")), "formula": pick(row, ("molecularformula",)), "smiles": pick(row, ("smiles",)), "inchi": pick(row, ("inchi",)), "inchikey": pick(row, ("inchkey",)), "cas": pick(row, ("cas",)), "cid": pick(row, ("pubchemcid",)), "aliases": ( split_aliases(pick(row, ("sourceingredientalias",))) + ([queried_name] if queried_name else []) + split_aliases(pick(row, ("sourcepubchemname",))) ), } if record["name"] or record["iupac"] or record["aliases"]: add_record(index, record) finally: handle.close() smiles_by_file: dict[str, str] = {} handle, reader = open_csv_with_fallback(QQCM_SMILES) try: for row in reader: smiles = pick(row, ("smiles",)) file_name = pick(row, ("file_name",)) put_file_lookup(smiles_by_file, file_name, smiles) finally: handle.close() inchikey_by_file: dict[str, str] = {} handle, reader = open_csv_with_fallback(QQCM_INCHIKEY) try: for row in reader: inchikey = pick(row, ("inchikey",)) file_name = pick(row, ("file_name",)) put_file_lookup(inchikey_by_file, file_name, inchikey) finally: handle.close() lookup_cids = load_lookup_cid_map() group_cids = load_group_cid_map() tcmsp_cache = load_tcmsp_cache() handle, reader = open_csv_with_fallback(QQCM_NAME_MAP, delimiter="\t") try: for row in reader: file_name = pick(row, ("file_name",)) compound_name = clean_reference_name(pick(row, ("compound_name",))) if not file_name or not compound_name: continue record = { "source": "qqcm_pubchem_drugbank_mapping", "name": compound_name, "iupac": "", "formula": "", "smiles": get_file_lookup(smiles_by_file, file_name), "inchi": "", "inchikey": get_file_lookup(inchikey_by_file, file_name), "cas": "", "cid": resolve_qqcm_pubchem_cid(file_name, lookup_cids, group_cids, tcmsp_cache), "aliases": [], } add_record(index, record) finally: handle.close() return index def match_records( name: str, formula: str, index: dict[str, defaultdict[str, list]], ) -> tuple[str, list[dict[str, str]], str]: if is_inchi_literal(name): return "无法解明结构", [], "名称字段是 InChI 文本,当前流程未解析 InChI 到标准标识符" if is_unresolved_noise(name): return "无法解明结构", [], "名称像缩写、内部代号、截断值或带噪声后缀,无法稳定对应唯一结构" candidates: list[dict[str, str]] = [] reason = "" normalized = normalize_name(name) compact = alnum_name(name) if is_cas_name(name): candidates = dedup_records(index["cas"].get(name.strip(), [])) reason = "按 CAS 号匹配本地参考库" else: candidates = dedup_records(index["norm"].get(normalized, [])) if candidates: reason = "按标准化名称精确匹配本地参考库" elif compact: candidates = dedup_records(index["alnum"].get(compact, [])) if candidates: reason = "按去符号名称匹配本地参考库" if not candidates: return "无法解明结构", [], "本地参考库未找到可用同名结构" matched_formula = [rec for rec in candidates if norm_formula(rec.get("formula", "")) == formula] if formula and len(matched_formula) == 1: return "唯一结构", matched_formula, f"{reason},且分子式唯一一致" if formula and len(matched_formula) > 1: return "多候选结构", matched_formula, f"{reason},但同名同分子式仍对应多个候选结构" if len(candidates) == 1: return "唯一结构", candidates, f"{reason},本地仅找到一个候选结构" return "多候选结构", candidates, f"{reason},同名对应多个候选结构" def format_candidates(records: list[dict[str, str]], limit: int = 5) -> str: parts = [] for record in records[:limit]: bits = [] if record.get("name"): bits.append(record["name"]) if record.get("formula"): bits.append(record["formula"]) if record.get("cid"): bits.append(f"CID={record['cid']}") if record.get("inchikey"): bits.append(f"InChIKey={record['inchikey']}") parts.append(" | ".join(bits)) return " ; ".join(parts) def main() -> None: index = build_reference_index() status_counter: Counter[str] = Counter() with MS_CSV.open("r", encoding="utf-8-sig", newline="") as src, OUTPUT_CSV.open( "w", encoding="utf-8-sig", newline="" ) as dst: reader = csv.DictReader(src) fieldnames = list(reader.fieldnames or []) extra = [ "structure_resolution", "matched_smiles", "matched_inchi", "matched_inchikey", "matched_pubchem_cid", "match_reason", "candidate_count", "candidate_examples", ] writer = csv.DictWriter(dst, fieldnames=fieldnames + extra) writer.writeheader() for row in reader: name = row.get("Name", "").strip() formula = norm_formula(row.get("Formula", "")) status, records, reason = match_records(name, formula, index) status_counter[status] += 1 primary = records[0] if records else {} row.update( { "structure_resolution": status, "matched_smiles": primary.get("smiles", "") if status == "唯一结构" else "", "matched_inchi": primary.get("inchi", "") if status == "唯一结构" else "", "matched_inchikey": primary.get("inchikey", "") if status == "唯一结构" else "", "matched_pubchem_cid": primary.get("cid", "") if status == "唯一结构" else "", "match_reason": reason, "candidate_count": str(len(records)), "candidate_examples": format_candidates(records), } ) writer.writerow(row) print(f"output={OUTPUT_CSV}") for status, count in sorted(status_counter.items()): print(f"{status}\t{count}") if __name__ == "__main__": main()