|
| 1 | +#!/usr/bin/env python |
| 2 | +import argparse |
| 3 | +import os |
| 4 | +import torch |
| 5 | +import json |
| 6 | +from spatial_transcript_former.visualization import run_inference_plot |
| 7 | + |
| 8 | + |
| 9 | +# Dummy class to hold loaded arguments |
| 10 | +class RunArgs: |
| 11 | + def __init__(self, **entries): |
| 12 | + self.__dict__.update(entries) |
| 13 | + |
| 14 | + |
| 15 | +def parse_args(): |
| 16 | + parser = argparse.ArgumentParser("Predict sample pathways") |
| 17 | + parser.add_argument( |
| 18 | + "--sample-id", |
| 19 | + required=True, |
| 20 | + type=str, |
| 21 | + help="Sample ID to run inference on (e.g. TENX156)", |
| 22 | + ) |
| 23 | + parser.add_argument( |
| 24 | + "--run-dir", |
| 25 | + required=True, |
| 26 | + type=str, |
| 27 | + help="Directory containing model weights and args.json", |
| 28 | + ) |
| 29 | + parser.add_argument( |
| 30 | + "--output-dir", type=str, default=".", help="Where to save the output plot" |
| 31 | + ) |
| 32 | + parser.add_argument( |
| 33 | + "--epoch", type=int, default=0, help="Epoch number to label the plot with" |
| 34 | + ) |
| 35 | + return parser.parse_args() |
| 36 | + |
| 37 | + |
| 38 | +def main(): |
| 39 | + cli_args = parse_args() |
| 40 | + |
| 41 | + # Load args from run_dir |
| 42 | + args_path = os.path.join(cli_args.run_dir, "results_summary.json") |
| 43 | + if not os.path.exists(args_path): |
| 44 | + raise FileNotFoundError(f"Missing {args_path}") |
| 45 | + |
| 46 | + with open(args_path, "r") as f: |
| 47 | + summary_dict = json.load(f) |
| 48 | + run_args_dict = summary_dict.get("config", {}) |
| 49 | + |
| 50 | + run_args = RunArgs(**run_args_dict) |
| 51 | + run_args.output_dir = cli_args.output_dir |
| 52 | + run_args.run_dir = cli_args.run_dir |
| 53 | + |
| 54 | + # Optional arguments that might be missing from older args.json |
| 55 | + if not hasattr(run_args, "log_transform"): |
| 56 | + run_args.log_transform = False |
| 57 | + |
| 58 | + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| 59 | + |
| 60 | + # Re-initialize the model based on run_args |
| 61 | + if run_args.model == "baseline": |
| 62 | + from spatial_transcript_former.models import SpatialTranscriptFormer |
| 63 | + |
| 64 | + model = SpatialTranscriptFormer( |
| 65 | + backbone=run_args.backbone, |
| 66 | + num_genes=run_args.num_genes, |
| 67 | + dropout=run_args.dropout, |
| 68 | + n_neighbors=run_args.n_neighbors, |
| 69 | + ) |
| 70 | + elif run_args.model == "interaction": |
| 71 | + from spatial_transcript_former.models import SpatialTranscriptFormer |
| 72 | + |
| 73 | + model = SpatialTranscriptFormer( |
| 74 | + num_genes=run_args.num_genes, |
| 75 | + backbone_name=run_args.backbone, |
| 76 | + pretrained=run_args.pretrained, |
| 77 | + token_dim=getattr(run_args, "token_dim", 384), |
| 78 | + n_heads=getattr(run_args, "n_heads", 6), |
| 79 | + n_layers=getattr(run_args, "n_layers", 4), |
| 80 | + num_pathways=getattr(run_args, "num_pathways", 0), |
| 81 | + use_spatial_pe=getattr(run_args, "use_spatial_pe", True), |
| 82 | + output_mode="zinb" if getattr(run_args, "loss", "") == "zinb" else "counts", |
| 83 | + interactions=getattr(run_args, "interactions", None), |
| 84 | + ) |
| 85 | + else: |
| 86 | + raise ValueError(f"Unknown model type: {run_args.model}") |
| 87 | + |
| 88 | + model.to(device) |
| 89 | + |
| 90 | + # Note: we explicitly load the *best* model if it exists, otherwise the latest |
| 91 | + ckpt_path = os.path.join(cli_args.run_dir, f"best_model_{run_args.model}.pth") |
| 92 | + if not os.path.exists(ckpt_path): |
| 93 | + ckpt_path = os.path.join(cli_args.run_dir, f"latest_model_{run_args.model}.pth") |
| 94 | + |
| 95 | + if os.path.exists(ckpt_path): |
| 96 | + print(f"Loading checkpoint from {ckpt_path}...") |
| 97 | + checkpoint = torch.load(ckpt_path, map_location=device, weights_only=True) |
| 98 | + if "model_state_dict" in checkpoint: |
| 99 | + model.load_state_dict(checkpoint["model_state_dict"]) |
| 100 | + else: |
| 101 | + model.load_state_dict(checkpoint) |
| 102 | + else: |
| 103 | + print( |
| 104 | + f"Warning: No checkpoint found in {cli_args.run_dir}. Using untrained model." |
| 105 | + ) |
| 106 | + |
| 107 | + print(f"Running inference for sample {cli_args.sample_id}...") |
| 108 | + run_inference_plot(model, run_args, cli_args.sample_id, cli_args.epoch, device) |
| 109 | + |
| 110 | + |
| 111 | +if __name__ == "__main__": |
| 112 | + main() |
0 commit comments