Library only: remove tests, cluster verification, deploy tooling and submodules
Pipeline.map keeps its API. Development-cluster specifics removed: the DASK_SCHEDULER variable (DASK_SCHEDULER_ADDRESS stays), direct_to_workers=False, the shared-cluster priority rule (default priority 0) and the SeaweedFS S3 defaults. README: install as a submodule, batches.
This commit is contained in:
@@ -1,19 +0,0 @@
|
||||
.git
|
||||
**/.git
|
||||
.venv/
|
||||
eeg/
|
||||
**/__pycache__/
|
||||
**/.pytest_cache/
|
||||
**/mlruns/
|
||||
**/datos/
|
||||
**/salidas/
|
||||
**/*.edf
|
||||
**/*.EDF
|
||||
**/*.npz
|
||||
**/*.parquet
|
||||
**/*.erd
|
||||
**/*.eeg
|
||||
**/*_metadata.json
|
||||
biomarcadores-tea/experimentos/**/salidas/
|
||||
mlflow_local/
|
||||
**/mlflow_local/
|
||||
@@ -1,6 +0,0 @@
|
||||
[submodule "biomarcadores-tea"]
|
||||
path = biomarcadores-tea
|
||||
url = ssh://git@10.0.10.41:2222/ulises/biomarcadores-tea.git
|
||||
[submodule "codigo"]
|
||||
path = codigo
|
||||
url = ssh://git@10.0.10.41:2222/francisco/codigo.git
|
||||
@@ -12,7 +12,7 @@ https://claude.ai/artifact/H9Rh19Lv79dVeikeVD9KFZ
|
||||
|---|---|---|
|
||||
| Code | the director's methods on MNE, SciPy, scikit-learn, antropy, fooof, meegkit | the director's code (biomarcadores-tea @ 7dfc641, codigo @ c7a4736) copied unchanged except imports |
|
||||
| Batches | Dask (`cluster="auto"/"remote"/"local"/"sync"`) | plain single-threaded loop |
|
||||
| Checked against | legacy, on synthetic EDFs | the submodule's own scripts, exactly |
|
||||
| Provenance | written against legacy (equal to float32 precision without acquisition gaps) | each file's header names its source file and commit |
|
||||
|
||||
## Modules
|
||||
|
||||
@@ -47,7 +47,7 @@ study = pipe.study("study.edf", plan=DIRECTOR_CLUSTER, age_months=27.5)
|
||||
pipe.biomarker("posterior_rhythm").measure(study)
|
||||
|
||||
table = pipe.map(paths, plan=DIRECTOR_CLUSTER, ages_months=ages,
|
||||
biomarkers=("posterior_rhythm", "spindles")) # Dask: cluster or LocalCluster
|
||||
biomarkers=("posterior_rhythm", "spindles")) # Dask: LocalCluster, or scheduler=
|
||||
rhythm = pipe.biomarker("posterior_rhythm").train(table) # baseline: curves or age_blocks
|
||||
rhythm.predict(table.iloc[[0]]) # outside -1/0/+1, z
|
||||
|
||||
@@ -58,22 +58,25 @@ Replace a module: `pipe.replace("spindle_detection", MyDetector())`, or register
|
||||
it under the same name in the `tea.modules` entry-point group. Check it
|
||||
with `tea.contracts.testing`.
|
||||
|
||||
## Tests and cluster verification
|
||||
## Install
|
||||
|
||||
- `uv run pytest` (synthetic EDFs only; no patient data).
|
||||
- Cluster checks live in `verification/`, outside the package (not in the
|
||||
wheel). `deploy/verify.sh` builds `tea-verify:<commit>` from this checkout and
|
||||
runs one in a `DaskJob` of its own:
|
||||
- `deploy/verify.sh` (`hk1k`): the test suite plus `python -m verification hk1k`
|
||||
(HK1K, public, `raw/eeg-helsinki/`);
|
||||
- `deploy/verify.sh issste`: `python -m verification issste` on
|
||||
`processed/eeg-edf-2025/` and `eeg-edf-2026/`, with every biomarker in both
|
||||
implementations.
|
||||
- `deploy/verify.sh --logs`, `--delete`.
|
||||
- `python tools/vendor_legacy.py --check` confirms the legacy copies are
|
||||
unchanged.
|
||||
Python ≥ 3.12. As a git submodule of another project:
|
||||
|
||||
The unit tests never read patient data. Both cluster checks write group
|
||||
summaries only, to `processed/usuarios/`. The ISSSTELEÓN check keeps file
|
||||
names, paths, birthdates and per-study rows inside the job (the 2026 file names
|
||||
carry the patient's surname), and suppresses groups under 5.
|
||||
```sh
|
||||
git submodule add ssh://git@10.0.10.41:2222/alberto/tea.git libs/tea
|
||||
uv add --editable ./libs/tea # or: pip install -e libs/tea
|
||||
```
|
||||
|
||||
or as a plain dependency: `uv add "tea @ git+ssh://git@10.0.10.41:2222/alberto/tea.git"`.
|
||||
Extras: `tea[s3]` reads `s3://` paths (endpoint and keys from the environment),
|
||||
`tea[export]` for the KTLX → EDF exporter.
|
||||
|
||||
## Batches
|
||||
|
||||
`Pipeline.map(..., cluster=)` runs the modern pipeline as a Dask graph:
|
||||
`"local"` (a LocalCluster on this machine), `"sync"` (one study at a time, in
|
||||
this process), `"remote"` with `scheduler="tcp://host:8786"` (any Dask
|
||||
scheduler you provide), or `"auto"` (`scheduler=` / `DASK_SCHEDULER_ADDRESS`
|
||||
if set, otherwise local). Legacy always runs a plain single-threaded loop.
|
||||
A study that fails becomes a row with `error` set; it never stops the batch.
|
||||
Rows carry the caller's `key`, never file names, paths or dates.
|
||||
|
||||
Submodule biomarcadores-tea deleted from 7dfc641b09
-1
Submodule codigo deleted from c7a4736069
@@ -1,19 +0,0 @@
|
||||
# tea-verify: the team's dask image plus what the tea verification needs.
|
||||
# Built from the local checkout (submodules included) by deploy/verify.sh.
|
||||
FROM 192.168.20.18:5000/dask:1.1
|
||||
|
||||
# missing from dask:1.1; versions as checked locally
|
||||
RUN pip install --no-cache-dir "antropy==0.2.3" "fhir.resources==8.3.0" "meegkit==0.2.0" pytest
|
||||
|
||||
# tea from the local checkout (biomarcadores-tea @ 7dfc641, codigo @ c7a4736:
|
||||
# the legacy = submodule tests need them). .dockerignore keeps .venv, eeg/ and any
|
||||
# signal or patient file out of the build context.
|
||||
COPY . /opt/tea
|
||||
ARG TEA_COMMIT=unknown
|
||||
ENV TEA_COMMIT=$TEA_COMMIT
|
||||
LABEL tea.commit=$TEA_COMMIT
|
||||
RUN pip install --no-cache-dir --no-deps -e /opt/tea
|
||||
WORKDIR /opt/tea
|
||||
# verification/ (cluster checks) is not in the package: import it from the checkout,
|
||||
# on the runner and on the workers
|
||||
ENV PYTHONPATH=/opt/tea
|
||||
@@ -1,74 +0,0 @@
|
||||
# tea-verify: a cluster check of tea in its own Dask cluster, 9 pods.
|
||||
# hk1k: test suite + HK1K check; 4 workers per pod x 4.25 GiB
|
||||
# issste: ISSSTELEÓN check on processed/eeg-edf-2025|2026 (group summaries
|
||||
# only); 3 workers per pod x 6 GiB (long recordings)
|
||||
# Applied by deploy/verify.sh, which substitutes COMMIT, CHECK, NWORKERS and
|
||||
# MEMLIMIT. The eeg-data PVC is NOT mounted; S3 is read in the tasks only.
|
||||
apiVersion: kubernetes.dask.org/v1
|
||||
kind: DaskJob
|
||||
metadata:
|
||||
name: tea-verify
|
||||
spec:
|
||||
job:
|
||||
spec:
|
||||
restartPolicy: Never
|
||||
containers:
|
||||
- name: job
|
||||
image: 192.168.20.18:5000/tea-verify:COMMIT
|
||||
workingDir: /opt/tea
|
||||
command: [sh, -c]
|
||||
args:
|
||||
- |
|
||||
set -e
|
||||
export DASK_SCHEDULER="$DASK_SCHEDULER_ADDRESS"
|
||||
export MLFLOW_DISABLE_AGENT_HINT=1
|
||||
if [ "CHECK" = hk1k ]; then
|
||||
python -m pytest -q -p no:cacheprovider -m "not cluster"
|
||||
python -m pytest -q -p no:cacheprovider -m cluster
|
||||
fi
|
||||
python -m verification CHECK --out processed/usuarios/alberto/tea-verify/
|
||||
env:
|
||||
- {name: OMP_NUM_THREADS, value: "1"}
|
||||
- {name: OPENBLAS_NUM_THREADS, value: "1"}
|
||||
- {name: MKL_NUM_THREADS, value: "1"}
|
||||
- {name: TEA_MLFLOW_URI, value: "http://10.0.10.41:5000"}
|
||||
resources:
|
||||
requests: {memory: 6Gi, cpu: "2"}
|
||||
limits: {memory: 6Gi}
|
||||
cluster:
|
||||
spec:
|
||||
worker:
|
||||
replicas: 9
|
||||
spec:
|
||||
containers:
|
||||
- name: worker
|
||||
image: 192.168.20.18:5000/tea-verify:COMMIT
|
||||
args: [dask-worker, --name, $(DASK_WORKER_NAME), --nworkers, "NWORKERS", --nthreads, "1", --memory-limit, MEMLIMIT]
|
||||
resources:
|
||||
requests: {memory: 19Gi, cpu: "4"}
|
||||
limits: {memory: 19Gi}
|
||||
env:
|
||||
- {name: AWS_ENDPOINT_URL, value: "http://seaweedfs-s3.seaweedfs:8333"}
|
||||
- {name: OMP_NUM_THREADS, value: "1"}
|
||||
- {name: OPENBLAS_NUM_THREADS, value: "1"}
|
||||
- {name: MKL_NUM_THREADS, value: "1"}
|
||||
- {name: MLFLOW_DISABLE_AGENT_HINT, value: "1"}
|
||||
envFrom:
|
||||
- secretRef: {name: seaweed-s3}
|
||||
scheduler:
|
||||
spec:
|
||||
containers:
|
||||
- name: scheduler
|
||||
image: 192.168.20.18:5000/tea-verify:COMMIT
|
||||
args: [dask-scheduler]
|
||||
ports:
|
||||
- {name: tcp-comm, containerPort: 8786}
|
||||
- {name: http-dashboard, containerPort: 8787}
|
||||
service:
|
||||
type: ClusterIP
|
||||
selector:
|
||||
dask.org/cluster-name: tea-verify
|
||||
dask.org/component: scheduler
|
||||
ports:
|
||||
- {name: tcp-comm, port: 8786, targetPort: tcp-comm}
|
||||
- {name: http-dashboard, port: 8787, targetPort: http-dashboard}
|
||||
@@ -1,26 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build, push and run the tea-verify DaskJob for the current commit.
|
||||
# deploy/verify.sh [hk1k] build + push + apply: tests + HK1K check
|
||||
# deploy/verify.sh issste build + push + apply: ISSSTELEÓN check (group numbers only)
|
||||
# deploy/verify.sh --logs follow the job pod's log
|
||||
# deploy/verify.sh --delete remove the DaskJob
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
REG=192.168.20.18:5000
|
||||
case "${1:-}" in
|
||||
--logs) exec kubectl logs -f tea-verify-runner ;;
|
||||
--delete) exec kubectl delete daskjob tea-verify --ignore-not-found ;;
|
||||
""|hk1k) CHECK=hk1k; NW=4; MEM=4.25GiB ;;
|
||||
issste) CHECK=issste; NW=3; MEM=6GiB ;;
|
||||
*) echo "usage: deploy/verify.sh [hk1k|issste|--logs|--delete]" >&2; exit 2 ;;
|
||||
esac
|
||||
if [ -n "$(git status --porcelain --ignore-submodules=none)" ]; then
|
||||
echo "uncommitted changes: commit first, so the image tag is a real commit" >&2; exit 1
|
||||
fi
|
||||
C=$(git rev-parse --short HEAD)
|
||||
docker build -f deploy/Dockerfile.verify --build-arg TEA_COMMIT="$C" -t "$REG/tea-verify:$C" .
|
||||
docker push "$REG/tea-verify:$C"
|
||||
kubectl delete daskjob tea-verify --ignore-not-found
|
||||
sed -e "s/tea-verify:COMMIT/tea-verify:$C/g" -e "s/CHECK/$CHECK/g" -e "s/NWORKERS/$NW/g" \
|
||||
-e "s/MEMLIMIT/$MEM/g" deploy/dask-verify.yaml | kubectl apply -f -
|
||||
echo "applied tea-verify:$C ($CHECK) — follow with: deploy/verify.sh --logs"
|
||||
+1
-11
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "tea"
|
||||
version = "0.1.0"
|
||||
description = "Add your description here"
|
||||
description = "Modular EEG biomarker library for TEA: validation, preprocessing, processes and biomarkers, each a replaceable module"
|
||||
readme = "README.md"
|
||||
authors = [
|
||||
{ name = "AlbertoPMDM", email = "albertopmdm@gmail.com" }
|
||||
@@ -73,13 +73,3 @@ ktlx2edf = "tea.export.cli:main"
|
||||
[build-system]
|
||||
requires = ["uv_build>=0.13.1,<0.14.0"]
|
||||
build-backend = "uv_build"
|
||||
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"pytest>=9.2.0",
|
||||
]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
pythonpath = ["tests", "."] # "." for verification/ (cluster checks, not in the wheel)
|
||||
markers = ["cluster: needs a Dask scheduler (DASK_SCHEDULER or DASK_SCHEDULER_ADDRESS)"]
|
||||
|
||||
@@ -99,7 +99,7 @@ class Pipeline:
|
||||
# ------------------------------------------------------------------ batches
|
||||
def map(self, edf_paths: Sequence, *, plan, ages_months: Sequence | None = None,
|
||||
biomarkers: Sequence[str] = (), cluster: str = "auto", scheduler: str | None = None,
|
||||
priority: int = -10, memory_per_worker="4.25GiB", n_workers: int | None = None,
|
||||
priority: int = 0, memory_per_worker="4.25GiB", n_workers: int | None = None,
|
||||
line_hz: float = 60.0, keys: Sequence | None = None, on_result=None) -> pd.DataFrame:
|
||||
"""
|
||||
One row per study. Modern: a Dask graph (cluster='auto'|'remote'|'local'|'sync').
|
||||
|
||||
@@ -4,17 +4,17 @@ The modern pipeline's batch runner: Dask-native.
|
||||
A batch is a graph of `dask.delayed(run_study)` tasks, one per study, built
|
||||
under `dask.annotate(priority=..., retries=1)`. The same graph runs on:
|
||||
|
||||
cluster="remote" (or an address) the team's cluster: Client(addr, direct_to_workers=False)
|
||||
cluster="remote" (or an address) an existing Dask scheduler: Client(addr)
|
||||
cluster="local" a LocalCluster on this computer (processes, 1 thread each,
|
||||
worker count from free RAM / memory_per_worker)
|
||||
cluster="sync" Dask's synchronous scheduler: one task at a time in
|
||||
this process (debugging, tests)
|
||||
cluster="auto" scheduler= / DASK_SCHEDULER / DASK_SCHEDULER_ADDRESS if
|
||||
set, otherwise local
|
||||
cluster="auto" scheduler= / DASK_SCHEDULER_ADDRESS if set, otherwise
|
||||
local
|
||||
|
||||
Cluster rules (biomarcadores-tea/CLAUDE.md) are built in: positive priorities
|
||||
are refused, a remote cluster is only ever `client.close()`d (never restart or
|
||||
shutdown), and a LocalCluster is closed only if this runner started it.
|
||||
A remote scheduler is only ever `client.close()`d (never restarted or shut
|
||||
down: it may be shared), and a LocalCluster is closed only if this runner
|
||||
started it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -27,7 +27,7 @@ BLAS_ENV = {"OMP_NUM_THREADS": "1", "OPENBLAS_NUM_THREADS": "1", "MKL_NUM_THREAD
|
||||
|
||||
|
||||
def scheduler_address(scheduler: str | None = None) -> str | None:
|
||||
return scheduler or os.environ.get("DASK_SCHEDULER") or os.environ.get("DASK_SCHEDULER_ADDRESS")
|
||||
return scheduler or os.environ.get("DASK_SCHEDULER_ADDRESS")
|
||||
|
||||
|
||||
def _bytes(s) -> int:
|
||||
@@ -56,15 +56,15 @@ def client_for(cluster: str = "auto", scheduler: str | None = None,
|
||||
if cluster not in ("auto", "remote", "local", "sync") and "://" in str(cluster):
|
||||
addr = cluster
|
||||
if cluster == "remote" and not addr:
|
||||
raise ValueError("cluster='remote' needs scheduler= or DASK_SCHEDULER / DASK_SCHEDULER_ADDRESS")
|
||||
raise ValueError("cluster='remote' needs scheduler= or DASK_SCHEDULER_ADDRESS")
|
||||
if addr:
|
||||
client = Client(addr, direct_to_workers=False)
|
||||
client = Client(addr)
|
||||
try:
|
||||
if check_versions:
|
||||
client.get_versions(check=True)
|
||||
yield client
|
||||
finally:
|
||||
client.close() # never restart() or shutdown(): shared cluster
|
||||
client.close() # never restart() or shutdown(): it may be shared
|
||||
return
|
||||
lc = LocalCluster(n_workers=local_workers(memory_per_worker, n_workers), threads_per_worker=1,
|
||||
processes=True, memory_limit=memory_per_worker, dashboard_address=None,
|
||||
@@ -78,7 +78,7 @@ def client_for(cluster: str = "auto", scheduler: str | None = None,
|
||||
|
||||
|
||||
def run(fn: Callable, argsets: Sequence[tuple], *, cluster="auto", scheduler=None,
|
||||
priority: int = -10, retries: int = 1, memory_per_worker="4.25GiB",
|
||||
priority: int = 0, retries: int = 1, memory_per_worker="4.25GiB",
|
||||
n_workers: int | None = None, on_result: Callable | None = None,
|
||||
on_error: Callable | None = None) -> list:
|
||||
"""Run fn(*args) for every args in argsets; results in the input order.
|
||||
@@ -88,8 +88,6 @@ def run(fn: Callable, argsets: Sequence[tuple], *, cluster="auto", scheduler=Non
|
||||
the batch; without it the exception propagates."""
|
||||
import dask
|
||||
|
||||
if priority > 0:
|
||||
raise ValueError("positive priorities are not allowed on the shared cluster (use <= 0)")
|
||||
with dask.annotate(priority=priority, retries=retries):
|
||||
tasks = [dask.delayed(fn, pure=False)(*a) for a in argsets]
|
||||
with client_for(cluster, scheduler, memory_per_worker, n_workers) as client:
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
"""
|
||||
Where an EDF comes from: a local path, or an S3 object fetched to a temporary
|
||||
file inside the task (on the team's cluster S3 is reachable only from the
|
||||
workers). The S3 filesystem is created inside the task with the worker's
|
||||
AWS_ENDPOINT_URL and path addressing; keys come from the environment, never
|
||||
from code. Nothing is ever written back to S3 from here.
|
||||
file inside the task (so only the workers need S3 access). The S3 filesystem
|
||||
is created inside the task; endpoint (AWS_ENDPOINT_URL) and keys come from the
|
||||
worker's environment, never from code. Nothing is ever written back to S3.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,9 +19,8 @@ def is_s3(path) -> bool:
|
||||
|
||||
def s3():
|
||||
import s3fs
|
||||
endpoint = os.environ.get("AWS_ENDPOINT_URL", "http://seaweedfs-s3.seaweedfs:8333")
|
||||
return s3fs.S3FileSystem(client_kwargs={"endpoint_url": endpoint},
|
||||
config_kwargs={"s3": {"addressing_style": "path"}})
|
||||
endpoint = os.environ.get("AWS_ENDPOINT_URL")
|
||||
return s3fs.S3FileSystem(client_kwargs={"endpoint_url": endpoint} if endpoint else {})
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
|
||||
def make_prep(seconds=60.0, fs=250.0, channels=("Fp1", "Fp2", "O1", "O2"), seed=0,
|
||||
window_s=4.0, step_s=2.0):
|
||||
"""A small Preprocessed made in memory (white noise, one variant)."""
|
||||
import mne
|
||||
from tea.contracts import Preprocessed
|
||||
|
||||
rng = np.random.default_rng(seed)
|
||||
n = int(seconds * fs)
|
||||
info = mne.create_info(list(channels), fs, ch_types="eeg")
|
||||
raw = mne.io.RawArray(rng.normal(0, 20e-6, (len(channels), n)), info, verbose="error")
|
||||
starts = np.arange(0, seconds - window_s + 1e-9, step_s)
|
||||
windows = pd.DataFrame({"start_s": starts, "end_s": starts + window_s,
|
||||
"clean": np.ones(len(starts), bool),
|
||||
"gap": np.zeros(len(starts), bool)})
|
||||
plan = {"schema": 1, "name": "test"}
|
||||
return Preprocessed(variants={"hp05_prom": raw}, windows=windows, age_months=24.0,
|
||||
plan=plan, plan_hash="test")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def prep():
|
||||
return make_prep()
|
||||
@@ -1,154 +0,0 @@
|
||||
"""
|
||||
The contracts themselves, and the contract suites run against fake modules
|
||||
(the shape a replacement module must have).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from tea.contracts import (
|
||||
CONTRACT_VERSION,
|
||||
DEVIATION_COLUMNS,
|
||||
ContractError,
|
||||
Labels,
|
||||
Preprocessed,
|
||||
Study,
|
||||
check_module,
|
||||
)
|
||||
from tea.contracts.testing import check_biomarker, check_process
|
||||
|
||||
|
||||
class ConstantState:
|
||||
"""A fake process: every window is 'vigilia'."""
|
||||
|
||||
name = "sleep_state"
|
||||
version = "0.0.1"
|
||||
contract_version = CONTRACT_VERSION
|
||||
requires = ()
|
||||
|
||||
def train(self, studies):
|
||||
return self
|
||||
|
||||
def predict(self, study):
|
||||
w = study.prep.windows
|
||||
return Labels(self.name, per_window=pd.Series("vigilia", index=w.index))
|
||||
|
||||
def save(self, path):
|
||||
Path(path, "params.json").write_text("{}")
|
||||
|
||||
@classmethod
|
||||
def load(cls, path):
|
||||
return cls()
|
||||
|
||||
|
||||
class MeanAmplitude:
|
||||
"""A fake biomarker: mean absolute amplitude in µV, baseline = median and MAD."""
|
||||
|
||||
name = "mean_amplitude"
|
||||
version = "0.0.1"
|
||||
contract_version = CONTRACT_VERSION
|
||||
requires = ("sleep_state",)
|
||||
features = ("mean_abs_uv",)
|
||||
|
||||
def __init__(self):
|
||||
self.median = None
|
||||
self.mad = None
|
||||
|
||||
def measure(self, study):
|
||||
x = study.prep.variant("hp05_prom").get_data() * 1e6
|
||||
return {"mean_abs_uv": float(np.mean(np.abs(x)))}
|
||||
|
||||
def train(self, data, ages_months=None):
|
||||
if isinstance(data, pd.DataFrame):
|
||||
v = data["mean_abs_uv"].to_numpy()
|
||||
else:
|
||||
v = np.array([self.measure(s)["mean_abs_uv"] for s in data])
|
||||
self.median = float(np.median(v))
|
||||
self.mad = float(np.median(np.abs(v - self.median))) or 1.0
|
||||
return self
|
||||
|
||||
def predict(self, data, age_months=None):
|
||||
if isinstance(data, pd.DataFrame):
|
||||
rows = data.to_dict("records")
|
||||
else:
|
||||
rows = [{**self.measure(data), "age_months": age_months}]
|
||||
out = []
|
||||
for r in rows:
|
||||
z = (r["mean_abs_uv"] - self.median) / self.mad
|
||||
out.append({"feature": "mean_abs_uv", "value": r["mean_abs_uv"],
|
||||
"age_months": r.get("age_months"), "outside": int(np.sign(z)) if abs(z) > 3 else 0,
|
||||
"z": z, "baseline": "median_mad"})
|
||||
return pd.DataFrame(out, columns=list(DEVIATION_COLUMNS))
|
||||
|
||||
def save(self, path):
|
||||
Path(path, "baseline.json").write_text(json.dumps({"median": self.median, "mad": self.mad}))
|
||||
|
||||
@classmethod
|
||||
def load(cls, path):
|
||||
m = cls()
|
||||
d = json.loads(Path(path, "baseline.json").read_text())
|
||||
m.median, m.mad = d["median"], d["mad"]
|
||||
return m
|
||||
|
||||
|
||||
def _study(prep):
|
||||
return Study(prep).with_labels(ConstantState().predict(Study(prep)))
|
||||
|
||||
|
||||
def test_preprocessed_requires_window_columns(prep):
|
||||
with pytest.raises(ValueError, match="lacks columns"):
|
||||
Preprocessed(variants=prep.variants, windows=prep.windows.drop(columns="gap"),
|
||||
age_months=None, plan={"schema": 1}, plan_hash="x")
|
||||
|
||||
|
||||
def test_missing_variant_and_label_messages(prep):
|
||||
with pytest.raises(KeyError, match="hp05_orejas"):
|
||||
prep.variant("hp05_orejas")
|
||||
with pytest.raises(KeyError, match="no labels from process 'spindle_detection'"):
|
||||
Study(prep).label("spindle_detection")
|
||||
|
||||
|
||||
def test_labels_need_content_and_event_columns():
|
||||
with pytest.raises(ValueError, match="neither"):
|
||||
Labels("x")
|
||||
with pytest.raises(ValueError, match="duration_s"):
|
||||
Labels("x", events=pd.DataFrame({"onset_s": [1.0]}))
|
||||
|
||||
|
||||
def test_check_module_refuses_wrong_kind_and_version():
|
||||
with pytest.raises(ContractError, match="missing"):
|
||||
check_module(object(), "process")
|
||||
old = ConstantState()
|
||||
old.contract_version = "0.9"
|
||||
with pytest.raises(ContractError, match="contract 0.9"):
|
||||
check_module(old, "process")
|
||||
|
||||
|
||||
def test_fake_process_passes_the_suite(prep):
|
||||
check_process(ConstantState(), Study(prep))
|
||||
|
||||
|
||||
def test_fake_biomarker_passes_the_suite():
|
||||
from conftest import make_prep
|
||||
studies = [_study(make_prep(seed=i)) for i in range(6)]
|
||||
out = check_biomarker(MeanAmplitude(), studies, [20, 22, 24, 26, 28, 30])
|
||||
assert out["feature"].iloc[0] == "mean_abs_uv"
|
||||
|
||||
|
||||
def test_recording_from_edf(tmp_path):
|
||||
"""Recording.from_edf reads an EDF with MNE and keeps only the file stem."""
|
||||
import mne
|
||||
from tea.contracts import Recording
|
||||
info = mne.create_info(["Fp1", "O1"], 250.0, "eeg")
|
||||
raw = mne.io.RawArray(np.random.default_rng(0).normal(0, 20e-6, (2, 2500)), info, verbose="error")
|
||||
p = tmp_path / "study.edf"
|
||||
mne.export.export_raw(p, raw, fmt="edf", verbose="error")
|
||||
rec = Recording.from_edf(p, age_months=30)
|
||||
assert rec.raw.ch_names == ["Fp1", "O1"]
|
||||
assert rec.source_name == "study" and len(rec.source_sha256) == 64
|
||||
@@ -1,237 +0,0 @@
|
||||
"""
|
||||
Edge cases on synthetic KTLX studies (tests/ktlx_synth.py): internal gap, edge padding, photic train, accented annotations, headbox
|
||||
constants, schema 8, clamping and 8-character header fields.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import struct
|
||||
import warnings
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
import edfio
|
||||
import mne
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
import ktlx_synth as tr
|
||||
from edfio import EdfSignal
|
||||
|
||||
from tea.export import edf_export as ex
|
||||
from tea.export import ktlx
|
||||
from tea.export.edf_annotations import BAD_ACQ_SKIP, clamped
|
||||
from tea.export.edf_header import EDF_RECORDING_LEN, recording_header
|
||||
from tea.export.edf_signals import DIGITAL_RANGE, build_signals, half_range
|
||||
|
||||
ACCENTED = "Fotoestimulación ñandú"
|
||||
ACCENTED_STAMP = 200
|
||||
|
||||
|
||||
def _append_note(folder, text, stamp):
|
||||
"""Add an annotation to the synthetic .ent (before its terminator)."""
|
||||
ent = next(folder.glob("*.ent"))
|
||||
blob = ent.read_bytes()[:-16]
|
||||
payload = f'(."Annotation" (.Stamp {stamp}) (.Text "{text}"))'.encode(
|
||||
"cp1252") + b"\x00\x00"
|
||||
blob += struct.pack("<4i", 1, 16 + len(payload), 0, 0) + payload
|
||||
ent.write_bytes(blob + struct.pack("<4i", 0, 0, 0, 0))
|
||||
|
||||
|
||||
def _set_headbox(folder, headbox):
|
||||
for erd in folder.glob("*.erd"):
|
||||
b = bytearray(erd.read_bytes())
|
||||
struct.pack_into("<i", b, ktlx.HEADBOX_OFFSET, headbox)
|
||||
erd.write_bytes(bytes(b))
|
||||
|
||||
|
||||
def _read(path):
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
raw = mne.io.read_raw_edf(path, preload=True, verbose="warning")
|
||||
assert [str(w.message) for w in caught] == []
|
||||
return raw
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def study(tmp_path):
|
||||
folder = tmp_path / "study"
|
||||
data, events, stamps, spans, n_tot = tr.build_study(folder)
|
||||
_append_note(folder, ACCENTED, ACCENTED_STAMP)
|
||||
return SimpleNamespace(folder=folder, data=data, stamps=stamps,
|
||||
spans=spans, n_tot=n_tot)
|
||||
|
||||
|
||||
def test_synthetic_roundtrip(study, tmp_path):
|
||||
out = ex.ktlx_to_edf(study.folder, tmp_path / "s.edf")
|
||||
raw = _read(out)
|
||||
fs = tr.FS
|
||||
k_v, _ = ktlx.scale_v_per_lsb(ktlx.KtlxStudy(study.folder).hdr)
|
||||
|
||||
# values: every packet lands at its global stamp, in volts
|
||||
got = raw.get_data()
|
||||
sigs = edfio.read_edf(out).signals
|
||||
step = np.array([(s.physical_range.max - s.physical_range.min)
|
||||
/ (s.digital_range.max - s.digital_range.min)
|
||||
for s in sigs]) * 1e-6 # uV -> V
|
||||
assert len({tuple(s.physical_range) for s in sigs}) == 1
|
||||
assert all(s.physical_range.min == -s.physical_range.max for s in sigs)
|
||||
full_v = sigs[0].physical_range.max * 1e-6
|
||||
a = 0
|
||||
for stamp, n in zip(study.stamps, study.spans):
|
||||
exp = np.clip(study.data[a:a + n].T.astype(np.float64) * k_v,
|
||||
-full_v, full_v)
|
||||
assert np.all(np.abs(got[:, stamp:stamp + n] - exp)
|
||||
<= step[:, None] / 2 + 1e-12)
|
||||
a += n
|
||||
|
||||
# internal gap (zero-filled) and edge padding, both BAD_ACQ_SKIP
|
||||
gap_a = int(study.stamps[1] + study.spans[1])
|
||||
gap_b = int(study.stamps[2])
|
||||
assert all(np.all(sig.digital[gap_a:gap_b] == 0) for sig in sigs)
|
||||
assert np.allclose(got[:, gap_a:gap_b], 0, rtol=0, atol=1e-15)
|
||||
n_data = study.n_tot
|
||||
n_pad = raw.n_times - n_data
|
||||
assert n_pad == (-n_data) % int(fs) and n_pad > 0
|
||||
assert np.all(got[:, n_data:] == got[:, [n_data - 1]])
|
||||
bad = sorted((round(o * fs), round(d * fs)) for o, d, t in zip(
|
||||
raw.annotations.onset, raw.annotations.duration,
|
||||
raw.annotations.description) if t == BAD_ACQ_SKIP)
|
||||
assert bad == [(gap_a, gap_b - gap_a), (n_data, n_pad)]
|
||||
|
||||
# events: .ent notes (incl. UTF-8 text), photic train, IDS
|
||||
desc = dict(zip(raw.annotations.description, raw.annotations.onset))
|
||||
assert desc["Fotica 10 Hz"] == pytest.approx(100 / fs)
|
||||
assert desc["Ojos abiertos"] == pytest.approx(620 / fs)
|
||||
assert desc[ACCENTED] == pytest.approx(ACCENTED_STAMP / fs)
|
||||
photic = [d for d in desc if d.startswith("Photic ")]
|
||||
assert len(photic) == 1 and photic[0].endswith(" Hz (20 flashes)")
|
||||
assert desc[photic[0]] == pytest.approx(100 / fs)
|
||||
assert any(d.startswith("IDS guid=abc123 ") for d in desc)
|
||||
|
||||
# header: name anonymized, synthetic ID kept, stem name not leaked
|
||||
si = raw.info["subject_info"]
|
||||
assert si["his_id"] == "ID-0001" and si.get("last_name") == "X"
|
||||
assert b"PEREZ" not in out.read_bytes()
|
||||
|
||||
|
||||
def test_unknown_headbox_uses_classic_constant(study, tmp_path, caplog):
|
||||
_set_headbox(study.folder, 15)
|
||||
with caplog.at_level(logging.WARNING):
|
||||
ex.ktlx_to_edf(study.folder, tmp_path / "hb15.edf")
|
||||
assert "headbox_type=15" in caplog.text
|
||||
k15, aviso = ktlx.scale_v_per_lsb({"headbox_type": [15], "discardbits": 0})
|
||||
k26, ok = ktlx.scale_v_per_lsb({"headbox_type": [26], "discardbits": 0})
|
||||
assert aviso and ok is None
|
||||
assert k15 / k26 == pytest.approx(8711 / 5000)
|
||||
assert k26 == pytest.approx(5000 / (2 ** 21 - 0.5) * 1e-6)
|
||||
|
||||
|
||||
def test_schema_8(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(tr, "SCHEMA", 8)
|
||||
folder = tmp_path / "s8"
|
||||
tr.build_study(folder)
|
||||
raw = _read(ex.ktlx_to_edf(folder, tmp_path / "s8.edf"))
|
||||
assert len(raw.ch_names) == tr.N_CHAN
|
||||
|
||||
|
||||
@pytest.mark.parametrize("onset, dur, text, expected", [
|
||||
(-30, 40, "early", (0.0, 10, "early [pre-start -0.1 s]")),
|
||||
(-30, 10, "early", (0.0, None, "early [pre-start -0.1 s]")),
|
||||
(300, None, "late", (299 / 256, None, "late [post-end +0.0 s]")),
|
||||
(250, 100, "long", (250 / 256, 50, "long")),
|
||||
])
|
||||
def test_clamped(onset, dur, text, expected):
|
||||
a = clamped(onset, dur, 300, 256.0, text)
|
||||
exp_onset, exp_dur, exp_text = expected
|
||||
assert a.onset == pytest.approx(exp_onset)
|
||||
assert a.text == exp_text
|
||||
if exp_dur is None:
|
||||
assert a.duration is None
|
||||
else:
|
||||
assert a.duration == pytest.approx(exp_dur / 256)
|
||||
|
||||
|
||||
HB3 = {"headbox_type": [26], "discardbits": 6}
|
||||
HB3_V_PER_LSB = ktlx.scale_v_per_lsb(HB3)[0]
|
||||
|
||||
|
||||
def test_hb3_resolution():
|
||||
"""Datasheet: ±5 mV over 16 bits, 0.153 uV/bit (rounded)."""
|
||||
assert HB3_V_PER_LSB * 1e6 == pytest.approx(10_000 / 65536, rel=1e-6)
|
||||
for db in (0, 6):
|
||||
assert ktlx.full_scale_v({**HB3, "discardbits": db}) == pytest.approx(
|
||||
32767 * HB3_V_PER_LSB)
|
||||
|
||||
|
||||
def test_fixed_range_lossless_and_clipped(caplog):
|
||||
counts = np.array([[0, 131070], [32767, 131070], [-32768, 131070],
|
||||
[-5, 131070], [12345, 131070]], np.int32)
|
||||
with caplog.at_level(logging.WARNING):
|
||||
sigs = build_signals(counts, HB3_V_PER_LSB, ktlx.full_scale_v(HB3),
|
||||
256.0, ["Cz", "DC"],
|
||||
["Xltek phys=7 erd=0", "Xltek phys=32 erd=1"])
|
||||
assert "Cz=1, DC=5" in caplog.text
|
||||
for s in sigs:
|
||||
assert (s.physical_range.min, s.physical_range.max) == (-4999.9,
|
||||
4999.9)
|
||||
assert tuple(s.digital_range) == DIGITAL_RANGE
|
||||
assert s.physical_dimension == "uV" and s.prefiltering == ""
|
||||
assert sigs[0].transducer_type == "Xltek phys=7 erd=0"
|
||||
assert list(sigs[0].digital) == [0, 32767, -32767, -5, 12345]
|
||||
assert list(sigs[1].digital) == [32767] * 5
|
||||
|
||||
|
||||
@pytest.mark.parametrize("x", [0.000873456, 0.0123456789, 0.7629394,
|
||||
0.15304122616866642, 12.3456789, 1e-4,
|
||||
4999.847])
|
||||
def test_half_range_fits_8_chars(x):
|
||||
h = half_range(x)
|
||||
assert x <= h <= 1.5 * x
|
||||
assert len(str(-h)) <= 8 and "e" not in str(h)
|
||||
sig = EdfSignal(np.array([0.0, x, -x]), 1.0, physical_range=(-h, h),
|
||||
digital_range=DIGITAL_RANGE)
|
||||
assert (sig.physical_range.min, sig.physical_range.max) == (-h, h)
|
||||
assert sig.digital[0] == 0
|
||||
assert abs(sig.data[0]) < 1e-15 * max(h, 1)
|
||||
|
||||
|
||||
def test_recording_field_fits(study):
|
||||
st = ktlx.KtlxStudy(study.folder)
|
||||
st.hdr["headbox_sw_version"] = ["9" * 10] * 4
|
||||
rec = recording_header(datetime(2020, 1, 1).date(), st.guid,
|
||||
ex._equipment(st))
|
||||
field = (f"Startdate 01-JAN-2020 {rec.hospital_administration_code} "
|
||||
f"X {rec.equipment_code}")
|
||||
assert len(field) <= EDF_RECORDING_LEN
|
||||
assert rec.equipment_code.startswith("Xltek_HB26")
|
||||
|
||||
|
||||
def test_start_time_without_snc_is_utc(study, tmp_path, monkeypatch):
|
||||
"""Without .snc the .stc creation time (Unix, UTC) is used, whatever
|
||||
the time zone of the converting machine."""
|
||||
import time
|
||||
monkeypatch.setenv("TZ", "America/Mexico_City")
|
||||
time.tzset()
|
||||
try:
|
||||
next(study.folder.glob("*.snc")).unlink()
|
||||
raw = _read(ex.ktlx_to_edf(study.folder, tmp_path / "nosnc.edf"))
|
||||
finally:
|
||||
monkeypatch.undo()
|
||||
time.tzset()
|
||||
expected = datetime.fromtimestamp(1_600_000_000, ktlx.timezone.utc)
|
||||
assert raw.info["meas_date"] == expected
|
||||
|
||||
|
||||
def test_cli_reports_errors_without_traceback(tmp_path, caplog, capsys):
|
||||
from tea.export import cli
|
||||
with caplog.at_level(logging.ERROR):
|
||||
assert cli.main([str(tmp_path / "missing")]) == 1
|
||||
assert "La carpeta no existe" in caplog.text
|
||||
assert "Traceback" not in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_cli_converts(study, tmp_path, capsys):
|
||||
from tea.export import cli
|
||||
out = tmp_path / "cli.edf"
|
||||
assert cli.main([str(study.folder), "-o", str(out)]) == 0
|
||||
assert out.exists() and str(out) in capsys.readouterr().out
|
||||
@@ -1,71 +0,0 @@
|
||||
"""Unit tests for the sex / birthdate extraction (tea.export.patient)."""
|
||||
|
||||
import struct
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from tea.export import patient
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw, expected", [
|
||||
("F", "F"), ("Female", "F"), ("Mujer", "F"), ("madre", "F"), ("2", "F"),
|
||||
("M", "M"), ("Male", "M"), ("Masculino", "M"), ("Hombre", "M"), ("1", "M"),
|
||||
("", None), ("X", None), ("unknown", None),
|
||||
])
|
||||
def test_normalizar_sexo(raw, expected):
|
||||
assert patient.normalizar_sexo(raw) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ident, orden, expected", [
|
||||
("11012022", "dmy", date(2022, 1, 11)),
|
||||
("11012022", "mdy", date(2022, 11, 1)),
|
||||
("25122019", "mdy", date(2019, 12, 25)), # month 25 impossible: swapped
|
||||
(" 01022020 ", "dmy", date(2020, 2, 1)),
|
||||
("ID-0001", "dmy", None),
|
||||
("99992020", "dmy", None),
|
||||
])
|
||||
def test_fecha_del_identificador(ident, orden, expected):
|
||||
d, motivo = patient.fecha_del_identificador(ident, orden)
|
||||
assert (d.date() if d else None) == expected
|
||||
assert motivo
|
||||
|
||||
|
||||
def _ole(d: datetime) -> bytes:
|
||||
return struct.pack("<d", (d - datetime(1899, 12, 30)) / timedelta(days=1))
|
||||
|
||||
|
||||
def test_fields_skip_label_and_read_value():
|
||||
blob = (b"GenderLabel\x00Sexo\x00" # display label: skipped
|
||||
b"Gender\x00\x00Female\x00"
|
||||
b"BirthDateLabel\x00Fecha\x00"
|
||||
b"BirthDate\x00\x00" + _ole(datetime(2021, 3, 4)))
|
||||
bloques = [blob]
|
||||
assert patient.sexo_del_eeg(bloques)[0] == "F"
|
||||
d, _ = patient.fecha_tras_campo(bloques, referencia=datetime(2025, 1, 1))
|
||||
assert d.date() == date(2021, 3, 4)
|
||||
|
||||
|
||||
def test_fields_inside_hex_block():
|
||||
inner = b"Gender\x00M\x00"
|
||||
blob = b'(."Bin", 0x' + inner.hex().encode() + b"00" * 12 + b")"
|
||||
assert patient.sexo_del_eeg(patient.desde_hex(blob))[0] == "M"
|
||||
|
||||
|
||||
def test_birthdate_rejects_implausible_age():
|
||||
blob = b"BirthDate\x00" + _ole(datetime(1850, 1, 1))
|
||||
d, _ = patient.fecha_tras_campo([blob], referencia=datetime(2025, 1, 1))
|
||||
assert d is None
|
||||
|
||||
|
||||
def test_patient_info_sources(tmp_path):
|
||||
eeg = tmp_path / "x.eeg"
|
||||
eeg.write_bytes(b"Gender\x00F\x00BirthDate\x00"
|
||||
+ _ole(datetime(2018, 6, 7)))
|
||||
rec = datetime(2025, 1, 1)
|
||||
# identifier is a date: it wins over the OLE double
|
||||
assert patient.patient_info(eeg, "11012022", rec) == ("F", date(2022, 1, 11))
|
||||
# identifier is not a date: OLE double after BirthDate
|
||||
assert patient.patient_info(eeg, "ID-0001", rec) == ("F", date(2018, 6, 7))
|
||||
# no .eeg at all
|
||||
assert patient.patient_info(None, "ID-0001", rec) == (None, None)
|
||||
@@ -1,188 +0,0 @@
|
||||
"""
|
||||
Synthetic KTLX studies for tests.
|
||||
|
||||
Writes a complete schema 8/9 study (.erd/.etc/.stc/.snc/.ent) with two
|
||||
segments, a 500-sample gap, a 10 Hz photic train and two annotations. The
|
||||
builder and the reference encoder come from examples/test_roundtrip.py and
|
||||
examples/xltek_convert.py (encode_packet); they live here so the tests do not
|
||||
depend on examples/.
|
||||
"""
|
||||
|
||||
import struct
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
from tea.export import ktlx
|
||||
|
||||
FS = 256.0
|
||||
N_CHAN = 20
|
||||
CHAN_NAMES = ["Fp1", "Fp2", "F3", "F4", "C3", "C4", "P3", "P4", "O1", "O2",
|
||||
"F7", "F8", "T3", "T4", "T5", "T6", "Fz", "Cz", "Pz", "EKG"]
|
||||
DISCARDBITS = 0
|
||||
SCHEMA = 9
|
||||
DATA_OFFSET = 8656 # 352 + campos + headbox + shorted/frequency_factor
|
||||
|
||||
|
||||
def encode_packet(data: np.ndarray, events: np.ndarray, n_chan: int,
|
||||
sentinel: int = -1) -> bytes:
|
||||
"""
|
||||
Codificador de referencia (solo se usa en las pruebas de ida y vuelta).
|
||||
Fuerza valores absolutos en la primera muestra del paquete.
|
||||
"""
|
||||
out = bytearray()
|
||||
l_mask = (n_chan + 7) // 8
|
||||
prev = np.zeros(n_chan, dtype=np.int64)
|
||||
for t in range(data.shape[0]):
|
||||
cur = data[t].astype(np.int64)
|
||||
delta = cur - prev
|
||||
fits8 = (delta >= -128) & (delta <= 127)
|
||||
fits16 = (delta >= -32768) & (delta <= 32767) & (delta != sentinel)
|
||||
if t == 0: # la primera muestra del paquete va siempre absoluta
|
||||
small = np.zeros(n_chan, dtype=bool)
|
||||
big_ok = np.zeros(n_chan, dtype=bool)
|
||||
else:
|
||||
small = fits8
|
||||
big_ok = fits16 & ~fits8
|
||||
absolute = ~(small | big_ok)
|
||||
bits = np.zeros(n_chan, dtype=np.uint8)
|
||||
bits[big_ok | absolute] = 1
|
||||
out.append(int(events[t]) & 0x01)
|
||||
out += np.packbits(
|
||||
np.concatenate([bits, np.zeros(l_mask * 8 - n_chan, np.uint8)]),
|
||||
bitorder="little").tobytes()
|
||||
vals = np.where(absolute, sentinel, delta).astype(np.int64)
|
||||
fmt = "<" + "".join("h" if b else "b" for b in bits)
|
||||
out += struct.pack(fmt, *[int(v) for v in vals])
|
||||
if absolute.any():
|
||||
out += cur[absolute].astype("<i4").tobytes()
|
||||
prev = cur
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def generic_header(schema: int) -> bytes:
|
||||
b = bytearray(352)
|
||||
b[0:16] = bytes(range(16))
|
||||
struct.pack_into("<H", b, 16, schema)
|
||||
struct.pack_into("<H", b, 18, 1)
|
||||
struct.pack_into("<i", b, 20, 1_600_000_000)
|
||||
struct.pack_into("<i", b, 24, 111)
|
||||
struct.pack_into("<i", b, 28, 222)
|
||||
b[32:32 + 6] = b"PEREZ\x00"
|
||||
b[112:112 + 4] = b"ANA\x00"
|
||||
b[272:272 + 7] = b"ID-0001"
|
||||
return bytes(b)
|
||||
|
||||
|
||||
def erd_header() -> bytes:
|
||||
b = bytearray(DATA_OFFSET)
|
||||
b[0:352] = generic_header(SCHEMA)
|
||||
struct.pack_into("<d", b, 352, FS)
|
||||
struct.pack_into("<i", b, 360, N_CHAN)
|
||||
struct.pack_into("<i", b, 364, 8) # deltabits
|
||||
struct.pack_into(f"<{N_CHAN}i", b, 368, *range(N_CHAN)) # phys_chan
|
||||
off = 4464
|
||||
struct.pack_into("<4i", b, off, 26, 0, 0, 0) # headbox_type = 26
|
||||
struct.pack_into("<4i", b, off + 16, 987654, 0, 0, 0) # headbox_sn
|
||||
b[off + 32:off + 42] = b"1.2.3\x00\x00\x00\x00\x00"
|
||||
b[off + 72:off + 82] = b"HW-A\x00\x00\x00\x00\x00\x00"
|
||||
b[off + 82:off + 92] = b"SW-B\x00\x00\x00\x00\x00\x00"
|
||||
struct.pack_into("<i", b, off + 92, DISCARDBITS) # 4556
|
||||
# shorted[1024] en 4560 y frequency_factor[1024] en 6608: todo cero/uno
|
||||
struct.pack_into("<1024h", b, 4560, *([0] * 1024))
|
||||
struct.pack_into("<1024h", b, 6608, *([1] * 1024))
|
||||
assert len(b) == DATA_OFFSET
|
||||
return bytes(b)
|
||||
|
||||
|
||||
def make_signal(n_smp: int, seed: int = 0) -> np.ndarray:
|
||||
"""Senal con deltas pequenos, saltos grandes y saturaciones ocasionales."""
|
||||
rng = np.random.default_rng(seed)
|
||||
t = np.arange(n_smp)
|
||||
x = np.zeros((n_smp, N_CHAN), dtype=np.int64)
|
||||
for c in range(N_CHAN):
|
||||
base = (12000 * np.sin(2 * np.pi * (8 + c * 0.3) * t / FS)
|
||||
+ 3000 * np.sin(2 * np.pi * 0.7 * t / FS + c))
|
||||
ruido = rng.integers(-40, 41, size=n_smp)
|
||||
x[:, c] = base.astype(np.int64) + ruido + c * 1000
|
||||
# saltos que fuerzan deltas de 16 bit y valores absolutos
|
||||
for c in range(0, N_CHAN, 5):
|
||||
x[n_smp // 3:, c] += 900 # -> delta de 16 bit
|
||||
x[2 * n_smp // 3:, c] += 5_000_000 # -> valor absoluto int32
|
||||
return x.astype(np.int32)
|
||||
|
||||
|
||||
def build_study(folder: Path, packets_smp=(300, 300, 257), gap_after=1):
|
||||
"""Crea un estudio con dos segmentos .erd y un hueco intencional."""
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
stem = "PEREZ, ANA_abc123"
|
||||
|
||||
total = sum(packets_smp)
|
||||
data = make_signal(total)
|
||||
events = np.zeros(total, dtype=np.uint8)
|
||||
# tren fotico: 10 Hz durante 2 s a partir de la muestra 100
|
||||
for k in range(20):
|
||||
events[100 + int(k * FS / 10)] = 1
|
||||
|
||||
# dos segmentos: paquetes 0-1 en el primer .erd, paquete 2 en el segundo
|
||||
reparto = [(0, [0, 1]), (1, [2])]
|
||||
stamps_ini = np.concatenate([[0], np.cumsum(packets_smp)[:-1]])
|
||||
# hueco de 500 muestras antes del ultimo paquete
|
||||
hueco = 500
|
||||
stamps_glob = stamps_ini.copy()
|
||||
stamps_glob[gap_after + 1:] += hueco
|
||||
|
||||
stc_entries = []
|
||||
for seg_i, pks in reparto:
|
||||
name = stem if seg_i == 0 else f"{stem}_{seg_i:03d}"
|
||||
erd = folder / f"{name}.erd"
|
||||
etc = folder / f"{name}.etc"
|
||||
blob = bytearray(erd_header())
|
||||
etc_rows = []
|
||||
for k in pks:
|
||||
a = int(stamps_ini[k])
|
||||
n = packets_smp[k]
|
||||
off = len(blob)
|
||||
blob += encode_packet(data[a:a + n], events[a:a + n], N_CHAN)
|
||||
etc_rows.append((off, int(stamps_glob[k]), n, n, 0))
|
||||
erd.write_bytes(bytes(blob))
|
||||
eb = bytearray(generic_header(SCHEMA))
|
||||
for row in etc_rows:
|
||||
eb += struct.pack("<iiihh", *row)
|
||||
etc.write_bytes(bytes(eb))
|
||||
a0 = int(stamps_glob[pks[0]])
|
||||
a1 = int(stamps_glob[pks[-1]] + packets_smp[pks[-1]])
|
||||
stc_entries.append((name.encode(), a0, a1, a1 - a0, a1 - a0))
|
||||
|
||||
sb = bytearray(generic_header(SCHEMA))
|
||||
sb += struct.pack("<ii", len(stc_entries), 1) + b"\x00" * 48
|
||||
for name, a0, a1, num, span in stc_entries:
|
||||
sb += name.ljust(256, b"\x00") + struct.pack("<iiii", a0, a1, num, span)
|
||||
(folder / f"{stem}.stc").write_bytes(bytes(sb))
|
||||
|
||||
# .snc: dos anclas
|
||||
nb = bytearray(generic_header(SCHEMA))
|
||||
ft0 = ktlx.EPOCH_AS_FILETIME + 1_600_000_000 * ktlx.HUNDREDS_OF_NS
|
||||
n_tot = int(stamps_glob[-1] + packets_smp[-1])
|
||||
nb += struct.pack("<iq", 0, ft0)
|
||||
nb += struct.pack("<iq", n_tot,
|
||||
int(ft0 + n_tot / FS * ktlx.HUNDREDS_OF_NS))
|
||||
(folder / f"{stem}.snc").write_bytes(bytes(nb))
|
||||
|
||||
# .ent: nota de montaje con ChanNames + dos anotaciones
|
||||
eb = bytearray(generic_header(SCHEMA))
|
||||
notas = [
|
||||
'(."Montage" (.ChanNames (' + ", ".join(f'"{c}"' for c in CHAN_NAMES)
|
||||
+ ')) (.Stamp 0))',
|
||||
'(."Annotation" (.Stamp 100) (.Text "Fotica 10 Hz") '
|
||||
'(.Data (.User "tecnico1")))',
|
||||
'(."Annotation" (.Stamp 620) (.Text "Ojos abiertos") '
|
||||
'(.Data (.User "tecnico1")))',
|
||||
]
|
||||
for nota in notas:
|
||||
payload = nota.encode() + b"\x00\x00"
|
||||
eb += struct.pack("<4i", 1, 16 + len(payload), 0, 0) + payload
|
||||
eb += struct.pack("<4i", 0, 0, 0, 0)
|
||||
(folder / f"{stem}.ent").write_bytes(bytes(eb))
|
||||
|
||||
return data, events, stamps_glob, packets_smp, n_tot
|
||||
@@ -1,97 +0,0 @@
|
||||
"""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.contracts.testing import check_preprocessed
|
||||
from tea.legacy.preprocessing import MODULE, PlanNotSupported, windows_from_qc
|
||||
from tea.legacy.validation import MODULE as VAL
|
||||
from tea.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]
|
||||
@@ -1,118 +0,0 @@
|
||||
"""
|
||||
Legacy annotation_mask + sleep_state + posterior_rhythm = the cluster route on the
|
||||
submodule (un_estudio -> senal._mascara_excluir -> vigilancia -> HK1K cut-offs ->
|
||||
medidas_director.ritmo), exactly.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from synth_edf import make_edf
|
||||
from tea.contracts import Study
|
||||
from tea.contracts.testing import check_biomarker, check_process
|
||||
from tea.legacy.biomarkers.posterior_rhythm import LegacyPosteriorRhythm
|
||||
from tea.legacy.preprocessing import MODULE as PRE
|
||||
from tea.legacy.processes.annotation_mask import MODULE as AM
|
||||
from tea.legacy.processes.sleep_state import MODULE as SS
|
||||
from tea.legacy.validation import MODULE as VAL
|
||||
from tea.preprocessing import DIRECTOR_CLUSTER
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
BT = ROOT / "biomarcadores-tea"
|
||||
|
||||
|
||||
def _study(edf, age=28.0):
|
||||
prep = PRE.run(edf, PRE.plan_for(VAL.summarize(edf), DIRECTOR_CLUSTER.to_dict()), age_months=age)
|
||||
s = Study(prep)
|
||||
s = s.with_labels(AM.predict(s))
|
||||
return s.with_labels(SS.predict(s))
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def edf(tmp_path_factory):
|
||||
return make_edf(tmp_path_factory.mktemp("legstate") / "s.edf", minutes=8, rhythm_hz=6.5,
|
||||
annotations=[(5, None, "Paciente despierto"), (240.5, None, "Dormido"),
|
||||
(100, 20, "Fotica 5 Hz"), (150, None, "llanto")])
|
||||
|
||||
|
||||
def _director(edf_path: Path) -> dict:
|
||||
code = f"""
|
||||
import json, sys, contextlib, io, warnings
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
sys.path.insert(0, {str(BT / 'preproceso')!r})
|
||||
warnings.simplefilter("ignore")
|
||||
import un_estudio, eeg_io, vigilancia, seleccion, ritmo as r
|
||||
with contextlib.redirect_stdout(io.StringIO()), un_estudio.temporal(Path({str(edf_path)!r}),
|
||||
linea_hz=60.0, pasa_altas=(0.3, 0.5), pasa_bajas=100.0) as res:
|
||||
est = eeg_io.Estudio(res["preproc_npz"], preferir="hp05_prom", estricto=True)
|
||||
ivs = [{{k: d[k] for k in ("t_ini", "t_fin", "estado", "fuente")}} for d in eeg_io.intervalos_estado(est)]
|
||||
m = np.zeros(est.n, dtype=bool) # senal._mascara_excluir
|
||||
for v in res["ventanas_qc"]:
|
||||
if v.get("veredicto") != "limpia" or v.get("montaje", False):
|
||||
m[int(v["t_ini"] * est.fs):int(v["t_fin"] * est.fs)] = True
|
||||
for d in ivs:
|
||||
if d["estado"] in seleccion.EXCLUIDOS + seleccion.PROVOCACION:
|
||||
m[int(d["t_ini"] * est.fs):int(d["t_fin"] * est.fs)] = True
|
||||
rasgos = vigilancia.rasgos(est, linea_hz=60.0, excluir=m)
|
||||
d = json.loads(Path({str(BT / 'normas' / 'estado_hk1k.json')!r}).read_text())
|
||||
t, _ = vigilancia.clasificar(rasgos, d["ref"], [float(d["cortes_A"][0]), float(d["corte_B"])], edad_meses=28.0)
|
||||
inicios = [float(a) for a, e in zip(t.t_ini_s, t.vigilancia) if e == "vigilia"]
|
||||
picos = []
|
||||
for c in ("O1", "O2", "P3", "P4"):
|
||||
f, P, n = r.psd_de_ventanas(est.datos(canales=[c])[:, 0], est.fs, inicios, r.VENT_S)
|
||||
if f is not None:
|
||||
pico, prom, hay = eeg_io.pico_dominante(f, P)
|
||||
if hay:
|
||||
picos.append(float(pico))
|
||||
val = float(np.median(picos)) if len(picos) >= 2 and len(inicios) >= r.MIN_VENTANAS else float("nan")
|
||||
print(json.dumps({{"labels": dict(zip([round(float(a), 2) for a in t.t_ini_s], t.vigilancia)),
|
||||
"ritmo": val, "n_vigilia": len(inicios)}}))
|
||||
"""
|
||||
out = subprocess.run([sys.executable, "-W", "ignore", "-c", code], capture_output=True,
|
||||
text=True, check=True)
|
||||
return json.loads(out.stdout.strip().splitlines()[-1])
|
||||
|
||||
|
||||
@pytest.mark.skipif(not BT.exists(), reason="submodule absent")
|
||||
def test_legacy_equals_cluster_route(edf):
|
||||
ref = _director(edf)
|
||||
s = _study(edf)
|
||||
w = s.prep.windows
|
||||
got = dict(zip([str(round(float(a), 2)) for a in w.start_s], s.label("sleep_state").per_window))
|
||||
for t0, lab in ref["labels"].items():
|
||||
assert got[str(round(float(t0), 2))] == lab, f"window {t0}"
|
||||
# every window the director did not label is 'sin_estado' here
|
||||
assert all(v == "sin_estado" for k, v in got.items() if k not in {str(round(float(a), 2)) for a in ref["labels"]})
|
||||
m = LegacyPosteriorRhythm().detail(s)
|
||||
assert m["n_ventanas"] == ref["n_vigilia"]
|
||||
assert m["ritmo_Hz"] == pytest.approx(ref["ritmo"], abs=0) or (np.isnan(m["ritmo_Hz"]) and np.isnan(ref["ritmo"]))
|
||||
|
||||
|
||||
def test_states_follow_the_signal(edf):
|
||||
s = _study(edf)
|
||||
lab, w = s.label("sleep_state").per_window, s.prep.windows
|
||||
assert (lab[w.start_s < 240] == "vigilia").mean() > 0.6
|
||||
assert (lab[w.start_s > 250] == "sueno").mean() > 0.6
|
||||
assert (lab[(w.start_s >= 100) & (w.end_s <= 120)] == "sin_estado").all() # photic excluded
|
||||
assert LegacyPosteriorRhythm().measure(s)["posterior_rhythm_hz"] == pytest.approx(6.5, abs=0.3)
|
||||
|
||||
|
||||
def test_process_contracts(edf):
|
||||
s = _study(edf)
|
||||
check_process(AM, Study(s.prep))
|
||||
check_process(SS, Study(s.prep).with_labels(AM.predict(Study(s.prep))))
|
||||
|
||||
|
||||
def test_biomarker_contract(tmp_path):
|
||||
studies = [_study(make_edf(tmp_path / f"s{i}.edf", minutes=4, seed=i, rhythm_hz=6 + i * 0.4), 20 + 4 * i)
|
||||
for i in range(3)]
|
||||
check_biomarker(LegacyPosteriorRhythm(baseline="age_blocks"), studies, [20, 24, 28])
|
||||
@@ -1,121 +0,0 @@
|
||||
"""
|
||||
Legacy validation = the director's code, exactly.
|
||||
|
||||
The submodule's own scripts (biomarcadores-tea/preproceso via sys.path) and
|
||||
tea.legacy.validation run on the same synthetic EDF must give identical
|
||||
results: channel table, dropped channels, window QC and triage.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from synth_edf import SCALP, make_edf
|
||||
from tea.contracts.testing import check_validation
|
||||
from tea.legacy.validation import MODULE
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PREPROCESO = ROOT / "biomarcadores-tea" / "preproceso"
|
||||
needs_submodule = pytest.mark.skipif(not PREPROCESO.exists(), reason="submodule absent")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def edf(tmp_path_factory):
|
||||
d = tmp_path_factory.mktemp("legval")
|
||||
return make_edf(d / "s.edf", minutes=6, gaps=[(100.0, 4.0)],
|
||||
bad={"flat": ["P3"], "bursts": ["P4"], "bridge": [("F3", "C3")]})
|
||||
|
||||
|
||||
def _director_run(edf_path: Path, line_hz=60.0) -> dict:
|
||||
"""Steps 1-4 of un_estudio.procesar, run on the submodule itself in a subprocess."""
|
||||
code = f"""
|
||||
import json, sys, tempfile, contextlib, io
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, {str(PREPROCESO)!r})
|
||||
import edf_convert, lote, triaje, preproceso, eeg_io
|
||||
import pandas as pd
|
||||
p = Path({str(edf_path)!r}); nombre = p.stem
|
||||
with tempfile.TemporaryDirectory() as tmp, contextlib.redirect_stdout(io.StringIO()):
|
||||
conv = Path(tmp)
|
||||
edf_convert.convertir(p, conv)
|
||||
npz = conv / nombre / f"{{nombre}}_signals.npz"; meta = conv / nombre / f"{{nombre}}_metadata.json"
|
||||
excluir, tabla = lote.excluidos_para_qc(npz, meta, {line_hz})
|
||||
reg = {{"estudio": nombre, **lote.qc_estudio(npz, meta, linea_hz={line_hz}, nombre_estudio=nombre, excluir=excluir)}}
|
||||
reg["veredicto"], reg["motivo"] = lote.veredicto(reg)
|
||||
est = eeg_io.Estudio(npz, meta)
|
||||
todos = eeg_io.canales_de(est.canales, "eeg", "orejas", "eog", "cardiaco")
|
||||
malos, motivo = preproceso.canales_malos(est, todos, tabla)
|
||||
pub = {{k: v for k, v in reg.items() if not k.startswith("_")}}
|
||||
qc_df = pd.DataFrame([pub]).rename(columns=lote.UNIDADES)
|
||||
can_df = pd.DataFrame([dict(estudio=nombre, **c) for c in reg.get("_por_canal", [])])
|
||||
tri = triaje.triar(qc_df, can_df if len(can_df) else None).iloc[0]
|
||||
print(json.dumps({{"qc": pub, "ventanas": reg["_por_ventana"], "tabla": tabla.to_dict("records"),
|
||||
"malos": {{n: motivo.get(n, "") for n in sorted(malos)}}, "excluir": excluir,
|
||||
"nivel": tri.nivel, "accion": tri.accion}}, default=str))
|
||||
"""
|
||||
out = subprocess.run([sys.executable, "-W", "ignore", "-c", code], capture_output=True,
|
||||
text=True, check=True, cwd=str(edf_path.parent))
|
||||
return json.loads(out.stdout.strip().splitlines()[-1])
|
||||
|
||||
|
||||
def _norm(x):
|
||||
return json.loads(json.dumps(x, default=str))
|
||||
|
||||
|
||||
@needs_submodule
|
||||
def test_legacy_equals_submodule(edf):
|
||||
ref = _director_run(edf)
|
||||
r = MODULE.run(edf)
|
||||
assert r["malos"] == ref["malos"]
|
||||
assert r["excluidos_qc"] == ref["excluir"]
|
||||
assert _norm(r["qc"]) == ref["qc"]
|
||||
assert _norm(r["ventanas"]) == ref["ventanas"]
|
||||
assert _norm(r["tabla"].to_dict("records")) == ref["tabla"]
|
||||
assert r["triaje"]["nivel"] == ref["nivel"] and r["triaje"]["accion"] == ref["accion"]
|
||||
|
||||
|
||||
def test_finds_the_faults_and_passes(edf):
|
||||
r = MODULE.run(edf)
|
||||
assert {"P3", "P4", "F3", "C3"} <= set(r["malos"])
|
||||
assert "puente" in r["malos"]["F3"]
|
||||
assert r["valid"] == 1 and r["triaje"]["nivel"] == "completo"
|
||||
|
||||
|
||||
def test_validate_contract_and_fhir(edf):
|
||||
bundle, valid = MODULE.validate(edf)
|
||||
summary = MODULE.summarize(edf)
|
||||
check_validation(bundle, valid, summary)
|
||||
from fhir.resources.R4B.bundle import Bundle
|
||||
Bundle.model_validate(bundle)
|
||||
obs = [e["resource"] for e in bundle["entry"] if e["resource"]["resourceType"] == "Observation"]
|
||||
electrodes = {c.get("valueString") for o in obs for c in o.get("component", [])
|
||||
if c["code"]["text"] == "electrode"}
|
||||
assert {"P3", "P4"} <= electrodes
|
||||
assert not any("subject" in e["resource"] for e in bundle["entry"])
|
||||
|
||||
|
||||
def test_too_few_scalp_electrodes_is_not_valid(tmp_path):
|
||||
flat = SCALP[:8] # 8 dead -> 11 usable < 12
|
||||
p = make_edf(tmp_path / "bad.edf", minutes=4, bad={"flat": flat})
|
||||
bundle, valid = MODULE.validate(p)
|
||||
assert valid == 0
|
||||
r = MODULE.run(p)
|
||||
assert any("electrodos de cuero" in x for x in r["razones"])
|
||||
check_validation(bundle, valid)
|
||||
|
||||
|
||||
def test_vendored_copies_are_unchanged():
|
||||
out = subprocess.run([sys.executable, str(ROOT / "tools" / "vendor_legacy.py"), "--check"],
|
||||
capture_output=True, text=True)
|
||||
if out.returncode == 2:
|
||||
pytest.skip(out.stderr.strip())
|
||||
assert out.returncode == 0, out.stdout
|
||||
@@ -1,226 +0,0 @@
|
||||
"""
|
||||
Synthetic EDF+ studies for tests. No patient data: every signal is generated.
|
||||
|
||||
from synth_edf import make_edf
|
||||
path = make_edf(tmp_path / "s.edf", minutes=6, bad={"flat": ["P3"], "bursts": ["P4"]})
|
||||
|
||||
Signal model (all in µV), designed to exercise the director's rules:
|
||||
- background: spatially mixed pink noise (sources placed on the head, weights
|
||||
falling with distance), so neighbouring electrodes correlate as on a real
|
||||
scalp and A1/A2 follow T3/T5/F7 and T4/T6/F8;
|
||||
- wake segments: a posterior rhythm at `rhythm_hz` (O1 O2 P3 P4 strongest),
|
||||
blinks on Fp1 Fp2 / LOC ROC;
|
||||
- sleep segments: frontal slow waves (~1 Hz, 80-200 µV) and 13 Hz spindles
|
||||
(central and frontal, 0.5-2 s, every ~8 s);
|
||||
- EKG: a QRS-like spike train at ~1.6 Hz;
|
||||
- mains line at `line_hz`;
|
||||
- `bad` channel faults: flat, frozen, clipped (saturated), bridge (pairs),
|
||||
bursts (> 4x the montage in many 10 s blocks), loud (4x amplitude);
|
||||
- `gaps`: zero-filled spans marked `BAD_ACQ_SKIP` (as ktlx2edf writes them).
|
||||
|
||||
Written like ktlx2edf: labels without prefixes, unit uV, one fixed range
|
||||
±4999.9 µV, digital ±32767.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
SCALP = ("Fp1 Fp2 F7 F3 Fz F4 F8 T3 C3 Cz C4 T4 T5 P3 Pz P4 T6 O1 O2").split()
|
||||
EARS = ("A1", "A2")
|
||||
AUX = ("LOC", "ROC", "EKG")
|
||||
POSTERIOR = ("O1", "O2", "P3", "P4")
|
||||
SPINDLE = ("F3", "F4", "Fz", "C3", "C4", "Cz")
|
||||
FRONTAL = ("Fp1", "Fp2", "F3", "F4", "Fz", "F7", "F8")
|
||||
FULL_SCALE = 4999.9
|
||||
|
||||
|
||||
def _positions():
|
||||
import mne
|
||||
# colin27_1020 replaces the deprecated standard_1020 (MNE 1.13) and has the
|
||||
# old names (T3, T5, A1...) too
|
||||
pos = mne.channels.make_standard_montage("colin27_1020").get_positions()["ch_pos"]
|
||||
return {ch: np.asarray(pos[ch], float) for ch in SCALP + list(EARS)}
|
||||
|
||||
|
||||
def _pink(rng, n, fs):
|
||||
f = np.fft.rfftfreq(n, 1 / fs)
|
||||
spec = rng.normal(size=f.size) + 1j * rng.normal(size=f.size)
|
||||
spec[1:] /= np.sqrt(f[1:])
|
||||
spec[0] = 0
|
||||
x = np.fft.irfft(spec, n)
|
||||
return x / x.std()
|
||||
|
||||
|
||||
def _segments(states, n, fs):
|
||||
lab = np.full(n, "vigilia", dtype=object)
|
||||
for st, a, b in states:
|
||||
lab[int(a * fs):int(b * fs)] = st
|
||||
return lab
|
||||
|
||||
|
||||
def make_signals(*, fs=250.0, minutes=6.0, states=None, rhythm_hz=7.0, line_hz=60.0,
|
||||
line_uv=2.0, bad=None, seed=0):
|
||||
"""Return (data µV dict label -> array, states list)."""
|
||||
rng = np.random.default_rng(seed)
|
||||
n = int(round(minutes * 60 * fs))
|
||||
t = np.arange(n) / fs
|
||||
dur = n / fs
|
||||
if states is None:
|
||||
states = [("vigilia", 0.0, dur / 2), ("sueno", dur / 2, dur)]
|
||||
lab = _segments(states, n, fs)
|
||||
wake = lab == "vigilia"
|
||||
sleep = lab == "sueno"
|
||||
|
||||
pos = _positions()
|
||||
names = SCALP + list(EARS)
|
||||
n_src = 24
|
||||
src_pos = rng.normal(size=(n_src, 3))
|
||||
src_pos /= np.linalg.norm(src_pos, axis=1, keepdims=True)
|
||||
src_pos *= np.mean([np.linalg.norm(p) for p in pos.values()])
|
||||
sources = np.stack([_pink(rng, n, fs) for _ in range(n_src)])
|
||||
data = {}
|
||||
for ch in names:
|
||||
d = np.linalg.norm(src_pos - pos[ch], axis=1)
|
||||
w = np.exp(-d / 0.04)
|
||||
w /= w.sum()
|
||||
x = 18.0 * (w @ sources) / np.sqrt((w ** 2).sum()) / np.sqrt(n_src) * 3
|
||||
x += 4.0 * _pink(rng, n, fs) # local, uncorrelated part
|
||||
data[ch] = x
|
||||
|
||||
# posterior rhythm in wake (amplitude falls toward the front)
|
||||
phase = rng.uniform(0, 2 * np.pi)
|
||||
alpha = np.sin(2 * np.pi * rhythm_hz * t + phase)
|
||||
for ch in names:
|
||||
y = pos[ch][1] # anterior (+) / posterior (-)
|
||||
amp = 30.0 if ch in POSTERIOR else 12.0 * np.exp(-(y + 0.05) * 25) if y < 0.05 else 3.0
|
||||
data[ch] += amp * alpha * wake
|
||||
|
||||
# sleep: frontal slow waves and spindles
|
||||
sw = np.zeros(n)
|
||||
k = 0
|
||||
while k < n:
|
||||
L = int(fs * rng.uniform(0.8, 1.6))
|
||||
if k + L < n and sleep[k]:
|
||||
sw[k:k + L] = -rng.uniform(80, 200) * np.sin(np.pi * np.arange(L) / L)
|
||||
k += L + int(fs * rng.uniform(0.2, 1.5))
|
||||
spin = np.zeros(n)
|
||||
for c in np.arange(5.0, dur, 8.0):
|
||||
i0 = int(c * fs)
|
||||
if i0 < n and sleep[i0]:
|
||||
L = int(fs * rng.uniform(0.6, 1.8))
|
||||
tt = np.arange(L) / fs
|
||||
env = np.exp(-0.5 * ((tt - tt[-1] / 2) / (tt[-1] / 5)) ** 2)
|
||||
seg = 35.0 * env * np.sin(2 * np.pi * 13.0 * tt)
|
||||
spin[i0:i0 + L] += seg[: max(0, min(L, n - i0))]
|
||||
for ch in names:
|
||||
if ch in FRONTAL:
|
||||
data[ch] += sw
|
||||
elif ch in SPINDLE:
|
||||
data[ch] += 0.6 * sw
|
||||
if ch in SPINDLE:
|
||||
data[ch] += spin
|
||||
|
||||
# blinks (wake) and EOG
|
||||
blinks = np.zeros(n)
|
||||
for c in np.arange(2.0, dur, 4.0):
|
||||
i0 = int((c + rng.uniform(-0.5, 0.5)) * fs)
|
||||
L = int(0.3 * fs)
|
||||
if 0 <= i0 < n - L and wake[i0]:
|
||||
blinks[i0:i0 + L] += 120 * np.hanning(L)
|
||||
data["Fp1"] += blinks
|
||||
data["Fp2"] += blinks
|
||||
data["LOC"] = 0.8 * blinks + 10 * _pink(rng, n, fs) + 0.3 * sw
|
||||
data["ROC"] = -0.8 * blinks + 10 * _pink(rng, n, fs) + 0.3 * sw
|
||||
|
||||
# EKG
|
||||
ekg = 20 * rng.normal(size=n)
|
||||
for c in np.arange(0.3, dur, 1 / 1.6):
|
||||
i0 = int(c * fs)
|
||||
if i0 + 10 < n:
|
||||
ekg[i0:i0 + 10] += 900 * np.hanning(10)
|
||||
data["EKG"] = ekg
|
||||
|
||||
# mains line
|
||||
for ch in data:
|
||||
data[ch] = data[ch] + line_uv * np.sin(2 * np.pi * line_hz * t)
|
||||
|
||||
_apply_faults(data, bad or {}, rng, fs)
|
||||
return data, states
|
||||
|
||||
|
||||
def _apply_faults(data, bad, rng, fs):
|
||||
n = len(next(iter(data.values())))
|
||||
for ch in bad.get("spikes", []): # focal spike-and-wave every ~3 s with a field
|
||||
# the director's own synthetic spike (candidatos_punta._punta): 50 ms, then a slow wave
|
||||
m = int(0.05 * fs)
|
||||
t = np.linspace(-1, 1, max(m, 3))
|
||||
shape = np.concatenate([250 * (1 - t ** 2) ** 2,
|
||||
-100 * np.sin(np.pi * np.linspace(0, 1, int(0.3 * fs)))])
|
||||
nb = {"C3": ("F3", "T3", "Cz", "P3"), "C4": ("F4", "T4", "Cz", "P4")}.get(ch, ())
|
||||
for c in np.arange(3.0, n / fs - 2, 3.1):
|
||||
i0 = int(c * fs)
|
||||
data[ch][i0:i0 + len(shape)] += shape
|
||||
for v in nb:
|
||||
data[v][i0:i0 + len(shape)] += 0.6 * shape
|
||||
for ch in bad.get("flat", []):
|
||||
data[ch] = np.zeros(n) + rng.normal(0, 0.05, n)
|
||||
for ch in bad.get("frozen", []):
|
||||
x = data[ch].copy()
|
||||
hold = np.repeat(x[::50], 50)[:n] # stuck value for 50 samples at a time
|
||||
data[ch] = hold
|
||||
for ch in bad.get("clipped", []):
|
||||
data[ch] = np.clip(data[ch] * 60, -FULL_SCALE, FULL_SCALE)
|
||||
for a, b in bad.get("bridge", []):
|
||||
data[b] = data[a] + rng.normal(0, 0.3, n)
|
||||
for ch in bad.get("loud", []):
|
||||
data[ch] = data[ch] * 8
|
||||
for ch in bad.get("bursts", []):
|
||||
blk = int(10 * fs)
|
||||
for b0 in range(0, n - blk, blk):
|
||||
if rng.random() < 0.3: # 30 % of the 10 s blocks
|
||||
i0 = b0 + int(rng.uniform(0, blk - fs * 3))
|
||||
L = int(fs * 2.5)
|
||||
data[ch][i0:i0 + L] += rng.choice([-1, 1]) * 600 * np.hanning(L) * \
|
||||
np.sign(np.sin(2 * np.pi * 3 * np.arange(L) / fs))
|
||||
|
||||
|
||||
def make_edf(path, *, fs=250.0, minutes=6.0, states=None, rhythm_hz=7.0, line_hz=60.0,
|
||||
line_uv=2.0, bad=None, gaps=(), annotations=None, seed=0, channels=None,
|
||||
label_prefix="") -> Path:
|
||||
"""Write a synthetic EDF+ and return its path."""
|
||||
from edfio import Edf, EdfAnnotation, EdfSignal
|
||||
|
||||
data, states = make_signals(fs=fs, minutes=minutes, states=states, rhythm_hz=rhythm_hz,
|
||||
line_hz=line_hz, line_uv=line_uv, bad=bad, seed=seed)
|
||||
labels = list(channels) if channels else SCALP + list(EARS) + list(AUX)
|
||||
n = len(data[labels[0]])
|
||||
ann = []
|
||||
for a, d in gaps:
|
||||
i0, i1 = int(a * fs), int((a + d) * fs)
|
||||
for ch in labels:
|
||||
data[ch][i0:i1] = 0.0
|
||||
ann.append(EdfAnnotation(float(a), float(d), "BAD_ACQ_SKIP"))
|
||||
if annotations is None:
|
||||
annotations = []
|
||||
for st, a, b in states:
|
||||
txt = {"vigilia": "Paciente despierto", "sueno": "Dormido"}.get(st)
|
||||
if txt:
|
||||
annotations.append((float(a) + 0.5, None, txt))
|
||||
for a, d, txt in annotations:
|
||||
ann.append(EdfAnnotation(float(a), d, txt))
|
||||
|
||||
signals = [EdfSignal(np.clip(data[ch], -FULL_SCALE, FULL_SCALE), fs,
|
||||
label=label_prefix + ch, physical_dimension="uV",
|
||||
physical_range=(-FULL_SCALE, FULL_SCALE),
|
||||
digital_range=(-32767, 32767))
|
||||
for ch in labels]
|
||||
rec_s = 1.0 if n % int(fs) == 0 else n / fs
|
||||
edf = Edf(signals, starttime=time(10, 0, 0), data_record_duration=rec_s,
|
||||
annotations=ann)
|
||||
path = Path(path)
|
||||
edf.write(path)
|
||||
return path
|
||||
@@ -1,52 +0,0 @@
|
||||
"""Aperiodic exponent and multiscale entropy: legacy copies unchanged, modern agrees with legacy."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from synth_edf import make_edf
|
||||
from tea.contracts.testing import check_biomarker
|
||||
from tea.pipeline import Pipeline
|
||||
from tea.preprocessing import DIRECTOR_CLUSTER
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BIO = ROOT / "biomarcadores-tea" / "biomarcadores"
|
||||
LEG = ROOT / "src" / "tea" / "legacy" / "biomarkers"
|
||||
|
||||
|
||||
@pytest.mark.skipif(not BIO.exists(), reason="submodule absent")
|
||||
@pytest.mark.parametrize("copy", ["aperiodic/_bio/aperiodico.py", "aperiodic/_bio/espectro.py", "mse/_bio/complejidad.py"])
|
||||
def test_copies_unchanged(copy):
|
||||
body = (LEG / copy).read_text(encoding="utf-8").split("\n", 1)[1]
|
||||
assert body == (BIO / Path(copy).name).read_text(encoding="utf-8")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def studies(tmp_path_factory):
|
||||
p = make_edf(tmp_path_factory.mktemp("apmse") / "s.edf", minutes=8)
|
||||
return (Pipeline.default("modern").study(p, plan=DIRECTOR_CLUSTER, age_months=28),
|
||||
Pipeline.default("legacy").study(p, plan=DIRECTOR_CLUSTER, age_months=28))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name,rel", [("aperiodic", 0.02), ("mse", 0.01)])
|
||||
def test_modern_agrees_with_legacy(studies, name, rel):
|
||||
m = Pipeline.default("modern").module(name).measure(studies[0])
|
||||
l = Pipeline.default("legacy").module(name).measure(studies[1])
|
||||
assert any(np.isfinite(v) for v in l.values())
|
||||
for k in m:
|
||||
if np.isnan(l[k]):
|
||||
assert np.isnan(m[k]), k
|
||||
else:
|
||||
assert m[k] == pytest.approx(l[k], rel=rel), k
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["aperiodic", "mse"])
|
||||
def test_biomarker_contract(tmp_path, name):
|
||||
pipe = Pipeline.default("modern")
|
||||
sts = [pipe.study(make_edf(tmp_path / f"s{i}.edf", minutes=6, seed=i), plan=DIRECTOR_CLUSTER,
|
||||
age_months=20 + 4 * i) for i in range(3)]
|
||||
mod = type(pipe.module(name))(baseline="age_blocks")
|
||||
check_biomarker(mod, sts, [20, 24, 28])
|
||||
@@ -1,111 +0,0 @@
|
||||
"""
|
||||
The boundary rule: a module imports only `tea.contracts`, the standard
|
||||
library and its approved third-party libraries. It never imports another
|
||||
`tea` module, so any module can be replaced without touching the rest.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
SRC = Path(__file__).resolve().parents[1] / "src" / "tea"
|
||||
|
||||
# Approved third-party libraries (top-level import names).
|
||||
BASE = {"numpy", "scipy", "pandas", "mne", "sklearn", "antropy", "fooof", "yasa",
|
||||
"meegkit", "edfio"}
|
||||
LEGACY = {"numpy", "scipy", "pandas", "sklearn", "fooof"} # fooof: biomarcadores-tea dependency
|
||||
EXTRA = {
|
||||
"validation": {"fhir"},
|
||||
"serving": {"mlflow"},
|
||||
"pipeline": {"dask", "distributed", "s3fs", "fsspec", "psutil"},
|
||||
"export": set(),
|
||||
}
|
||||
# lazy imports inside the director's figure / HDF5 helpers (never reached by legacy)
|
||||
DIRECTOR_LAZY = {"matplotlib", "h5py"}
|
||||
# files allowed to touch MNE / FHIR inside legacy (the contract adapters)
|
||||
LEGACY_ADAPTERS = {"_adapter.py", "fhir.py", "api.py", "__init__.py"}
|
||||
|
||||
|
||||
def unit_of(path: Path) -> tuple[str, ...]:
|
||||
"""The replaceable unit a file belongs to, as a path tuple under tea."""
|
||||
rel = path.relative_to(SRC).parts
|
||||
if rel[0] == "legacy":
|
||||
rest = rel[1:]
|
||||
if len(rest) >= 2 and rest[0] in ("processes", "biomarkers") and len(rest) > 2:
|
||||
return ("legacy", rest[0], rest[1])
|
||||
if len(rest) >= 2:
|
||||
return ("legacy", rest[0])
|
||||
return ("legacy",)
|
||||
if rel[0] in ("processes", "biomarkers") and len(rel) > 2:
|
||||
return (rel[0], rel[1])
|
||||
if len(rel) == 1:
|
||||
return ()
|
||||
return (rel[0],)
|
||||
|
||||
|
||||
def imports_of(path: Path):
|
||||
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
|
||||
pkg = list(path.relative_to(SRC.parent).with_suffix("").parts)
|
||||
if path.name != "__init__.py":
|
||||
pkg = pkg[:-1]
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Import):
|
||||
for a in node.names:
|
||||
yield a.name, node.lineno
|
||||
elif isinstance(node, ast.ImportFrom):
|
||||
if node.level:
|
||||
base = pkg[: len(pkg) - (node.level - 1)]
|
||||
mod = ".".join(base + ([node.module] if node.module else []))
|
||||
yield mod, node.lineno
|
||||
else:
|
||||
yield node.module or "", node.lineno
|
||||
|
||||
|
||||
def allowed_third_party(unit: tuple[str, ...], fname: str) -> set[str]:
|
||||
if not unit:
|
||||
return set()
|
||||
if unit[0] == "legacy":
|
||||
extra = {"mne", "fhir", "edfio"} if fname in LEGACY_ADAPTERS else set()
|
||||
return LEGACY | extra | DIRECTOR_LAZY
|
||||
if unit[0] == "export":
|
||||
return {"numpy", "edfio"}
|
||||
return BASE | EXTRA.get(unit[0], set())
|
||||
|
||||
|
||||
FILES = sorted(p for p in SRC.rglob("*.py"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", FILES, ids=[str(p.relative_to(SRC)) for p in FILES])
|
||||
def test_imports_respect_boundaries(path):
|
||||
unit = unit_of(path)
|
||||
own = "tea." + ".".join(unit) if unit else "tea"
|
||||
bad = []
|
||||
for mod, line in imports_of(path):
|
||||
top = mod.split(".")[0]
|
||||
if top == "tea":
|
||||
if unit and unit[0] == "export":
|
||||
ok = mod == own or mod.startswith(own + ".")
|
||||
elif not unit:
|
||||
ok = mod in ("tea", "tea.contracts") or mod.startswith("tea.contracts.")
|
||||
else:
|
||||
ok = (mod == "tea.contracts" or mod.startswith("tea.contracts.")
|
||||
or mod == own or mod.startswith(own + "."))
|
||||
if unit == ("contracts",):
|
||||
ok = mod.startswith("tea.contracts")
|
||||
elif top in sys.stdlib_module_names or top == "__future__":
|
||||
ok = True
|
||||
else:
|
||||
ok = top in allowed_third_party(unit, path.name)
|
||||
if not ok:
|
||||
bad.append(f"line {line}: {mod}")
|
||||
assert not bad, f"{path.relative_to(SRC)} ({'.'.join(unit) or 'root'}) breaks the boundary: " + "; ".join(bad)
|
||||
|
||||
|
||||
def test_legacy_never_imports_dask():
|
||||
for p in (SRC / "legacy").rglob("*.py") if (SRC / "legacy").exists() else []:
|
||||
for mod, line in imports_of(p):
|
||||
assert mod.split(".")[0] not in ("dask", "distributed"), f"{p}:{line} imports {mod}"
|
||||
@@ -1,64 +0,0 @@
|
||||
"""Coupling: modern agrees with legacy; phase-locked spindles give R well above the chance floor."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from synth_edf import make_edf
|
||||
from tea.contracts import Labels, Study
|
||||
from tea.contracts.testing import check_biomarker
|
||||
from tea.pipeline import Pipeline
|
||||
from tea.preprocessing import DIRECTOR_CLUSTER
|
||||
|
||||
from conftest import make_prep
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def studies(tmp_path_factory):
|
||||
p = make_edf(tmp_path_factory.mktemp("cpl") / "s.edf", minutes=8)
|
||||
return (Pipeline.default("modern").study(p, plan=DIRECTOR_CLUSTER, age_months=28),
|
||||
Pipeline.default("legacy").study(p, plan=DIRECTOR_CLUSTER, age_months=28))
|
||||
|
||||
|
||||
def test_modern_agrees_with_legacy(studies):
|
||||
m = Pipeline.default("modern").module("coupling").measure(studies[0])
|
||||
l = Pipeline.default("legacy").module("coupling").measure(studies[1])
|
||||
assert m["coupling_r"] == pytest.approx(l["coupling_r"], abs=0.03)
|
||||
assert m["coupling_r_raw"] == pytest.approx(l["coupling_r_raw"], abs=0.03)
|
||||
|
||||
|
||||
def _locked_study():
|
||||
"""A 1 Hz oscillation on Fz with 13 Hz bursts always at its trough, every 2.3 s."""
|
||||
prep = make_prep(seconds=240, channels=("Fz", "Cz", "Pz", "C3", "C4"))
|
||||
raw = prep.variant("hp05_prom")
|
||||
fs = raw.info["sfreq"]
|
||||
t = np.arange(raw.n_times) / fs
|
||||
so = 60e-6 * np.cos(2 * np.pi * 1.0 * t)
|
||||
rows = []
|
||||
burst = np.zeros_like(t)
|
||||
for c in np.arange(5.5, 235, 2.3):
|
||||
trough = np.floor(c) + 0.5 # cos(2*pi*t) minimum at half seconds
|
||||
m = np.abs(t - trough) < 0.4
|
||||
burst[m] += 20e-6 * np.hanning(m.sum()) * np.sin(2 * np.pi * 13 * t[m])
|
||||
rows.append({"onset_s": trough - 0.4, "duration_s": 0.8, "channel": "Fz", "frequency_hz": 13.0})
|
||||
raw._data[0] += so + burst
|
||||
ev = pd.DataFrame(rows)
|
||||
ev.attrs.update({"minutes": 4.0, "channels": ["Fz"], "searched": True})
|
||||
return Study(prep).with_labels(Labels("spindle_detection", events=ev))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("impl", ["modern", "legacy"])
|
||||
def test_phase_locked_spindles_are_coupled(impl):
|
||||
r = Pipeline.default(impl).module("coupling").measure(_locked_study())
|
||||
assert r["coupling_r"] > 0.8 and r["coupling_r_over_floor"] > 0.7
|
||||
assert abs(abs(r["coupling_angle_deg"]) - 180) < 30 # at the trough
|
||||
|
||||
|
||||
def test_biomarker_contract(tmp_path):
|
||||
pipe = Pipeline.default("modern")
|
||||
sts = [pipe.study(make_edf(tmp_path / f"s{i}.edf", minutes=6, seed=i), plan=DIRECTOR_CLUSTER,
|
||||
age_months=20 + 4 * i) for i in range(3)]
|
||||
from tea.biomarkers.coupling import Coupling
|
||||
check_biomarker(Coupling(baseline="age_blocks"), sts, [20, 24, 28])
|
||||
@@ -1,86 +0,0 @@
|
||||
"""Gradient: legacy = the cluster route on the submodule; modern agrees with legacy."""
|
||||
|
||||
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.contracts.testing import check_biomarker
|
||||
from tea.pipeline import Pipeline
|
||||
from tea.preprocessing import DIRECTOR_CLUSTER
|
||||
|
||||
BT = Path(__file__).resolve().parents[1] / "biomarcadores-tea"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def edf(tmp_path_factory):
|
||||
return make_edf(tmp_path_factory.mktemp("grad") / "s.edf", minutes=8)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def studies(edf):
|
||||
return (Pipeline.default("modern").study(edf, plan=DIRECTOR_CLUSTER, age_months=28),
|
||||
Pipeline.default("legacy").study(edf, plan=DIRECTOR_CLUSTER, age_months=28))
|
||||
|
||||
|
||||
def _director(edf_path):
|
||||
code = f"""
|
||||
import json, sys, contextlib, io, warnings
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
sys.path.insert(0, {str(BT / 'preproceso')!r}); warnings.simplefilter("ignore")
|
||||
import un_estudio, eeg_io, vigilancia, seleccion, gradiente as g
|
||||
with contextlib.redirect_stdout(io.StringIO()), un_estudio.temporal(Path({str(edf_path)!r}),
|
||||
linea_hz=60.0, pasa_altas=(0.3, 0.5), pasa_bajas=100.0) as res:
|
||||
est = eeg_io.Estudio(res["preproc_npz"], preferir="hp05_prom", estricto=True)
|
||||
ivs = [{{k: d[k] for k in ("t_ini", "t_fin", "estado", "fuente")}} for d in eeg_io.intervalos_estado(est)]
|
||||
m = np.zeros(est.n, dtype=bool)
|
||||
for v in res["ventanas_qc"]:
|
||||
if v.get("veredicto") != "limpia" or v.get("montaje", False):
|
||||
m[int(v["t_ini"] * est.fs):int(v["t_fin"] * est.fs)] = True
|
||||
for d in ivs:
|
||||
if d["estado"] in seleccion.EXCLUIDOS + seleccion.PROVOCACION:
|
||||
m[int(d["t_ini"] * est.fs):int(d["t_fin"] * est.fs)] = True
|
||||
d = json.loads(Path({str(BT / 'normas' / 'estado_hk1k.json')!r}).read_text())
|
||||
t, _ = vigilancia.clasificar(vigilancia.rasgos(est, linea_hz=60.0, excluir=m), d["ref"],
|
||||
[float(d["cortes_A"][0]), float(d["corte_B"])], edad_meses=28.0)
|
||||
sue = [float(a) for a, e in zip(t.t_ini_s, t.vigilancia) if e == "sueno"]
|
||||
fila, _, n = g.analizar(est, sue)
|
||||
print(json.dumps({{k: fila.get(f"pendiente_{{k}}") for k in ("delta", "theta", "alfa", "beta")}}, default=float))
|
||||
"""
|
||||
out = subprocess.run([sys.executable, "-W", "ignore", "-c", code], capture_output=True, text=True)
|
||||
assert out.returncode == 0, out.stderr[-1500:]
|
||||
return json.loads(out.stdout.strip().splitlines()[-1])
|
||||
|
||||
|
||||
@pytest.mark.skipif(not BT.exists(), reason="submodule absent")
|
||||
def test_legacy_equals_cluster_route(edf, studies):
|
||||
ref = _director(edf)
|
||||
got = Pipeline.default("legacy").module("gradient").measure(studies[1])
|
||||
for b, v in ref.items():
|
||||
assert got[f"gradient_{b}_sueno"] == v, b
|
||||
|
||||
|
||||
def test_modern_agrees_with_legacy(studies):
|
||||
sm, sl = studies
|
||||
m = Pipeline.default("modern").module("gradient").measure(sm)
|
||||
l = Pipeline.default("legacy").module("gradient").measure(sl)
|
||||
for k in m:
|
||||
if np.isnan(l[k]):
|
||||
assert np.isnan(m[k]), k
|
||||
else:
|
||||
assert m[k] == pytest.approx(l[k], abs=0.01), k
|
||||
|
||||
|
||||
def test_biomarker_contract(tmp_path):
|
||||
pipe = Pipeline.default("modern")
|
||||
sts = [pipe.study(make_edf(tmp_path / f"s{i}.edf", minutes=6, seed=i), plan=DIRECTOR_CLUSTER,
|
||||
age_months=20 + 4 * i) for i in range(3)]
|
||||
from tea.biomarkers.gradient import Gradient
|
||||
check_biomarker(Gradient(baseline="age_blocks"), sts, [20, 24, 28])
|
||||
@@ -1,53 +0,0 @@
|
||||
"""
|
||||
Modern = legacy on a gap-free recording: since the modern modules use the director's own
|
||||
filter (scipy sosfiltfilt) and spectra (DPSS multitaper with demeaned windows, symmetric
|
||||
Hann periodogram), every biomarker agrees with legacy to float32 precision (legacy stores
|
||||
its variants as float32). With gaps they differ by design: modern keeps gaps as NaN.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from synth_edf import make_edf
|
||||
from tea.pipeline import Pipeline
|
||||
from tea.preprocessing import DIRECTOR_CLUSTER
|
||||
|
||||
TOL = 1e-4
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def tables(tmp_path_factory):
|
||||
d = tmp_path_factory.mktemp("prec")
|
||||
st = [("vigilia", 0, 150), ("sueno", 150, 600)]
|
||||
paths = [make_edf(d / f"p{i}.edf", minutes=10, states=st, seed=i, rhythm_hz=6.5 + i) for i in range(2)]
|
||||
bios = tuple(Pipeline.default(impl="legacy").biomarker_names())
|
||||
kw = dict(plan=DIRECTOR_CLUSTER, ages_months=[24, 30], biomarkers=bios)
|
||||
return (Pipeline.default(impl="legacy").map(paths, **kw),
|
||||
Pipeline.default(impl="modern").map(paths, cluster="sync", **kw))
|
||||
|
||||
|
||||
def test_every_feature_matches_legacy_without_gaps(tables):
|
||||
legacy, modern = tables
|
||||
assert (legacy.error == "").all() and (modern.error == "").all()
|
||||
skip = {"key", "age_months", "valid", "level", "reasons", "plan_hash", "error", "versions", "seconds",
|
||||
"clean_fraction", "n_bad_channels"}
|
||||
feats = [c for c in legacy.columns if c in modern.columns and c not in skip]
|
||||
assert len(feats) > 60
|
||||
bad = {}
|
||||
for f in feats:
|
||||
a, b = legacy[f].astype(float).to_numpy(), modern[f].astype(float).to_numpy()
|
||||
if (np.isfinite(a) != np.isfinite(b)).any():
|
||||
bad[f] = "NaN in one only"
|
||||
continue
|
||||
ok = np.isfinite(a)
|
||||
if ok.any():
|
||||
tol = TOL * max(1.0, float(np.abs(a[ok]).max()))
|
||||
if f == "coupling_angle_deg":
|
||||
d = np.abs((a[ok] - b[ok] + 180) % 360 - 180)
|
||||
else:
|
||||
d = np.abs(a[ok] - b[ok])
|
||||
if d.max() > tol:
|
||||
bad[f] = float(d.max())
|
||||
assert not bad, bad
|
||||
@@ -1,65 +0,0 @@
|
||||
"""Modern annotation_mask + sleep_state + posterior_rhythm agree with the legacy (director) ones."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from synth_edf import make_edf
|
||||
from tea.contracts import Study
|
||||
from tea.contracts.testing import check_biomarker, check_process
|
||||
from tea.pipeline import Pipeline
|
||||
from tea.preprocessing import DIRECTOR_CLI, DIRECTOR_CLUSTER
|
||||
from tea.processes.sleep_state import SleepState
|
||||
|
||||
ANN = [(5, None, "Paciente despierto"), (240.5, None, "Dormido"), (100, 20, "Fotica 5 Hz"), (150, None, "llanto")]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def studies(tmp_path_factory):
|
||||
p = make_edf(tmp_path_factory.mktemp("slice") / "s.edf", minutes=8, rhythm_hz=6.5, annotations=ANN)
|
||||
return (Pipeline.default("modern").study(p, plan=DIRECTOR_CLUSTER, age_months=28),
|
||||
Pipeline.default("legacy").study(p, plan=DIRECTOR_CLUSTER, age_months=28))
|
||||
|
||||
|
||||
def test_annotation_states_equal(studies):
|
||||
m, l = studies
|
||||
assert (m.label("annotation_mask").per_window.values == l.label("annotation_mask").per_window.values).all()
|
||||
|
||||
|
||||
def test_sleep_state_agrees(studies):
|
||||
m, l = studies
|
||||
a, b = m.label("sleep_state").per_window, l.label("sleep_state").per_window
|
||||
assert (a.values == b.values).mean() >= 0.95
|
||||
|
||||
|
||||
def test_rhythm_agrees(studies):
|
||||
m, l = studies
|
||||
rm = Pipeline.default("modern").module("posterior_rhythm").measure(m)["posterior_rhythm_hz"]
|
||||
rl = Pipeline.default("legacy").module("posterior_rhythm").measure(l)["posterior_rhythm_hz"]
|
||||
assert rm == pytest.approx(rl, abs=0.25) and rm == pytest.approx(6.5, abs=0.3)
|
||||
|
||||
|
||||
def test_contracts(studies):
|
||||
m, _ = studies
|
||||
pm = Pipeline.default("modern")
|
||||
check_process(pm.module("annotation_mask"), Study(m.prep))
|
||||
check_process(pm.module("sleep_state"), Study(m.prep).with_labels(pm.module("annotation_mask").predict(Study(m.prep))))
|
||||
|
||||
|
||||
def test_biomarker_contract(tmp_path):
|
||||
pipe = Pipeline.default("modern")
|
||||
sts = [pipe.study(make_edf(tmp_path / f"s{i}.edf", minutes=4, seed=i, rhythm_hz=6 + 0.4 * i),
|
||||
plan=DIRECTOR_CLUSTER, age_months=20 + 4 * i) for i in range(3)]
|
||||
from tea.biomarkers.posterior_rhythm import PosteriorRhythm
|
||||
check_biomarker(PosteriorRhythm(baseline="age_blocks"), sts, [20, 24, 28])
|
||||
|
||||
|
||||
def test_cohort_cutoffs_train(tmp_path):
|
||||
"""DIRECTOR_CLI route: KMeans cut-offs on the cohort (cutoffs='cohort')."""
|
||||
pipe = Pipeline.default("modern")
|
||||
sts = [pipe.study(make_edf(tmp_path / f"c{i}.edf", minutes=6, seed=10 + i), plan=DIRECTOR_CLI,
|
||||
age_months=24, processes=["annotation_mask"]) for i in range(2)]
|
||||
ss = SleepState(cutoffs="cohort").train(sts)
|
||||
assert ss.cut["origin"] == "cohort" and len(ss.cut["cuts"]) == 2
|
||||
lab = ss.predict(sts[0]).per_window
|
||||
assert {"vigilia", "sueno"} <= set(lab)
|
||||
@@ -1,172 +0,0 @@
|
||||
"""Pipeline: module lookup, dependency order, executors and cluster rules."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from synth_edf import SCALP, make_edf
|
||||
from tea.pipeline import NotValid, Pipeline, order_for
|
||||
from tea.pipeline import dask_runner
|
||||
from tea.preprocessing import DIRECTOR_CLUSTER
|
||||
|
||||
BIOS = ("posterior_rhythm",)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def edfs(tmp_path_factory):
|
||||
d = tmp_path_factory.mktemp("pipe")
|
||||
good = [make_edf(d / f"s{i}.edf", minutes=3, seed=i, rhythm_hz=6.5 + 0.5 * i) for i in range(2)]
|
||||
bad = make_edf(d / "bad.edf", minutes=3, bad={"flat": SCALP[:9]}) # 10 usable < 12
|
||||
broken = d / "broken.edf"
|
||||
broken.write_bytes(b"not an edf at all")
|
||||
return good, bad, broken
|
||||
|
||||
|
||||
def _cmp(a: pd.DataFrame, b: pd.DataFrame):
|
||||
cols = [c for c in a.columns if c != "seconds"]
|
||||
pd.testing.assert_frame_equal(a[cols].reset_index(drop=True), b[cols].reset_index(drop=True))
|
||||
|
||||
|
||||
def test_order_is_topological():
|
||||
class M:
|
||||
def __init__(self, *req):
|
||||
self.requires = req
|
||||
mods = {"a": M(), "b": M("a"), "c": M("b", "a"), "bio": M("c")}
|
||||
assert order_for(["bio"], mods) == ["a", "b", "c"]
|
||||
mods["a"] = M("c")
|
||||
with pytest.raises(ValueError, match="cycle"):
|
||||
order_for(["bio"], mods)
|
||||
|
||||
|
||||
def test_legacy_pipeline_is_registered():
|
||||
for impl in ("legacy", "modern"):
|
||||
pipe = Pipeline.default(impl=impl)
|
||||
assert set(pipe.process_names()) == {"annotation_mask", "window_selection", "sleep_state",
|
||||
"slow_wave_staging", "spindle_detection"}, impl
|
||||
assert set(pipe.biomarker_names()) == {"posterior_rhythm", "spindles", "gradient", "slow_waves",
|
||||
"aperiodic", "mse", "coupling", "spindle_topography",
|
||||
"spikes"}, impl
|
||||
|
||||
|
||||
def test_legacy_loop_rows_and_errors(edfs):
|
||||
good, bad, broken = edfs
|
||||
pipe = Pipeline.default(impl="legacy")
|
||||
t = pipe.map([*good, bad, broken], plan=DIRECTOR_CLUSTER, ages_months=[24, 30, 26, 28],
|
||||
biomarkers=BIOS)
|
||||
assert list(t.key) == [0, 1, 2, 3]
|
||||
assert t.valid.tolist()[:3] == [1, 1, 0]
|
||||
assert t.posterior_rhythm_hz.iloc[0] == pytest.approx(6.5, abs=0.3)
|
||||
assert t.posterior_rhythm_hz.iloc[1] == pytest.approx(7.0, abs=0.3)
|
||||
assert "electrodos de cuero" in t.reasons.iloc[2]
|
||||
assert t.error.iloc[3] and "/" not in t.error.iloc[3] # no path in errors
|
||||
for c in ("path", "file", "name"):
|
||||
assert c not in t.columns
|
||||
|
||||
|
||||
def test_dask_sync_and_local_equal_legacy_loop(edfs):
|
||||
good, bad, _ = edfs
|
||||
paths, ages = [*good, bad], [24, 30, 26]
|
||||
legacy = Pipeline.default(impl="legacy")
|
||||
ref = legacy.map(paths, plan=DIRECTOR_CLUSTER, ages_months=ages, biomarkers=BIOS)
|
||||
modern = Pipeline(legacy.modules, impl="modern") # same modules, Dask runner
|
||||
_cmp(modern.map(paths, plan=DIRECTOR_CLUSTER, ages_months=ages, biomarkers=BIOS, cluster="sync"), ref)
|
||||
_cmp(modern.map(paths, plan=DIRECTOR_CLUSTER, ages_months=ages, biomarkers=BIOS,
|
||||
cluster="local", n_workers=2, memory_per_worker="2GiB"), ref)
|
||||
|
||||
|
||||
def test_no_posterior_channels_is_not_an_error(tmp_path):
|
||||
"""HK1K K7535V: no O1 O2 P3 P4 left. Every module must give NaN / no events, not raise."""
|
||||
from synth_edf import AUX, EARS
|
||||
keep = [c for c in SCALP if c not in ("O1", "O2", "P3", "P4")] + list(EARS) + list(AUX)
|
||||
p = make_edf(tmp_path / "noposterior.edf", minutes=6, channels=keep)
|
||||
bios = tuple(Pipeline.default(impl="legacy").biomarker_names())
|
||||
for impl in ("legacy", "modern"):
|
||||
t = Pipeline.default(impl=impl).map([p], plan=DIRECTOR_CLUSTER, ages_months=[24], biomarkers=bios,
|
||||
**({"cluster": "sync"} if impl == "modern" else {}))
|
||||
assert t.error.iloc[0] == "", (impl, t.error.iloc[0])
|
||||
assert t.valid.iloc[0] == 1, (impl, t.reasons.iloc[0])
|
||||
assert not np.isfinite(t.posterior_rhythm_hz.iloc[0]), impl
|
||||
|
||||
|
||||
def test_annotation_text_not_utf8_is_not_an_error(tmp_path):
|
||||
"""ISSSTELEÓN: annotation texts written in a Windows code page (bytes invalid in UTF-8).
|
||||
Legacy reads them as the director's edf_convert does (UTF-8 with replacement)."""
|
||||
p = make_edf(tmp_path / "cp1252.edf", minutes=6, annotations=[(30.0, None, "ojos cerrXdos")])
|
||||
b = Path(p).read_bytes()
|
||||
assert b.count(b"cerrXdos") == 1
|
||||
Path(p).write_bytes(b.replace(b"cerrXdos", b"cerr\x8cdos"))
|
||||
for impl in ("legacy", "modern"):
|
||||
t = Pipeline.default(impl=impl).map([p], plan=DIRECTOR_CLUSTER, ages_months=[24],
|
||||
biomarkers=("posterior_rhythm",),
|
||||
**({"cluster": "sync"} if impl == "modern" else {}))
|
||||
assert t.error.iloc[0] == "", (impl, t.error.iloc[0])
|
||||
from tea.legacy.preprocessing.api import _annotations
|
||||
a = _annotations(p)
|
||||
assert any(d.startswith("ojos cerr") for d in a.description)
|
||||
|
||||
|
||||
def _inverse(x):
|
||||
return 1 / x
|
||||
|
||||
|
||||
def test_task_failure_becomes_a_row_not_a_stopped_batch():
|
||||
"""A task that fails at the Dask level (KilledWorker on the cluster) must not stop the batch."""
|
||||
out = dask_runner.run(_inverse, [(1,), (0,), (4,)], cluster="local", n_workers=1,
|
||||
memory_per_worker="1GiB", on_error=lambda a, e: f"{type(e).__name__} {a[0]}")
|
||||
assert out == [1.0, "ZeroDivisionError 0", 0.25]
|
||||
with pytest.raises(ZeroDivisionError):
|
||||
dask_runner.run(_inverse, [(0,)], cluster="local", n_workers=1, memory_per_worker="1GiB")
|
||||
|
||||
|
||||
def test_positive_priority_refused():
|
||||
with pytest.raises(ValueError, match="positive priorities"):
|
||||
dask_runner.run(lambda: 1, [()], cluster="sync", priority=1)
|
||||
|
||||
|
||||
def test_remote_client_is_closed_never_shut_down(monkeypatch):
|
||||
calls = []
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, addr, direct_to_workers=None):
|
||||
calls.append(("init", addr, direct_to_workers))
|
||||
|
||||
def get_versions(self, check=False):
|
||||
calls.append(("versions", check))
|
||||
|
||||
def close(self):
|
||||
calls.append(("close",))
|
||||
|
||||
def shutdown(self):
|
||||
calls.append(("shutdown",))
|
||||
|
||||
def restart(self):
|
||||
calls.append(("restart",))
|
||||
|
||||
import distributed
|
||||
monkeypatch.setattr(distributed, "Client", FakeClient)
|
||||
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://scheduler:8786")
|
||||
monkeypatch.delenv("DASK_SCHEDULER", raising=False)
|
||||
with dask_runner.client_for("auto"):
|
||||
pass
|
||||
assert calls == [("init", "tcp://scheduler:8786", False), ("versions", True), ("close",)]
|
||||
|
||||
|
||||
def test_study_raises_not_valid(edfs):
|
||||
_, bad, _ = edfs
|
||||
with pytest.raises(NotValid, match="electrodos de cuero"):
|
||||
Pipeline.default(impl="legacy").study(bad, plan=DIRECTOR_CLUSTER, age_months=26)
|
||||
|
||||
|
||||
@pytest.mark.cluster
|
||||
@pytest.mark.skipif(not dask_runner.scheduler_address(), reason="no DASK_SCHEDULER")
|
||||
def test_remote_equals_sync(edfs):
|
||||
"""On the cluster job: the synthetic files are local to the job pod, so they are
|
||||
read by the driver-side sync run only; the remote run uses the HK1K check instead
|
||||
(verification/, python -m verification hk1k). Here we only check the remote scheduler answers a trivial graph."""
|
||||
out = dask_runner.run(lambda x: x * 2, [(1,), (2,)], cluster="remote")
|
||||
assert out == [2, 4]
|
||||
@@ -1,52 +0,0 @@
|
||||
"""PreprocessPlan: checks, round trip, hash."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from tea.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
|
||||
@@ -1,105 +0,0 @@
|
||||
"""Modern preprocessing: same plan, same filter as the director (scipy sosfiltfilt per gap-free
|
||||
run), agrees with the director's output sample by sample, edges and gaps included."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from synth_edf import make_edf
|
||||
from tea.contracts.testing import check_preprocessed
|
||||
from tea.legacy.preprocessing import MODULE as LEGACY
|
||||
from tea.legacy.validation import MODULE as LVAL
|
||||
from tea.preprocessing import DIRECTOR_CLI, DIRECTOR_CLUSTER, MODULE, PreprocessPlan
|
||||
from tea.validation import MODULE as VAL
|
||||
|
||||
# the director stores variants as float32: compare to float32 precision
|
||||
TOL_UV = 1e-3
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def edf(tmp_path_factory):
|
||||
return make_edf(tmp_path_factory.mktemp("pre") / "s.edf", minutes=5, bad={"bursts": ["P4"]}, line_uv=8)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def edf_gaps(tmp_path_factory):
|
||||
return make_edf(tmp_path_factory.mktemp("pregap") / "g.edf", minutes=5, line_uv=8,
|
||||
gaps=((40.0, 6.0), (130.5, 2.0), (200.0, 12.0)))
|
||||
|
||||
|
||||
def _both(path, base):
|
||||
pm = MODULE.run(path, MODULE.plan_for(VAL.summarize(path), base.to_dict()))
|
||||
pl = LEGACY.run(path, LEGACY.plan_for(LVAL.summarize(path), base.to_dict()))
|
||||
check_preprocessed(pm)
|
||||
assert set(pm.variants) == set(pl.variants)
|
||||
return pm, pl
|
||||
|
||||
|
||||
@pytest.mark.parametrize("base", [DIRECTOR_CLUSTER, DIRECTOR_CLI], ids=lambda p: p.name)
|
||||
def test_agrees_with_legacy_sample_by_sample(edf, base):
|
||||
"""No gaps: the same numbers as the director, edges included (float32 precision)."""
|
||||
pm, pl = _both(edf, base)
|
||||
for v in pm.variants:
|
||||
a, b = pm.variant(v), pl.variant(v)
|
||||
assert a.ch_names == b.ch_names
|
||||
xa, xb = a.get_data() * 1e6, b.get_data() * 1e6
|
||||
assert np.isfinite(xa).all() and np.isfinite(xb).all()
|
||||
d = np.abs(xa - xb).max()
|
||||
assert d < TOL_UV * max(1.0, np.abs(xb).max() / 100), f"{v}: max difference {d:.4f} uV"
|
||||
assert (pm.windows.clean == pl.windows.clean).all()
|
||||
|
||||
|
||||
GAPS = ((40.0, 6.0), (130.5, 2.0), (200.0, 12.0))
|
||||
|
||||
|
||||
def test_gaps_stay_gaps(edf_gaps):
|
||||
"""BAD_ACQ_SKIP: NaN in every variant and channel (the director's EDF reader reads the
|
||||
zeros as signal and filters across them; his Natus route keeps NaN, as here). Away from
|
||||
the gaps the numbers stay close to the director's."""
|
||||
pm, pl = _both(edf_gaps, DIRECTOR_CLUSTER)
|
||||
for v in pm.variants:
|
||||
a, b = pm.variant(v).get_data() * 1e6, pl.variant(v).get_data() * 1e6
|
||||
fs = pm.variant(v).info["sfreq"]
|
||||
t = np.arange(a.shape[1]) / fs
|
||||
in_gap = np.zeros(len(t), bool)
|
||||
near = np.zeros(len(t), bool)
|
||||
for g0, d in GAPS:
|
||||
in_gap |= (t >= g0) & (t < g0 + d)
|
||||
near |= (t >= g0 - 20) & (t < g0 + d + 20)
|
||||
assert np.isnan(a[:, in_gap]).all(), v
|
||||
assert np.isfinite(a[:, ~in_gap]).all(), v
|
||||
far = ~near # the notch is an FFT over each gap-free run: runs
|
||||
d = np.abs(a[:, far] - b[:, far]) # split differently change it a little everywhere
|
||||
assert np.median(d) < 0.5 and np.corrcoef(a[:, far].ravel(), b[:, far].ravel())[0, 1] > 0.999, v
|
||||
|
||||
|
||||
def test_aux_filtered_not_rereferenced(edf):
|
||||
pm = MODULE.run(edf, MODULE.plan_for(VAL.summarize(edf), DIRECTOR_CLUSTER.to_dict()))
|
||||
r = pm.variant("hp05_prom")
|
||||
assert set(r.get_channel_types(picks=["LOC", "ROC", "EKG"])) == {"eog", "ecg"}
|
||||
assert "P4" not in r.ch_names and "A1" not in r.ch_names
|
||||
assert np.nanmax(abs(r.get_data(picks="eeg").mean(axis=0))) < 1e-12 # average reference
|
||||
|
||||
|
||||
def test_zapline_step(edf):
|
||||
d = DIRECTOR_CLUSTER.to_dict()
|
||||
d["steps"] = [s for s in d["steps"] if s["kind"] != "interpolated_notch"] + \
|
||||
[{"kind": "zapline", "params": {"nremove": 1}}]
|
||||
pm = MODULE.run(edf, MODULE.plan_for(VAL.summarize(edf), PreprocessPlan.from_dict(d).to_dict()))
|
||||
assert pm.plan["run"]["line_removal"] == "zapline"
|
||||
from mne.time_frequency import psd_array_welch
|
||||
P, f = psd_array_welch(pm.variant("hp05_prom").get_data(picks="eeg"), 250.0, n_fft=1000, verbose="error")
|
||||
at60 = P[:, np.argmin(abs(f - 60))].mean()
|
||||
near = P[:, (abs(f - 60) > 3) & (abs(f - 60) < 8)].mean()
|
||||
assert at60 < 3 * near
|
||||
|
||||
|
||||
def test_plan_bads_and_gates(edf):
|
||||
d = MODULE.plan_for(VAL.summarize(edf), DIRECTOR_CLUSTER.to_dict())
|
||||
assert "P4" in d["bads"] and "P4" in d["reasons"]
|
||||
many = {**d, "bads": d["bads"] + ["Fp1", "Fp2", "F3", "F4", "F7", "F8", "Fz"]}
|
||||
with pytest.raises(ValueError, match="scalp electrodes usable"):
|
||||
MODULE.run(edf, many)
|
||||
@@ -1,95 +0,0 @@
|
||||
"""MLflow round trips on a temporary sqlite store, and the privacy guard."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
mlflow = pytest.importorskip("mlflow")
|
||||
|
||||
from tea.legacy.biomarkers.posterior_rhythm import LegacyPosteriorRhythm # noqa: E402
|
||||
from tea.preprocessing import DIRECTOR_CLUSTER, PreprocessPlan # noqa: E402
|
||||
from tea.serving import Forbidden, load_biomarker, load_plan, log_biomarker, log_plan # noqa: E402
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def store(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("MLFLOW_DISABLE_AGENT_HINT", "1")
|
||||
uri = f"sqlite:///{tmp_path / 'mlflow.db'}"
|
||||
mlflow.set_tracking_uri(uri)
|
||||
mlflow.set_registry_uri(uri)
|
||||
monkeypatch.chdir(tmp_path) # artifacts land under tmp_path/mlruns
|
||||
yield uri
|
||||
mlflow.set_tracking_uri(None)
|
||||
|
||||
|
||||
def _table(n=300, seed=0):
|
||||
rng = np.random.default_rng(seed)
|
||||
ages = rng.uniform(12, 48, n)
|
||||
return pd.DataFrame({"posterior_rhythm_hz": 5 + ages / 20 + rng.normal(0, .5, n), "age_months": ages})
|
||||
|
||||
|
||||
def test_plan_round_trip(store):
|
||||
v = log_plan(DIRECTOR_CLUSTER, registered_name="tea-plan-director-cluster")
|
||||
d = load_plan(f"models:/tea-plan-director-cluster/{v.version}")
|
||||
assert d["hash"] == DIRECTOR_CLUSTER.content_hash()
|
||||
assert PreprocessPlan.from_dict(d) == DIRECTOR_CLUSTER
|
||||
run = mlflow.get_run(v.run_id)
|
||||
assert run.data.tags["plan_hash"] == DIRECTOR_CLUSTER.content_hash()
|
||||
art = mlflow.artifacts.download_artifacts(run_id=v.run_id, artifact_path="plan/plan.json")
|
||||
assert json.loads(Path(art).read_text())["name"] == "director-cluster"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("baseline", ["curves", "age_blocks"])
|
||||
def test_biomarker_round_trip_pinned_to_plan(store, baseline):
|
||||
pv = log_plan(DIRECTOR_CLUSTER, registered_name="tea-plan-director-cluster")
|
||||
plan_uri = f"models:/tea-plan-director-cluster/{pv.version}"
|
||||
rhythm = LegacyPosteriorRhythm(baseline=baseline).train(_table())
|
||||
bv = log_biomarker(rhythm, plan_uri=plan_uri, registered_name="tea-bio-posterior-rhythm")
|
||||
uri = f"models:/tea-bio-posterior-rhythm/{bv.version}"
|
||||
x = pd.DataFrame({"posterior_rhythm_hz": [5.0, 6.5, 9.0], "age_months": [30.0] * 3})
|
||||
want = rhythm.predict(x)
|
||||
pd.testing.assert_frame_equal(mlflow.pyfunc.load_model(uri).predict(x), want)
|
||||
pd.testing.assert_frame_equal(load_biomarker(uri).predict(x), want)
|
||||
tags = mlflow.get_run(bv.run_id).data.tags
|
||||
assert tags["plan_uri"] == plan_uri and tags["impl"] == "legacy"
|
||||
assert tags["plan_hash"] == DIRECTOR_CLUSTER.content_hash()
|
||||
|
||||
|
||||
def test_biomarker_model_runs_with_only_its_code(store, tmp_path):
|
||||
rhythm = LegacyPosteriorRhythm(baseline="curves").train(_table())
|
||||
bv = log_biomarker(rhythm, registered_name="tea-bio-iso")
|
||||
code = f"""
|
||||
import sys, json, mlflow, pandas as pd
|
||||
mlflow.set_tracking_uri({store!r}); mlflow.set_registry_uri({store!r})
|
||||
m = mlflow.pyfunc.load_model("models:/tea-bio-iso/{bv.version}")
|
||||
import tea
|
||||
out = m.predict(pd.DataFrame({{"posterior_rhythm_hz": [5.0], "age_months": [30.0]}}))
|
||||
try:
|
||||
import tea.pipeline
|
||||
other = "importable"
|
||||
except ImportError:
|
||||
other = "missing"
|
||||
print(json.dumps({{"pkg": tea.__file__, "pipeline": other, "outside": int(out.outside.iloc[0])}}))
|
||||
"""
|
||||
out = subprocess.run([sys.executable, "-W", "ignore", "-c", code], capture_output=True, text=True,
|
||||
cwd=tmp_path, env={**__import__("os").environ, "MLFLOW_DISABLE_AGENT_HINT": "1"})
|
||||
assert out.returncode == 0, out.stderr[-2000:]
|
||||
r = json.loads(out.stdout.strip().splitlines()[-1])
|
||||
assert "code" in Path(r["pkg"]).parts, r["pkg"] # tea comes from the model's code
|
||||
assert r["pipeline"] == "missing" # nothing else of the library is there
|
||||
assert r["outside"] == -1
|
||||
|
||||
|
||||
def test_privacy_guard(store):
|
||||
with pytest.raises(Forbidden, match="study code"):
|
||||
log_plan(DIRECTOR_CLUSTER, registered_name="eeg_012-plan")
|
||||
small = LegacyPosteriorRhythm(baseline="age_blocks").train(_table(n=4))
|
||||
with pytest.raises(Forbidden, match="fewer than 5"):
|
||||
log_biomarker(small, registered_name="tea-bio-small")
|
||||
@@ -1,88 +0,0 @@
|
||||
"""Slow waves: legacy = the submodule's detector; modern agrees with legacy."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from synth_edf import make_edf
|
||||
from tea.contracts import Study
|
||||
from tea.contracts.testing import check_biomarker, check_process
|
||||
from tea.pipeline import Pipeline
|
||||
from tea.preprocessing import DIRECTOR_CLUSTER
|
||||
from tea.processes.slow_wave_staging import api as sws
|
||||
|
||||
BT = Path(__file__).resolve().parents[1] / "biomarcadores-tea"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def edf(tmp_path_factory):
|
||||
return make_edf(tmp_path_factory.mktemp("sw") / "s.edf", minutes=8)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def studies(edf):
|
||||
return (Pipeline.default("modern").study(edf, plan=DIRECTOR_CLUSTER, age_months=28),
|
||||
Pipeline.default("legacy").study(edf, plan=DIRECTOR_CLUSTER, age_months=28))
|
||||
|
||||
|
||||
@pytest.mark.skipif(not BT.exists(), reason="submodule absent")
|
||||
def test_legacy_waves_equal_submodule(edf, studies):
|
||||
code = f"""
|
||||
import json, sys, contextlib, io, warnings
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, {str(BT / 'preproceso')!r}); warnings.simplefilter("ignore")
|
||||
import un_estudio, eeg_io, ondas_lentas
|
||||
with contextlib.redirect_stdout(io.StringIO()), un_estudio.temporal(Path({str(edf)!r}),
|
||||
linea_hz=60.0, pasa_altas=(0.3, 0.5), pasa_bajas=100.0) as res:
|
||||
est = eeg_io.Estudio(res["preproc_npz"], preferir="hp05_prom", estricto=True)
|
||||
out = []
|
||||
for c in ondas_lentas.CANALES_FRONTAL:
|
||||
o = ondas_lentas.detectar(est.datos(canales=[c])[:, 0], est.fs)
|
||||
out += [[c, float(r.t_ini_s), float(r.p2p_uV)] for r in o.itertuples()]
|
||||
print(json.dumps(out))
|
||||
"""
|
||||
r = subprocess.run([sys.executable, "-W", "ignore", "-c", code], capture_output=True, text=True)
|
||||
assert r.returncode == 0, r.stderr[-1500:]
|
||||
ref = json.loads(r.stdout.strip().splitlines()[-1])
|
||||
ev = studies[1].label("slow_wave_staging").events
|
||||
assert [[c, t, p] for c, t, p in zip(ev.canal, ev.t_ini_s.astype(float), ev.p2p_uV.astype(float))] == ref
|
||||
|
||||
|
||||
def test_modern_agrees_with_legacy(studies):
|
||||
sm, sl = studies
|
||||
a, b = sm.label("slow_wave_staging"), sl.label("slow_wave_staging")
|
||||
assert (a.per_window.values == b.per_window.values).mean() >= 0.95
|
||||
assert abs(len(a.events) - len(b.events)) <= max(2, 0.1 * len(b.events))
|
||||
m = Pipeline.default("modern").module("slow_waves").measure(sm)
|
||||
l = Pipeline.default("legacy").module("slow_waves").measure(sl)
|
||||
for k in m:
|
||||
assert (np.isnan(m[k]) and np.isnan(l[k])) or m[k] == pytest.approx(l[k], rel=0.1, abs=0.05), k
|
||||
|
||||
|
||||
def test_n3_rule():
|
||||
"""20% coverage of the 30 s epoch around the window decides N3."""
|
||||
iv = np.array([[10.0, 16.5]]) # 6.5 s of slow waves
|
||||
assert sws.coverage(iv, 0.0, 30.0) == pytest.approx(6.5 / 30)
|
||||
assert sws.coverage(iv, 0.0, 30.0) >= sws.FRAC_N3
|
||||
assert sws.coverage(np.array([[10.0, 15.0]]), 0.0, 30.0) < sws.FRAC_N3
|
||||
|
||||
|
||||
def test_contracts(studies):
|
||||
for impl, s in zip(("modern", "legacy"), studies):
|
||||
base = Study(s.prep, {k: v for k, v in s.labels.items() if k == "sleep_state" or k == "annotation_mask"})
|
||||
check_process(Pipeline.default(impl).module("slow_wave_staging"), base)
|
||||
|
||||
|
||||
def test_biomarker_contract(tmp_path):
|
||||
pipe = Pipeline.default("modern")
|
||||
sts = [pipe.study(make_edf(tmp_path / f"s{i}.edf", minutes=6, seed=i), plan=DIRECTOR_CLUSTER,
|
||||
age_months=20 + 4 * i) for i in range(3)]
|
||||
from tea.biomarkers.slow_waves import SlowWaves
|
||||
check_biomarker(SlowWaves(baseline="age_blocks"), sts, [20, 24, 28])
|
||||
@@ -1,48 +0,0 @@
|
||||
"""Window selection and spikes: modern equals legacy; the focus is found."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from synth_edf import make_edf
|
||||
from tea.contracts import Study
|
||||
from tea.contracts.testing import check_biomarker, check_process
|
||||
from tea.pipeline import Pipeline
|
||||
from tea.preprocessing import DIRECTOR_CLUSTER
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def studies(tmp_path_factory):
|
||||
p = make_edf(tmp_path_factory.mktemp("spk") / "s.edf", minutes=8, bad={"spikes": ["C3"]})
|
||||
return (Pipeline.default("modern").study(p, plan=DIRECTOR_CLUSTER, age_months=28),
|
||||
Pipeline.default("legacy").study(p, plan=DIRECTOR_CLUSTER, age_months=28))
|
||||
|
||||
|
||||
def test_window_selection_equal(studies):
|
||||
a = studies[0].label("window_selection").events
|
||||
b = studies[1].label("window_selection").events
|
||||
assert len(a) == len(b) and (a.apto.values == b.apto.values).all()
|
||||
|
||||
|
||||
def test_spike_indicators_equal(studies):
|
||||
im = Pipeline.default("modern").module("spikes").indicators(studies[0])
|
||||
il = Pipeline.default("legacy").module("spikes").indicators(studies[1])
|
||||
for k in ("n_total", "n_util", "canal_foco", "foco_frac", "lateralidad", "tasa_NREM", "tasa_despierto"):
|
||||
a, b = im[k], il[k]
|
||||
assert (isinstance(a, float) and np.isnan(a) and np.isnan(b)) or a == b, k
|
||||
assert im["n_total"] > 100 and im["canal_foco"] == "C3"
|
||||
|
||||
|
||||
def test_contracts(studies):
|
||||
for impl, s in zip(("modern", "legacy"), studies):
|
||||
base = Study(s.prep, {k: v for k, v in s.labels.items() if k == "annotation_mask"})
|
||||
check_process(Pipeline.default(impl).module("window_selection"), base)
|
||||
|
||||
|
||||
def test_biomarker_contract(tmp_path):
|
||||
pipe = Pipeline.default("modern")
|
||||
sts = [pipe.study(make_edf(tmp_path / f"s{i}.edf", minutes=5, seed=i, bad={"spikes": ["C3"]}),
|
||||
plan=DIRECTOR_CLUSTER, age_months=20 + 4 * i) for i in range(3)]
|
||||
from tea.biomarkers.spikes import Spikes
|
||||
check_biomarker(Spikes(baseline="age_blocks"), sts, [20, 24, 28])
|
||||
@@ -1,43 +0,0 @@
|
||||
"""Spindle topography: modern agrees with legacy; spindle channels stand out."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from synth_edf import SPINDLE, make_edf
|
||||
from tea.contracts.testing import check_biomarker
|
||||
from tea.pipeline import Pipeline
|
||||
from tea.preprocessing import DIRECTOR_CLUSTER
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def studies(tmp_path_factory):
|
||||
p = make_edf(tmp_path_factory.mktemp("topo") / "s.edf", minutes=8)
|
||||
return (Pipeline.default("modern").study(p, plan=DIRECTOR_CLUSTER, age_months=28),
|
||||
Pipeline.default("legacy").study(p, plan=DIRECTOR_CLUSTER, age_months=28))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("laplacian", [False, True])
|
||||
def test_modern_agrees_with_legacy(studies, laplacian):
|
||||
from tea.biomarkers.spindle_topography import SpindleTopography
|
||||
from tea.legacy.biomarkers.spindle_topography import LegacySpindleTopography
|
||||
m = SpindleTopography(laplacian=laplacian).measure(studies[0])
|
||||
l = LegacySpindleTopography(laplacian=laplacian).measure(studies[1])
|
||||
for k in m:
|
||||
assert (np.isnan(m[k]) and np.isnan(l[k])) or m[k] == pytest.approx(l[k], rel=0.02), k
|
||||
|
||||
|
||||
def test_spindle_channels_stand_out(studies):
|
||||
m = Pipeline.default("modern").module("spindle_topography").measure(studies[0])
|
||||
inside = np.mean([m[f"topo_enh_{c}"] for c in SPINDLE])
|
||||
outside = np.mean([m[f"topo_enh_{c}"] for c in ("Fp1", "Fp2", "F7", "F8", "P3", "P4", "Pz")])
|
||||
assert inside > 1.5 * outside
|
||||
|
||||
|
||||
def test_biomarker_contract(tmp_path):
|
||||
pipe = Pipeline.default("modern")
|
||||
sts = [pipe.study(make_edf(tmp_path / f"s{i}.edf", minutes=6, seed=i), plan=DIRECTOR_CLUSTER,
|
||||
age_months=20 + 4 * i) for i in range(3)]
|
||||
from tea.biomarkers.spindle_topography import SpindleTopography
|
||||
check_biomarker(SpindleTopography(baseline="age_blocks"), sts, [20, 24, 28])
|
||||
@@ -1,119 +0,0 @@
|
||||
"""Spindles: legacy = the cluster route on the submodule; modern agrees with legacy."""
|
||||
|
||||
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.contracts import Study
|
||||
from tea.contracts.testing import check_biomarker, check_process
|
||||
from tea.pipeline import Pipeline
|
||||
from tea.preprocessing import DIRECTOR_CLUSTER
|
||||
|
||||
BT = Path(__file__).resolve().parents[1] / "biomarcadores-tea"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def edf(tmp_path_factory):
|
||||
return make_edf(tmp_path_factory.mktemp("spin") / "s.edf", minutes=8, rhythm_hz=6.5)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def studies(edf):
|
||||
return (Pipeline.default("modern").study(edf, plan=DIRECTOR_CLUSTER, age_months=28),
|
||||
Pipeline.default("legacy").study(edf, plan=DIRECTOR_CLUSTER, age_months=28))
|
||||
|
||||
|
||||
def _director(edf_path):
|
||||
code = f"""
|
||||
import json, sys, contextlib, io, warnings
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
sys.path.insert(0, {str(BT / 'preproceso')!r}); warnings.simplefilter("ignore")
|
||||
import un_estudio, eeg_io, vigilancia, seleccion, husos, ritmo as r
|
||||
with contextlib.redirect_stdout(io.StringIO()), un_estudio.temporal(Path({str(edf_path)!r}),
|
||||
linea_hz=60.0, pasa_altas=(0.3, 0.5), pasa_bajas=100.0) as res:
|
||||
est = eeg_io.Estudio(res["preproc_npz"], preferir="hp05_prom", estricto=True)
|
||||
ivs = [{{k: d[k] for k in ("t_ini", "t_fin", "estado", "fuente")}} for d in eeg_io.intervalos_estado(est)]
|
||||
m = np.zeros(est.n, dtype=bool)
|
||||
for v in res["ventanas_qc"]:
|
||||
if v.get("veredicto") != "limpia" or v.get("montaje", False):
|
||||
m[int(v["t_ini"] * est.fs):int(v["t_fin"] * est.fs)] = True
|
||||
for d in ivs:
|
||||
if d["estado"] in seleccion.EXCLUIDOS + seleccion.PROVOCACION:
|
||||
m[int(d["t_ini"] * est.fs):int(d["t_fin"] * est.fs)] = True
|
||||
d = json.loads(Path({str(BT / 'normas' / 'estado_hk1k.json')!r}).read_text())
|
||||
t, _ = vigilancia.clasificar(vigilancia.rasgos(est, linea_hz=60.0, excluir=m), d["ref"],
|
||||
[float(d["cortes_A"][0]), float(d["corte_B"])], edad_meses=28.0)
|
||||
vig = [float(a) for a, e in zip(t.t_ini_s, t.vigilancia) if e == "vigilia"]
|
||||
sue = [float(a) for a, e in zip(t.t_ini_s, t.vigilancia) if e == "sueno"]
|
||||
picos = []
|
||||
for c in ("O1", "O2", "P3", "P4"):
|
||||
f, P, n = r.psd_de_ventanas(est.datos(canales=[c])[:, 0], est.fs, vig, r.VENT_S)
|
||||
if f is not None:
|
||||
pk, pr, hay = eeg_io.pico_dominante(f, P)
|
||||
if hay: picos.append(float(pk))
|
||||
rh = float(np.median(picos)) if len(picos) >= 2 and len(vig) >= r.MIN_VENTANAS else float("nan")
|
||||
ev, minutos, nombres, cont = husos.detectar(est, sue, ritmo_posterior=rh)
|
||||
res_ = husos.resumen(ev, minutos, nombres, estudio="")
|
||||
print(json.dumps({{k: v for k, v in res_.items() if k != "estudio"}}, default=float))
|
||||
"""
|
||||
out = subprocess.run([sys.executable, "-W", "ignore", "-c", code], capture_output=True, text=True)
|
||||
assert out.returncode == 0, out.stderr[-1500:]
|
||||
return json.loads(out.stdout.strip().splitlines()[-1])
|
||||
|
||||
|
||||
@pytest.mark.skipif(not BT.exists(), reason="submodule absent")
|
||||
def test_legacy_equals_cluster_route(edf, studies):
|
||||
ref = _director(edf)
|
||||
_, sl = studies
|
||||
got = Pipeline.default("legacy").module("spindles").summary(sl)
|
||||
for k in ("n_husos", "densidad_por_min_canal", "frecuencia_mediana_Hz", "pct_rapidos",
|
||||
"duracion_mediana_s", "densidad_lento", "densidad_rapido"):
|
||||
assert got[k] == ref[k], k
|
||||
|
||||
|
||||
def test_modern_agrees_with_legacy(studies):
|
||||
sm, sl = studies
|
||||
m = Pipeline.default("modern").module("spindles").measure(sm)
|
||||
l = Pipeline.default("legacy").module("spindles").measure(sl)
|
||||
for k in m:
|
||||
assert m[k] == pytest.approx(l[k], rel=0.05, abs=0.05), k
|
||||
assert m["spindle_frequency_hz"] == pytest.approx(13.0, abs=0.3)
|
||||
|
||||
|
||||
def test_contracts(studies):
|
||||
for impl, s in zip(("modern", "legacy"), studies):
|
||||
pipe = Pipeline.default(impl)
|
||||
base = Study(s.prep, {k: v for k, v in s.labels.items() if k != "spindle_detection"})
|
||||
check_process(pipe.module("spindle_detection"), base)
|
||||
|
||||
|
||||
def test_biomarker_contract(tmp_path):
|
||||
pipe = Pipeline.default("modern")
|
||||
sts = [pipe.study(make_edf(tmp_path / f"s{i}.edf", minutes=6, seed=i), plan=DIRECTOR_CLUSTER,
|
||||
age_months=20 + 4 * i) for i in range(3)]
|
||||
from tea.biomarkers.spindles import Spindles
|
||||
check_biomarker(Spindles(baseline="age_blocks"), sts, [20, 24, 28])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("impl", ["modern", "legacy"])
|
||||
def test_phase_restricts_the_search(studies, impl):
|
||||
"""phase='N3' searches only N3 sleep windows (none in this study: no spindles, no minutes)."""
|
||||
s = studies[0] if impl == "modern" else studies[1]
|
||||
pipe = Pipeline.default(impl)
|
||||
det = type(pipe.module("spindle_detection"))(phase="N3")
|
||||
assert det.requires == ("sleep_state", "slow_wave_staging")
|
||||
ev = det.predict(s).events
|
||||
n3 = (s.label("slow_wave_staging").per_window == "N3").sum()
|
||||
assert n3 == 0 and len(ev) == 0 and ev.attrs["minutes"] == 0
|
||||
det2 = type(pipe.module("spindle_detection"))(phase="N2")
|
||||
assert len(det2.predict(s).events) == len(s.label("spindle_detection").events) # all sleep is N2 here
|
||||
with pytest.raises(ValueError, match="phase"):
|
||||
type(pipe.module("spindle_detection"))(phase="REM")
|
||||
@@ -1,48 +0,0 @@
|
||||
"""The synthetic EDF builder: readable by MNE and by the director's EDF reader."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from synth_edf import AUX, EARS, SCALP, make_edf
|
||||
|
||||
PREPROCESO = Path(__file__).resolve().parents[1] / "biomarcadores-tea" / "preproceso"
|
||||
|
||||
|
||||
def test_mne_reads_it(tmp_path):
|
||||
import mne
|
||||
p = make_edf(tmp_path / "s.edf", minutes=2, gaps=[(30.0, 5.0)])
|
||||
raw = mne.io.read_raw_edf(p, preload=True, verbose="error")
|
||||
assert raw.ch_names == SCALP + list(EARS) + list(AUX)
|
||||
assert raw.info["sfreq"] == 250.0
|
||||
assert any(d == "BAD_ACQ_SKIP" for d in raw.annotations.description)
|
||||
assert any("Dormido" in d for d in raw.annotations.description)
|
||||
x = raw.get_data(picks="O1")[0] * 1e6
|
||||
assert 10 < x.std() < 150
|
||||
|
||||
|
||||
def test_neighbours_correlate_and_ears_follow_temporal(tmp_path):
|
||||
import mne
|
||||
raw = mne.io.read_raw_edf(make_edf(tmp_path / "s.edf", minutes=2), preload=True, verbose="error")
|
||||
x = raw.copy().filter(1, 40, verbose="error").get_data()
|
||||
i = {c: k for k, c in enumerate(raw.ch_names)}
|
||||
r = np.corrcoef(x)
|
||||
assert r[i["C3"], i["Cz"]] > 0.2
|
||||
assert r[i["A1"], i["T3"]] > 0.2
|
||||
|
||||
|
||||
@pytest.mark.skipif(not PREPROCESO.exists(), reason="biomarcadores-tea submodule absent")
|
||||
def test_director_reader_reads_it(tmp_path):
|
||||
sys.path.insert(0, str(PREPROCESO))
|
||||
try:
|
||||
import edf_convert
|
||||
X, nombres, fs, h, desc = edf_convert.leer_edf(make_edf(tmp_path / "s.edf", minutes=1))
|
||||
finally:
|
||||
sys.path.remove(str(PREPROCESO))
|
||||
assert fs == 250.0
|
||||
assert set(SCALP) <= set(nombres) and "EKG" in nombres
|
||||
assert any(txt == "Dormido" for _, _, txt in h["anotaciones"])
|
||||
@@ -1,63 +0,0 @@
|
||||
"""Modern validation: agrees with the legacy (director) validation on synthetic studies."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from synth_edf import SCALP, make_edf
|
||||
from tea.contracts.testing import check_validation
|
||||
from tea.legacy.validation import MODULE as LEGACY
|
||||
from tea.validation import MODULE, Validation, ValidationConfig
|
||||
|
||||
CASES = {
|
||||
"faults": dict(bad={"flat": ["P3"], "bursts": ["P4"], "bridge": [("F3", "C3")]}),
|
||||
"too_few_scalp": dict(bad={"flat": SCALP[:8]}),
|
||||
"loud_and_frozen": dict(bad={"loud": ["O1"], "frozen": ["T4"]}),
|
||||
"clean": dict(),
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", params=list(CASES))
|
||||
def case(request, tmp_path_factory):
|
||||
p = make_edf(tmp_path_factory.mktemp(request.param) / "s.edf", minutes=5, **CASES[request.param])
|
||||
return request.param, p
|
||||
|
||||
|
||||
def test_agrees_with_legacy(case):
|
||||
name, p = case
|
||||
m, l = MODULE.run(p), LEGACY.run(p)
|
||||
assert sorted(m["bad"]) == sorted(l["malos"]), name
|
||||
assert m["valid"] == l["valid"], name
|
||||
assert m["level"] == l["triaje"]["nivel"], name
|
||||
assert abs(m["clean_pct"] - l["qc"]["pct_ventanas_limpias"]) <= 5.0, name
|
||||
|
||||
|
||||
def test_contract_and_fhir(case):
|
||||
_, p = case
|
||||
bundle, valid = MODULE.validate(p)
|
||||
check_validation(bundle, valid, MODULE.summarize(p))
|
||||
from fhir.resources.R4B.bundle import Bundle
|
||||
Bundle.model_validate(bundle)
|
||||
|
||||
|
||||
def test_gaps_are_gaps_not_signal(tmp_path):
|
||||
"""Accepted difference: a BAD_ACQ_SKIP span makes its windows HUECO (legacy reads zeros)."""
|
||||
p = make_edf(tmp_path / "g.edf", minutes=5, gaps=[(60.0, 8.0)])
|
||||
r = MODULE.run(p)
|
||||
assert any(w["verdict"] == "HUECO" for w in r["windows"])
|
||||
assert r["coverage"] < 1.0 and r["valid"] == 1
|
||||
|
||||
|
||||
def test_broken_file_is_not_valid_not_an_exception(tmp_path):
|
||||
p = tmp_path / "x.edf"
|
||||
p.write_bytes(b"0" * 300)
|
||||
bundle, valid = MODULE.validate(p)
|
||||
assert valid == 0
|
||||
check_validation(bundle, valid)
|
||||
|
||||
|
||||
def test_config_changes_the_verdict(tmp_path):
|
||||
p = make_edf(tmp_path / "s.edf", minutes=4, bad={"flat": SCALP[:2]}) # 17 usable, 2 bad
|
||||
assert MODULE.run(p)["valid"] == 1
|
||||
assert Validation(ValidationConfig(min_scalp=18)).run(p)["valid"] == 0
|
||||
assert Validation(ValidationConfig(max_bad_scalp=1)).run(p)["level"] == "no_analizable"
|
||||
@@ -1,84 +0,0 @@
|
||||
"""The cluster checks (verification/, outside the package): input guards, privacy, ages."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from verification import common, hk1k, issste
|
||||
|
||||
|
||||
@pytest.mark.parametrize("p", ["raw/eeg-data/eeg_001/x.edf", "processed/eeg-edf-2025/a/x.edf",
|
||||
"raw/2021-204/a.edf", "raw/eeg-helsinki/../eeg-data/x.edf"])
|
||||
def test_hk1k_guard_refuses_other_prefixes(p):
|
||||
with pytest.raises(PermissionError):
|
||||
hk1k.guard(p)
|
||||
|
||||
|
||||
def test_hk1k_guard_accepts_hk1k():
|
||||
assert hk1k.guard("s3://raw/eeg-helsinki/sub-1/x.edf") == "raw/eeg-helsinki/sub-1/x.edf"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("p", ["raw/eeg-data/eeg_001/x.edf", "raw/eeg-data-2026/a/x.erd",
|
||||
"raw/2021-204/a.edf", "processed/eeg-edf/eeg_001.edf",
|
||||
"processed/eeg-edf-2025/../cohort-edf-2025/x.edf", "raw/eeg-helsinki/x.edf"])
|
||||
def test_issste_guard_refuses_other_prefixes(p):
|
||||
with pytest.raises(PermissionError):
|
||||
issste.guard(p)
|
||||
|
||||
|
||||
def test_issste_guard_accepts_the_two_lots():
|
||||
for lot in ("2025", "2026"):
|
||||
p = f"processed/eeg-edf-{lot}/a/b.edf"
|
||||
assert issste.guard("s3://" + p) == p
|
||||
|
||||
|
||||
def test_group_stats_suppresses_small_groups():
|
||||
assert common.group_stats([1.0, 2.0, 3.0]) == {"n": 3, "suppressed": True}
|
||||
s = common.group_stats([6.0, 6.5, 7.0, 7.5, 8.0])
|
||||
assert s["n"] == 5 and s["median"] == 7.0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("out", ["processed/eeg-edf-2025/", "raw/x/", "processed/usuarios/../eeg-edf/"])
|
||||
def test_summary_writes_only_to_user_area(out):
|
||||
with pytest.raises(PermissionError):
|
||||
common.write_summary("{}", out, "x.json")
|
||||
|
||||
|
||||
def test_clean_removes_paths_file_names_and_study_codes():
|
||||
msg = ("ValueError: bad header in /tmp/tea_s3_x/PEREZ~ GARCIA_1a2b.edf (eeg_017) "
|
||||
"and 'LOPEZ_3c.edf', [MARTINEZ.EDF]")
|
||||
out = common.clean(msg)
|
||||
for s in ("PEREZ", "GARCIA", "LOPEZ", "MARTINEZ", "eeg_017", "/tmp", ".edf", ".EDF"):
|
||||
assert s not in out, (s, out)
|
||||
assert out.startswith("ValueError: bad header")
|
||||
|
||||
|
||||
def test_age_from_a_real_edf_header(tmp_path):
|
||||
from edfio import Edf, EdfSignal, Patient, Recording
|
||||
p = tmp_path / "a.edf"
|
||||
Edf([EdfSignal(np.zeros(256), 256.0, label="Fz")],
|
||||
patient=Patient(birthdate=date(2023, 1, 15)),
|
||||
recording=Recording(startdate=date(2025, 4, 1))).write(p)
|
||||
head = p.read_bytes()[:256]
|
||||
assert issste.age_from_header(head) == round((date(2025, 4, 1) - date(2023, 1, 15)).days / 30.4375, 1)
|
||||
|
||||
|
||||
def test_age_missing_or_impossible_is_none(tmp_path):
|
||||
from edfio import Edf, EdfSignal, Patient, Recording
|
||||
p = tmp_path / "b.edf"
|
||||
Edf([EdfSignal(np.zeros(256), 256.0, label="Fz")], patient=Patient(),
|
||||
recording=Recording(startdate=date(2025, 4, 1))).write(p)
|
||||
assert issste.age_from_header(p.read_bytes()[:256]) is None
|
||||
assert issste.age_from_header(b"short") is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("m, g", [(15.9, "<16"), (16.0, "16-36"), (36.9, "16-36"), (37.0, "37-48"),
|
||||
(49.0, ">48"), (None, "no age"), (float("nan"), "no age")])
|
||||
def test_age_groups(m, g):
|
||||
assert issste.age_group(m) == g
|
||||
|
||||
|
||||
def test_verification_is_not_in_the_package():
|
||||
import importlib.util
|
||||
assert importlib.util.find_spec("tea.verify") is None
|
||||
@@ -1,169 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Copy the director's code into tea.legacy, unchanged except imports.
|
||||
|
||||
python tools/vendor_legacy.py # (re)write every legacy _director/ folder
|
||||
python tools/vendor_legacy.py --check # exit 1 if any copy differs from the source
|
||||
|
||||
Each legacy module gets its OWN copy of every file it needs (the import
|
||||
closure of its roots), so legacy modules stay independent like the modern
|
||||
ones. The only changes to a copied file:
|
||||
|
||||
- the line `sys.path.insert(0, str(Path(__file__).resolve().parent))` is removed;
|
||||
- imports of sibling scripts become relative (`import eeg_io` ->
|
||||
`from . import eeg_io`; `from validacion import X` -> `from .validacion import X`);
|
||||
- a header comment records the source path, commit and SHA-256.
|
||||
|
||||
`--check` re-applies the same transformation to the pinned submodule and
|
||||
compares, so an edit to a legacy copy is caught (tests/legacy/test_vendor.py).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LEGACY = ROOT / "src" / "tea" / "legacy"
|
||||
SOURCES = {
|
||||
"preproceso": ROOT / "biomarcadores-tea" / "preproceso",
|
||||
}
|
||||
PINNED = {"biomarcadores-tea": "7dfc641"}
|
||||
|
||||
# legacy module -> (source tree, root scripts). The closure is computed.
|
||||
MANIFEST: dict[str, tuple[str, tuple[str, ...]]] = {
|
||||
"validation": ("preproceso", ("edf_convert", "lote", "triaje", "preproceso")),
|
||||
"preprocessing": ("preproceso", ("edf_convert", "lote", "preproceso")),
|
||||
"processes/annotation_mask": ("preproceso", ("eeg_io", "seleccion")),
|
||||
"processes/sleep_state": ("preproceso", ("eeg_io", "seleccion", "vigilancia")),
|
||||
"biomarkers/posterior_rhythm": ("preproceso", ("eeg_io", "ritmo")),
|
||||
"processes/spindle_detection": ("preproceso", ("eeg_io", "husos", "ritmo")),
|
||||
"biomarkers/spindles": ("preproceso", ("husos",)),
|
||||
"biomarkers/gradient": ("preproceso", ("eeg_io", "gradiente")),
|
||||
"processes/slow_wave_staging": ("preproceso", ("eeg_io", "ondas_lentas")),
|
||||
"biomarkers/slow_waves": ("preproceso", ("ondas_lentas",)),
|
||||
"biomarkers/coupling": ("preproceso", ("eeg_io", "acoplamiento")),
|
||||
"biomarkers/spindle_topography": ("preproceso", ("eeg_io", "topografia_huso")),
|
||||
"biomarkers/spikes": ("preproceso", ("eeg_io", "candidatos_punta")),
|
||||
"processes/window_selection": ("preproceso", ("eeg_io", "seleccion")),
|
||||
}
|
||||
|
||||
SYS_PATH_LINE = "sys.path.insert(0, str(Path(__file__).resolve().parent))"
|
||||
_IMPORT = re.compile(r"^(?P<ind>\s*)import (?P<mod>[A-Za-z_][A-Za-z_0-9]*)(?P<rest>(\s+as\s+\w+)?\s*(#.*)?)$")
|
||||
_FROM = re.compile(r"^(?P<ind>\s*)from (?P<mod>[A-Za-z_][A-Za-z_0-9]*) import (?P<rest>.*)$")
|
||||
|
||||
|
||||
def local_names(src: Path) -> set[str]:
|
||||
return {p.stem for p in src.glob("*.py")}
|
||||
|
||||
|
||||
def deps_of(path: Path, local: set[str]) -> set[str]:
|
||||
out = set()
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
m = _IMPORT.match(line) or _FROM.match(line)
|
||||
if m and m.group("mod") in local and m.group("mod") != path.stem:
|
||||
out.add(m.group("mod"))
|
||||
return out
|
||||
|
||||
|
||||
def closure(src: Path, roots) -> list[str]:
|
||||
local = local_names(src)
|
||||
todo, seen = list(roots), set()
|
||||
while todo:
|
||||
m = todo.pop()
|
||||
if m in seen:
|
||||
continue
|
||||
seen.add(m)
|
||||
todo += sorted(deps_of(src / f"{m}.py", local) - seen)
|
||||
return sorted(seen)
|
||||
|
||||
|
||||
def transform(text: str, local: set[str]) -> str:
|
||||
out = []
|
||||
for line in text.splitlines(keepends=True):
|
||||
body = line.rstrip("\n")
|
||||
if body.strip() == SYS_PATH_LINE:
|
||||
continue
|
||||
m = _IMPORT.match(body)
|
||||
if m and m.group("mod") in local:
|
||||
out.append(f"{m.group('ind')}from . import {m.group('mod')}{m.group('rest')}\n")
|
||||
continue
|
||||
m = _FROM.match(body)
|
||||
if m and m.group("mod") in local:
|
||||
out.append(f"{m.group('ind')}from .{m.group('mod')} import {m.group('rest')}\n")
|
||||
continue
|
||||
out.append(line)
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def header(src_name: str, rel: str, sha: str, commit: str) -> str:
|
||||
return (f"# Vendored by tools/vendor_legacy.py from {src_name}/{rel} @ {commit}\n"
|
||||
f"# source sha256 {sha}. Do not edit: changed only in imports.\n")
|
||||
|
||||
|
||||
def submodule_commit() -> str | None:
|
||||
"""The submodule's commit, or None where there is no git history (e.g. a Docker image)."""
|
||||
try:
|
||||
r = subprocess.run(["git", "-C", str(ROOT / "biomarcadores-tea"), "rev-parse", "--short", "HEAD"],
|
||||
capture_output=True, text=True, check=True)
|
||||
except (OSError, subprocess.CalledProcessError):
|
||||
return None
|
||||
return r.stdout.strip()
|
||||
|
||||
|
||||
def expected_files(module: str) -> dict[str, str]:
|
||||
"""{file name: expected content} for one legacy module's _director folder."""
|
||||
src_name, roots = MANIFEST[module]
|
||||
src = SOURCES[src_name]
|
||||
local = local_names(src)
|
||||
commit = PINNED["biomarcadores-tea"]
|
||||
files = {"__init__.py": f'"""Director code vendored from {src_name} @ {commit} (see tools/vendor_legacy.py)."""\n'}
|
||||
for name in closure(src, roots):
|
||||
raw = (src / f"{name}.py").read_text(encoding="utf-8")
|
||||
sha = hashlib.sha256(raw.encode("utf-8")).hexdigest()
|
||||
files[f"{name}.py"] = header(src_name, f"{name}.py", sha, commit) + transform(raw, local)
|
||||
return files
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--check", action="store_true")
|
||||
args = ap.parse_args(argv)
|
||||
commit = submodule_commit()
|
||||
if commit is None:
|
||||
if not args.check:
|
||||
print("no git history: cannot confirm the pinned commit; refusing to re-vendor", file=sys.stderr)
|
||||
return 2
|
||||
print("no git history: comparing contents without confirming the commit", file=sys.stderr)
|
||||
elif commit != PINNED["biomarcadores-tea"]:
|
||||
print(f"biomarcadores-tea is at {commit}, legacy is pinned to "
|
||||
f"{PINNED['biomarcadores-tea']}: check out the pinned commit first", file=sys.stderr)
|
||||
return 2
|
||||
bad = 0
|
||||
for module in MANIFEST:
|
||||
folder = LEGACY / Path(*module.split("/")) / "_director"
|
||||
want = expected_files(module)
|
||||
if args.check:
|
||||
have = {p.name for p in folder.glob("*.py")} if folder.exists() else set()
|
||||
for name in sorted(set(want) | have):
|
||||
p = folder / name
|
||||
if name not in want or not p.exists() or p.read_text(encoding="utf-8") != want[name]:
|
||||
print(f"differs: {p.relative_to(ROOT)}")
|
||||
bad += 1
|
||||
else:
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
for old in folder.glob("*.py"):
|
||||
if old.name not in want:
|
||||
old.unlink()
|
||||
for name, text in want.items():
|
||||
(folder / name).write_text(text, encoding="utf-8")
|
||||
print(f"{module}: {len(want) - 1} files")
|
||||
return 1 if bad else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1210,15 +1210,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/7f/61/0c0fae37eb561d8fddb788cbae0f227051628d70d67498a8a116c1f547d7/importlib_metadata-10.2.0-py3-none-any.whl", hash = "sha256:c7a4bf1c7479601f6b8e437cfc14f4f77028ba62a8f34ae95cd93d9774dfba51", size = 34109, upload-time = "2026-11-09T19:09:09.942Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iniconfig"
|
||||
version = "2.3.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/01/e1/2069291243c926a2ff1cd706c7f3eeb9b62144bf60f77c9fb9ff2fb26bd3/iniconfig-2.3.1.tar.gz", hash = "sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960", size = 21209, upload-time = "2026-10-06T22:48:38.076Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552, upload-time = "2026-10-06T22:48:36.959Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "interface-meta"
|
||||
version = "2.0.1"
|
||||
@@ -2350,15 +2341,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/f8/46/3737af9f971f3934794103256d7f1ed6200a62be0c7b7ff09ac4cf6b3422/platformdirs-4.14.7-py3-none-any.whl", hash = "sha256:391513b74707c42335fff3ea17eaac657a7ee9ffcadd809634d34ea594d0122c", size = 89658, upload-time = "2026-11-17T20:03:31.16Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pluggy"
|
||||
version = "1.7.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/bf/db/7fc19e6f2dc92a966727031389fc2e08b558f0f25eb7403c1119ad4713cd/pluggy-1.7.0.tar.gz", hash = "sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8", size = 123304, upload-time = "2026-10-15T09:50:58.343Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/40/9e/2b38731e0fc536806f16490e1a12d7f0dc2a1235aa8cc07bcc75416a7daa/pluggy-1.7.0-py3-none-any.whl", hash = "sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec", size = 27082, upload-time = "2026-10-15T09:50:56.808Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pooch"
|
||||
version = "1.9.0"
|
||||
@@ -2743,15 +2725,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e3/d5/b76fc647e473377ca6e693c21549ee3a4a7677e4962c28ae4659337c5114/pydantic_core-2.50.4-graalpy313-graalpy253_313_native-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:4eb15be588407148ef5937dc8d9256a71f6b115e6cddadb7aa20b6ee384680dc", size = 2280639, upload-time = "2026-11-05T09:15:05.374Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pygments"
|
||||
version = "2.21.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pyparsing"
|
||||
version = "3.3.3"
|
||||
@@ -2779,22 +2752,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/57/5c/e788ad2f904c633520d9f283785e6177a66096b2efa356b46b4647a3240f/pyriemann-0.12-py2.py3-none-any.whl", hash = "sha256:74a90b2ef0938c94fe9bf90b6506991fc19da55850aae5fdf992026b3845d43a", size = 153585, upload-time = "2026-07-01T20:03:06.55Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pytest"
|
||||
version = "9.2.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "colorama", marker = "sys_platform == 'win32'" },
|
||||
{ name = "iniconfig" },
|
||||
{ name = "packaging" },
|
||||
{ name = "pluggy" },
|
||||
{ name = "pygments" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/79/42/bb4641652e58dedeac2ec51abc1f8cae4fee4ec63899a0999016229a0f2a/pytest-9.2.0.tar.gz", hash = "sha256:97c4f3b1f3c7414aa36465e09b8220f1d03627993bd51b1282e193753c80557b", size = 1797555, upload-time = "2026-10-27T21:30:20.728Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/51/39/1f5d8c8877a0fa327db959c19341d4be61660de1ab6b7391f9eb805bcd67/pytest-9.2.0-py3-none-any.whl", hash = "sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588", size = 411776, upload-time = "2026-10-27T21:30:19.131Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "python-dateutil"
|
||||
version = "2.9.0.post0"
|
||||
@@ -3288,11 +3245,6 @@ s3 = [
|
||||
{ name = "s3fs" },
|
||||
]
|
||||
|
||||
[package.dev-dependencies]
|
||||
dev = [
|
||||
{ name = "pytest" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "antropy", specifier = ">=0.2.3" },
|
||||
@@ -3314,9 +3266,6 @@ requires-dist = [
|
||||
]
|
||||
provides-extras = ["export", "s3"]
|
||||
|
||||
[package.metadata.requires-dev]
|
||||
dev = [{ name = "pytest", specifier = ">=9.2.0" }]
|
||||
|
||||
[[package]]
|
||||
name = "threadpoolctl"
|
||||
version = "3.8.0"
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Cluster checks of tea (testing only; not part of the distributed package)."""
|
||||
@@ -1,25 +0,0 @@
|
||||
"""python -m verification {hk1k|issste} --out processed/usuarios/<name>/tea-verify/
|
||||
python -m verification mlflow [--uri http://10.0.10.41:5000] [--table features.csv]
|
||||
|
||||
Cluster checks of tea. They live outside the package (not in the wheel):
|
||||
they are for testing only, and run from the tea-verify image (PYTHONPATH=/opt/tea)."""
|
||||
|
||||
import sys
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
if not argv or argv[0] not in ("hk1k", "issste", "mlflow"):
|
||||
print(__doc__, file=sys.stderr)
|
||||
return 2
|
||||
if argv[0] == "hk1k":
|
||||
from verification import hk1k as check
|
||||
elif argv[0] == "issste":
|
||||
from verification import issste as check
|
||||
else:
|
||||
from verification import mlflow_check as check
|
||||
return check.main(argv[1:])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,198 +0,0 @@
|
||||
"""
|
||||
What both cluster checks share: run the pipeline (legacy and modern) on a list of
|
||||
S3 EDFs through the remote scheduler, check remote = sequential, compare modern
|
||||
with legacy, diagnose the failures, and keep everything to group numbers.
|
||||
|
||||
Only group numbers leave the tasks and the runner pod: counts, medians,
|
||||
percentiles, correlations. Groups with fewer than 5 studies are suppressed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
MIN_GROUP = 5
|
||||
FEATURE_PREFIXES = ("posterior_", "spindle_", "gradient_", "slow_wave_", "aperiodic_", "mse_",
|
||||
"coupling_", "spike_", "spikes_", "topography_")
|
||||
ALL_BIOMARKERS = ("posterior_rhythm", "spindles", "gradient", "slow_waves", "aperiodic", "mse",
|
||||
"coupling", "spindle_topography", "spikes")
|
||||
|
||||
|
||||
def clean(text) -> str:
|
||||
"""No paths, file names or study codes in anything that leaves a task (the 2026 file
|
||||
names carry the patient's surname)."""
|
||||
t = re.sub(r"(/|[A-Za-z]:\\)[^\s'\"]*", "<path>", str(text))
|
||||
t = re.sub(r"eeg_\d+", "<study>", t)
|
||||
return re.sub(r"[^\s:'\"(),\[\]]*\.(edf|EDF|erd|eeg|stc|json|npz|parquet)\b", "<file>", t)
|
||||
|
||||
|
||||
def write_summary(text: str, out_prefix: str, name: str) -> str:
|
||||
"""In a task: write the summary JSON under processed/usuarios/... (never raw/ or eeg-edf)."""
|
||||
from tea.pipeline.storage import s3
|
||||
if not out_prefix.startswith("processed/usuarios/") or ".." in out_prefix:
|
||||
raise PermissionError("summaries go only under processed/usuarios/<name>/")
|
||||
key = out_prefix.rstrip("/") + "/" + name
|
||||
with s3().open(key, "w") as f:
|
||||
f.write(text)
|
||||
return key
|
||||
|
||||
|
||||
def sequential(fn, argsets):
|
||||
"""A plain loop inside one task (the reference for the remote run)."""
|
||||
return [fn(*a) for a in argsets]
|
||||
|
||||
|
||||
def group_stats(values) -> dict:
|
||||
import numpy as np
|
||||
v = np.asarray([x for x in values if x is not None and math.isfinite(x)], float)
|
||||
if len(v) < MIN_GROUP:
|
||||
return {"n": int(len(v)), "suppressed": True}
|
||||
return {"n": int(len(v)), "p5": round(float(np.percentile(v, 5)), 3),
|
||||
"median": round(float(np.median(v)), 3), "p95": round(float(np.percentile(v, 95)), 3)}
|
||||
|
||||
|
||||
def features_of(table) -> list[str]:
|
||||
return [c for c in table.columns if c.startswith(FEATURE_PREFIXES)]
|
||||
|
||||
|
||||
def compare(legacy, modern) -> dict:
|
||||
"""Per feature, over studies valid in both: n, median |modern - legacy|, Pearson r. Also how
|
||||
often the verdicts agree. Group numbers only."""
|
||||
import numpy as np
|
||||
m = legacy.merge(modern, on="key", suffixes=("_l", "_m"))
|
||||
out = {"n": int(len(m)),
|
||||
"verdict_agreement": round(float((m.valid_l == m.valid_m).mean()), 4) if len(m) else None,
|
||||
"features": {}}
|
||||
feats = [c[:-2] for c in m.columns if c.endswith("_l") and c[:-2] + "_m" in m.columns
|
||||
and c.startswith(FEATURE_PREFIXES)]
|
||||
for f in feats:
|
||||
a, b = m[f + "_l"].astype(float).to_numpy(), m[f + "_m"].astype(float).to_numpy()
|
||||
ok = np.isfinite(a) & np.isfinite(b)
|
||||
if ok.sum() < MIN_GROUP:
|
||||
out["features"][f] = {"n": int(ok.sum()), "suppressed": True}
|
||||
continue
|
||||
same = np.allclose(a[ok], b[ok]) or np.ptp(a[ok]) == 0 or np.ptp(b[ok]) == 0
|
||||
out["features"][f] = {"n": int(ok.sum()),
|
||||
"median_abs_diff": round(float(np.median(np.abs(a[ok] - b[ok]))), 4),
|
||||
"r": None if same else round(float(np.corrcoef(a[ok], b[ok])[0, 1]), 4),
|
||||
"identical": bool(np.allclose(a[ok], b[ok])),
|
||||
"nan_mismatch": int((np.isfinite(a) != np.isfinite(b)).sum())}
|
||||
return out
|
||||
|
||||
|
||||
def diagnose(path, age_months, plan, modules, order, biomarkers, line_hz, name_file: bool) -> dict:
|
||||
"""In a task: re-run one failed study step by step, without catching, and report the step
|
||||
that raised, the message and the last frames of the traceback (cleaned). The file name is
|
||||
reported only when `name_file` (public data)."""
|
||||
import traceback
|
||||
|
||||
from tea.contracts import Study
|
||||
from tea.pipeline import storage
|
||||
out = {"file": Path(str(path)).name if name_file else None, "step": None, "error": "",
|
||||
"traceback": ""}
|
||||
step = "read"
|
||||
try:
|
||||
with storage.local_copy(path) as p:
|
||||
step = "validation"
|
||||
summary = modules["validation"].summarize(p, line_hz=line_hz)
|
||||
step = "preprocessing"
|
||||
prep = modules["preprocessing"].run(p, modules["preprocessing"].plan_for(summary, plan),
|
||||
age_months=age_months)
|
||||
study = Study(prep)
|
||||
for name in order:
|
||||
step = name
|
||||
study = study.with_labels(modules[name].predict(study))
|
||||
for name in biomarkers:
|
||||
step = name
|
||||
modules[name].measure(study)
|
||||
out["step"] = "none (did not fail again)"
|
||||
except Exception as e: # noqa: BLE001
|
||||
out.update(step=step, error=clean(f"{type(e).__name__}: {e}")[:500],
|
||||
traceback=clean("".join(traceback.format_exception(e)[-12:]))[-4000:])
|
||||
return out
|
||||
|
||||
|
||||
def versions(client) -> dict:
|
||||
v = client.get_versions(check=False)
|
||||
return {k: v["scheduler"]["packages"].get(k) for k in ("python", "dask", "distributed")}
|
||||
|
||||
|
||||
def run_impls(client, items, *, plan, impls, biomarkers, check_n, line_hz, name_files: bool,
|
||||
strata: dict | None = None, max_diagnoses: int = 20) -> tuple[dict, dict]:
|
||||
"""Run every implementation on `items` [(s3 path, age months)] through the remote scheduler.
|
||||
Returns (summary per impl, tables per impl); the tables stay in the runner pod. `strata`
|
||||
maps a group label to the item indices it holds (e.g. lot, age group)."""
|
||||
import pandas as pd
|
||||
|
||||
from tea.pipeline import Pipeline, run_study
|
||||
from tea.pipeline.run_study import order_for
|
||||
|
||||
paths, ages = [p for p, _ in items], [a for _, a in items]
|
||||
infos, tables = {}, {}
|
||||
for impl in impls:
|
||||
try:
|
||||
pipe = Pipeline.default(impl=impl)
|
||||
except Exception as e: # noqa: BLE001
|
||||
infos[impl] = {"skipped": clean(f"{type(e).__name__}: {e}")[:200]}
|
||||
continue
|
||||
bios = tuple(b for b in biomarkers if b in pipe.modules)
|
||||
if not bios:
|
||||
infos[impl] = {"skipped": "none of the biomarkers is registered"}
|
||||
continue
|
||||
remote = Pipeline(pipe.modules, impl="modern").map(
|
||||
paths, plan=plan, ages_months=ages, biomarkers=bios, cluster="remote", line_hz=line_hz)
|
||||
remote["error"] = remote["error"].fillna("").map(clean)
|
||||
tables[impl] = remote
|
||||
# equality: the first studies again, sequentially, in one task
|
||||
order = tuple(order_for(list(bios), pipe.modules))
|
||||
mods = {n: pipe.modules[n] for n in ("validation", "preprocessing", *order, *bios)}
|
||||
k = min(check_n, len(paths))
|
||||
argsets = [(i, paths[i], ages[i], plan, mods, order, bios, line_hz) for i in range(k)]
|
||||
seq = pd.DataFrame(client.submit(sequential, run_study, argsets, pure=False, priority=-10).result())
|
||||
seq["error"] = seq["error"].fillna("").map(clean)
|
||||
cols = [c for c in seq.columns if c != "seconds"]
|
||||
a = remote[remote.key < k][cols].reset_index(drop=True)
|
||||
b = seq[cols].reset_index(drop=True)
|
||||
equal = bool(a.equals(b) or a.fillna(-999).astype(str).equals(b.fillna(-999).astype(str)))
|
||||
err = remote.error != ""
|
||||
ok = remote[(remote.valid == 1) & ~err]
|
||||
info = {"biomarkers": list(bios), "n": int(len(remote)), "valid": int((remote.valid == 1).sum()),
|
||||
"not_valid": int((remote.valid == 0).sum()), "errors": int(err.sum()),
|
||||
"error_types": remote.loc[err, "error"].str.split(":").str[0].value_counts().to_dict(),
|
||||
"not_valid_reasons": _reason_counts(remote.loc[remote.valid == 0, "reasons"]),
|
||||
"remote_equals_sequential": equal, "checked": k,
|
||||
"seconds_median": float(remote.seconds.median()) if len(remote) else None,
|
||||
"seconds_p95": float(remote.seconds.quantile(0.95)) if len(remote) else None,
|
||||
"features": {c: group_stats(ok[c]) for c in features_of(ok)}}
|
||||
if strata:
|
||||
info["by_group"] = {}
|
||||
for label, idx in strata.items():
|
||||
g = remote[remote.key.isin(idx)]
|
||||
info["by_group"][label] = {"n": int(len(g)), "valid": int((g.valid == 1).sum()),
|
||||
"errors": int((g.error != "").sum())}
|
||||
failed = remote.loc[err, "key"].tolist()[:max_diagnoses]
|
||||
info["diagnosis"] = []
|
||||
for i in failed:
|
||||
try:
|
||||
d = client.submit(diagnose, paths[i], ages[i], plan, mods, order, bios, line_hz,
|
||||
name_files, pure=False, priority=-10, retries=0).result()
|
||||
except Exception as e: # noqa: BLE001 - e.g. KilledWorker
|
||||
d = {"file": Path(paths[i]).name if name_files else None, "step": "task",
|
||||
"error": clean(f"{type(e).__name__}: {e}")[:300], "traceback": ""}
|
||||
d["first_error"] = remote.loc[remote.key == i, "error"].iloc[0][:300]
|
||||
info["diagnosis"].append(d)
|
||||
infos[impl] = info
|
||||
return infos, tables
|
||||
|
||||
|
||||
def _reason_counts(reasons) -> dict:
|
||||
"""How often each not-valid reason appears (numbers stripped so they group)."""
|
||||
from collections import Counter
|
||||
c = Counter()
|
||||
for r in reasons.fillna(""):
|
||||
for part in str(r).split("; "):
|
||||
if part:
|
||||
c[re.sub(r"[\d.]+", "#", clean(part))[:80]] += 1
|
||||
return {k: v for k, v in c.most_common(15)}
|
||||
@@ -1,132 +0,0 @@
|
||||
"""
|
||||
HK1K check on the team's cluster (public data).
|
||||
|
||||
python -m verification hk1k --out processed/usuarios/alberto/tea-verify/ [--limit 40]
|
||||
|
||||
1. Lists the HK1K EDFs and ages (anon_codex_age_sex.csv) in a worker task.
|
||||
2. Runs the pipeline (legacy and modern) on every study with age in --ages
|
||||
(default 16-36 months) through the remote Dask scheduler, mains 50 Hz.
|
||||
3. Checks that the remote run equals a sequential run of the first studies.
|
||||
4. Compares modern with legacy per feature, and the posterior rhythm by age group
|
||||
with the HK1K reference table (normas/referencia_hk1k.csv), when present.
|
||||
5. Re-runs each failed study step by step (file name, step, message, traceback:
|
||||
HK1K is public).
|
||||
6. Prints a JSON summary and writes it to S3 under --out (worker task).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from verification.common import (ALL_BIOMARKERS, compare, group_stats, run_impls, versions,
|
||||
write_summary)
|
||||
|
||||
HK1K = "raw/eeg-helsinki/"
|
||||
LINE_HZ = 50.0
|
||||
REF = Path(__file__).resolve().parents[1] / "biomarcadores-tea" / "normas" / "referencia_hk1k.csv"
|
||||
|
||||
|
||||
def guard(path: str) -> str:
|
||||
p = str(path)
|
||||
p = p[len("s3://"):] if p.startswith("s3://") else p
|
||||
if not p.startswith(HK1K) or ".." in p:
|
||||
raise PermissionError(f"the HK1K check reads only {HK1K}; refused another prefix")
|
||||
return p
|
||||
|
||||
|
||||
def list_hk1k(base: str = HK1K) -> list[tuple[str, float]]:
|
||||
"""In a task: (s3 path, age in months) of each HK1K EDF with an age."""
|
||||
import pandas as pd
|
||||
|
||||
from tea.pipeline.storage import s3
|
||||
fs = s3()
|
||||
paths = fs.find(guard(base))
|
||||
tables = [r for r in paths if r.endswith("anon_codex_age_sex.csv")]
|
||||
if not tables:
|
||||
raise FileNotFoundError("anon_codex_age_sex.csv not found under the HK1K prefix")
|
||||
with fs.open(tables[0], "rb") as f:
|
||||
codex = pd.read_csv(f)
|
||||
codex.columns = ["archivo", "edad_anos", "sexo"]
|
||||
edfs = {Path(r).name: r for r in paths if r.endswith(".edf")}
|
||||
return [("s3://" + guard(edfs[r.archivo]), round(float(r.edad_anos) * 12, 1))
|
||||
for r in codex.itertuples() if r.archivo in edfs]
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
import argparse
|
||||
|
||||
from distributed import Client
|
||||
|
||||
from tea.pipeline.dask_runner import scheduler_address
|
||||
from tea.preprocessing import DIRECTOR_CLUSTER
|
||||
|
||||
ap = argparse.ArgumentParser(prog="python -m verification hk1k")
|
||||
ap.add_argument("--out", required=True)
|
||||
ap.add_argument("--ages", nargs=2, type=float, default=(16.0, 36.0))
|
||||
ap.add_argument("--limit", type=int, default=None)
|
||||
ap.add_argument("--check-n", type=int, default=4, help="studies re-run sequentially for the equality check")
|
||||
ap.add_argument("--impl", nargs="+", default=["legacy", "modern"])
|
||||
ap.add_argument("--biomarkers", nargs="+", default=list(ALL_BIOMARKERS))
|
||||
ap.add_argument("--mlflow-uri", default=os.environ.get("TEA_MLFLOW_URI", ""),
|
||||
help="register plans and HK1K-trained biomarkers there (skipped if it does not answer)")
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
addr = scheduler_address()
|
||||
if not addr:
|
||||
print("no DASK_SCHEDULER / DASK_SCHEDULER_ADDRESS: run this inside the tea-verify DaskJob",
|
||||
file=sys.stderr)
|
||||
return 2
|
||||
plan = {**DIRECTOR_CLUSTER.to_dict(), "line_hz": LINE_HZ}
|
||||
summary = {"check": "hk1k", "plan_hash": plan["hash"], "line_hz": LINE_HZ, "ages": list(args.ages),
|
||||
"commit": os.environ.get("TEA_COMMIT", "")}
|
||||
|
||||
with Client(addr, direct_to_workers=False) as client:
|
||||
summary["scheduler"] = versions(client)
|
||||
items = client.submit(list_hk1k, pure=False, priority=-10).result()
|
||||
items = sorted((p, a) for p, a in items if args.ages[0] <= a <= args.ages[1])
|
||||
if args.limit:
|
||||
items = items[: args.limit]
|
||||
summary["n_listed"] = len(items)
|
||||
infos, tables = run_impls(client, items, plan=plan, impls=args.impl, biomarkers=args.biomarkers,
|
||||
check_n=args.check_n, line_hz=LINE_HZ, name_files=True)
|
||||
for impl, info in infos.items():
|
||||
if impl in tables:
|
||||
t = tables[impl]
|
||||
ok = t[(t.valid == 1) & (t.error == "")]
|
||||
info["by_age_group"] = {f"{lo}-{hi}": group_stats(
|
||||
ok[(ok.age_months >= lo) & (ok.age_months < hi)].get("posterior_rhythm_hz", []))
|
||||
for lo, hi in ((12, 24), (24, 36))}
|
||||
summary["impl"] = infos
|
||||
if {"legacy", "modern"} <= set(tables):
|
||||
summary["modern_vs_legacy"] = compare(tables["legacy"], tables["modern"])
|
||||
summary["reference"] = _reference()
|
||||
if args.mlflow_uri and tables:
|
||||
from verification.mlflow_check import register_all
|
||||
ok = {i: t[(t.valid == 1) & (t.error == "")] for i, t in tables.items()}
|
||||
try:
|
||||
summary["mlflow"] = register_all(ok, uri=args.mlflow_uri, impls=tuple(ok),
|
||||
data_label=f"hk1k-{summary['commit'] or 'local'}",
|
||||
fallback_local=False)
|
||||
except Exception as e: # noqa: BLE001
|
||||
summary["mlflow"] = {"error": f"{type(e).__name__}: {e}"[:300]}
|
||||
text = json.dumps(summary, indent=1, default=str)
|
||||
print(text)
|
||||
key = client.submit(write_summary, text, args.out,
|
||||
f"summary_{summary['commit'] or 'local'}.json", pure=False).result()
|
||||
print(f"summary written to s3://{key}", file=sys.stderr)
|
||||
bad = [i for i, v in infos.items() if v.get("remote_equals_sequential") is False]
|
||||
return 1 if bad else 0
|
||||
|
||||
|
||||
def _reference() -> dict:
|
||||
"""HK1K reference rhythm (E15) for the age groups the run covers, if the table is here."""
|
||||
if not REF.exists():
|
||||
return {"available": False}
|
||||
import pandas as pd
|
||||
r = pd.read_csv(REF, encoding="utf-8-sig")
|
||||
r = r[(r.biomarcador == "ritmo_posterior") & (r.estado == "vigilia")]
|
||||
return {"available": True, "ritmo_posterior_vigilia": r[["grupo_edad_anos", "n", "p5", "mediana", "p95"]]
|
||||
.to_dict("records")}
|
||||
@@ -1,181 +0,0 @@
|
||||
"""
|
||||
ISSSTELEÓN check on the team's cluster (patient data: group numbers only).
|
||||
|
||||
python -m verification issste --out processed/usuarios/alberto/tea-verify/
|
||||
|
||||
Reads only processed/eeg-edf-2025/ and processed/eeg-edf-2026/ (the EDFs of the
|
||||
2025 and 2026 lots); writes only the summary under processed/usuarios/.
|
||||
|
||||
1. Lists each lot's EDFs in a worker task (a lot with no EDF is reported as not
|
||||
available, and the check stops: the conversion is a separate step).
|
||||
2. Age in months from each EDF header, in a worker task: measurement date minus
|
||||
birthdate (EDF+ patient and recording fields), as eeg.validate.study.edad_meses.
|
||||
The birthdate and dates never leave the task.
|
||||
3. Runs the pipeline (legacy and modern, every biomarker) on every EDF, mains
|
||||
60 Hz, through the remote Dask scheduler; remote = sequential on the first 4.
|
||||
4. Compares modern with legacy per feature, on all studies and on 16-36 months.
|
||||
5. Re-runs each failed study step by step: step, error type and cleaned message
|
||||
and traceback only (no file name: the 2026 names carry the patient's surname).
|
||||
|
||||
Nothing per study leaves the runner pod: file names, paths, ages and rows stay
|
||||
in its memory. The summary holds counts, percentiles and correlations, with
|
||||
groups under 5 suppressed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from verification.common import (ALL_BIOMARKERS, clean, compare, group_stats, run_impls, versions,
|
||||
write_summary)
|
||||
|
||||
LOTS = {"2025": "processed/eeg-edf-2025/", "2026": "processed/eeg-edf-2026/"}
|
||||
LINE_HZ = 60.0
|
||||
AGE_GROUPS = (("<16", 0, 15), ("16-36", 16, 36), ("37-48", 37, 48), (">48", 49, 10_000))
|
||||
|
||||
|
||||
def guard(path: str) -> str:
|
||||
p = str(path)
|
||||
p = p[len("s3://"):] if p.startswith("s3://") else p
|
||||
if not any(p.startswith(lot) for lot in LOTS.values()) or ".." in p:
|
||||
raise PermissionError("the ISSSTELEÓN check reads only processed/eeg-edf-2025/ and eeg-edf-2026/")
|
||||
return p
|
||||
|
||||
|
||||
def list_lot(prefix: str) -> list[str]:
|
||||
"""In a task: s3 paths of the EDFs of one lot (they stay in the runner pod)."""
|
||||
from tea.pipeline.storage import s3
|
||||
return sorted("s3://" + guard(r) for r in s3().find(guard(prefix)) if r.lower().endswith(".edf"))
|
||||
|
||||
|
||||
def _edf_date(text: str) -> date | None:
|
||||
try:
|
||||
return datetime.strptime(text, "%d-%b-%Y").date()
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def age_from_header(header: bytes) -> float | None:
|
||||
"""Age in months at the recording, from the first 256 bytes of an EDF(+) header."""
|
||||
if len(header) < 176:
|
||||
return None
|
||||
patient = header[8:88].decode("latin-1").split()
|
||||
recording = header[88:168].decode("latin-1").split()
|
||||
birth = _edf_date(patient[2]) if len(patient) >= 3 else None
|
||||
meas = _edf_date(recording[1]) if len(recording) >= 2 and recording[0] == "Startdate" else None
|
||||
if meas is None:
|
||||
try:
|
||||
d, m, y = (int(x) for x in header[168:176].decode("latin-1").split("."))
|
||||
meas = date(1900 + y if y >= 85 else 2000 + y, m, d)
|
||||
except ValueError:
|
||||
return None
|
||||
if birth is None or birth > meas:
|
||||
return None
|
||||
return round((meas - birth).days / 30.4375, 1)
|
||||
|
||||
|
||||
def header_age(path: str) -> float | None:
|
||||
"""In a task: the age of one EDF (reads only its first 256 bytes)."""
|
||||
from tea.pipeline.storage import s3
|
||||
with s3().open(guard(path), "rb") as f:
|
||||
return age_from_header(f.read(256))
|
||||
|
||||
|
||||
def age_group(m) -> str:
|
||||
if m is None or not math.isfinite(m):
|
||||
return "no age"
|
||||
for label, lo, hi in AGE_GROUPS:
|
||||
if lo <= math.floor(m) <= hi:
|
||||
return label
|
||||
return "no age"
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
import argparse
|
||||
|
||||
from distributed import Client
|
||||
|
||||
from tea.pipeline.dask_runner import scheduler_address
|
||||
from tea.preprocessing import DIRECTOR_CLUSTER
|
||||
|
||||
ap = argparse.ArgumentParser(prog="python -m verification issste")
|
||||
ap.add_argument("--out", required=True)
|
||||
ap.add_argument("--lots", nargs="+", default=list(LOTS), choices=list(LOTS))
|
||||
ap.add_argument("--cohort-only", action="store_true", help="only 16-36 months")
|
||||
ap.add_argument("--limit", type=int, default=None)
|
||||
ap.add_argument("--check-n", type=int, default=4)
|
||||
ap.add_argument("--impl", nargs="+", default=["legacy", "modern"])
|
||||
ap.add_argument("--biomarkers", nargs="+", default=list(ALL_BIOMARKERS))
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
addr = scheduler_address()
|
||||
if not addr:
|
||||
print("no DASK_SCHEDULER / DASK_SCHEDULER_ADDRESS: run this inside the tea-verify DaskJob",
|
||||
file=sys.stderr)
|
||||
return 2
|
||||
plan = {**DIRECTOR_CLUSTER.to_dict(), "line_hz": LINE_HZ}
|
||||
summary = {"check": "issste", "plan_hash": plan["hash"], "line_hz": LINE_HZ,
|
||||
"commit": os.environ.get("TEA_COMMIT", ""), "lots": {}}
|
||||
out_name = f"summary_issste_{summary['commit'] or 'local'}.json"
|
||||
|
||||
with Client(addr, direct_to_workers=False) as client:
|
||||
summary["scheduler"] = versions(client)
|
||||
lots = {lot: client.submit(list_lot, LOTS[lot], pure=False, priority=-10).result()
|
||||
for lot in args.lots}
|
||||
for lot, paths in lots.items():
|
||||
summary["lots"][lot] = {"edf_files": len(paths),
|
||||
"folders": len({str(Path(p).parent) for p in paths}),
|
||||
"available": bool(paths)}
|
||||
if not all(v["available"] for v in summary["lots"].values()):
|
||||
text = json.dumps(summary, indent=1)
|
||||
print(text)
|
||||
client.submit(write_summary, text, args.out, out_name, pure=False).result()
|
||||
print("a lot has no EDF: convert it first", file=sys.stderr)
|
||||
return 3
|
||||
items, lot_of = [], []
|
||||
for lot, paths in lots.items():
|
||||
items += paths
|
||||
lot_of += [lot] * len(paths)
|
||||
ages = client.gather(client.map(header_age, items, pure=False, priority=-10))
|
||||
groups = [age_group(a) for a in ages]
|
||||
for lot in lots:
|
||||
g = [gr for gr, lo in zip(groups, lot_of) if lo == lot]
|
||||
summary["lots"][lot]["age_groups"] = {k: g.count(k) for k in [x[0] for x in AGE_GROUPS] + ["no age"]}
|
||||
keep = [i for i, g in enumerate(groups) if not args.cohort_only or g == "16-36"]
|
||||
if args.limit:
|
||||
keep = keep[: args.limit]
|
||||
run_items = [(items[i], ages[i]) for i in keep]
|
||||
strata = {f"lot {lot}": [j for j, i in enumerate(keep) if lot_of[i] == lot] for lot in lots}
|
||||
strata.update({f"age {g}": [j for j, i in enumerate(keep) if groups[i] == g]
|
||||
for g in [x[0] for x in AGE_GROUPS] + ["no age"]})
|
||||
summary["n_run"] = len(run_items)
|
||||
|
||||
infos, tables = run_impls(client, run_items, plan=plan, impls=args.impl, biomarkers=args.biomarkers,
|
||||
check_n=args.check_n, line_hz=LINE_HZ, name_files=False, strata=strata)
|
||||
cohort = strata["age 16-36"]
|
||||
for impl, info in infos.items():
|
||||
if impl in tables:
|
||||
t = tables[impl]
|
||||
ok = t[(t.valid == 1) & (t.error == "") & t.key.isin(cohort)]
|
||||
info["features_16_36"] = {c: group_stats(ok[c]) for c in ok.columns
|
||||
if c in info.get("features", {})}
|
||||
summary["impl"] = infos
|
||||
if {"legacy", "modern"} <= set(tables):
|
||||
leg, mod = tables["legacy"], tables["modern"]
|
||||
summary["modern_vs_legacy"] = compare(leg, mod)
|
||||
summary["modern_vs_legacy_16_36"] = compare(leg[leg.key.isin(cohort)], mod[mod.key.isin(cohort)])
|
||||
text = json.dumps(summary, indent=1, default=str)
|
||||
assert "eeg-edf-20" not in text and ".edf" not in text.lower(), "a path reached the summary"
|
||||
print(text)
|
||||
key = client.submit(write_summary, text, args.out, out_name, pure=False).result()
|
||||
print(f"summary written to s3://{key}", file=sys.stderr)
|
||||
bad = [i for i, v in infos.items() if v.get("remote_equals_sequential") is False]
|
||||
return 1 if bad else 0
|
||||
|
||||
|
||||
__all__ = ["age_from_header", "age_group", "clean", "guard", "main"]
|
||||
@@ -1,185 +0,0 @@
|
||||
"""
|
||||
Registration check: preprocessing plans and every biomarker (legacy and modern)
|
||||
logged and registered in MLflow, then loaded back in a fresh interpreter.
|
||||
|
||||
python -m verification mlflow [--uri http://10.0.10.41:5000] [--table hk1k.csv]
|
||||
|
||||
- --uri: the team's MLflow server. If it does not answer, a local store is used
|
||||
instead (sqlite + artifacts under ./mlflow_local/), and its files are kept.
|
||||
- Training data: a measured feature table (--table, or the tables the HK1K check
|
||||
passes in); otherwise a synthetic table, tagged data=synthetic, which checks
|
||||
only the registration path, not the baselines.
|
||||
- Registered names: tea-test.plan.<plan>, tea-test.<impl>.<biomarker>,
|
||||
in the experiment "tea · registro (prueba)".
|
||||
- Each model is loaded in a new Python process; its predictions must equal the
|
||||
in-memory module's.
|
||||
|
||||
MLflow receives parameters and baselines (group numbers) only; the privacy guard
|
||||
refuses groups under 5 and texts with names, paths or dates.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_URI = "http://10.0.10.41:5000"
|
||||
EXPERIMENT = "tea · registro (prueba)"
|
||||
PREFIX = "tea-test"
|
||||
LOCAL = Path("mlflow_local")
|
||||
|
||||
|
||||
def reachable(uri: str, timeout: float = 5.0) -> bool:
|
||||
if not uri.startswith("http"):
|
||||
return True
|
||||
try:
|
||||
with urllib.request.urlopen(uri.rstrip("/") + "/health", timeout=timeout) as r:
|
||||
return r.status == 200
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
def use_store(uri: str | None, fallback_local: bool = True) -> str | None:
|
||||
"""Point MLflow at the server, or at a local store kept on disk when it does not answer
|
||||
(None when it does not answer and fallback_local is off)."""
|
||||
import mlflow
|
||||
if uri and reachable(uri):
|
||||
chosen = uri
|
||||
elif not fallback_local:
|
||||
return None
|
||||
else:
|
||||
LOCAL.mkdir(exist_ok=True)
|
||||
chosen = f"sqlite:///{(LOCAL / 'mlflow.db').resolve()}"
|
||||
os.environ["MLFLOW_ARTIFACT_ROOT"] = str((LOCAL / "artifacts").resolve())
|
||||
mlflow.set_tracking_uri(chosen)
|
||||
mlflow.set_registry_uri(chosen)
|
||||
return chosen
|
||||
|
||||
|
||||
def synthetic_table(features, n=60, seed=0):
|
||||
"""Feature values that drift with age plus noise: enough for every baseline to fit."""
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
rng = np.random.default_rng(seed)
|
||||
age = np.sort(rng.uniform(12, 48, n))
|
||||
t = {"age_months": age}
|
||||
for i, f in enumerate(features):
|
||||
t[f] = np.abs(1.0 + 0.02 * (i + 1) * age + rng.normal(0, 0.3, n))
|
||||
return pd.DataFrame(t)
|
||||
|
||||
|
||||
def _fresh_predict(model_uri: str, rows_json: str, tracking_uri: str) -> list:
|
||||
"""predict() of the model in a new Python process (nothing shared with this one)."""
|
||||
code = ("import json,sys,mlflow,pandas as pd;"
|
||||
f"mlflow.set_tracking_uri({tracking_uri!r});mlflow.set_registry_uri({tracking_uri!r});"
|
||||
f"m=mlflow.pyfunc.load_model({model_uri!r});"
|
||||
f"out=m.predict(pd.read_json(__import__('io').StringIO({rows_json!r})));"
|
||||
"print(json.dumps(pd.DataFrame(out).astype(object).where(pd.DataFrame(out).notna(),None)"
|
||||
".to_dict('records')))")
|
||||
env = {**os.environ, "MLFLOW_DISABLE_AGENT_HINT": "1", "PYTHONWARNINGS": "ignore"}
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
r = subprocess.run([sys.executable, "-c", code], cwd=tmp, env=env, capture_output=True, text=True,
|
||||
timeout=600)
|
||||
if r.returncode:
|
||||
raise RuntimeError(r.stderr.strip().splitlines()[-1] if r.stderr.strip() else "failed")
|
||||
return json.loads(r.stdout.strip().splitlines()[-1])
|
||||
|
||||
|
||||
def _same(a: list, b: list) -> bool:
|
||||
import math
|
||||
if len(a) != len(b):
|
||||
return False
|
||||
for x, y in zip(a, b):
|
||||
for k in set(x) | set(y):
|
||||
u, v = x.get(k), y.get(k)
|
||||
if isinstance(u, float) and isinstance(v, float):
|
||||
if not (math.isclose(u, v, rel_tol=1e-9, abs_tol=1e-12) or (u != u and v != v)):
|
||||
return False
|
||||
elif (u is None) != (v is None) or (u is not None and str(u) != str(v)):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def register_all(tables=None, *, uri: str | None = DEFAULT_URI, data_label: str = "synthetic",
|
||||
impls=("legacy", "modern"), biomarkers=None, fallback_local: bool = True) -> dict:
|
||||
"""Log + register plans and biomarkers, then reload each in a fresh process. Group results only."""
|
||||
import mlflow
|
||||
import pandas as pd
|
||||
|
||||
from tea.pipeline import Pipeline
|
||||
from tea.preprocessing import DIRECTOR_CLI, DIRECTOR_CLUSTER
|
||||
from tea.serving import load_plan, log_biomarker, log_plan
|
||||
|
||||
os.environ.setdefault("MLFLOW_DISABLE_AGENT_HINT", "1")
|
||||
chosen = use_store(uri, fallback_local)
|
||||
if chosen is None:
|
||||
return {"tracking_uri": uri, "server_used": False, "ok": None, "skipped": "server not reachable"}
|
||||
out = {"tracking_uri": chosen if chosen.startswith("http") else "local (mlflow_local/)",
|
||||
"server_used": chosen.startswith("http"), "data": data_label, "plans": {}, "biomarkers": {}}
|
||||
plan_uris = {}
|
||||
for plan in (DIRECTOR_CLUSTER, DIRECTOR_CLI):
|
||||
name = f"{PREFIX}.plan.{plan.name}"
|
||||
try:
|
||||
v = log_plan(plan, registered_name=name, experiment=EXPERIMENT)
|
||||
muri = f"models:/{name}/{v.version}"
|
||||
back = load_plan(muri)
|
||||
plan_uris[plan.name] = muri
|
||||
out["plans"][plan.name] = {"model": muri, "hash": plan.content_hash(),
|
||||
"round_trip": back.get("hash") == plan.to_dict().get("hash")}
|
||||
except Exception as e: # noqa: BLE001
|
||||
out["plans"][plan.name] = {"error": f"{type(e).__name__}: {e}"[:300]}
|
||||
plan_uri = plan_uris.get(DIRECTOR_CLUSTER.name, "")
|
||||
for impl in impls:
|
||||
pipe = Pipeline.default(impl=impl)
|
||||
for b in (biomarkers or pipe.biomarker_names()):
|
||||
name = f"{PREFIX}.{impl}.{b}"
|
||||
res = {}
|
||||
try:
|
||||
mod = type(pipe.biomarker(b))()
|
||||
t = (tables or {}).get(impl)
|
||||
if t is None:
|
||||
t = synthetic_table(mod.features)
|
||||
cols = ["age_months", *[f for f in mod.features if f in t.columns]]
|
||||
t = t[cols].dropna(subset=["age_months"])
|
||||
mod.train(t)
|
||||
res["n_reference"] = int(len(t))
|
||||
v =log_biomarker(mod, plan_uri=plan_uri, registered_name=name, experiment=EXPERIMENT,
|
||||
n_reference=len(t))
|
||||
muri = f"models:/{name}/{v.version}"
|
||||
mlflow.MlflowClient().set_model_version_tag(name, v.version, "data", data_label)
|
||||
rows = t.dropna().head(3) if len(t.dropna()) else t.head(3)
|
||||
local = mod.predict(rows)
|
||||
local = json.loads(pd.DataFrame(local).astype(object).where(pd.DataFrame(local).notna(), None)
|
||||
.to_json(orient="records"))
|
||||
fresh = _fresh_predict(muri, rows.to_json(orient="records"), chosen)
|
||||
res.update(model=muri, round_trip=_same(local, fresh), rows_checked=len(rows))
|
||||
except Exception as e: # noqa: BLE001
|
||||
res["error"] = f"{type(e).__name__}: {e}"[:300]
|
||||
out["biomarkers"][f"{impl}.{b}"] = res
|
||||
out["ok"] = (all(p.get("round_trip") for p in out["plans"].values())
|
||||
and all(r.get("round_trip") for r in out["biomarkers"].values()))
|
||||
return out
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
import argparse
|
||||
|
||||
import pandas as pd
|
||||
ap = argparse.ArgumentParser(prog="python -m verification mlflow")
|
||||
ap.add_argument("--uri", default=os.environ.get("MLFLOW_TRACKING_URI", DEFAULT_URI))
|
||||
ap.add_argument("--table", help="measured feature table (CSV, with age_months) to train on")
|
||||
ap.add_argument("--data-label", default=None)
|
||||
args = ap.parse_args(argv)
|
||||
tables = None
|
||||
label = "synthetic"
|
||||
if args.table:
|
||||
t = pd.read_csv(args.table)
|
||||
tables, label = {"legacy": t, "modern": t}, args.data_label or Path(args.table).stem
|
||||
out = register_all(tables, uri=args.uri, data_label=label)
|
||||
print(json.dumps(out, indent=1))
|
||||
return 0 if out["ok"] else 1
|
||||
Reference in New Issue
Block a user