diff --git a/src/tea_modulo/legacy/preprocessing/__init__.py b/src/tea_modulo/legacy/preprocessing/__init__.py index a866e3c..a5520f0 100644 --- a/src/tea_modulo/legacy/preprocessing/__init__.py +++ b/src/tea_modulo/legacy/preprocessing/__init__.py @@ -1 +1,13 @@ -"""Legacy: the director's code, ported as it is (see tools/vendor_legacy.py).""" +""" +Legacy preprocessing: the director's preproceso.procesar (biomarcadores-tea +@ 7dfc641, vendored unchanged in `_director/`) behind the Preprocessor protocol. +""" + +from tea_modulo.legacy.preprocessing.api import ( + MODULE, + LegacyPreprocessing, + PlanNotSupported, + windows_from_qc, +) + +__all__ = ["MODULE", "LegacyPreprocessing", "PlanNotSupported", "windows_from_qc"] diff --git a/src/tea_modulo/legacy/preprocessing/api.py b/src/tea_modulo/legacy/preprocessing/api.py new file mode 100644 index 0000000..eb7ec0f --- /dev/null +++ b/src/tea_modulo/legacy/preprocessing/api.py @@ -0,0 +1,184 @@ +""" +Legacy preprocessing: the director's `preproceso.procesar` (vendored unchanged +in `_director/`) behind the `Preprocessor` protocol. + +Run order, as in `un_estudio.procesar` step 5: + edf_convert.convertir -> lote.excluidos_para_qc (validation table) + -> lote.qc_estudio (4 s window QC, for the window table) + -> preproceso.procesar(tabla_val, linea_hz, pasa_altas, pasa_bajas, ancho_red) + +The plan dict is mapped onto the director's parameters. What his code cannot +do is refused with a message (never silently ignored): + - `zapline`, a notch `min_db` other than his NOTCH_MIN_DB (6 dB); + - manual `bads` (his code decides the channels); + - a variant whose reference he does not write. +His code always writes every high-pass x reference he computes; only the +variants named in the plan are returned. +""" + +from __future__ import annotations + +import contextlib +import io +import json +import tempfile +import warnings +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd + +from tea_modulo.contracts import CONTRACT_VERSION, Preprocessed, ValidationSummary, sha256_of + +DIRECTOR_COMMIT = "7dfc641" +_SUFFIX = {"average": "prom", "linked_ears": "orejas"} + + +class PlanNotSupported(ValueError): + """The plan asks for something the director's code cannot do.""" + + +class LegacyPreprocessing: + name = "preprocessing" + version = f"0.1.0+director.{DIRECTOR_COMMIT}" + contract_version = CONTRACT_VERSION + impl = "legacy" + + # ---------------------------------------------------------------- plan + def plan_for(self, summary: ValidationSummary, base: Mapping[str, Any]) -> dict: + """The base plan for this study: the director decides bads and notch at run time, + so only the ear variants are dropped when the ears are not usable.""" + plan = json.loads(json.dumps(dict(base))) + if not summary.ears_usable: + plan["variants"] = [v for v in plan["variants"] if v["reference"] != "linked_ears"] + plan.setdefault("reasons", {})["variants"] = "ears not usable: linked-ears variants dropped" + return plan + + def director_args(self, plan: Mapping[str, Any]) -> dict: + """The plan as preproceso.procesar arguments; refuses what it cannot honour.""" + from ._director import preproceso + + if plan.get("schema") != 1: + raise PlanNotSupported(f"plan schema {plan.get('schema')} is not supported") + steps = {s["kind"]: s.get("params", {}) for s in plan.get("steps", [])} + if "zapline" in steps: + raise PlanNotSupported("the director's code has no zapline step") + notch = steps.get("interpolated_notch") + if notch is None: + raise PlanNotSupported("the director's code always evaluates the interpolated notch") + if float(notch.get("min_db", preproceso.NOTCH_MIN_DB)) != preproceso.NOTCH_MIN_DB: + raise PlanNotSupported(f"notch min_db is fixed at {preproceso.NOTCH_MIN_DB} dB " + f"in the director's code") + if plan.get("bads"): + raise PlanNotSupported("manual bads: the director's code decides the channels") + if "lowpass" not in steps: + raise PlanNotSupported("the director's code always low-passes") + refs = {v["reference"] for v in plan["variants"]} + if not refs <= set(_SUFFIX): + raise PlanNotSupported(f"references {refs - set(_SUFFIX)} are not written by the director") + return { + "linea_hz": float(plan.get("line_hz", 60.0)), + "pasa_altas": tuple(sorted({float(v["highpass_hz"]) for v in plan["variants"]})), + "pasa_bajas": float(steps["lowpass"]["hz"]), + "metodo_red": "interpolacion", + "ancho_red": float(notch.get("width_hz", 1.5)), + } + + # ---------------------------------------------------------------- run + def run(self, edf_path, plan: Mapping[str, Any], *, age_months: float | None = None) -> Preprocessed: + import mne + + from ._director import edf_convert, lote, preproceso + + args = self.director_args(plan) + edf_path = Path(edf_path) + nombre = edf_path.stem + with tempfile.TemporaryDirectory(prefix="tea_legacy_pre_") as tmp, \ + contextlib.redirect_stdout(io.StringIO()), warnings.catch_warnings(): + warnings.simplefilter("ignore") + conv, pre = Path(tmp) / "convertidos", Path(tmp) / "preprocesado" + conv.mkdir() + edf_convert.convertir(edf_path, conv) + npz = conv / nombre / f"{nombre}_signals.npz" + meta = conv / nombre / f"{nombre}_metadata.json" + excluir, tabla = lote.excluidos_para_qc(npz, meta, args["linea_hz"]) + qc = lote.qc_estudio(npz, meta, linea_hz=args["linea_hz"], nombre_estudio=nombre, + excluir=excluir) + tabla["estudio"] = nombre + fila = preproceso.procesar(conv / nombre, pre, tabla_val=tabla, **args) + with np.load(pre / nombre / f"{nombre}_preproc.npz") as z: + arrays = {k: z[k] for k in z.files} + proc = json.loads(str(arrays["procedencia"])) + + fs = float(arrays["fs_hz"]) + cuero = [str(c) for c in arrays["canales"]] + aux = [str(c) for c in arrays.get("canales_aux", np.array([]))] + anns = _annotations(proc.get("eventos", []), fs) + variants = {} + for v in plan["variants"]: + etq = f"{float(v['highpass_hz']):g}".replace(".", "") + key = f"signals_hp{etq}_{_SUFFIX[v['reference']]}_uV" + if key not in arrays: + raise PlanNotSupported(f"variant {v['name']}: the director did not write {key} " + f"(ear reference needs both ears usable)") + x = arrays[key].astype(np.float64) + names, types = list(cuero), ["eeg"] * len(cuero) + ak = f"aux_hp{etq}_uV" + if aux and ak in arrays: + x = np.hstack([x, arrays[ak].astype(np.float64)]) + names += aux + types += ["ecg" if a == "EKG" else "eog" for a in aux] + info = mne.create_info(names, fs, types) + raw = mne.io.RawArray(x.T * 1e-6, info, verbose="error") + raw.set_annotations(anns) + variants[v["name"]] = raw + + n = next(iter(variants.values())).n_times + windows = windows_from_qc(qc.get("_por_ventana", []), n / fs, + float(plan.get("window_s", 4.0)), float(plan.get("step_s", 2.0))) + plan_out = {**dict(plan), "director": {**{k: v for k, v in fila.items() if k != "archivo"}, + "args": {**args, "pasa_altas": list(args["pasa_altas"])}}} + return Preprocessed(variants=variants, windows=windows, age_months=age_months, + plan=plan_out, plan_hash=str(plan.get("hash", "")), + source_sha256=sha256_of(edf_path)) + + +def windows_from_qc(qc_windows, duration_s: float, window_s: float, step_s: float) -> pd.DataFrame: + """ + The analysis window grid (window_s / step_s) with flags from the director's + 4 s back-to-back QC: clean if every QC window it overlaps is 'limpia' and + outside the set-up ('montaje'); gap if any overlapped QC window is 'HUECO'. + Windows that reach past the last QC window are not clean. + """ + starts = np.arange(0.0, duration_s - window_s + 1e-9, step_s) + q = pd.DataFrame(qc_windows) if qc_windows else pd.DataFrame( + columns=["t_ini", "t_fin", "veredicto", "montaje"]) + clean, gap = [], [] + for s in starts: + e = s + window_s + o = q[(q.t_ini < e) & (q.t_fin > s)] if len(q) else q + covered = len(o) > 0 and float(o.t_fin.max()) >= e - 1e-6 and float(o.t_ini.min()) <= s + 1e-6 + clean.append(bool(covered and (o.veredicto == "limpia").all() + and not o.get("montaje", pd.Series(False, index=o.index)).any())) + gap.append(bool(len(o) and (o.veredicto == "HUECO").any())) + return pd.DataFrame({"start_s": starts, "end_s": starts + window_s, + "clean": np.array(clean, bool), "gap": np.array(gap, bool)}) + + +def _annotations(eventos, fs): + import mne + on, du, de = [], [], [] + for e in eventos: + t = e.get("t_seg") + if t is None: + continue + fin = e.get("stamp_fin") + on.append(float(t)) + du.append(max(0.0, fin / fs - float(t)) if fin is not None else 0.0) + de.append(str(e.get("texto") or "")) + return mne.Annotations(on, du, de) + + +MODULE = LegacyPreprocessing() diff --git a/src/tea_modulo/preprocessing/__init__.py b/src/tea_modulo/preprocessing/__init__.py new file mode 100644 index 0000000..99162ba --- /dev/null +++ b/src/tea_modulo/preprocessing/__init__.py @@ -0,0 +1,16 @@ +""" +Preprocessing: PreprocessPlan, the default plans and (later) the modern +Preprocessor built on MNE. +""" + +from tea_modulo.preprocessing.defaults import DIRECTOR_CLI, DIRECTOR_CLUSTER, PLANS +from tea_modulo.preprocessing.plan import ( + GateSettings, + PreprocessPlan, + StateSettings, + StepSpec, + VariantSpec, +) + +__all__ = ["PreprocessPlan", "StepSpec", "VariantSpec", "StateSettings", "GateSettings", + "DIRECTOR_CLUSTER", "DIRECTOR_CLI", "PLANS"] diff --git a/src/tea_modulo/preprocessing/defaults.py b/src/tea_modulo/preprocessing/defaults.py new file mode 100644 index 0000000..3db1f90 --- /dev/null +++ b/src/tea_modulo/preprocessing/defaults.py @@ -0,0 +1,44 @@ +""" +The two routes of the director's code as named plans (the CLI/cluster +differences of the pipeline map become data). + +- DIRECTOR_CLUSTER (default): what biomarcadores-tea runs on the cluster + (parametros.toml [director]): low-pass 100 Hz, hp05 variants, HK1K state + cut-offs, gates always on, state mask on. +- DIRECTOR_CLI: the director's scripts as run by hand: low-pass 45 Hz + (preproceso.PASA_BAJAS), hp03 and hp05 variants (PASA_ALTAS = (0.3, 0.5)), + cohort KMeans cut-offs, N2/N3 on, no state mask. Gates on (they were + optional on the CLI; here they are always applied). +""" + +from tea_modulo.preprocessing.plan import ( + GateSettings, + PreprocessPlan, + StateSettings, + StepSpec, + VariantSpec, +) + +_NOTCH = StepSpec("interpolated_notch", {"min_db": 6.0, "width_hz": 1.5}) + +DIRECTOR_CLUSTER = PreprocessPlan( + name="director-cluster", + steps=(StepSpec("drop_channels"), _NOTCH, StepSpec("lowpass", {"hz": 100.0})), + variants=(VariantSpec("hp05_prom", 0.5, "average"), + VariantSpec("hp05_orejas", 0.5, "linked_ears")), + state=StateSettings(mask=True, cutoffs="hk1k", use_n3=False), + gates=GateSettings(min_clean=0.60, min_scalp=12, skip_no_analizable=True), +) + +DIRECTOR_CLI = PreprocessPlan( + name="director-cli", + steps=(StepSpec("drop_channels"), _NOTCH, StepSpec("lowpass", {"hz": 45.0})), + variants=(VariantSpec("hp03_prom", 0.3, "average"), + VariantSpec("hp03_orejas", 0.3, "linked_ears"), + VariantSpec("hp05_prom", 0.5, "average"), + VariantSpec("hp05_orejas", 0.5, "linked_ears")), + state=StateSettings(mask=False, cutoffs="cohort", use_n3=True), + gates=GateSettings(min_clean=0.60, min_scalp=12, skip_no_analizable=True), +) + +PLANS = {p.name: p for p in (DIRECTOR_CLUSTER, DIRECTOR_CLI)} diff --git a/src/tea_modulo/preprocessing/plan.py b/src/tea_modulo/preprocessing/plan.py new file mode 100644 index 0000000..d14719f --- /dev/null +++ b/src/tea_modulo/preprocessing/plan.py @@ -0,0 +1,165 @@ +""" +PreprocessPlan: every choice of one preprocessing run, as data. + +`run()` reads only the plan, so the plan you log is the plan that ran. The +plan crosses module boundaries as a schema-tagged dict (`to_dict`), so other +modules (and the legacy preprocessing) never import this class. + + plan = PreprocessPlan.from_dict(d) + plan = plan.with_step("lowpass", hz=70) + plan.content_hash() +""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Mapping +from dataclasses import asdict, dataclass, field, fields, replace +from typing import Any + +SCHEMA = 1 +REFERENCES = ("average", "linked_ears") +STEP_KINDS = ("drop_channels", "interpolated_notch", "zapline", "lowpass") + + +@dataclass(frozen=True) +class StepSpec: + kind: str + params: Mapping[str, Any] = field(default_factory=dict) + + def __post_init__(self): + if self.kind not in STEP_KINDS: + raise ValueError(f"unknown step {self.kind!r}; known steps: {', '.join(STEP_KINDS)}") + object.__setattr__(self, "params", dict(self.params)) + + +@dataclass(frozen=True) +class VariantSpec: + name: str + highpass_hz: float + reference: str + + def __post_init__(self): + if self.reference not in REFERENCES: + raise ValueError(f"variant {self.name}: reference must be one of " + f"{', '.join(REFERENCES)}, not {self.reference!r}") + if not self.highpass_hz > 0: + raise ValueError(f"variant {self.name}: highpass_hz must be > 0") + + +@dataclass(frozen=True) +class StateSettings: + mask: bool = True # only clean, unannotated windows get a state + cutoffs: str = "hk1k" # "hk1k" (fixed, E13) | "cohort" (KMeans on the run) + use_n3: bool = False + + def __post_init__(self): + if self.cutoffs not in ("hk1k", "cohort"): + raise ValueError(f"state.cutoffs must be 'hk1k' or 'cohort', not {self.cutoffs!r}") + + +@dataclass(frozen=True) +class GateSettings: + min_clean: float = 0.60 + min_scalp: int = 12 + skip_no_analizable: bool = True + + +@dataclass(frozen=True) +class PreprocessPlan: + name: str + steps: tuple[StepSpec, ...] + variants: tuple[VariantSpec, ...] + line_hz: float = 60.0 + window_s: float = 4.0 + step_s: float = 2.0 + state: StateSettings = field(default_factory=StateSettings) + gates: GateSettings = field(default_factory=GateSettings) + bads: tuple[str, ...] = () + reasons: dict[str, str] = field(default_factory=dict, hash=False, compare=False) + + def __post_init__(self): + object.__setattr__(self, "steps", tuple( + s if isinstance(s, StepSpec) else StepSpec(**s) for s in self.steps)) + object.__setattr__(self, "variants", tuple( + v if isinstance(v, VariantSpec) else VariantSpec(**v) for v in self.variants)) + if isinstance(self.state, Mapping): + object.__setattr__(self, "state", StateSettings(**self.state)) + if isinstance(self.gates, Mapping): + object.__setattr__(self, "gates", GateSettings(**self.gates)) + object.__setattr__(self, "bads", tuple(self.bads)) + object.__setattr__(self, "reasons", dict(self.reasons)) + self._check() + + def _check(self): + if not self.variants: + raise ValueError("the plan has no variant") + names = [v.name for v in self.variants] + if len(set(names)) != len(names): + raise ValueError(f"repeated variant names: {names}") + kinds = [s.kind for s in self.steps] + if "interpolated_notch" in kinds and "zapline" in kinds: + raise ValueError("use one line-removal step, not both interpolated_notch and zapline") + if not 0 < self.step_s <= self.window_s: + raise ValueError("windows need 0 < step_s <= window_s") + lp = self.step("lowpass") + if lp is not None: + for v in self.variants: + if not v.highpass_hz < lp.params["hz"]: + raise ValueError(f"variant {v.name}: highpass {v.highpass_hz} Hz must be " + f"below the lowpass {lp.params['hz']} Hz") + + # ------------------------------------------------------------------ access + def step(self, kind: str) -> StepSpec | None: + return next((s for s in self.steps if s.kind == kind), None) + + def with_step(self, kind: str, **params) -> PreprocessPlan: + """Change the params of a step (added at the end if absent).""" + steps, done = [], False + for s in self.steps: + if s.kind == kind: + steps.append(StepSpec(kind, {**s.params, **params})) + done = True + else: + steps.append(s) + if not done: + steps.append(StepSpec(kind, params)) + return replace(self, steps=tuple(steps)) + + def without(self, *channels: str, reason: str) -> PreprocessPlan: + if not isinstance(reason, str) or not reason.strip(): + raise ValueError("without() needs a reason: a manual exclusion changes the average reference") + new = tuple(c for c in dict.fromkeys(channels) if c not in self.bads) + return replace(self, bads=self.bads + new, + reasons={**self.reasons, **{c: reason for c in new}}) + + # ------------------------------------------------------------------ serialisation + def to_dict(self) -> dict: + d = asdict(self) + d["steps"] = [{"kind": s.kind, "params": dict(s.params)} for s in self.steps] + d["schema"] = SCHEMA + d["hash"] = self.content_hash() + return d + + @classmethod + def from_dict(cls, d: Mapping[str, Any]) -> PreprocessPlan: + d = dict(d) + schema = d.pop("schema", SCHEMA) + d.pop("hash", None) + if schema != SCHEMA: + raise ValueError(f"plan schema {schema} is not supported (this library reads {SCHEMA})") + known = {f.name for f in fields(cls)} + unknown = set(d) - known + if unknown: + raise ValueError(f"unknown plan keys: {', '.join(sorted(unknown))}") + return cls(**d) + + def content_hash(self) -> str: + """SHA-256 of the canonical JSON, without `reasons` and the per-study `bads`.""" + d = asdict(self) + d.pop("reasons") + d.pop("bads") + d["steps"] = [{"kind": s.kind, "params": dict(s.params)} for s in self.steps] + blob = json.dumps(d, sort_keys=True, separators=(",", ":"), default=float) + return hashlib.sha256(blob.encode()).hexdigest()[:16] diff --git a/tests/legacy/test_legacy_preprocessing.py b/tests/legacy/test_legacy_preprocessing.py new file mode 100644 index 0000000..6580619 --- /dev/null +++ b/tests/legacy/test_legacy_preprocessing.py @@ -0,0 +1,97 @@ +"""Legacy preprocessing = the director's preproceso.procesar, exactly.""" + +from __future__ import annotations + +import json +import subprocess +import sys +from pathlib import Path + +import numpy as np +import pytest + +from synth_edf import make_edf +from tea_modulo.contracts.testing import check_preprocessed +from tea_modulo.legacy.preprocessing import MODULE, PlanNotSupported, windows_from_qc +from tea_modulo.legacy.validation import MODULE as VAL +from tea_modulo.preprocessing import DIRECTOR_CLI, DIRECTOR_CLUSTER + +ROOT = Path(__file__).resolve().parents[2] +PREPROCESO = ROOT / "biomarcadores-tea" / "preproceso" + + +@pytest.fixture(scope="module") +def edf(tmp_path_factory): + return make_edf(tmp_path_factory.mktemp("legpre") / "s.edf", minutes=5, bad={"bursts": ["P4"]}) + + +def _director_preproc(edf_path: Path, out: Path, args: dict): + code = f""" +import sys, tempfile, contextlib, io +from pathlib import Path +sys.path.insert(0, {str(PREPROCESO)!r}) +import edf_convert, lote, preproceso +p = Path({str(edf_path)!r}); nombre = p.stem +with tempfile.TemporaryDirectory() as tmp, contextlib.redirect_stdout(io.StringIO()): + conv = Path(tmp) / "c"; conv.mkdir() + edf_convert.convertir(p, conv) + npz = conv / nombre / f"{{nombre}}_signals.npz"; meta = conv / nombre / f"{{nombre}}_metadata.json" + _, tabla = lote.excluidos_para_qc(npz, meta, {args['linea_hz']}) + tabla["estudio"] = nombre + preproceso.procesar(conv / nombre, Path({str(out)!r}), tabla_val=tabla, + linea_hz={args['linea_hz']}, pasa_altas={tuple(args['pasa_altas'])!r}, + pasa_bajas={args['pasa_bajas']}, metodo_red="interpolacion", + ancho_red={args['ancho_red']}) +""" + subprocess.run([sys.executable, "-W", "ignore", "-c", code], check=True, capture_output=True) + with np.load(out / edf_path.stem / f"{edf_path.stem}_preproc.npz") as z: + return {k: z[k] for k in z.files} + + +@pytest.mark.skipif(not PREPROCESO.exists(), reason="submodule absent") +@pytest.mark.parametrize("base", [DIRECTOR_CLUSTER, DIRECTOR_CLI], ids=lambda p: p.name) +def test_legacy_equals_submodule(edf, tmp_path, base): + plan = MODULE.plan_for(VAL.summarize(edf), base.to_dict()) + prep = MODULE.run(edf, plan) + ref = _director_preproc(edf, tmp_path, MODULE.director_args(plan)) + cuero = [str(c) for c in ref["canales"]] + for v in plan["variants"]: + etq = f"{v['highpass_hz']:g}".replace(".", "") + suf = {"average": "prom", "linked_ears": "orejas"}[v["reference"]] + got = prep.variant(v["name"]).get_data(picks=cuero) * 1e6 + want = ref[f"signals_hp{etq}_{suf}_uV"].astype(np.float64).T + np.testing.assert_allclose(got, want, rtol=1e-9, atol=1e-9) + + +def test_contract_and_variants(edf): + prep = MODULE.run(edf, MODULE.plan_for(VAL.summarize(edf), DIRECTOR_CLUSTER.to_dict())) + check_preprocessed(prep) + raw = prep.variant("hp05_prom") + assert "P4" not in raw.ch_names # bursting electrode dropped + assert set(raw.get_channel_types(picks=["LOC", "EKG"])) == {"eog", "ecg"} + assert prep.plan["director"]["fs_hz"] == 250.0 + assert prep.windows.clean.mean() > 0.9 + + +def test_refuses_what_the_director_cannot_do(): + base = DIRECTOR_CLUSTER.to_dict() + for change, msg in [ + (lambda d: d["steps"].__setitem__(1, {"kind": "zapline", "params": {}}), "zapline"), + (lambda d: d["steps"][1]["params"].__setitem__("min_db", 3.0), "min_db"), + (lambda d: d.__setitem__("bads", ["Fz"]), "manual bads"), + ]: + d = json.loads(json.dumps(base)) + change(d) + with pytest.raises(PlanNotSupported, match=msg): + MODULE.director_args(d) + + +def test_windows_from_qc(): + qc = [{"t_ini": 0.0, "t_fin": 4.0, "veredicto": "limpia", "montaje": True}, + {"t_ini": 4.0, "t_fin": 8.0, "veredicto": "limpia", "montaje": False}, + {"t_ini": 8.0, "t_fin": 12.0, "veredicto": "sospechosa", "montaje": False}, + {"t_ini": 12.0, "t_fin": 16.0, "veredicto": "HUECO", "montaje": False}] + w = windows_from_qc(qc, 16.0, 4.0, 2.0) + assert list(w.start_s) == [0, 2, 4, 6, 8, 10, 12] + assert list(w.clean) == [False, False, True, False, False, False, False] + assert list(w.gap) == [False, False, False, False, False, True, True] diff --git a/tests/test_plan.py b/tests/test_plan.py new file mode 100644 index 0000000..b35469e --- /dev/null +++ b/tests/test_plan.py @@ -0,0 +1,52 @@ +"""PreprocessPlan: checks, round trip, hash.""" + +from __future__ import annotations + +import json + +import pytest + +from tea_modulo.preprocessing import ( + DIRECTOR_CLI, + DIRECTOR_CLUSTER, + PreprocessPlan, + StepSpec, + VariantSpec, +) + + +def test_round_trip_through_json(): + for plan in (DIRECTOR_CLUSTER, DIRECTOR_CLI): + d = json.loads(json.dumps(plan.to_dict())) + again = PreprocessPlan.from_dict(d) + assert again == plan + assert again.content_hash() == plan.content_hash() == d["hash"] + + +def test_hash_ignores_reasons_and_bads_but_not_parameters(): + p = DIRECTOR_CLUSTER + assert p.without("Fz", reason="test").content_hash() == p.content_hash() + assert p.with_step("lowpass", hz=70).content_hash() != p.content_hash() + + +def test_checks(): + with pytest.raises(ValueError, match="unknown step"): + StepSpec("wavelet") + with pytest.raises(ValueError, match="reference"): + VariantSpec("x", 0.5, "ipsilateral") + with pytest.raises(ValueError, match="below the lowpass"): + DIRECTOR_CLUSTER.with_step("lowpass", hz=0.4) + with pytest.raises(ValueError, match="one line-removal"): + DIRECTOR_CLUSTER.with_step("zapline") + with pytest.raises(ValueError, match="unknown plan keys"): + PreprocessPlan.from_dict({**DIRECTOR_CLUSTER.to_dict(), "lowpas": 3}) + with pytest.raises(ValueError, match="reason"): + DIRECTOR_CLUSTER.without("Fz", reason=" ") + + +def test_route_differences_are_data(): + c, l = DIRECTOR_CLUSTER, DIRECTOR_CLI + assert c.step("lowpass").params["hz"] == 100 and l.step("lowpass").params["hz"] == 45 + assert c.state.cutoffs == "hk1k" and l.state.cutoffs == "cohort" + assert c.state.mask and not l.state.mask + assert l.state.use_n3 and not c.state.use_n3