#!/usr/bin/env python3
"""FlashMemory MOS-C learning model only. Python 3 stdlib; not a calibrated CV tool."""
import csv
import json
from pathlib import Path

path = Path(__file__).with_name("mos-cv-synthetic.csv")
rows = list(csv.DictReader(path.open(encoding="utf-8", newline="")))
curves = {}
for r in rows:
    key = r["sample"], r["mode"]
    v = float(r["vgs_v"])
    c = float(r["c_over_cox"])
    if key[0] not in ("Reference", "Comparison") or key[1] not in ("HF", "LF"):
        raise ValueError("Unexpected model category")
    if not (0 < c <= 1) or float(r["temp_c"]) != 25:
        raise ValueError("Out-of-range teaching value")
    curves.setdefault(key, {})[v] = c
assert len(rows) == 52
assert len(curves) == 4
assert all(len(v) == 13 for v in curves.values())

def find_shift(mode):
    reference = curves["Reference", mode]
    comparison = curves["Comparison", mode]
    results = []
    for shift in [-1, -0.5, 0, 0.5, 1]:
        paired = [(c, reference[v-shift]) for v,c in comparison.items() if v-shift in reference]
        if len(paired) < 10:
            continue
        mse = sum((c-ref)**2 for c,ref in paired)/len(paired)
        results.append((mse, shift, len(paired)))
    mse, shift, count = min(results)
    return {"horizontal_shift_v":shift, "paired_points":count, "mean_squared_error":round(mse,12)}
hf = find_shift("HF")
lf = find_shift("LF")
assert hf["horizontal_shift_v"] == 0.5 and lf["horizontal_shift_v"] == 0.5
c_hf = curves["Reference","HF"][3.0]
c_lf = curves["Reference","LF"][3.0]
assert c_lf > c_hf
result = {
 "dataset":"SYNTHETIC_TRAINING_ONLY",
 "samples":2,
 "modes":["HF","LF"],
 "data_rows":len(rows),
 "teaching_curve_alignment":{"HF":hf,"LF":lf},
 "reference_c_over_cox_at_vgs_3v":{"HF":round(c_hf,5),"LF":round(c_lf,5)},
 "limits":"This alignment is an imposed synthetic translation, not a flat-band-voltage, oxide-charge, Dit, physical-thickness or failure-mechanism extraction."
}
print(json.dumps(result,ensure_ascii=False,indent=2))
