Skip to content

Commit 4608c21

Browse files
committed
freeze Gate-1 feature map and replay contract
1 parent c19101b commit 4608c21

10 files changed

Lines changed: 776 additions & 0 deletions

File tree

‎active_solvai_v3/data/derived/gate1_dataset_manifest.json‎

Lines changed: 243 additions & 0 deletions
Large diffs are not rendered by default.
22.7 KB
Binary file not shown.
278 KB
Binary file not shown.
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# V3 master protocol freeze amendment 001
2+
3+
**Committed before any Gate-1 model fitting or held-out scoring:** 2026-09-03
4+
**Information known:** inherited aggregate results, raw trajectory inventory and
5+
the frozen twelve-molecule feature/time-series tables; no v3 target-model result.
6+
7+
## Clarification
8+
9+
The master freeze says that structure- and SolvAI-conditioned models add their
10+
fixed molecule-level coordinates to lambda/protocol features. An additive
11+
linear model would allow those coordinates to shift average difficulty between
12+
molecules but could not represent a molecule-conditioned *ranking of lambda
13+
windows*. That would fail to implement the registered scientific question.
14+
15+
Accordingly, the predeclared linear feature map is clarified as follows:
16+
17+
- every molecule-level structure or SolvAI coordinate enters as a main effect;
18+
- it also enters multiplied by `(lambda - 0.5)` and `(lambda - 0.5)^2`;
19+
- no outcome-dependent interaction selection is performed;
20+
- all interactions use the same training-only imputation, standardization,
21+
grouped validation and ridge-alpha grid already frozen;
22+
- the lambda/protocol and generic observed-only models are unchanged.
23+
24+
The molecule-shuffled control applies the same interaction map after jointly
25+
permuting the complete response vector among outer-training molecules. The
26+
held-out molecule's response vector is not inserted into any training row.
27+
28+
This clarification changes neither the target, data, folds, penalties, metrics
29+
nor pass rules. It prevents an implementation artifact from making the
30+
molecule-conditioned hypothesis algebraically untestable.

