sync code
Browse files- code/pimamba/predict.py +142 -0
code/pimamba/predict.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Inference / deployment: run a trained checkpoint on new alloy conditions.
|
| 2 |
+
|
| 3 |
+
Two use cases
|
| 4 |
+
-------------
|
| 5 |
+
1. *Re-score* held-out samples with a published checkpoint::
|
| 6 |
+
|
| 7 |
+
python -m pimamba.predict --run results/runs/main_pimamba_f2_s0
|
| 8 |
+
|
| 9 |
+
2. *What-if* on new compositions / conditions: give a CSV with the same columns
|
| 10 |
+
as ``data/processed/samples_meta.csv`` (one row per condition)::
|
| 11 |
+
|
| 12 |
+
python -m pimamba.predict --run results/runs/main_pimamba_f0_s0 \
|
| 13 |
+
--meta my_alloys.csv --out my_preds.csv
|
| 14 |
+
|
| 15 |
+
Only the *static* columns are used for a new sample; the strain grid is
|
| 16 |
+
synthesised (0 -> eps_max), because the dynamic input channels depend only on
|
| 17 |
+
strain, strain rate, T0 and load mode. Every column of ``samples_meta.csv``
|
| 18 |
+
must be present (missing optional ones may be left empty / NaN).
|
| 19 |
+
|
| 20 |
+
Output: long-format CSV with ``sample_id, strain, <13 targets>``.
|
| 21 |
+
"""
|
| 22 |
+
from __future__ import annotations
|
| 23 |
+
|
| 24 |
+
import argparse
|
| 25 |
+
import json
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
import pandas as pd
|
| 30 |
+
|
| 31 |
+
from .data import (PROC, TARGETS, Normalizer, PackedDataset, build_static_frame,
|
| 32 |
+
collate)
|
| 33 |
+
from .models import build_model
|
| 34 |
+
|
| 35 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def synth_traj(sids, n_points: int = 401, eps_max: float = 0.2) -> pd.DataFrame:
|
| 39 |
+
"""Strain grid with all targets missing -> the loss mask is all-zero."""
|
| 40 |
+
eps = np.linspace(0.0, eps_max, n_points)
|
| 41 |
+
frames = []
|
| 42 |
+
for s in sids:
|
| 43 |
+
d = {"sample_id": int(s), "strain": eps}
|
| 44 |
+
for t in TARGETS:
|
| 45 |
+
d[t.name] = np.nan
|
| 46 |
+
frames.append(pd.DataFrame(d))
|
| 47 |
+
return pd.concat(frames, ignore_index=True)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def load_run(run_dir: Path, device="cpu"):
|
| 51 |
+
import torch
|
| 52 |
+
|
| 53 |
+
ck = torch.load(run_dir / "model.pt", map_location=device, weights_only=False)
|
| 54 |
+
meta = json.loads((run_dir / "metrics.json").read_text())
|
| 55 |
+
cfg = ck["cfg"]
|
| 56 |
+
model = build_model(cfg["model"], n_static=int(np.sum(ck["keep_mask"])),
|
| 57 |
+
n_out=len(TARGETS), d_model=cfg["d_model"],
|
| 58 |
+
n_layers=cfg["n_layers"], d_state=cfg["d_state"],
|
| 59 |
+
dropout=cfg["dropout"], coupling=cfg["coupling"]).to(device)
|
| 60 |
+
model.load_state_dict(ck["state"])
|
| 61 |
+
model.eval()
|
| 62 |
+
return model, cfg, meta, ck
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def predict(run_dir: Path, meta: pd.DataFrame, sids, n_points: int = 401,
|
| 66 |
+
eps_max: float = 0.2, device="cpu") -> pd.DataFrame:
|
| 67 |
+
import torch
|
| 68 |
+
|
| 69 |
+
model, cfg, run_meta, ck = load_run(run_dir, device)
|
| 70 |
+
names = ck["names"]
|
| 71 |
+
km = np.asarray(ck["keep_mask"], dtype=bool)
|
| 72 |
+
kinds = build_static_frame(meta)[2]
|
| 73 |
+
norm = Normalizer.from_json(run_meta["normalizer"])
|
| 74 |
+
|
| 75 |
+
mtab = meta.reset_index(drop=True)
|
| 76 |
+
traj = synth_traj(sids, n_points, eps_max)
|
| 77 |
+
ds = PackedDataset(sids, mtab, traj, norm, names, kinds, km)
|
| 78 |
+
dl = torch.utils.data.DataLoader(ds, batch_size=8, shuffle=False,
|
| 79 |
+
collate_fn=collate)
|
| 80 |
+
|
| 81 |
+
preds, used = [], []
|
| 82 |
+
with torch.no_grad():
|
| 83 |
+
for st, x, _Y, _M, sid in dl:
|
| 84 |
+
out = model(st.to(device), x.to(device))
|
| 85 |
+
preds.append(out["pred"].cpu().numpy())
|
| 86 |
+
used.extend([int(v) for v in sid])
|
| 87 |
+
raw = norm.inverse_targets(np.concatenate(preds, 0)) # (N, T, 13)
|
| 88 |
+
|
| 89 |
+
eps = np.linspace(0.0, eps_max, n_points)
|
| 90 |
+
frames = []
|
| 91 |
+
for i, s in enumerate(used):
|
| 92 |
+
d = {"sample_id": s, "strain": eps}
|
| 93 |
+
for k, t in enumerate(TARGETS):
|
| 94 |
+
d[t.name] = raw[i, :, k]
|
| 95 |
+
frames.append(pd.DataFrame(d))
|
| 96 |
+
return pd.concat(frames, ignore_index=True)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def main():
|
| 100 |
+
ap = argparse.ArgumentParser("pimamba.predict")
|
| 101 |
+
ap.add_argument("--run", default="results/runs/main_pimamba_f2_s0",
|
| 102 |
+
help="run directory containing model.pt + metrics.json")
|
| 103 |
+
ap.add_argument("--meta", default=None,
|
| 104 |
+
help="CSV of new samples (same columns as samples_meta.csv)")
|
| 105 |
+
ap.add_argument("--sids", default=None,
|
| 106 |
+
help="comma separated sample_ids of data/processed/samples_meta.csv")
|
| 107 |
+
ap.add_argument("--n-points", type=int, default=401)
|
| 108 |
+
ap.add_argument("--eps-max", type=float, default=0.2)
|
| 109 |
+
ap.add_argument("--out", default="predictions.csv")
|
| 110 |
+
ap.add_argument("--device", default="cpu")
|
| 111 |
+
a = ap.parse_args()
|
| 112 |
+
|
| 113 |
+
run_dir = Path(a.run)
|
| 114 |
+
if not run_dir.is_absolute():
|
| 115 |
+
run_dir = ROOT / run_dir
|
| 116 |
+
run_meta = json.loads((run_dir / "metrics.json").read_text())
|
| 117 |
+
|
| 118 |
+
if a.meta:
|
| 119 |
+
meta = pd.read_csv(a.meta)
|
| 120 |
+
else:
|
| 121 |
+
meta = pd.read_csv(PROC / "samples_meta.csv")
|
| 122 |
+
if a.sids:
|
| 123 |
+
sids = [int(s) for s in a.sids.split(",") if s.strip()]
|
| 124 |
+
elif a.meta:
|
| 125 |
+
# a new alloy table: predict every row it contains
|
| 126 |
+
sids = [int(s) for s in meta.sample_id]
|
| 127 |
+
else:
|
| 128 |
+
sids = [int(s) for s in run_meta["test_ids"]]
|
| 129 |
+
|
| 130 |
+
missing = set(sids) - set(meta.sample_id.astype(int))
|
| 131 |
+
if missing:
|
| 132 |
+
raise SystemExit(f"sample_id not found in meta table: {sorted(missing)}")
|
| 133 |
+
|
| 134 |
+
df = predict(run_dir, meta, sids, a.n_points, a.eps_max, a.device)
|
| 135 |
+
df.to_csv(a.out, index=False)
|
| 136 |
+
print(f"wrote {a.out}: {df.shape[0]} rows x {df.shape[1]} cols "
|
| 137 |
+
f"({len(sids)} samples, {a.n_points} strain points)")
|
| 138 |
+
print(df.head(3).to_string(index=False))
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
if __name__ == "__main__":
|
| 142 |
+
main()
|