Download re/tcm_dataset/run_reference_batch_prediction.py from JX-Lab/QQCM: direct link, hf CLI and curl.
- Browser
- Download file 20.3 kB
-
https://huggingface.co/datasets/JX-Lab/QQCM/resolve/main/re/tcm_dataset/run_reference_batch_prediction.py
- Command line
-
hf download hf://datasets/JX-Lab/QQCM/re/tcm_dataset/run_reference_batch_prediction.py
-
curl -L -o run_reference_batch_prediction.py https://huggingface.co/datasets/JX-Lab/QQCM/resolve/main/re/tcm_dataset/run_reference_batch_prediction.py
20.3 kB
| #!/usr/bin/env python3 | |
| """Prepare and run QQCM AMVL predictions against a chosen AMVL reference set.""" | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import json | |
| import subprocess | |
| import sys | |
| import time | |
| from pathlib import Path | |
| ROOT = Path("/mnt/disk1/yanganqi/QQCM") | |
| DEFAULT_QQCM_COM = ROOT / "re" / "Fdataset" / "data" / "com.csv" | |
| DEFAULT_QQCM_TAR = ROOT / "re" / "Fdataset" / "data" / "tar.csv" | |
| DEFAULT_NEW_DRUG_IDS = ROOT / "re" / "Fdataset" / "data" / "new_drug_ids.txt" | |
| DEFAULT_COMPOUND_NAME_MAP = ROOT / "id_trans" / "qqcm_pubchem_drugbank_mapping.tsv" | |
| CALC_MORGAN_SCRIPT = ROOT / "COM" / "calc_morgan_similarity.py" | |
| TARGET_SIM_SCRIPT = ROOT / "TAR" / "compute_compound_target_similarity.py" | |
| BUILD_NEW_DRUG_MAT_SCRIPT = ROOT / "AMVL" / "tool" / "build_new_drug_mat.py" | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser( | |
| description="Prepare and run QQCM AMVL predictions for one reference dataset." | |
| ) | |
| parser.add_argument("--reference-set", required=True, help="Dataset label, e.g. Cdataset.") | |
| parser.add_argument( | |
| "--reference-wrname-csv", | |
| type=Path, | |
| required=True, | |
| help="Reference ordered drug ID CSV.", | |
| ) | |
| parser.add_argument( | |
| "--reference-structure-csv", | |
| type=Path, | |
| required=True, | |
| help="Reference structure CSV with drugbank_id and smiles columns.", | |
| ) | |
| parser.add_argument( | |
| "--reference-target-csv", | |
| type=Path, | |
| required=True, | |
| help="Reference target CSV with Wrname and UniProt ID columns.", | |
| ) | |
| parser.add_argument( | |
| "--input-mat", | |
| type=Path, | |
| required=True, | |
| help="Reference AMVL MAT file.", | |
| ) | |
| parser.add_argument( | |
| "--disease-mapping-csv", | |
| type=Path, | |
| required=True, | |
| help="Disease ID mapping CSV for the selected reference set.", | |
| ) | |
| parser.add_argument( | |
| "--output-dir", | |
| type=Path, | |
| required=True, | |
| help="Output directory under re/, e.g. /mnt/.../re/Cdataset", | |
| ) | |
| parser.add_argument("--qqcm-com-csv", type=Path, default=DEFAULT_QQCM_COM) | |
| parser.add_argument("--qqcm-tar-csv", type=Path, default=DEFAULT_QQCM_TAR) | |
| parser.add_argument("--new-drug-ids-file", type=Path, default=DEFAULT_NEW_DRUG_IDS) | |
| parser.add_argument("--compound-name-map-tsv", type=Path, default=DEFAULT_COMPOUND_NAME_MAP) | |
| parser.add_argument("--top-n", type=int, default=20) | |
| return parser.parse_args() | |
| def read_csv_rows(path: Path) -> list[dict[str, str]]: | |
| csv.field_size_limit(sys.maxsize) | |
| with path.open("r", encoding="utf-8-sig", newline="") as handle: | |
| reader = csv.DictReader(handle) | |
| if reader.fieldnames is None: | |
| raise ValueError(f"CSV has no header row: {path}") | |
| return list(reader) | |
| def detect_id_column(rows: list[dict[str, str]], candidates: list[str], path: Path) -> str: | |
| if not rows: | |
| raise ValueError(f"CSV has no data rows: {path}") | |
| row_keys = set(rows[0].keys()) | |
| for candidate in candidates: | |
| if candidate in row_keys: | |
| return candidate | |
| raise KeyError(f"Could not find any of {candidates} in {path}") | |
| def load_ordered_ids_from_csv(path: Path, candidates: list[str]) -> tuple[list[str], str]: | |
| rows = read_csv_rows(path) | |
| id_column = detect_id_column(rows, candidates, path) | |
| ordered_ids: list[str] = [] | |
| for row in rows: | |
| value = (row.get(id_column, "") or "").strip() | |
| if value: | |
| ordered_ids.append(value) | |
| if not ordered_ids: | |
| raise ValueError(f"No IDs found in {path} columns {candidates!r}") | |
| return ordered_ids, id_column | |
| def load_ids_from_text(path: Path) -> list[str]: | |
| ids: list[str] = [] | |
| for line in path.read_text(encoding="utf-8-sig").splitlines(): | |
| value = line.strip() | |
| if value: | |
| ids.append(value) | |
| if not ids: | |
| raise ValueError(f"No IDs found in {path}") | |
| return ids | |
| def index_rows(rows: list[dict[str, str]], key_field: str) -> dict[str, dict[str, str]]: | |
| indexed: dict[str, dict[str, str]] = {} | |
| for row in rows: | |
| key = (row.get(key_field, "") or "").strip() | |
| if key and key not in indexed: | |
| indexed[key] = row | |
| return indexed | |
| def write_simple_csv(path: Path, fieldnames: list[str], rows: list[dict[str, str]]) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| with path.open("w", encoding="utf-8", newline="") as handle: | |
| writer = csv.DictWriter(handle, fieldnames=fieldnames) | |
| writer.writeheader() | |
| writer.writerows(rows) | |
| def run_command(cmd: list[str]) -> None: | |
| subprocess.run(cmd, cwd=ROOT, check=True) | |
| def build_reference_structure_rows( | |
| ordered_ids: list[str], | |
| structure_map: dict[str, dict[str, str]], | |
| ) -> tuple[list[dict[str, str]], int]: | |
| rows: list[dict[str, str]] = [] | |
| missing_smiles_count = 0 | |
| for drug_id in ordered_ids: | |
| source_row = structure_map.get(drug_id, {}) | |
| smiles = (source_row.get("smiles", "") or "").strip() | |
| if not smiles: | |
| missing_smiles_count += 1 | |
| rows.append({"file_name": drug_id, "smiles": smiles}) | |
| return rows, missing_smiles_count | |
| def build_reference_target_rows( | |
| ordered_ids: list[str], | |
| target_map: dict[str, dict[str, str]], | |
| ) -> tuple[list[dict[str, str]], int]: | |
| rows: list[dict[str, str]] = [] | |
| missing_target_count = 0 | |
| for drug_id in ordered_ids: | |
| source_row = target_map.get(drug_id, {}) | |
| target_ids = (source_row.get("UniProt ID", "") or "").strip() | |
| if not target_ids: | |
| missing_target_count += 1 | |
| rows.append({"file_name": drug_id, "target_uniprot_ids": target_ids}) | |
| return rows, missing_target_count | |
| def build_qqcm_rows( | |
| ordered_ids: list[str], | |
| qqcm_map: dict[str, dict[str, str]], | |
| value_field: str, | |
| ) -> tuple[list[dict[str, str]], int]: | |
| rows: list[dict[str, str]] = [] | |
| missing_value_count = 0 | |
| missing_ids: list[str] = [] | |
| for compound_id in ordered_ids: | |
| source_row = qqcm_map.get(compound_id) | |
| if source_row is None: | |
| missing_ids.append(compound_id) | |
| value = "" | |
| else: | |
| value = (source_row.get(value_field, "") or "").strip() | |
| if not value: | |
| missing_value_count += 1 | |
| output_field = "smiles" if value_field == "smiles" else "target_uniprot_ids" | |
| rows.append({"file_name": compound_id, output_field: value}) | |
| if missing_ids: | |
| raise ValueError( | |
| f"Missing {len(missing_ids)} QQCM IDs from source table for field {value_field!r}. " | |
| f"Examples: {missing_ids[:10]}" | |
| ) | |
| return rows, missing_value_count | |
| def load_compound_name_map(path: Path | None) -> dict[str, str]: | |
| if path is None or not path.exists(): | |
| return {} | |
| mapping: dict[str, str] = {} | |
| with path.open("r", encoding="utf-8-sig", newline="") as handle: | |
| reader = csv.DictReader(handle, delimiter="\t") | |
| if reader.fieldnames is None: | |
| return {} | |
| if "file_name" not in reader.fieldnames or "compound_name" not in reader.fieldnames: | |
| return {} | |
| for row in reader: | |
| compound_id = (row.get("file_name", "") or "").strip() | |
| compound_name = (row.get("compound_name", "") or "").strip() | |
| if compound_id and compound_name and compound_id not in mapping: | |
| mapping[compound_id] = compound_name | |
| return mapping | |
| def resolve_compound_name(compound_id: str, compound_name_map: dict[str, str]) -> str: | |
| if compound_id in compound_name_map: | |
| return compound_name_map[compound_id] | |
| if compound_id.isdigit(): | |
| return compound_name_map.get(f"CID_{compound_id}", compound_id) | |
| return compound_id | |
| def load_disease_mapping(path: Path | None) -> dict[str, dict[str, str]]: | |
| if path is None or not path.exists(): | |
| return {} | |
| mapping: dict[str, dict[str, str]] = {} | |
| with path.open("r", encoding="utf-8-sig", newline="") as handle: | |
| reader = csv.DictReader(handle) | |
| if reader.fieldnames is None or "disease_id" not in reader.fieldnames: | |
| return {} | |
| for row in reader: | |
| disease_id = (row.get("disease_id", "") or "").strip() | |
| if disease_id and disease_id not in mapping: | |
| mapping[disease_id] = { | |
| "omim_id": (row.get("omim_id", "") or "").strip(), | |
| "disease_name_en": (row.get("disease_name_en", "") or "").strip(), | |
| "disease_name_zh": (row.get("disease_name_zh", "") or "").strip(), | |
| "official_title_en": (row.get("official_title_en", "") or "").strip(), | |
| "resolution_status": (row.get("resolution_status", "") or "").strip(), | |
| } | |
| return mapping | |
| def write_prediction_matrix( | |
| output_path: Path, | |
| disease_ids: list[str], | |
| compound_ids: list[str], | |
| predictions_all, | |
| ) -> None: | |
| with output_path.open("w", encoding="utf-8-sig", newline="") as handle: | |
| writer = csv.writer(handle) | |
| writer.writerow(["compound_id", *disease_ids]) | |
| for compound_id, scores in zip(compound_ids, predictions_all): | |
| writer.writerow([compound_id, *[f"{float(score):.12f}" for score in scores]]) | |
| def write_topn_table( | |
| output_path: Path, | |
| ranked_results_all: list[list[tuple[int, float, str]]], | |
| compound_ids: list[str], | |
| compound_name_map: dict[str, str], | |
| disease_mapping: dict[str, dict[str, str]], | |
| top_n: int, | |
| mat_file: Path, | |
| drug_sim_names: list[str], | |
| disease_sim_names: list[str], | |
| ) -> None: | |
| fieldnames = [ | |
| "compound_id", | |
| "compound_name", | |
| "rank", | |
| "disease_index", | |
| "disease_id", | |
| "omim_id", | |
| "disease_name_en", | |
| "disease_name_zh", | |
| "official_title_en", | |
| "disease_resolution_status", | |
| "score", | |
| "mat_file_path", | |
| "drug_sim_names", | |
| "disease_sim_names", | |
| ] | |
| with output_path.open("w", encoding="utf-8-sig", newline="") as handle: | |
| writer = csv.DictWriter(handle, fieldnames=fieldnames) | |
| writer.writeheader() | |
| for compound_id, ranked_results in zip(compound_ids, ranked_results_all): | |
| compound_name = resolve_compound_name(compound_id, compound_name_map) | |
| for rank, (disease_index, score, disease_id) in enumerate( | |
| ranked_results[:top_n], | |
| start=1, | |
| ): | |
| disease_info = disease_mapping.get( | |
| str(disease_id), | |
| { | |
| "omim_id": str(disease_id)[1:] if str(disease_id).startswith("D") else "", | |
| "disease_name_en": "", | |
| "disease_name_zh": "", | |
| "official_title_en": "", | |
| "resolution_status": "", | |
| }, | |
| ) | |
| writer.writerow( | |
| { | |
| "compound_id": compound_id, | |
| "compound_name": compound_name, | |
| "rank": rank, | |
| "disease_index": disease_index, | |
| "disease_id": disease_id, | |
| "omim_id": disease_info.get("omim_id", ""), | |
| "disease_name_en": disease_info.get("disease_name_en", ""), | |
| "disease_name_zh": disease_info.get("disease_name_zh", ""), | |
| "official_title_en": disease_info.get("official_title_en", ""), | |
| "disease_resolution_status": disease_info.get("resolution_status", ""), | |
| "score": f"{float(score):.12f}", | |
| "mat_file_path": str(mat_file), | |
| "drug_sim_names": ",".join(drug_sim_names), | |
| "disease_sim_names": ",".join(disease_sim_names), | |
| } | |
| ) | |
| def main() -> None: | |
| args = parse_args() | |
| reference_set = args.reference_set.strip() | |
| if not reference_set: | |
| raise ValueError("--reference-set must not be empty.") | |
| for required_path in ( | |
| args.reference_wrname_csv, | |
| args.reference_structure_csv, | |
| args.reference_target_csv, | |
| args.input_mat, | |
| args.disease_mapping_csv, | |
| args.qqcm_com_csv, | |
| args.qqcm_tar_csv, | |
| args.new_drug_ids_file, | |
| CALC_MORGAN_SCRIPT, | |
| TARGET_SIM_SCRIPT, | |
| BUILD_NEW_DRUG_MAT_SCRIPT, | |
| ): | |
| if not required_path.exists(): | |
| raise FileNotFoundError(f"Required file not found: {required_path}") | |
| output_dir = args.output_dir | |
| data_dir = output_dir / "data" | |
| data_dir.mkdir(parents=True, exist_ok=True) | |
| reference_ids, reference_id_column = load_ordered_ids_from_csv( | |
| args.reference_wrname_csv, | |
| ["drugbank_id", "Wrname"], | |
| ) | |
| qqcm_ids = load_ids_from_text(args.new_drug_ids_file) | |
| reference_structure_rows = read_csv_rows(args.reference_structure_csv) | |
| reference_target_rows_source = read_csv_rows(args.reference_target_csv) | |
| qqcm_com_rows_source = read_csv_rows(args.qqcm_com_csv) | |
| qqcm_tar_rows_source = read_csv_rows(args.qqcm_tar_csv) | |
| reference_structure_map = index_rows(reference_structure_rows, "drugbank_id") | |
| reference_target_map = index_rows(reference_target_rows_source, "Wrname") | |
| qqcm_com_map = index_rows(qqcm_com_rows_source, "file_name") | |
| qqcm_tar_map = index_rows(qqcm_tar_rows_source, "file_name") | |
| reference_com_rows, reference_missing_smiles = build_reference_structure_rows( | |
| ordered_ids=reference_ids, | |
| structure_map=reference_structure_map, | |
| ) | |
| reference_tar_rows, reference_missing_targets = build_reference_target_rows( | |
| ordered_ids=reference_ids, | |
| target_map=reference_target_map, | |
| ) | |
| qqcm_com_rows, qqcm_missing_smiles = build_qqcm_rows( | |
| ordered_ids=qqcm_ids, | |
| qqcm_map=qqcm_com_map, | |
| value_field="smiles", | |
| ) | |
| qqcm_tar_rows, qqcm_missing_targets = build_qqcm_rows( | |
| ordered_ids=qqcm_ids, | |
| qqcm_map=qqcm_tar_map, | |
| value_field="target_uniprot_ids", | |
| ) | |
| combined_com_rows = reference_com_rows + qqcm_com_rows | |
| combined_tar_rows = reference_tar_rows + qqcm_tar_rows | |
| com_csv = data_dir / "com.csv" | |
| tar_csv = data_dir / "tar.csv" | |
| new_drug_ids_out = data_dir / "new_drug_ids.txt" | |
| com_similarity_csv = data_dir / "com_morgan_similarity.csv" | |
| tar_matrix_csv = data_dir / "tar_jaccard_matrix.csv" | |
| tar_pairs_csv = data_dir / "tar_jaccard_pairs.csv" | |
| append_mat = data_dir / f"{reference_set}_re_chemtarget_append.mat" | |
| preparation_summary_json = data_dir / "preparation_summary.json" | |
| write_simple_csv(com_csv, ["file_name", "smiles"], combined_com_rows) | |
| write_simple_csv(tar_csv, ["file_name", "target_uniprot_ids"], combined_tar_rows) | |
| new_drug_ids_out.write_text("\n".join(qqcm_ids) + "\n", encoding="utf-8") | |
| run_command( | |
| [ | |
| sys.executable, | |
| str(CALC_MORGAN_SCRIPT), | |
| "--smiles-csv", | |
| str(com_csv), | |
| "--output", | |
| str(com_similarity_csv), | |
| ] | |
| ) | |
| run_command( | |
| [ | |
| sys.executable, | |
| str(TARGET_SIM_SCRIPT), | |
| "--input", | |
| str(tar_csv), | |
| "--id-column", | |
| "file_name", | |
| "--target-column", | |
| "target_uniprot_ids", | |
| "--metric", | |
| "jaccard", | |
| "--matrix-output", | |
| str(tar_matrix_csv), | |
| "--pairs-output", | |
| str(tar_pairs_csv), | |
| "--include-empty-compounds", | |
| ] | |
| ) | |
| run_command( | |
| [ | |
| sys.executable, | |
| str(BUILD_NEW_DRUG_MAT_SCRIPT), | |
| "--input-mat", | |
| str(args.input_mat), | |
| "--output-mat", | |
| str(append_mat), | |
| "--chem-csv", | |
| str(com_similarity_csv), | |
| "--target-csv", | |
| str(tar_matrix_csv), | |
| "--new-drug-ids-file", | |
| str(new_drug_ids_out), | |
| "--drop-unmodified-drug-matrices", | |
| ] | |
| ) | |
| preparation_summary = { | |
| "reference_set": reference_set, | |
| "reference_drug_count": len(reference_ids), | |
| "reference_id_column": reference_id_column, | |
| "qqcm_new_drug_count": len(qqcm_ids), | |
| "combined_compound_count": len(combined_com_rows), | |
| "reference_missing_smiles_count": reference_missing_smiles, | |
| "reference_missing_target_count": reference_missing_targets, | |
| "qqcm_missing_smiles_count": qqcm_missing_smiles, | |
| "qqcm_missing_target_count": qqcm_missing_targets, | |
| "output_dir": str(data_dir), | |
| "com_csv": str(com_csv), | |
| "tar_csv": str(tar_csv), | |
| "new_drug_ids_txt": str(new_drug_ids_out), | |
| "com_morgan_similarity_csv": str(com_similarity_csv), | |
| "tar_jaccard_matrix_csv": str(tar_matrix_csv), | |
| "tar_jaccard_pairs_csv": str(tar_pairs_csv), | |
| "append_mat": str(append_mat), | |
| } | |
| preparation_summary_json.write_text( | |
| json.dumps(preparation_summary, indent=2, ensure_ascii=False) + "\n", | |
| encoding="utf-8", | |
| ) | |
| matrix_csv = output_dir / "amvl_prediction_matrix.csv" | |
| topn_csv = output_dir / f"amvl_predictions_top{args.top_n}.csv" | |
| prediction_summary_json = output_dir / "prediction_summary.json" | |
| compound_name_map = load_compound_name_map(args.compound_name_map_tsv) | |
| disease_mapping = load_disease_mapping(args.disease_mapping_csv) | |
| sys.path.insert(0, str(ROOT / "AMVL")) | |
| from function.AMVL import predict_new_drugs_from_mat | |
| drug_sim_names = ["drug_ChemS", "drug_TargetS"] | |
| disease_sim_names = ["disease_DoS", "disease_PhS", "disease_LlmS"] | |
| start_time = time.time() | |
| predictions_all, ranked_results_all, new_drug_names, disease_names = predict_new_drugs_from_mat( | |
| mat_file_path=str(append_mat), | |
| drug_sim_names=drug_sim_names, | |
| disease_sim_names=disease_sim_names, | |
| params=None, | |
| use_cupy=False, | |
| return_names=True, | |
| ) | |
| elapsed_seconds = time.time() - start_time | |
| compound_ids = [str(item) for item in new_drug_names] | |
| disease_ids = [str(item) for item in disease_names] | |
| write_prediction_matrix( | |
| output_path=matrix_csv, | |
| disease_ids=disease_ids, | |
| compound_ids=compound_ids, | |
| predictions_all=predictions_all, | |
| ) | |
| write_topn_table( | |
| output_path=topn_csv, | |
| ranked_results_all=ranked_results_all, | |
| compound_ids=compound_ids, | |
| compound_name_map=compound_name_map, | |
| disease_mapping=disease_mapping, | |
| top_n=args.top_n, | |
| mat_file=append_mat, | |
| drug_sim_names=drug_sim_names, | |
| disease_sim_names=disease_sim_names, | |
| ) | |
| prediction_summary = { | |
| "reference_set": reference_set, | |
| "mat_file": str(append_mat), | |
| "drug_sim_names": drug_sim_names, | |
| "disease_sim_names": disease_sim_names, | |
| "new_drug_count": len(compound_ids), | |
| "disease_count": len(disease_ids), | |
| "top_n": args.top_n, | |
| "prediction_matrix_csv": str(matrix_csv), | |
| "prediction_topn_csv": str(topn_csv), | |
| "disease_mapping_csv": str(args.disease_mapping_csv), | |
| "elapsed_seconds": round(elapsed_seconds, 3), | |
| } | |
| prediction_summary_json.write_text( | |
| json.dumps(prediction_summary, indent=2, ensure_ascii=False) + "\n", | |
| encoding="utf-8", | |
| ) | |
| print(f"Reference set: {reference_set}") | |
| print(f"Reference drugs: {len(reference_ids)}") | |
| print(f"QQCM new compounds: {len(qqcm_ids)}") | |
| print(f"Combined compounds: {len(combined_com_rows)}") | |
| print(f"Reference rows without smiles: {reference_missing_smiles}") | |
| print(f"Reference rows without targets: {reference_missing_targets}") | |
| print(f"QQCM rows without smiles: {qqcm_missing_smiles}") | |
| print(f"QQCM rows without targets: {qqcm_missing_targets}") | |
| print(f"Extended MAT file: {append_mat}") | |
| print(f"Prediction matrix: {matrix_csv}") | |
| print(f"Top{args.top_n} table: {topn_csv}") | |
| print(f"Preparation summary JSON: {preparation_summary_json}") | |
| print(f"Prediction summary JSON: {prediction_summary_json}") | |
| if __name__ == "__main__": | |
| main() | |