‎active_solvai_v3/runs/ledger.jsonl‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
{"run_id":"V3-0001","date_utc":"2026-09-03","kind":"blueprint_ingestion","status":"complete","gpu_hours":0.0,"outputs":["active_solvai_v3/reports/BLUEPRINT_INGESTION.md"],"notes":"Complete DOCX, tables, equations, figures, references and operating brief inspected."}
22
{"run_id":"V3-0002","date_utc":"2026-09-03","kind":"inherited_metric_reproduction","status":"complete","gpu_hours":0.0,"command":"uv run --project active_solvai python active_solvai_v3/scripts/reproduce_inherited.py","outputs":["active_solvai_v3/results/inherited/canonical_reproduction.csv","active_solvai_v3/results/inherited/canonical_reproduction.json"]}
33
{"run_id":"V3-0003","date_utc":"2026-09-03","kind":"trajectory_inventory","status":"complete","gpu_hours":0.0,"command":"uv run --project active_solvai python active_solvai_v3/scripts/inventory_trajectories.py","outputs":["active_solvai_v3/data/manifests/trajectory_inventory.csv","active_solvai_v3/data/manifests/trajectory_inventory.parquet","active_solvai_v3/data/manifests/trajectory_inventory_summary.json"],"notes":"No independent compatible full-grid replica sets found."}
4+
{"run_id":"V3-0004","date_utc":"2026-09-03","kind":"gate1_dataset_build","status":"complete","gpu_hours":0.0,"command":"PYTHONPATH=active_solvai_v3/src uv run --project . python active_solvai_v3/scripts/build_gate1_dataset.py","outputs":["active_solvai_v3/data/derived/gate1_time_series.parquet","active_solvai_v3/data/derived/gate1_molecule_features.parquet","active_solvai_v3/data/derived/gate1_dataset_manifest.json"],"notes":"Generated deterministic structure descriptors and 15 frozen SolvAI response coordinates; no Gate-1 target-model score inspected."}
Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
#!/usr/bin/env python3
2+
"""Build the frozen Gate-1 time-series and molecule-feature tables."""
3+
4+
from __future__ import annotations
5+
6+
import hashlib
7+
import json
8+
from pathlib import Path
9+
10+
import joblib
11+
import numpy as np
12+
import pandas as pd
13+
from rdkit import Chem
14+
15+
from solv_ai.features import descriptor_frame
16+
from solv_ai.teachers import response_features
17+
18+
ROOT = Path(__file__).resolve().parents[2]
19+
OUT = ROOT / "active_solvai_v3/data/derived"
20+
PHASE2 = ROOT / "active_solvai/results/phase2"
21+
MODEL = ROOT / "models/final"
22+
23+
STRUCTURE_COLUMNS = {
24+
"structure_molecular_weight": "rdkit__MolWt",
25+
"structure_heavy_atom_count": "rdkit__HeavyAtomCount",
26+
"structure_tpsa": "rdkit__TPSA",
27+
"structure_mol_logp": "rdkit__MolLogP",
28+
"structure_hbond_donors": "rdkit__NumHDonors",
29+
"structure_hbond_acceptors": "rdkit__NumHAcceptors",
30+
"structure_rotatable_bonds": "rdkit__NumRotatableBonds",
31+
"structure_ring_count": "rdkit__RingCount",
32+
"structure_fraction_csp3": "rdkit__FractionCSP3",
33+
}
34+
35+
36+
def sha256(path: Path) -> str:
37+
digest = hashlib.sha256()
38+
with path.open("rb") as handle:
39+
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
40+
digest.update(chunk)
41+
return digest.hexdigest()
42+
43+
44+
def read_energy(path: Path) -> pd.DataFrame:
45+
frame = pd.read_csv(path, sep="\t")
46+
frame.columns = [str(column).strip() for column in frame.columns]
47+
numeric = frame.apply(pd.to_numeric, errors="coerce")
48+
required = ["Time", "Temp", "Density", "dHdL"]
49+
missing = [column for column in required if column not in numeric]
50+
if missing:
51+
raise AssertionError(f"{path} lacks {missing}")
52+
if len(numeric) != 51:
53+
raise AssertionError(f"{path} has {len(numeric)} frames, expected 51")
54+
post = numeric[numeric["Time"] > 1e-9].copy().reset_index(drop=True)
55+
if len(post) != 50 or not np.isfinite(post[required]).all().all():
56+
raise AssertionError(f"{path} does not contain 50 finite post-initial records")
57+
post["frame_index"] = np.arange(1, 51)
58+
post["block_0p5ps"] = (post["frame_index"] - 1) // 5 + 1
59+
post["block_1ps"] = (post["frame_index"] - 1) // 10 + 1
60+
return post
61+
62+
63+
def main() -> None:
64+
OUT.mkdir(parents=True, exist_ok=True)
65+
source_paths = [
66+
PHASE2 / "dense_responses_calibration.parquet",
67+
PHASE2 / "dense_responses_prospective.parquet",
68+
]
69+
responses = pd.concat([pd.read_parquet(path) for path in source_paths], ignore_index=True)
70+
responses = responses.rename(columns={"lambda": "lambda_value"})
71+
if len(responses) != 180 or responses.groupby("molecule_id").size().ne(15).any():
72+
raise AssertionError("Gate-1 source is not a complete 12 x 15 grid")
73+
74+
time_rows: list[pd.DataFrame] = []
75+
raw_hashes: dict[str, str] = {}
76+
for row in responses.itertuples(index=False):
77+
path = Path(str(row.energy_file))
78+
observed_hash = sha256(path)
79+
if observed_hash != row.energy_sha256:
80+
raise AssertionError(f"energy hash mismatch: {path}")
81+
raw_hashes[str(path)] = observed_hash
82+
frame = read_energy(path)
83+
frame = frame.rename(
84+
columns={
85+
"Time": "time_ps",
86+
"Temp": "temperature_k",
87+
"Density": "density_g_cm3",
88+
"dHdL": "dhdl_kcal_mol",
89+
}
90+
)
91+
frame.insert(0, "lambda", float(row.lambda_value))
92+
frame.insert(0, "canonical_smiles", row.canonical_smiles)
93+
frame.insert(0, "molecule_name", row.molecule_name)
94+
frame.insert(0, "molecule_id", row.molecule_id)
95+
frame["energy_file"] = str(path)
96+
frame["energy_sha256"] = observed_hash
97+
time_rows.append(
98+
frame[
99+
[
100+
"molecule_id",
101+
"molecule_name",
102+
"canonical_smiles",
103+
"lambda",
104+
"frame_index",
105+
"block_0p5ps",
106+
"block_1ps",
107+
"time_ps",
108+
"dhdl_kcal_mol",
109+
"temperature_k",
110+
"density_g_cm3",
111+
"energy_file",
112+
"energy_sha256",
113+
]
114+
]
115+
)
116+
time_series = pd.concat(time_rows, ignore_index=True).sort_values(
117+
["molecule_id", "lambda", "frame_index"]
118+
)
119+
time_path = OUT / "gate1_time_series.parquet"
120+
time_series.to_parquet(time_path, index=False)
121+
122+
molecules = (
123+
responses[["molecule_id", "molecule_name", "canonical_smiles", "functional_group_family"]]
124+
.drop_duplicates()
125+
.sort_values("molecule_id")
126+
.reset_index(drop=True)
127+
)
128+
smiles = molecules.canonical_smiles.tolist()
129+
descriptors = descriptor_frame(smiles)
130+
physical = response_features(smiles, descriptors, MODEL)
131+
head = joblib.load(MODEL / "head.joblib")
132+
response_columns = [f"response__{name}" for name in head["teacher_columns"]]
133+
if physical.shape != (len(molecules), 15) or len(response_columns) != 15:
134+
raise AssertionError("frozen SolvAI response schema is not 15-dimensional")
135+
features = molecules.copy()
136+
for output_name, descriptor_name in STRUCTURE_COLUMNS.items():
137+
features[output_name] = descriptors[descriptor_name].to_numpy(float)
138+
features["structure_formal_charge"] = [
139+
int(Chem.GetFormalCharge(Chem.MolFromSmiles(value))) for value in smiles
140+
]
141+
for index, name in enumerate(response_columns):
142+
features[name] = physical[:, index]
143+
feature_path = OUT / "gate1_molecule_features.parquet"
144+
features.to_parquet(feature_path, index=False)
145+
146+
manifest = {
147+
"schema_version": 1,
148+
"molecules": int(features.molecule_id.nunique()),
149+
"windows": int(responses.shape[0]),
150+
"post_initial_frames": int(len(time_series)),
151+
"lambda_values": sorted(responses["lambda_value"].unique().tolist()),
152+
"structure_columns": [*STRUCTURE_COLUMNS, "structure_formal_charge"],
153+
"response_columns": response_columns,
154+
"source_tables": {str(path): sha256(path) for path in source_paths},
155+
"raw_energy_files": raw_hashes,
156+
"outputs": {
157+
str(time_path): sha256(time_path),
158+
str(feature_path): sha256(feature_path),
159+
},
160+
"independence_warning": (
161+
"One 5-ps stream per molecule-window; blocks are development diagnostics, not replicas."
162+
),
163+
}
164+
manifest_path = OUT / "gate1_dataset_manifest.json"
165+
manifest_path.write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n")
166+
print(json.dumps({key: value for key, value in manifest.items() if key != "raw_energy_files"}, indent=2))
167+
168+
169+
if __name__ == "__main__":
170+
main()
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
"""Time-series diagnostics for fixed-grid trajectory-effort allocation."""
2+
3+
from __future__ import annotations
4+
5+
import math
6+
7+
import numpy as np
8+
from scipy.stats import ks_2samp, rankdata
9+
10+
11+
def _finite(values: np.ndarray) -> np.ndarray:
12+
values = np.asarray(values, dtype=float)
13+
return values[np.isfinite(values)]
14+
15+
16+
def batch_variance_rate(values: np.ndarray, dt_ps: float, batches: int) -> float:
17+
"""Estimate the asymptotic variance rate from non-overlapping batch means."""
18+
x = _finite(values)
19+
if batches < 2 or len(x) < 2 * batches:
20+
return math.nan
21+
chunks = [chunk for chunk in np.array_split(x, batches) if len(chunk)]
22+
means = np.asarray([chunk.mean() for chunk in chunks], dtype=float)
23+
mean_batch_length = float(np.mean([len(chunk) for chunk in chunks]))
24+
return float(means.var(ddof=1) * mean_batch_length * dt_ps)
25+
26+
27+
def overlapping_batch_variance_rate(values: np.ndarray, dt_ps: float) -> float:
28+
"""Estimate variance rate with deterministic sqrt(n)-length overlapping batches."""
29+
x = _finite(values)
30+
n = len(x)
31+
batch = max(2, int(np.floor(np.sqrt(n))))
32+
if n < 2 * batch:
33+
return math.nan
34+
means = np.convolve(x, np.ones(batch) / batch, mode="valid")
35+
return float(batch * dt_ps * np.sum((means - x.mean()) ** 2) / len(means))
36+
37+
38+
def newey_west_variance_rate(values: np.ndarray, dt_ps: float) -> float:
39+
"""Bartlett/Newey-West long-run variance rate with a fixed length bandwidth."""
40+
x = _finite(values)
41+
n = len(x)
42+
if n < 4:
43+
return math.nan
44+
centered = x - x.mean()
45+
bandwidth = max(1, int(np.floor(4 * (n / 100) ** (2 / 9))))
46+
gamma0 = float(centered @ centered / n)
47+
long_run = gamma0
48+
for lag in range(1, min(bandwidth, n - 1) + 1):
49+
gamma = float(centered[lag:] @ centered[:-lag] / n)
50+
long_run += 2 * (1 - lag / (bandwidth + 1)) * gamma
51+
return float(max(long_run, 0.0) * dt_ps)
52+
53+
54+
def initial_positive_iat(values: np.ndarray) -> float:
55+
"""Initial-positive-sequence estimate of integrated autocorrelation time."""
56+
x = _finite(values)
57+
n = len(x)
58+
if n < 4 or np.isclose(x.var(), 0.0):
59+
return math.nan
60+
centered = x - x.mean()
61+
gamma0 = float(centered @ centered / n)
62+
correlations: list[float] = []
63+
for lag in range(1, n):
64+
gamma = float(centered[lag:] @ centered[:-lag] / n)
65+
correlations.append(gamma / gamma0)
66+
total = 1.0
67+
for index in range(0, len(correlations) - 1, 2):
68+
pair = correlations[index] + correlations[index + 1]
69+
if pair <= 0:
70+
break
71+
total += 2 * pair
72+
return float(max(total, 1.0))
73+
74+
75+
def prefix_diagnostics(values: np.ndarray, times_ps: np.ndarray) -> dict[str, float | bool]:
76+
"""Compute only diagnostics available in a revealed trajectory prefix."""
77+
x = _finite(values)
78+
t = np.asarray(times_ps, dtype=float)[: len(x)]
79+
n = len(x)
80+
if n < 2:
81+
raise ValueError("a prefix requires at least two finite observations")
82+
dt = float(np.median(np.diff(t)))
83+
split = n // 2
84+
first, second = x[:split], x[split:]
85+
slope = float(np.polyfit(t, x, 1)[0]) if n >= 3 else math.nan
86+
rank_correlation = float(np.corrcoef(rankdata(t), rankdata(x))[0, 1]) if n >= 3 else math.nan
87+
variance = float(x.var(ddof=1))
88+
naive_sem = float(np.sqrt(variance / n))
89+
iat = initial_positive_iat(x)
90+
ess = float(n / iat) if np.isfinite(iat) and iat > 0 else math.nan
91+
first_sem = float(first.std(ddof=1) / np.sqrt(len(first))) if len(first) > 1 else math.nan
92+
second_sem = float(second.std(ddof=1) / np.sqrt(len(second))) if len(second) > 1 else math.nan
93+
pooled = np.sqrt(first_sem**2 + second_sem**2)
94+
half_difference = float(second.mean() - first.mean())
95+
lag1 = float(np.corrcoef(x[:-1], x[1:])[0, 1]) if n >= 3 and variance > 0 else math.nan
96+
return {
97+
"prefix_frames": n,
98+
"prefix_mean": float(x.mean()),
99+
"prefix_variance": variance,
100+
"naive_sem": naive_sem,
101+
"batch_variance_rate_2": batch_variance_rate(x, dt, 2),
102+
"batch_variance_rate_5": batch_variance_rate(x, dt, 5),
103+
"overlap_batch_variance_rate": overlapping_batch_variance_rate(x, dt),
104+
"newey_west_variance_rate": newey_west_variance_rate(x, dt),
105+
"lag1_autocorrelation": lag1,
106+
"iat_initial_positive": iat,
107+
"effective_sample_size": ess,
108+
"half_mean_difference": half_difference,
109+
"half_variance_ratio_log": float(
110+
np.log((second.var(ddof=1) + 1e-8) / (first.var(ddof=1) + 1e-8))
111+
)
112+
if len(first) > 1 and len(second) > 1
113+
else math.nan,
114+
"half_ks_distance": float(ks_2samp(first, second).statistic),
115+
"linear_drift_per_ps": slope,
116+
"rank_drift": rank_correlation,
117+
"unresolved_equilibration": bool(np.isfinite(pooled) and abs(half_difference) > 2 * pooled),
118+
}
119+
120+
121+
def complementary_log_difficulty(
122+
block_a: np.ndarray, block_b: np.ndarray, stabilizer: float = 0.25
123+
) -> float:
124+
"""Return the frozen realized complementary-block log-difficulty proxy."""
125+
difference = float(np.mean(_finite(block_a)) - np.mean(_finite(block_b)))
126+
return float(np.log(0.5 * difference**2 + stabilizer**2))

0 commit comments

Comments
 (0)