Datasets:
Download code/downstream/prepare_local_copy.py from SeanWan05/MolAS-Active-Learning: direct link, hf CLI and curl.
- Browser
- Download file 8.31 kB
-
https://huggingface.co/datasets/SeanWan05/MolAS-Active-Learning/resolve/main/code/downstream/prepare_local_copy.py
- Command line
-
hf download hf://datasets/SeanWan05/MolAS-Active-Learning/code/downstream/prepare_local_copy.py
-
curl -L -o prepare_local_copy.py https://huggingface.co/datasets/SeanWan05/MolAS-Active-Learning/resolve/main/code/downstream/prepare_local_copy.py
8.31 kB
| #!/usr/bin/env python3 | |
| """Configure a NEW copy of recovered MolAS sources; never execute training/analysis. | |
| Only paths are changed. Original recovered sources remain byte-preserved. | |
| Analysis requires two explicitly supplied ground-truth matrices: they are not | |
| interchangeable and no matrix is generated by this utility. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import ast | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import re | |
| import shlex | |
| import shutil | |
| import sys | |
| HERE = Path(__file__).resolve().parent | |
| def replace_assignments(source: str, values: dict[str, str]) -> str: | |
| """Replace named top-level assignments with explicit Python expressions.""" | |
| lines = source.splitlines(keepends=True) | |
| found = {} | |
| for node in ast.parse(source).body: | |
| if isinstance(node, ast.Assign) and len(node.targets) == 1: | |
| target = node.targets[0] | |
| if isinstance(target, ast.Name) and target.id in values: | |
| if target.id in found: | |
| raise ValueError(f"Ambiguous assignment: {target.id}") | |
| found[target.id] = (node.lineno - 1, node.end_lineno) | |
| if set(found) != set(values): | |
| raise ValueError(f"Missing assignments: {sorted(set(values) - set(found))}") | |
| for key, (start, stop) in sorted(found.items(), key=lambda pair: pair[1][0], reverse=True): | |
| lines[start:stop] = [f"{key} = {values[key]}\n"] | |
| return "".join(lines) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--config", type=Path, required=True) | |
| parser.add_argument("--output", type=Path, required=True, | |
| help="New directory; an existing directory is never overwritten") | |
| parser.add_argument("--include-analysis", action="store_true", | |
| help="Also configure the primary analysis notebook; requires both explicit target paths") | |
| args = parser.parse_args() | |
| config_path = args.config.resolve() | |
| config = json.loads(config_path.read_text()) | |
| source = HERE / "historical_molas" | |
| output = args.output.expanduser().resolve() | |
| if output.exists() or source == output or source in output.parents: | |
| raise SystemExit("Choose a new output directory outside historical_molas") | |
| def path_value(key: str, kind: str) -> Path: | |
| raw = config.get(key) | |
| if not raw: | |
| raise ValueError(f"Supply an explicit {key} in the JSON configuration") | |
| path = Path(raw).expanduser() | |
| if not path.is_absolute(): | |
| path = config_path.parent / path | |
| path = path.resolve() | |
| if not (path.is_dir() if kind == "directory" else path.is_file()): | |
| raise ValueError(f"{key}: {kind} does not exist: {path}") | |
| return path | |
| raw = path_value("raw_data_dir", "directory") | |
| graphs = path_value("protein_graphs", "directory") | |
| ligand = path_value("ligand_features", "file") | |
| folds = path_value("fold_split", "file") | |
| acquisitions = path_value("acquisition_dir", "directory") | |
| if not any(acquisitions.glob("*/fold0/seed0/strict_score_matrices/strict_score_*pct.csv")): | |
| raise ValueError("acquisition_dir must contain expanded policy/fold0/seed0 matrices; materialize the archives first") | |
| for filename in ("moad_rmsd_trimmed.csv", "moad_pb_ratio_trimmed.csv", "moad_runtime_trimmed.csv"): | |
| if not (raw / filename).is_file(): | |
| raise ValueError(f"Missing raw input: {filename}") | |
| analysis_paths = {} | |
| if args.include_analysis: | |
| analysis_paths = { | |
| "downstream_dir": path_value("downstream_dir", "directory"), | |
| "molas_score_matrix": path_value("molas_score_matrix", "file"), | |
| "acquisition_score_matrix": path_value("acquisition_score_matrix", "file"), | |
| } | |
| if analysis_paths["molas_score_matrix"] == analysis_paths["acquisition_score_matrix"]: | |
| raise ValueError("The two target roles must be resolved independently; do not alias them to one file") | |
| if not any(analysis_paths["downstream_dir"].glob("*/seed0/b*_pct/test_composite/default/fold_*")): | |
| raise ValueError("downstream_dir must contain expanded policy/seed0/bNNN_pct/test_composite/default/fold_* directories") | |
| # Prepare all substitutions before creating the output directory. | |
| data_root = output / "local_data" | |
| dataset_source = (source / "data/dataset.py").read_text() | |
| dataset_configured = replace_assignments(dataset_source, {"path": repr(str(data_root))}) | |
| shell = (source / "main.sh").read_text() | |
| shell_values = { | |
| "PYTHON": str(config.get("training_python") or sys.executable), | |
| "al_matrices_root": str(acquisitions), | |
| "split_export_path": str(folds), | |
| "log_root": str(output / "run_outputs/lightning_logs"), | |
| "test_output_root": str(output / "run_outputs/test_outputs"), | |
| } | |
| for key, value in shell_values.items(): | |
| shell, count = re.subn(rf"^{re.escape(key)}=.*$", lambda _: f"{key}={shlex.quote(value)}", | |
| shell, flags=re.MULTILINE) | |
| if count != 1: | |
| raise ValueError(f"Expected one shell assignment for {key}, found {count}") | |
| notebook = None | |
| if args.include_analysis: | |
| notebook = json.loads((source / "analyses/port_as_analysis.ipynb").read_text()) | |
| expressions = { | |
| "DATA_ROOT": f"Path({str(data_root)!r})", | |
| "AL_ROOT": f"Path({str(acquisitions)!r})", | |
| "GROUND_TRUTH_PATH": f"Path({str(analysis_paths['molas_score_matrix'])!r})", | |
| "ACQUISITION_GROUND_TRUTH_PATH": f"Path({str(analysis_paths['acquisition_score_matrix'])!r})", | |
| "RUNTIME_PATH": f"Path({str(raw / 'moad_runtime_trimmed.csv')!r})", | |
| "SPLIT_PATH": f"Path({str(folds)!r})", | |
| "RESULT_ROOT": f"Path({str(analysis_paths['downstream_dir'])!r})", | |
| "ANALYSIS_ROOT": f"Path({str(output / 'analysis_outputs')!r})", | |
| "MOLAS_REPO_ROOT": f"Path({str(output)!r})", | |
| } | |
| first = "".join(notebook["cells"][1]["source"]) | |
| notebook["cells"][1]["source"] = replace_assignments(first, expressions).splitlines(keepends=True) | |
| for cell in notebook["cells"]: | |
| if cell["cell_type"] == "code": | |
| content = "".join(cell["source"]).replace( | |
| "/data1/home/jw1017/AS_Dock/data/MolAS/moad_runtime_trimmed.csv", | |
| str(raw / "moad_runtime_trimmed.csv")) | |
| cell["source"] = content.splitlines(keepends=True) | |
| cell["outputs"] = [] | |
| cell["execution_count"] = None | |
| shutil.copytree(source, output, ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) | |
| data_root.mkdir() | |
| for filename in ("moad_rmsd_trimmed.csv", "moad_pb_ratio_trimmed.csv", "moad_runtime_trimmed.csv"): | |
| (data_root / filename).symlink_to(raw / filename) | |
| (data_root / "protein_graphs_esmc_600m").symlink_to(graphs, target_is_directory=True) | |
| # The recovered loader uses this exact ligand-cache filename. | |
| (data_root / "ligand_chemberta.pt").symlink_to(ligand) | |
| (output / "data/dataset.py").write_text(dataset_configured) | |
| (output / "main.sh").write_text(shell) | |
| if notebook is not None: | |
| (output / "analyses/port_as_analysis.ipynb").write_text(json.dumps(notebook, indent=1) + "\n") | |
| manifest = { | |
| "operation": "configure_only_no_training_or_analysis_execution", | |
| "source_manifest": str(HERE / "historical_molas_manifest.json"), | |
| "config_sha256": hashlib.sha256(config_path.read_bytes()).hexdigest(), | |
| "training_paths_configured": True, | |
| "primary_notebook_paths_configured": notebook is not None, | |
| "runtime_probe_notebook_paths_configured": False, | |
| "new_results_or_features_generated": False, | |
| "scientific_settings_changed": False, | |
| "warning": "main.sh retains the recovered subset, seed, and training settings; review them before any future execution. Other notebooks retain historical paths. Configuring paths does not establish historical run identity.", | |
| } | |
| (output / "LOCAL_CONFIGURATION.json").write_text(json.dumps(manifest, indent=2) + "\n") | |
| print(json.dumps({"configured_directory": str(output), "executed_experiments": 0})) | |
| if __name__ == "__main__": | |
| main() | |