serving (MLflow), HK1K verification command and the tea-verify DaskJob
- serving: plans and biomarkers as MLflow "models from code" (standalone wrapper files), code_paths = only the module's package + contracts; plan.json artifact and plan params; biomarker models pin plan_uri and plan_hash. privacy: no study codes / dates / paths, binary artifacts refused, baselines from fewer than 5 children refused. - verify: python -m tea_modulo.verify hk1k lists HK1K in a worker task, runs the pipeline remotely (line 50 Hz), checks the remote run equals a plain sequential run in one task, summarizes the posterior rhythm by age group (groups < 5 suppressed) and writes the summary under processed/usuarios/. Any input prefix but raw/eeg-helsinki/ is refused. - deploy: Dockerfile.verify (dask:1.1 + antropy, fhir.resources, meegkit, pytest; tea-modulo from the local checkout), .dockerignore keeping .venv, eeg/ and any signal or patient file out, dask-verify.yaml (own 2x4-worker cluster, no eeg-data PVC, keys only on workers), verify.sh. Tests: MLflow round trips on sqlite, model loads with only its own code in a fresh interpreter, privacy refusals, verify guards.
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
"""
|
||||
Plans and biomarkers as MLflow models, behind a privacy guard.
|
||||
|
||||
from tea_modulo.serving import log_plan, log_biomarker, load_plan, load_biomarker
|
||||
"""
|
||||
|
||||
from tea_modulo.serving.models import (
|
||||
load_biomarker,
|
||||
load_plan,
|
||||
log_biomarker,
|
||||
log_plan,
|
||||
)
|
||||
from tea_modulo.serving.privacy import Forbidden
|
||||
|
||||
__all__ = ["log_plan", "log_biomarker", "load_plan", "load_biomarker", "Forbidden"]
|
||||
@@ -0,0 +1,30 @@
|
||||
"""
|
||||
MLflow "model from code" for a trained tea_modulo biomarker. Standalone on
|
||||
purpose: it imports nothing from tea_modulo at module level, so a logged model
|
||||
needs only its own module's code (shipped in code_paths) and `contracts`.
|
||||
|
||||
predict(df with the feature columns + age_months) -> deviation table
|
||||
(feature, value, age_months, outside, z, baseline).
|
||||
"""
|
||||
|
||||
import importlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import mlflow
|
||||
import pandas as pd
|
||||
|
||||
|
||||
class BiomarkerModel(mlflow.pyfunc.PythonModel):
|
||||
def load_context(self, context):
|
||||
folder = Path(context.artifacts["module"])
|
||||
cfg = json.loads((folder / "module.json").read_text())
|
||||
mod, _, attr = cfg["class"].partition(":")
|
||||
self.module = getattr(importlib.import_module(mod), attr).load(folder)
|
||||
self.config = cfg
|
||||
|
||||
def predict(self, context, model_input, params=None):
|
||||
return self.module.predict(pd.DataFrame(model_input))
|
||||
|
||||
|
||||
mlflow.models.set_model(BiomarkerModel())
|
||||
@@ -0,0 +1,22 @@
|
||||
"""
|
||||
MLflow "model from code" for a preprocessing plan. Standalone: the plan
|
||||
(plan.json) is the artifact; predict() returns it, one row per input row.
|
||||
"""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import mlflow
|
||||
import pandas as pd
|
||||
|
||||
|
||||
class PlanModel(mlflow.pyfunc.PythonModel):
|
||||
def load_context(self, context):
|
||||
self.plan = json.loads(Path(context.artifacts["plan"]).read_text(encoding="utf-8"))
|
||||
|
||||
def predict(self, context, model_input, params=None):
|
||||
n = max(1, len(model_input))
|
||||
return pd.DataFrame({"plan": [json.dumps(self.plan)] * n, "hash": [self.plan.get("hash", "")] * n})
|
||||
|
||||
|
||||
mlflow.models.set_model(PlanModel())
|
||||
@@ -0,0 +1,138 @@
|
||||
"""
|
||||
Plans and biomarkers as MLflow pyfunc models.
|
||||
|
||||
pv = log_plan(plan, registered_name="tea-plan-director-cluster")
|
||||
bv = log_biomarker(rhythm, plan_uri=f"models:/tea-plan-director-cluster/{pv.version}",
|
||||
registered_name="tea-bio-posterior-rhythm")
|
||||
plan_dict = load_plan("models:/tea-plan-director-cluster/1")
|
||||
rhythm = load_biomarker("models:/tea-bio-posterior-rhythm/3")
|
||||
mlflow.pyfunc.load_model(uri).predict(df) # df: features + age_months
|
||||
|
||||
A biomarker model carries only its own module's code plus `contracts`
|
||||
(code_paths), its saved state (baseline.json, params.json) and a copy of the
|
||||
plan it was trained with. Tags: plan_uri, plan_hash, module version, impl,
|
||||
CONTRACT_VERSION. Nothing is logged before the privacy checks pass.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import mlflow
|
||||
import pandas as pd
|
||||
|
||||
from tea_modulo.contracts import CONTRACT_VERSION
|
||||
|
||||
from . import privacy
|
||||
|
||||
PKG_ROOT = Path(__file__).resolve().parents[1] # .../tea_modulo
|
||||
|
||||
|
||||
MODEL_CODE = Path(__file__).with_name("model_code")
|
||||
|
||||
|
||||
def _stage_code(module_pkg: str, dest: Path) -> Path:
|
||||
"""A copy of tea_modulo with only `contracts` and the module's package (+ parent __init__s)."""
|
||||
root = dest / "tea_modulo"
|
||||
(root).mkdir(parents=True)
|
||||
shutil.copy(PKG_ROOT / "__init__.py", root / "__init__.py")
|
||||
shutil.copytree(PKG_ROOT / "contracts", root / "contracts",
|
||||
ignore=shutil.ignore_patterns("__pycache__"))
|
||||
parts = module_pkg.split(".")[1:] # drop "tea_modulo"
|
||||
cur_src, cur_dst = PKG_ROOT, root
|
||||
for p in parts[:-1]:
|
||||
cur_src, cur_dst = cur_src / p, cur_dst / p
|
||||
cur_dst.mkdir(exist_ok=True)
|
||||
shutil.copy(cur_src / "__init__.py", cur_dst / "__init__.py")
|
||||
shutil.copytree(PKG_ROOT.joinpath(*parts), root.joinpath(*parts),
|
||||
ignore=shutil.ignore_patterns("__pycache__"), dirs_exist_ok=True)
|
||||
return root
|
||||
|
||||
|
||||
def _package_of(module) -> str:
|
||||
"""'tea_modulo.legacy.biomarkers.posterior_rhythm' for a module object."""
|
||||
name = type(module).__module__
|
||||
return name.rsplit(".", 1)[0] if name.endswith(".api") else name
|
||||
|
||||
|
||||
def log_plan(plan, *, registered_name: str | None = None, run_name: str | None = None,
|
||||
experiment: str = "tea-modulo-plans"):
|
||||
d = plan.to_dict() if hasattr(plan, "to_dict") else dict(plan)
|
||||
d.pop("bads", None)
|
||||
d.pop("reasons", None)
|
||||
privacy.check_text(json.dumps(d), registered_name or "", run_name or "")
|
||||
mlflow.set_experiment(experiment)
|
||||
with tempfile.TemporaryDirectory() as tmp, mlflow.start_run(run_name=run_name or d.get("name")):
|
||||
mlflow.log_dict(d, "plan/plan.json")
|
||||
mlflow.log_params({"plan.name": d.get("name"), "plan.hash": d.get("hash"),
|
||||
"plan.line_hz": d.get("line_hz"),
|
||||
**{f"step.{s['kind']}.{k}": v for s in d.get("steps", [])
|
||||
for k, v in s.get("params", {}).items()},
|
||||
"variants": ",".join(v["name"] for v in d.get("variants", []))})
|
||||
mlflow.set_tags({"kind": "plan", "plan_hash": d.get("hash", ""),
|
||||
"contract_version": CONTRACT_VERSION})
|
||||
f = Path(tmp) / "plan.json"
|
||||
f.write_text(json.dumps(d, indent=1), encoding="utf-8")
|
||||
info = mlflow.pyfunc.log_model(name="plan", python_model=str(MODEL_CODE / "plan_model.py"),
|
||||
artifacts={"plan": str(f)},
|
||||
code_paths=[str(_stage_code("tea_modulo.contracts", Path(tmp) / "code"))],
|
||||
input_example=pd.DataFrame({"edf_path": ["study.edf"]}),
|
||||
registered_model_name=registered_name)
|
||||
return _version(info, registered_name)
|
||||
|
||||
|
||||
def log_biomarker(module, *, plan_uri: str = "", plan: dict | None = None,
|
||||
registered_name: str | None = None, run_name: str | None = None,
|
||||
n_reference: int | None = None, experiment: str = "tea-modulo-biomarkers",
|
||||
input_example: pd.DataFrame | None = None):
|
||||
privacy.check_text(registered_name or "", run_name or "", plan_uri)
|
||||
if plan is None and plan_uri:
|
||||
plan = load_plan(plan_uri)
|
||||
pkg = _package_of(module)
|
||||
mlflow.set_experiment(experiment)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
state = Path(tmp) / "module"
|
||||
state.mkdir()
|
||||
module.save(state)
|
||||
(state / "module.json").write_text(json.dumps(
|
||||
{"class": f"{type(module).__module__}:{type(module).__name__}", "name": module.name,
|
||||
"version": module.version, "impl": getattr(module, "impl", "modern")}))
|
||||
if plan is not None:
|
||||
(state / "plan.json").write_text(json.dumps(plan, indent=1))
|
||||
privacy.check_files(state)
|
||||
privacy.check_group(state, n_reference)
|
||||
if input_example is None:
|
||||
input_example = pd.DataFrame({**{f: [1.0] for f in module.features}, "age_months": [24.0]})
|
||||
code = _stage_code(pkg, Path(tmp) / "code")
|
||||
with mlflow.start_run(run_name=run_name or module.name):
|
||||
mlflow.set_tags({"kind": "biomarker", "module": module.name, "module_version": module.version,
|
||||
"impl": getattr(module, "impl", "modern"), "plan_uri": plan_uri,
|
||||
"plan_hash": (plan or {}).get("hash", ""),
|
||||
"contract_version": CONTRACT_VERSION})
|
||||
info = mlflow.pyfunc.log_model(name="biomarker", python_model=str(MODEL_CODE / "biomarker_model.py"),
|
||||
artifacts={"module": str(state)}, code_paths=[str(code)],
|
||||
input_example=input_example,
|
||||
registered_model_name=registered_name)
|
||||
return _version(info, registered_name)
|
||||
|
||||
|
||||
def load_plan(uri: str) -> dict:
|
||||
"""The plan dict of a plan model (models:/name/version or runs:/...)."""
|
||||
m = mlflow.pyfunc.load_model(uri)
|
||||
return m.unwrap_python_model().plan
|
||||
|
||||
|
||||
def load_biomarker(uri: str):
|
||||
"""The trained biomarker module object of a biomarker model."""
|
||||
return mlflow.pyfunc.load_model(uri).unwrap_python_model().module
|
||||
|
||||
|
||||
def _version(info, registered_name):
|
||||
if registered_name:
|
||||
client = mlflow.MlflowClient()
|
||||
vs = client.search_model_versions(f"name='{registered_name}'")
|
||||
return max(vs, key=lambda v: int(v.version))
|
||||
return info
|
||||
@@ -0,0 +1,67 @@
|
||||
"""
|
||||
What may leave the computer for MLflow (rule carried over from
|
||||
biomarcadores-tea/biomarcadores/registro.py, user decision 8 Oct 2026):
|
||||
plans, group-level baseline parameters, code versions. Never per-child
|
||||
values, study codes (eeg_###), dates or local paths, and never a group
|
||||
smaller than MIN_GROUP children.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
# registro._PROHIBIDO, plus POSIX home paths
|
||||
FORBIDDEN = re.compile(r"eeg_\d+|\d{4}-\d{2}-\d{2}|[A-Za-z]:\\|/Users/|/home/|Escritorio", re.I)
|
||||
MIN_GROUP = 5
|
||||
|
||||
|
||||
class Forbidden(ValueError):
|
||||
"""Something that must not leave the computer was about to be logged."""
|
||||
|
||||
|
||||
def check_text(*texts):
|
||||
for t in texts:
|
||||
m = FORBIDDEN.search(str(t))
|
||||
if m:
|
||||
raise Forbidden(f"text with a study code, date or path ({m.group(0)[:12]!r}…) "
|
||||
f"cannot go to MLflow")
|
||||
|
||||
|
||||
def check_files(folder: Path):
|
||||
"""Every text file a module saved, before it is logged as an artifact."""
|
||||
for p in Path(folder).rglob("*"):
|
||||
if p.is_file():
|
||||
try:
|
||||
check_text(p.read_text(encoding="utf-8"))
|
||||
except UnicodeDecodeError:
|
||||
raise Forbidden(f"{p.name}: binary artifacts are not allowed (only JSON / text)") from None
|
||||
|
||||
|
||||
def group_size(baseline: dict | None) -> float | None:
|
||||
"""Reference group size of a baseline dict, if its format is known."""
|
||||
if not baseline:
|
||||
return None
|
||||
st = baseline.get("state")
|
||||
if isinstance(st, dict) and "n" in st:
|
||||
return float(st["n"])
|
||||
curva = baseline.get("curva")
|
||||
if isinstance(curva, dict) and curva.get("n_efectivo"):
|
||||
vals = [v for v in curva["n_efectivo"] if v is not None]
|
||||
return max(vals) if vals else 0.0 # Kish n_eff <= n
|
||||
return None
|
||||
|
||||
|
||||
def check_group(folder: Path, n_reference: int | None = None):
|
||||
"""Refuse a trained baseline from fewer than MIN_GROUP children."""
|
||||
n = n_reference
|
||||
if n is None:
|
||||
f = Path(folder) / "baseline.json"
|
||||
if f.exists():
|
||||
n = group_size(json.loads(f.read_text(encoding="utf-8")))
|
||||
if n is None:
|
||||
raise Forbidden("cannot tell the reference group size: pass n_reference")
|
||||
if n < MIN_GROUP:
|
||||
raise Forbidden(f"baseline from {n:g} children: fewer than {MIN_GROUP} would almost "
|
||||
f"show each child's values")
|
||||
@@ -0,0 +1 @@
|
||||
"""Verification commands run on the team's cluster (HK1K only)."""
|
||||
@@ -0,0 +1,17 @@
|
||||
"""python -m tea_modulo.verify hk1k --out processed/usuarios/<name>/tea-verify/"""
|
||||
|
||||
import sys
|
||||
|
||||
from tea_modulo.verify import hk1k
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
if not argv or argv[0] != "hk1k":
|
||||
print(__doc__, file=sys.stderr)
|
||||
return 2
|
||||
return hk1k.main(argv[1:])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,186 @@
|
||||
"""
|
||||
HK1K verification on the team's cluster (public data only).
|
||||
|
||||
python -m tea_modulo.verify 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 when registered) on every study with
|
||||
age in --ages (default 16-36 months) through the remote Dask scheduler,
|
||||
mains line 50 Hz (Helsinki).
|
||||
3. Checks that the remote run equals a sequential run of the same first
|
||||
studies inside one task (same code path, one worker, plain loop).
|
||||
4. Compares the posterior rhythm by HK1K age group with the reference table
|
||||
(normas/referencia_hk1k.csv, ritmo_posterior / vigilia), when present.
|
||||
5. Prints a JSON summary and writes it to S3 under --out (worker task).
|
||||
|
||||
Only group numbers leave the tasks: counts, medians, percentiles; groups with
|
||||
fewer than 5 children are suppressed. Input paths other than raw/eeg-helsinki/
|
||||
are refused.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
HK1K = "raw/eeg-helsinki/"
|
||||
MIN_GROUP = 5
|
||||
REF = Path(__file__).resolve().parents[3] / "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"verification 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_modulo.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 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_modulo.pipeline.storage import s3
|
||||
if not out_prefix.startswith("processed/usuarios/"):
|
||||
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 | None:
|
||||
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 _versions(client) -> dict:
|
||||
v = client.get_versions(check=False)
|
||||
return {k: v["scheduler"]["packages"].get(k) for k in ("python", "dask", "distributed")}
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
import argparse
|
||||
|
||||
import pandas as pd
|
||||
from distributed import Client
|
||||
|
||||
from tea_modulo.pipeline import Pipeline, run_study
|
||||
from tea_modulo.pipeline.dask_runner import scheduler_address
|
||||
from tea_modulo.preprocessing import DIRECTOR_CLUSTER
|
||||
|
||||
ap = argparse.ArgumentParser(prog="python -m tea_modulo.verify 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"])
|
||||
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": 50.0}
|
||||
summary = {"plan_hash": plan["hash"], "line_hz": 50.0, "ages": list(args.ages), "impl": {},
|
||||
"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 = [(p, a) for p, a in items if args.ages[0] <= a <= args.ages[1]]
|
||||
items.sort()
|
||||
if args.limit:
|
||||
items = items[: args.limit]
|
||||
summary["n_listed"] = len(items)
|
||||
for impl in args.impl:
|
||||
try:
|
||||
pipe = Pipeline.default(impl=impl)
|
||||
except Exception as e: # noqa: BLE001
|
||||
summary["impl"][impl] = {"skipped": f"{type(e).__name__}: {e}"[:200]}
|
||||
continue
|
||||
if "posterior_rhythm" not in pipe.modules:
|
||||
summary["impl"][impl] = {"skipped": "posterior_rhythm not registered"}
|
||||
continue
|
||||
paths, ages = [p for p, _ in items], [a for _, a in items]
|
||||
remote = Pipeline(pipe.modules, impl="modern").map(
|
||||
paths, plan=plan, ages_months=ages, biomarkers=("posterior_rhythm",),
|
||||
cluster="remote", line_hz=50.0)
|
||||
# equality: the first studies again, sequentially, in one task
|
||||
from tea_modulo.pipeline.run_study import order_for
|
||||
mods = {n: pipe.modules[n] for n in ("validation", "preprocessing",
|
||||
*order_for(["posterior_rhythm"], pipe.modules),
|
||||
"posterior_rhythm")}
|
||||
order = tuple(order_for(["posterior_rhythm"], pipe.modules))
|
||||
k = min(args.check_n, len(paths))
|
||||
argsets = [(i, paths[i], ages[i], plan, mods, order, ("posterior_rhythm",), 50.0)
|
||||
for i in range(k)]
|
||||
seq = pd.DataFrame(client.submit(sequential, run_study, argsets, pure=False,
|
||||
priority=-10).result())
|
||||
cols = [c for c in seq.columns if c not in ("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)))
|
||||
ok = remote[(remote.valid == 1) & (remote.error == "")]
|
||||
info = {"n": int(len(remote)), "valid": int((remote.valid == 1).sum()),
|
||||
"not_valid": int((remote.valid == 0).sum()),
|
||||
"errors": int((remote.error != "").sum()),
|
||||
"error_types": remote.loc[remote.error != "", "error"].str.split(":").str[0]
|
||||
.value_counts().to_dict(),
|
||||
"remote_equals_sequential": equal, "checked": k,
|
||||
"seconds_median": float(remote.seconds.median()) if len(remote) else None,
|
||||
"posterior_rhythm_hz": group_stats(ok.get("posterior_rhythm_hz", [])),
|
||||
"by_age_group": {}}
|
||||
for lo, hi in ((12, 24), (24, 36)):
|
||||
g = ok[(ok.age_months >= lo) & (ok.age_months < hi)]
|
||||
info["by_age_group"][f"{lo}-{hi}"] = group_stats(g.get("posterior_rhythm_hz", []))
|
||||
summary["impl"][impl] = info
|
||||
summary["reference"] = _reference()
|
||||
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 summary["impl"].items() if isinstance(v, dict)
|
||||
and 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")}
|
||||
Reference in New Issue
Block a user