QQCM / MS /build_ms_intersection_compound_match.py
JX-Lab's picture
Add files using upload-large-folder tool
1d27ec0 verified
Raw History Blame Contribute Delete
27.3 kB
#!/usr/bin/env python3
"""Match QQCM mass-spec intersection hits against the local QQCM compound library."""
from __future__ import annotations
import argparse
import csv
import json
import re
import sys
from collections import Counter, defaultdict
from dataclasses import dataclass, field
from difflib import SequenceMatcher
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
MS_DIR = ROOT / "MS"
DEFAULT_MS_CSV = MS_DIR / "三者交集完整输出.csv"
DEFAULT_NAME_MAP = ROOT / "id_trans" / "qqcm_pubchem_drugbank_mapping.tsv"
DEFAULT_LABELS = (
ROOT / "KG" / "qqcm_compound_subgraph" / "helper_tables" / "qqcm_mol_id_labels.tsv"
)
DEFAULT_NODES = ROOT / "KG" / "qqcm_compound_subgraph" / "nodes.tsv"
DEFAULT_OUTPUT_DIR = MS_DIR / "ms_compare"
MASS_TOLERANCE = 0.01
GREEK_TRANSLATIONS = {
"α": "alpha",
"β": "beta",
"γ": "gamma",
"δ": "delta",
"κ": "kappa",
"λ": "lambda",
"μ": "mu",
"ω": "omega",
}
STEREO_PREFIX_RE = re.compile(r"^(?:d|l|dl|r|s)\s+", re.IGNORECASE)
NON_ALNUM_RE = re.compile(r"[^a-z0-9]+")
ACCEPTED_MATCH_STATUSES = {
"exact_name_formula_mass",
"high_fuzzy_formula_mass",
"fuzzy_formula_mass",
"formula_mass_single_candidate",
}
@dataclass
class CompoundRecord:
compound_node_id: str
preferred_name: str = ""
all_names: set[str] = field(default_factory=set)
drugbank_ids: set[str] = field(default_factory=set)
drugbank_names: set[str] = field(default_factory=set)
herb_names: set[str] = field(default_factory=set)
mol_ids: set[str] = field(default_factory=set)
file_names: set[str] = field(default_factory=set)
source_set: set[str] = field(default_factory=set)
parse_source_set: set[str] = field(default_factory=set)
inchikey: str = ""
smiles: str = ""
inchi: str = ""
formula: str = ""
exact_mass: float | None = None
molecular_weight: str = ""
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Compare the QQCM three-way mass-spec intersection table with local QQCM compounds."
)
parser.add_argument("--ms-csv", type=Path, default=DEFAULT_MS_CSV)
parser.add_argument("--name-map", type=Path, default=DEFAULT_NAME_MAP)
parser.add_argument("--labels", type=Path, default=DEFAULT_LABELS)
parser.add_argument("--nodes", type=Path, default=DEFAULT_NODES)
parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR)
parser.add_argument("--mass-tolerance", type=float, default=MASS_TOLERANCE)
return parser.parse_args()
def read_tsv_rows(path: Path) -> list[dict[str, str]]:
csv.field_size_limit(sys.maxsize)
with path.open("r", encoding="utf-8-sig", errors="replace", newline="") as handle:
return list(csv.DictReader(handle, delimiter="\t"))
def read_csv_rows(path: Path) -> list[dict[str, str]]:
csv.field_size_limit(sys.maxsize)
with path.open("r", encoding="utf-8-sig", errors="replace", newline="") as handle:
return list(csv.DictReader(handle))
def write_csv(path: Path, fieldnames: list[str], rows: list[dict[str, object]]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8-sig", newline="") as handle:
writer = csv.DictWriter(handle, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
def split_pipe_values(value: str) -> list[str]:
return [item.strip() for item in value.split("|") if item.strip()]
def choose_preferred_name(names: set[str], drugbank_names: set[str]) -> str:
candidates = {item.strip() for item in [*names, *drugbank_names] if item.strip()}
if not candidates:
return ""
def score(name: str) -> tuple[int, int, str]:
lower = name.lower()
return (
1 if lower.startswith("cid_") or lower.startswith("mol") else 0,
len(name),
lower,
)
return sorted(candidates, key=score)[0]
def normalize_name(name: str) -> str:
text = (name or "").strip().lower()
for original, replacement in GREEK_TRANSLATIONS.items():
text = text.replace(original, replacement)
text = text.replace("_qt", "")
text = text.replace("_", " ")
text = text.replace("/", " ")
text = text.replace("\\", " ")
text = text.replace("-", " ")
text = text.replace(",", " ")
text = text.replace("'", "")
text = re.sub(r"[\(\)\[\]\{\}:;]+", " ", text)
text = re.sub(r"\s+", " ", text).strip()
return text
def build_name_aliases(name: str) -> set[str]:
base = normalize_name(name)
if not base:
return set()
aliases = {base}
aliases.add(NON_ALNUM_RE.sub("", base))
stereo_removed = STEREO_PREFIX_RE.sub("", base).strip()
if stereo_removed and stereo_removed != base:
aliases.add(stereo_removed)
aliases.add(NON_ALNUM_RE.sub("", stereo_removed))
return {alias for alias in aliases if alias}
def tokenize_name(name: str) -> set[str]:
base = normalize_name(name)
tokens = [item for item in re.split(r"[^a-z0-9]+", base) if item]
if tokens and tokens[0] in {"d", "l", "dl", "r", "s"}:
tokens = tokens[1:]
return set(tokens)
def name_similarity(query: str, candidate_names: set[str]) -> tuple[float, str]:
query_aliases = build_name_aliases(query)
query_tokens = tokenize_name(query)
best_score = 0.0
best_name = ""
for candidate_name in candidate_names:
candidate_aliases = build_name_aliases(candidate_name)
candidate_tokens = tokenize_name(candidate_name)
exact_alias_overlap = query_aliases & candidate_aliases
if exact_alias_overlap:
return 1.0, candidate_name
for query_alias in query_aliases:
for candidate_alias in candidate_aliases:
if not query_alias or not candidate_alias:
continue
ratio = SequenceMatcher(None, query_alias, candidate_alias).ratio()
if query_tokens and candidate_tokens:
common = query_tokens & candidate_tokens
union = query_tokens | candidate_tokens
jaccard = len(common) / len(union) if union else 0.0
containment = len(common) / min(
len(query_tokens), len(candidate_tokens)
)
else:
jaccard = 0.0
containment = 0.0
score = max(
ratio,
0.75 * ratio + 0.25 * jaccard,
0.7 * ratio + 0.3 * containment,
)
if query_alias in candidate_alias or candidate_alias in query_alias:
short = min(len(query_alias), len(candidate_alias))
long = max(len(query_alias), len(candidate_alias))
score = max(score, short / long)
if score > best_score:
best_score = score
best_name = candidate_name
return best_score, best_name
def parse_float(value: str) -> float | None:
text = (value or "").strip()
if not text:
return None
try:
return float(text)
except ValueError:
return None
def load_name_map(path: Path) -> dict[str, dict[str, str]]:
rows = read_tsv_rows(path)
mapping: dict[str, dict[str, str]] = {}
for row in rows:
raw_name = (row.get("file_name") or "").strip()
if not raw_name:
continue
mapping[raw_name] = row
mapping[Path(raw_name).stem] = row
return mapping
def load_label_rows(path: Path) -> list[dict[str, str]]:
return read_tsv_rows(path)
def load_node_meta(
path: Path, wanted_node_ids: set[str]
) -> dict[str, dict[str, object]]:
csv.field_size_limit(sys.maxsize)
node_meta: dict[str, dict[str, object]] = {}
with path.open("r", encoding="utf-8-sig", errors="replace", newline="") as handle:
reader = csv.DictReader(handle, delimiter="\t")
for row in reader:
if row.get("node_type") != "compound":
continue
node_id = row.get("node_id", "")
if node_id not in wanted_node_ids:
continue
extra = json.loads(row.get("extra_json") or "{}")
node_meta[node_id] = {
"aliases": split_pipe_values(row.get("aliases", "")),
"extra": extra,
}
return node_meta
def build_reference_records(
name_map_path: Path, labels_path: Path, nodes_path: Path
) -> list[CompoundRecord]:
name_map = load_name_map(name_map_path)
label_rows = load_label_rows(labels_path)
wanted_node_ids = {row["compound_node_id"] for row in label_rows if row["compound_node_id"]}
node_meta = load_node_meta(nodes_path, wanted_node_ids)
records_by_node: dict[str, CompoundRecord] = {}
for row in label_rows:
compound_node_id = row["compound_node_id"]
record = records_by_node.setdefault(
compound_node_id, CompoundRecord(compound_node_id=compound_node_id)
)
file_name = row.get("file_name", "").strip()
mol_id = row.get("mol_id", "").strip()
if file_name:
record.file_names.add(file_name)
if mol_id:
record.mol_ids.add(mol_id)
if row.get("compound_inchikey", "").strip() and not record.inchikey:
record.inchikey = row["compound_inchikey"].strip()
if row.get("smiles", "").strip() and not record.smiles:
record.smiles = row["smiles"].strip()
record.source_set.update(split_pipe_values(row.get("source", "")))
record.parse_source_set.update(split_pipe_values(row.get("parse_source", "")))
record.herb_names.update(split_pipe_values(row.get("herb_names", "")))
mapped = name_map.get(file_name) or name_map.get(Path(file_name).stem)
if mapped:
compound_name = (mapped.get("compound_name") or "").strip()
if compound_name:
record.all_names.add(compound_name)
drugbank_id = (mapped.get("drugbank_id") or "").strip()
drugbank_name = (mapped.get("drugbank_name") or "").strip()
if drugbank_id:
record.drugbank_ids.add(drugbank_id)
if drugbank_name:
record.drugbank_names.add(drugbank_name)
for compound_node_id, record in records_by_node.items():
meta = node_meta.get(compound_node_id, {})
extra = meta.get("extra", {})
if not record.inchikey:
record.inchikey = str(extra.get("InChIKey") or "").strip()
if not record.smiles:
record.smiles = str(extra.get("SMILES") or extra.get("smiles") or "").strip()
record.inchi = str(extra.get("InChI") or "").strip()
record.formula = str(extra.get("Molecular_Formula") or "").strip()
record.exact_mass = parse_float(str(extra.get("ExactMolWt") or ""))
record.molecular_weight = str(extra.get("MolWt") or "").strip()
record.mol_ids.update(str(item) for item in extra.get("qqcm_mol_ids", []) if str(item))
record.source_set.update(str(item) for item in extra.get("qqcm_sources", []) if str(item))
record.parse_source_set.update(
str(item) for item in extra.get("qqcm_parse_sources", []) if str(item)
)
record.herb_names.update(str(item) for item in extra.get("qqcm_herbs", []) if str(item))
record.preferred_name = choose_preferred_name(record.all_names, record.drugbank_names)
return sorted(records_by_node.values(), key=lambda item: item.preferred_name.lower())
def build_reference_rows(records: list[CompoundRecord]) -> list[dict[str, object]]:
rows: list[dict[str, object]] = []
for record in records:
rows.append(
{
"compound_node_id": record.compound_node_id,
"preferred_name": record.preferred_name,
"all_names": "|".join(sorted(record.all_names)),
"drugbank_ids": "|".join(sorted(record.drugbank_ids)),
"drugbank_names": "|".join(sorted(record.drugbank_names)),
"herb_names": "|".join(sorted(record.herb_names)),
"mol_ids": "|".join(sorted(record.mol_ids)),
"file_names": "|".join(sorted(record.file_names)),
"source_set": "|".join(sorted(record.source_set)),
"parse_source_set": "|".join(sorted(record.parse_source_set)),
"formula": record.formula,
"exact_mass": f"{record.exact_mass:.6f}" if record.exact_mass is not None else "",
"molecular_weight": record.molecular_weight,
"inchikey": record.inchikey,
"smiles": record.smiles,
"inchi": record.inchi,
}
)
return rows
def match_status_from_scores(
candidate_count: int, top_score: float, second_score: float, is_exact_alias: bool
) -> tuple[str, str]:
if candidate_count == 0:
return "no_formula_mass_match", "none"
if is_exact_alias:
return "exact_name_formula_mass", "high"
if candidate_count == 1:
return "formula_mass_single_candidate", "medium"
if top_score >= 0.92 and (top_score - second_score) >= 0.08:
return "high_fuzzy_formula_mass", "high"
if top_score >= 0.78 and (top_score - second_score) >= 0.05:
return "fuzzy_formula_mass", "medium"
return "ambiguous_formula_mass", "low"
def build_candidate_summary(candidates: list[tuple[CompoundRecord, float, str]]) -> str:
summary_parts: list[str] = []
for record, score, alias_name in candidates[:3]:
name = record.preferred_name or next(iter(record.all_names), "")
herb_names = "|".join(sorted(record.herb_names))
summary_parts.append(
f"{name} (score={score:.3f}; alias={alias_name or name}; herbs={herb_names})"
)
return " || ".join(summary_parts)
def match_ms_rows(
ms_rows: list[dict[str, str]],
reference_records: list[CompoundRecord],
mass_tolerance: float,
) -> tuple[list[dict[str, object]], list[dict[str, object]], dict[str, object]]:
records_by_formula: dict[str, list[CompoundRecord]] = defaultdict(list)
for record in reference_records:
if record.formula:
records_by_formula[record.formula].append(record)
row_level_matches: list[dict[str, object]] = []
matched_by_compound: dict[str, dict[str, object]] = {}
status_counter: Counter[str] = Counter()
for row in ms_rows:
ms_name = (row.get("Name") or "").strip()
ms_formula = (row.get("Formula") or "").strip()
ms_mass = parse_float(row.get("Mass (Da)", ""))
formula_candidates = records_by_formula.get(ms_formula, [])
if ms_mass is None:
mass_candidates = list(formula_candidates)
else:
mass_candidates = [
candidate
for candidate in formula_candidates
if candidate.exact_mass is None
or abs(candidate.exact_mass - ms_mass) <= mass_tolerance
]
scored_candidates: list[tuple[CompoundRecord, float, str]] = []
query_aliases = build_name_aliases(ms_name)
for candidate in mass_candidates:
candidate_names = set(candidate.all_names) | set(candidate.drugbank_names)
if candidate.preferred_name:
candidate_names.add(candidate.preferred_name)
score, alias_name = name_similarity(ms_name, candidate_names)
scored_candidates.append((candidate, score, alias_name))
scored_candidates.sort(
key=lambda item: (
item[1],
len(item[0].preferred_name or ""),
item[0].preferred_name.lower(),
),
reverse=True,
)
top_candidate = scored_candidates[0][0] if scored_candidates else None
top_score = scored_candidates[0][1] if scored_candidates else 0.0
top_alias_name = scored_candidates[0][2] if scored_candidates else ""
second_score = scored_candidates[1][1] if len(scored_candidates) > 1 else 0.0
exact_alias = bool(
scored_candidates
and (
query_aliases
& {
alias
for candidate_name in (
set(top_candidate.all_names)
| set(top_candidate.drugbank_names)
| ({top_candidate.preferred_name} if top_candidate.preferred_name else set())
)
for alias in build_name_aliases(candidate_name)
}
)
)
status, confidence = match_status_from_scores(
candidate_count=len(scored_candidates),
top_score=top_score,
second_score=second_score,
is_exact_alias=exact_alias,
)
status_counter[status] += 1
best_mass_delta = ""
if top_candidate and ms_mass is not None and top_candidate.exact_mass is not None:
best_mass_delta = f"{top_candidate.exact_mass - ms_mass:.6f}"
top_candidates_summary = build_candidate_summary(scored_candidates)
row_level_match = {
"ms_row_number": row.get("#", ""),
"ms_name": ms_name,
"ms_formula": ms_formula,
"ms_mass_da": row.get("Mass (Da)", ""),
"ms_found_at_mass_da": row.get("Found At Mass (Da)", ""),
"ms_adduct": row.get("Adduct", ""),
"ms_rt_min": row.get("Found At RT (min)", ""),
"ms_intensity": row.get("Intensity", ""),
"ms_area": row.get("Area", ""),
"match_status": status,
"match_confidence": confidence,
"formula_candidate_count": len(formula_candidates),
"formula_mass_candidate_count": len(scored_candidates),
"best_name_similarity": f"{top_score:.3f}" if scored_candidates else "",
"best_alias_name": top_alias_name,
"top_candidate_summary": top_candidates_summary,
"matched_compound_node_id": top_candidate.compound_node_id if top_candidate else "",
"matched_preferred_name": top_candidate.preferred_name if top_candidate else "",
"matched_all_names": "|".join(sorted(top_candidate.all_names)) if top_candidate else "",
"matched_drugbank_ids": "|".join(sorted(top_candidate.drugbank_ids))
if top_candidate
else "",
"matched_drugbank_names": "|".join(sorted(top_candidate.drugbank_names))
if top_candidate
else "",
"matched_herb_names": "|".join(sorted(top_candidate.herb_names)) if top_candidate else "",
"matched_formula": top_candidate.formula if top_candidate else "",
"matched_exact_mass": f"{top_candidate.exact_mass:.6f}"
if top_candidate and top_candidate.exact_mass is not None
else "",
"matched_mass_delta_da": best_mass_delta,
"matched_inchikey": top_candidate.inchikey if top_candidate else "",
"matched_smiles": top_candidate.smiles if top_candidate else "",
"matched_inchi": top_candidate.inchi if top_candidate else "",
"matched_mol_ids": "|".join(sorted(top_candidate.mol_ids)) if top_candidate else "",
"matched_file_names": "|".join(sorted(top_candidate.file_names)) if top_candidate else "",
"matched_sources": "|".join(sorted(top_candidate.source_set)) if top_candidate else "",
"matched_parse_sources": "|".join(sorted(top_candidate.parse_source_set))
if top_candidate
else "",
}
row_level_matches.append(row_level_match)
if top_candidate and status in ACCEPTED_MATCH_STATUSES:
existing = matched_by_compound.setdefault(
top_candidate.compound_node_id,
{
"compound_node_id": top_candidate.compound_node_id,
"preferred_name": top_candidate.preferred_name,
"all_names": "|".join(sorted(top_candidate.all_names)),
"drugbank_ids": "|".join(sorted(top_candidate.drugbank_ids)),
"drugbank_names": "|".join(sorted(top_candidate.drugbank_names)),
"herb_names": "|".join(sorted(top_candidate.herb_names)),
"formula": top_candidate.formula,
"exact_mass": f"{top_candidate.exact_mass:.6f}"
if top_candidate.exact_mass is not None
else "",
"molecular_weight": top_candidate.molecular_weight,
"inchikey": top_candidate.inchikey,
"smiles": top_candidate.smiles,
"inchi": top_candidate.inchi,
"mol_ids": "|".join(sorted(top_candidate.mol_ids)),
"file_names": "|".join(sorted(top_candidate.file_names)),
"source_set": "|".join(sorted(top_candidate.source_set)),
"parse_source_set": "|".join(sorted(top_candidate.parse_source_set)),
"supporting_ms_rows": [],
"supporting_ms_names": [],
"supporting_match_statuses": [],
"best_match_confidence": confidence,
},
)
existing["supporting_ms_rows"].append(str(row.get("#", "")))
existing["supporting_ms_names"].append(ms_name)
existing["supporting_match_statuses"].append(status)
if existing["best_match_confidence"] == "medium" and confidence == "high":
existing["best_match_confidence"] = "high"
matched_compounds: list[dict[str, object]] = []
for record in matched_by_compound.values():
matched_compounds.append(
{
**{
key: value
for key, value in record.items()
if key
not in {
"supporting_ms_rows",
"supporting_ms_names",
"supporting_match_statuses",
}
},
"supporting_ms_rows": "|".join(record["supporting_ms_rows"]),
"supporting_ms_names": "|".join(record["supporting_ms_names"]),
"supporting_match_statuses": "|".join(record["supporting_match_statuses"]),
"supporting_ms_count": len(record["supporting_ms_rows"]),
}
)
matched_compounds.sort(
key=lambda item: (-int(item["supporting_ms_count"]), item["preferred_name"].lower())
)
report = {
"total_ms_rows": len(ms_rows),
"status_counts": dict(status_counter),
"accepted_match_row_count": sum(
count for status, count in status_counter.items() if status in ACCEPTED_MATCH_STATUSES
),
"accepted_unique_compound_count": len(matched_compounds),
}
return row_level_matches, matched_compounds, report
def main() -> None:
args = parse_args()
output_dir = args.output_dir
output_dir.mkdir(parents=True, exist_ok=True)
reference_records = build_reference_records(
name_map_path=args.name_map,
labels_path=args.labels,
nodes_path=args.nodes,
)
reference_rows = build_reference_rows(reference_records)
ms_rows = read_csv_rows(args.ms_csv)
row_level_matches, matched_compounds, report = match_ms_rows(
ms_rows=ms_rows,
reference_records=reference_records,
mass_tolerance=args.mass_tolerance,
)
reference_path = output_dir / "qqcm_compound_reference_for_ms_compare.csv"
row_match_path = output_dir / "qqcm_ms_intersection_matches.csv"
matched_compounds_path = output_dir / "qqcm_ms_intersection_matched_compounds.csv"
report_path = output_dir / "qqcm_ms_intersection_match_report.json"
write_csv(
reference_path,
[
"compound_node_id",
"preferred_name",
"all_names",
"drugbank_ids",
"drugbank_names",
"herb_names",
"mol_ids",
"file_names",
"source_set",
"parse_source_set",
"formula",
"exact_mass",
"molecular_weight",
"inchikey",
"smiles",
"inchi",
],
reference_rows,
)
write_csv(
row_match_path,
[
"ms_row_number",
"ms_name",
"ms_formula",
"ms_mass_da",
"ms_found_at_mass_da",
"ms_adduct",
"ms_rt_min",
"ms_intensity",
"ms_area",
"match_status",
"match_confidence",
"formula_candidate_count",
"formula_mass_candidate_count",
"best_name_similarity",
"best_alias_name",
"top_candidate_summary",
"matched_compound_node_id",
"matched_preferred_name",
"matched_all_names",
"matched_drugbank_ids",
"matched_drugbank_names",
"matched_herb_names",
"matched_formula",
"matched_exact_mass",
"matched_mass_delta_da",
"matched_inchikey",
"matched_smiles",
"matched_inchi",
"matched_mol_ids",
"matched_file_names",
"matched_sources",
"matched_parse_sources",
],
row_level_matches,
)
write_csv(
matched_compounds_path,
[
"compound_node_id",
"preferred_name",
"all_names",
"drugbank_ids",
"drugbank_names",
"herb_names",
"formula",
"exact_mass",
"molecular_weight",
"inchikey",
"smiles",
"inchi",
"mol_ids",
"file_names",
"source_set",
"parse_source_set",
"best_match_confidence",
"supporting_ms_rows",
"supporting_ms_names",
"supporting_match_statuses",
"supporting_ms_count",
],
matched_compounds,
)
report_path.write_text(
json.dumps(
{
**report,
"inputs": {
"ms_csv": str(args.ms_csv),
"name_map": str(args.name_map),
"labels": str(args.labels),
"nodes": str(args.nodes),
},
"outputs": {
"reference_csv": str(reference_path),
"row_match_csv": str(row_match_path),
"matched_compounds_csv": str(matched_compounds_path),
"report_json": str(report_path),
},
},
ensure_ascii=False,
indent=2,
)
+ "\n",
encoding="utf-8",
)
if __name__ == "__main__":
main()