mattbitzesty commited on
Commit
ef8e907
·
verified ·
1 Parent(s): 3fd8388

Upload scripts/augment_gamma_channel.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/augment_gamma_channel.py +103 -0
scripts/augment_gamma_channel.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Augment the empirical corpus with a non-redundant physics channel: the UNIFAC
2
+ activity-coefficient (gamma) interaction term.
3
+
4
+ Motivation (E2 finding): the existing 2-channel physics signal (x_liquid,
5
+ log10 OAV) is largely REDUNDANT with the model's existing molecular-weight
6
+ input (volatility is ~76% MW-recoverable). The genuinely non-redundant physics
7
+ is the *mixture interaction*: the activity coefficient gamma_i(t), which depends
8
+ on the whole liquid composition and is emphatically not contained in any
9
+ single-molecule embedding.
10
+
11
+ gamma is recovered without re-running UNIFAC. The engine's headspace obeys
12
+ non-ideal Raoult: P_i = gamma_i * x_i * P_sat_i, y_i = P_i / sum_j(P_j).
13
+ Hence gamma_i ∝ y_i / (x_i * P_sat_i). The shared normalizer cancels in any
14
+ ratio, and the FiLM block standardizes channels, so we store log10 of the
15
+ proportional gamma (a sufficient, monotone encoding of the interaction term).
16
+
17
+ Output: a new physics tensor per formula of shape (T, S, 3) with channels
18
+ [x_liquid, log10 OAV, log10 gamma_prop], written alongside the original record
19
+ so train.py can opt into state_dim=3.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import sqlite3
25
+ from pathlib import Path
26
+
27
+ import numpy as np
28
+
29
+ ROOT = Path(__file__).resolve().parent.parent
30
+ DB = ROOT / "src" / "pino" / "registry.db"
31
+
32
+
33
+ def load_psat() -> dict[str, float]:
34
+ con = sqlite3.connect(DB)
35
+ con.row_factory = sqlite3.Row
36
+ out = {}
37
+ for r in con.execute("SELECT cas, vapor_pressure_pa FROM aroma_chemicals WHERE vapor_pressure_pa > 0"):
38
+ out[r["cas"]] = float(r["vapor_pressure_pa"])
39
+ con.close()
40
+ return out
41
+
42
+
43
+ def gamma_prop_channel(step: dict, cass: list[str], psat: dict[str, float]) -> np.ndarray:
44
+ """Return (S,) log10 proportional-gamma for one timestep.
45
+
46
+ gamma_i ∝ y_i / (x_i * P_sat_i). Components with missing P_sat or zero
47
+ x_liquid get gamma=1 (log10=0, the ideal limit).
48
+ """
49
+ xl = step.get("x_liquid", {})
50
+ yg = step.get("y_gas", {})
51
+ logg = np.zeros(len(cass), dtype=np.float32)
52
+ for j, cas in enumerate(cass):
53
+ x = float(xl.get(cas, 0.0))
54
+ y = float(yg.get(cas, 0.0))
55
+ p = psat.get(cas.replace("NATURAL:", ""))
56
+ if p is None or x <= 1e-9 or y <= 0.0:
57
+ logg[j] = 0.0 # ideal / no signal
58
+ else:
59
+ logg[j] = np.log10(max(y / (x * p), 1e-12))
60
+ # center so the channel carries only relative (mixture-interaction) info
61
+ if len(cass) > 0:
62
+ logg = logg - logg.mean()
63
+ return logg
64
+
65
+
66
+ def augment_record(rec: dict, psat: dict[str, float]) -> dict:
67
+ formula = rec.get("formula", [])
68
+ traj = rec.get("trajectory", [])
69
+ cass = [str(c.get("cas", f"ing_{j}")) for j, c in enumerate(formula)]
70
+ # build (T, S, 1) gamma channel aligned with the existing physics tensor
71
+ gam = np.stack([gamma_prop_channel(st, cass, psat) for st in traj], axis=0) # (T, S)
72
+ rec["physics_gamma"] = gam.tolist()
73
+ return rec
74
+
75
+
76
+ def main(in_path: str, out_path: str, max_records: int | None = None):
77
+ psat = load_psat()
78
+ print(f"registry P_sat for {len(psat)} CAS")
79
+ n = 0
80
+ with open(in_path) as fin, open(out_path, "w") as fout:
81
+ for line in fin:
82
+ if not line.strip():
83
+ continue
84
+ rec = json.loads(line)
85
+ if "formula" in rec and "trajectory" in rec:
86
+ rec = augment_record(rec, psat)
87
+ fout.write(json.dumps(rec) + "\n")
88
+ n += 1
89
+ if max_records and n >= max_records:
90
+ break
91
+ if n % 1000 == 0:
92
+ print(f" {n} records...")
93
+ print(f"wrote {n} augmented records -> {out_path}")
94
+
95
+
96
+ if __name__ == "__main__":
97
+ import argparse
98
+ ap = argparse.ArgumentParser()
99
+ ap.add_argument("--in", dest="inp", default=str(ROOT / "data/empirical_dataset_v9_plus_wisemoor.jsonl"))
100
+ ap.add_argument("--out", dest="out", default=str(ROOT / "data/empirical_dataset_v9_gamma.jsonl"))
101
+ ap.add_argument("--max", type=int, default=None)
102
+ a = ap.parse_args()
103
+ main(a.inp, a.out, a.max)