"""TSV adapter for the OP3 AmbrosM ridge recommender with query source roles.""" import json import os import sys from pathlib import Path METHOD_DIR = Path(__file__).resolve().parent sys.path.insert(0, str(METHOD_DIR / "vendor" / "python")) sys.path.insert(0, str(METHOD_DIR / "vendor" / "op3")) sys.path.insert(0, str(Path(os.environ["CORE_DIR"]) / "interface")) import numpy as np import pandas as pd from helper import fit_predict_ridge_recommender from records import read_matrix, read_queries, write_prediction def main(): data_dir, output_dir = map(Path, sys.argv[1:]) header, rows, values = read_matrix(data_dir / "train.tsv") queries = read_queries(data_dir / "queries.tsv") with (data_dir / "names.json").open() as stream: names = json.load(stream) def identities(records): return pd.DataFrame( [(names["group"][row[1]], names["item"][row[2]]) for row in records], columns=["cell_type", "sm_name"], ) training_ids = identities(rows) id_map = identities(queries) genes = header[3:] de_tr = pd.DataFrame( values, index=pd.MultiIndex.from_frame(training_ids), columns=genes ) if not de_tr.index.is_unique: raise ValueError("The published predictor requires unique context-compound pairs") # Preserve the official script's exact bridge-compound selection. train_sm_names = training_ids.query("cell_type == 'B cells'").sm_name.sort_values().values if len(train_sm_names) == 0: raise ValueError("The published predictor requires B-cell bridge observations") for column in ("cell_type", "sm_name"): missing = set(id_map[column]) - set(training_ids[column]) if missing: raise ValueError(f"The published predictor cannot handle unseen {column}: {sorted(missing)}") # cell_type_ratio is unused by this predictor; no single-cell metadata is needed. predictions = fit_predict_ridge_recommender( de_tr, id_map, train_sm_names, genes, cell_type_ratio=None ) expected_index = pd.MultiIndex.from_frame(id_map) if not predictions.index.equals(expected_index) or list(predictions.columns) != genes: raise ValueError("Unexpected prediction ordering from the published predictor") if not np.isfinite(predictions.to_numpy()).all(): raise ValueError("The published predictor produced nonfinite values; no substitute is used") write_prediction(output_dir / "prediction.tsv", genes, queries, predictions.to_numpy()) if __name__ == "__main__": main()