Compare commits

..

2 Commits

5 changed files with 529 additions and 1 deletions
+117
View File
@@ -0,0 +1,117 @@
"""Probe a TEA scheduler and its associated services."""
import os
import re
from contextlib import suppress
from pathlib import Path
from time import perf_counter
from urllib.parse import urlsplit
from urllib.request import urlopen
from .dask_runner import scheduler_address
def _count_edfs(name: str) -> int:
root = Path("/referencia").resolve()
folder = (root / name).resolve()
if folder.parent != root:
raise ValueError("La carpeta de referencia está fuera de /referencia.")
return sum(path.is_file() for path in folder.rglob("*.edf"))
class ClusterStatus:
"""Report independent Dask health checks."""
def check(self, mode="auto", scheduler=None, reference_name=None) -> dict:
"""Resolve the mode and report cluster health."""
if mode not in ("auto", "local", "remote", "sync"):
raise ValueError("El modo debe ser auto, local, remote o sync.")
address = scheduler_address(scheduler) if mode in ("auto", "remote") else None
if mode == "auto":
mode = "remote" if address else "local"
if mode == "remote" and not address:
raise ValueError("El modo remote requiere un planificador Dask.")
status = {
"mode": mode,
"scheduler": address,
"reachable": mode != "remote",
"workers": None,
"expected_workers": None,
"versions_ok": None,
"version_error": None,
"dashboard_ok": None,
"dashboard_url": None,
"reference": None,
"latency_ms": None,
"error": None,
}
if mode != "remote":
return status
with suppress(ValueError):
status["expected_workers"] = int(os.environ.get("TEA_DASK_EXPECTED_WORKERS", ""))
self._check_scheduler(status, reference_name)
self._check_dashboard(status)
return status
def _check_scheduler(self, status: dict, reference_name: str | None) -> None:
try:
from distributed import Client
from distributed.versions import error_message
start = perf_counter()
client = Client(status["scheduler"], timeout=5)
except Exception as exc:
status["error"] = str(exc) or type(exc).__name__
return
try:
status["latency_ms"] = (perf_counter() - start) * 1000
status["reachable"] = True
with suppress(Exception):
status["workers"] = len(client.scheduler_info()["workers"])
try:
versions = client.get_versions(check=True)
# Dask can report mismatches as warnings.
mismatch = error_message(versions["scheduler"], versions["workers"], versions["client"])
except Exception as exc:
status["versions_ok"] = False
status["version_error"] = str(exc)
else:
status["version_error"] = mismatch["error"] or mismatch["warning"] or None
status["versions_ok"] = status["version_error"] is None
if (
status["workers"] != 0
and reference_name
and reference_name not in (".", "..")
and re.fullmatch(r"[A-Za-z0-9._-]{1,64}", reference_name)
):
with suppress(Exception):
future = client.submit(_count_edfs, reference_name, pure=False)
status["reference"] = {"name": reference_name, "edfs": future.result(timeout=5)}
finally:
with suppress(Exception):
client.close()
def _check_dashboard(self, status: dict) -> None:
status["dashboard_ok"] = False
with suppress(Exception):
url = os.environ.get("TEA_DASK_DASHBOARD_URL")
if not url:
address = status["scheduler"]
host = urlsplit(address if "://" in address else f"//{address}").hostname
if not host:
return
if ":" in host:
host = f"[{host}]"
port = os.environ.get("TEA_DASK_DASHBOARD_PORT", "8787")
url = f"http://{host}:{port}/status"
status["dashboard_url"] = url
parts = urlsplit(url)
health_url = parts._replace(path="/health", query="", fragment="").geturl()
with urlopen(health_url, timeout=3) as response:
status["dashboard_ok"] = 200 <= response.status < 300
+31 -1
View File
@@ -23,6 +23,8 @@ import contextlib
import os
from collections.abc import Callable, Sequence
from tea.pipeline.run_monitor import active_monitor
BLAS_ENV = {"OMP_NUM_THREADS": "1", "OPENBLAS_NUM_THREADS": "1", "MKL_NUM_THREADS": "1"}
@@ -38,11 +40,20 @@ def _bytes(s) -> int:
def local_workers(memory_per_worker="4.25GiB", n_workers: int | None = None) -> int:
if n_workers:
return int(n_workers)
if os.environ.get("TEA_LOCAL_WORKERS"):
return max(1, int(os.environ["TEA_LOCAL_WORKERS"]))
import psutil
by_mem = int(psutil.virtual_memory().available // _bytes(memory_per_worker))
return max(1, min(os.cpu_count() or 1, by_mem))
def _release(client) -> None:
"""Tell the job's monitor the client is going away, so it stops reporting the cluster's last figures."""
monitor = active_monitor()
if monitor is not None:
monitor.release(client)
@contextlib.contextmanager
def client_for(cluster: str = "auto", scheduler: str | None = None,
memory_per_worker="4.25GiB", n_workers: int | None = None, check_versions=True):
@@ -62,8 +73,12 @@ def client_for(cluster: str = "auto", scheduler: str | None = None,
try:
if check_versions:
client.get_versions(check=True)
monitor = active_monitor()
if monitor is not None:
monitor.start(client, ("remote", addr))
yield client
finally:
_release(client)
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,
@@ -71,8 +86,12 @@ def client_for(cluster: str = "auto", scheduler: str | None = None,
env=BLAS_ENV)
client = Client(lc)
try:
monitor = active_monitor()
if monitor is not None:
monitor.start(client, ("local", None))
yield client
finally:
_release(client)
client.close()
lc.close() # this runner started it, so it closes it
@@ -80,7 +99,7 @@ def client_for(cluster: str = "auto", scheduler: str | None = None,
def run(fn: Callable, argsets: Sequence[tuple], *, cluster="auto", scheduler=None,
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:
on_error: Callable | None = None, track_progress: bool = True) -> list:
"""Run fn(*args) for every args in argsets; results in the input order.
`on_error(args, exc)`, when given, turns a task that failed at the Dask level (a worker
@@ -88,10 +107,19 @@ def run(fn: Callable, argsets: Sequence[tuple], *, cluster="auto", scheduler=Non
the batch; without it the exception propagates."""
import dask
monitor = active_monitor() if track_progress else None
if monitor is not None:
monitor.total(len(argsets))
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:
if client is None:
def completed(result):
monitor.advance()
return result
if monitor is not None:
tasks = [dask.delayed(completed, pure=False)(task) for task in tasks]
out = list(dask.compute(*tasks, scheduler="synchronous"))
if on_result:
for r in out:
@@ -109,6 +137,8 @@ def run(fn: Callable, argsets: Sequence[tuple], *, cluster="auto", scheduler=Non
raise
r = on_error(argsets[index[f.key]], e)
out[index[f.key]] = r
if monitor is not None:
monitor.advance()
if on_result:
on_result(r)
return out
+225
View File
@@ -0,0 +1,225 @@
"""Publish best-effort job progress snapshots."""
import json
import os
from collections import Counter, deque
from contextvars import ContextVar
from datetime import datetime, timezone
from pathlib import Path
from tempfile import NamedTemporaryFile
from threading import Event, Lock, Thread
from time import monotonic
_MEASURING = {"midiendo", "analizando"}
_TASK_STATES = ("processing", "waiting", "memory", "erred")
_active = ContextVar("run_monitor", default=None)
def active_monitor():
"""Return the monitor for the current job, if any."""
return _active.get()
def _task_counts(dask_scheduler):
counts = Counter(task.state for task in dask_scheduler.tasks.values())
return {state: counts[state] for state in _TASK_STATES}
def _cluster_sample(info, mode, scheduler):
workers = []
for address, worker in info["workers"].items():
metrics = worker.get("metrics", {})
workers.append({
"name": str(worker.get("name", address)),
"cpu_pct": metrics.get("cpu", 0),
"memory_bytes": metrics.get("memory", 0),
"memory_limit": worker.get("memory_limit") or None,
"executing": metrics.get("executing", metrics.get("task_counts", {}).get("executing", 0)),
"threads": worker["nthreads"],
})
limit = sum(worker["memory_limit"] or 0 for worker in workers)
return {
"mode": mode, "scheduler": scheduler, "workers": workers,
"cpu_pct": min(100, sum(w["cpu_pct"] / w["threads"] for w in workers) / len(workers)) if workers else 0,
"memory_pct": 100 * sum(w["memory_bytes"] for w in workers) / limit if limit else 0,
}
class RunMonitor:
"""Track a job and publish atomic progress snapshots."""
def __init__(self, directory, interval=2.0, history=120):
self._directory = Path(directory)
self._interval = interval
self._history = deque(maxlen=history)
self._lock = Lock()
self._stopped = Event()
self._thread = None
self._started = None
self._client = None
self._cluster = None
self._tasks = None
self._phase = "preparando"
self._done = self._total = 0
self._rate = None
self._previous = None
def __enter__(self):
self.start()
self._token = _active.set(self)
return self
def __exit__(self, *exc):
try:
self.stop()
finally:
_active.reset(self._token)
def start(self, client=None, cluster=("local", None)):
"""Start sampling or attach a newly opened Dask client."""
with self._lock:
if client is not None:
mode, scheduler = cluster
self._client = client
if self._cluster is None or (self._cluster["mode"], self._cluster["scheduler"]) != cluster:
self._cluster = _cluster_sample({"workers": {}}, mode, scheduler)
self._tasks = None
if self._thread is None and not self._stopped.is_set():
self._started = monotonic()
self._thread = Thread(target=self._sample_loop, daemon=True)
try:
self._thread.start()
except RuntimeError:
pass
def release(self, client=None):
"""Forget the cluster once its client closes: later snapshots carry no CPU, RAM or task figures."""
with self._lock:
if client is None or client is self._client:
self._client = self._cluster = self._tasks = None
def phase(self, name):
with self._lock:
if name != self._phase and name in _MEASURING:
self._rate = None
elapsed = monotonic() - self._started if self._started is not None else 0
self._previous = (elapsed, self._done)
self._phase = name
def total(self, n):
with self._lock:
self._total = n
def advance(self, n=1):
with self._lock:
self._done += n
def stop(self):
"""Write a final snapshot with the most recent telemetry."""
with self._lock:
if self._thread is not None and not self._stopped.is_set():
self._stopped.set()
self._write_sample()
def _sample_loop(self):
while not self._stopped.is_set():
with self._lock:
client, cluster, tasks = self._client, self._cluster, self._tasks
gone = client is not None and getattr(client, "status", None) in {"closing", "closed"}
if client is not None and not gone:
try:
info = client.scheduler_info()
cluster = _cluster_sample(info, cluster["mode"], cluster["scheduler"])
if not hasattr(client, "run_on_scheduler"):
counts = info.get("tasks")
if isinstance(counts, dict):
tasks = {state: counts.get(state, 0) for state in _TASK_STATES}
except Exception:
pass
try:
if hasattr(client, "run_on_scheduler"):
tasks = client.run_on_scheduler(_task_counts, callback_timeout=self._interval)
except Exception:
pass
with self._lock:
if self._stopped.is_set():
return
if client is self._client:
if gone:
self._client = self._cluster = self._tasks = None
else:
self._cluster, self._tasks = cluster, tasks
self._write_sample()
self._stopped.wait(self._interval)
def _eta(self, elapsed):
if self._phase not in _MEASURING:
return None
when, done = self._previous
if elapsed > when:
rate = (self._done - done) / (elapsed - when)
self._rate = rate if self._rate is None else 0.3 * rate + 0.7 * self._rate
self._previous = (elapsed, self._done)
if self._done >= 3 and self._rate and self._rate > 0:
return max(0, self._total - self._done) / self._rate
return None
def _write_sample(self):
temporary = None
try:
elapsed = monotonic() - self._started
eta = self._eta(elapsed)
self._history.append({
"t": elapsed, "done": self._done,
"cpu_pct": self._cluster["cpu_pct"] if self._cluster else 0,
"memory_pct": self._cluster["memory_pct"] if self._cluster else 0,
})
snapshot = {
"updated_at": datetime.now(timezone.utc).isoformat(),
"phase": self._phase, "done": self._done, "total": self._total,
"elapsed_s": elapsed, "eta_s": eta, "tasks": self._tasks,
"cluster": self._cluster, "history": list(self._history),
}
self._directory.mkdir(parents=True, exist_ok=True)
with NamedTemporaryFile(mode="w", encoding="utf-8", dir=self._directory, delete=False) as stream:
temporary = Path(stream.name)
json.dump(snapshot, stream, allow_nan=False)
os.replace(temporary, self._directory / "progress.json")
except Exception:
if temporary is not None:
try:
temporary.unlink(missing_ok=True)
except OSError:
pass
class _NullMonitor:
def __enter__(self):
return self
def __exit__(self, *exc):
pass
def start(self, client=None, cluster=("local", None)):
pass
def release(self, client=None):
pass
def phase(self, name):
pass
def total(self, n):
pass
def advance(self, n=1):
pass
def stop(self):
pass
def monitor_from_env():
"""Enable progress reporting when a job directory is configured."""
directory = os.environ.get("RUN_PROGRESS_DIR")
return RunMonitor(directory) if directory else _NullMonitor()
+4
View File
@@ -0,0 +1,4 @@
"""Clinical scores computed from a study's recorded items, outside the per-study EEG pipeline."""
from tea.scoring.ados2 import Ados2Score, ModuleScorer, register, score
__all__ = ["Ados2Score", "ModuleScorer", "register", "score"]
+152
View File
@@ -0,0 +1,152 @@
"""ADOS-2 totals, calibrated severity score (CSS) and classification from the algorithm item scores.
A module's scorer is a `ModuleScorer` subclass registered with `@register`; adding a module touches nothing else.
Items are named by their code without the table prefix (`sa_a2`, `rrb_d1`); a score of 3 counts as 2, as the
algorithms do. The total is the sum of the items given, so a missing item lowers it.
The CSS cut points below are approximate values from the published calibrated severity tables (Gotham, Pickles and
Lord 2009; Hus and Lord 2014), kept as data so the licensed tables can replace them without changing the code. Each
row lists the lowest total that reaches CSS 2, 3, ... 10; a total under the first is CSS 1.
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Mapping
from dataclasses import dataclass
from typing import ClassVar
MAX_ALGORITHM_SCORE = 2
SOCIAL_AFFECT = "sa_"
RESTRICTED_REPETITIVE = "rrb_"
# Classification from the CSS: from 3 on the child is on the spectrum, from 5 on autism.
CSS_SPECTRUM = 3
CSS_AUTISM = 5
NO_SPECTRUM = "NO_ESPECTRO"
SPECTRUM = "ESPECTRO_AUTISTA"
AUTISM = "AUTISMO"
CONCERN_MILD_MODERATE = "PREOCUPACION_LEVE_MODERADA"
CONCERN_SEVERE = "PREOCUPACION_SEVERA"
MONTHS_PER_YEAR = 12
FIVE_YEARS = 5 * MONTHS_PER_YEAR
DAYS_PER_MONTH = 30.4375
@dataclass(frozen=True)
class Ados2Score:
"""What an evaluation's items give. `css` is empty where the module has none (Toddler) or the table needs an
age or a language level that wasn't given."""
social_affect: int
restricted_repetitive: int
total: int
css: int | None
classification: str | None
def classify_css(css: int) -> str:
if css < CSS_SPECTRUM:
return NO_SPECTRUM
return SPECTRUM if css < CSS_AUTISM else AUTISM
def totals(items: Mapping[str, int | None]) -> tuple[int, int] | None:
"""Social affect and restricted-repetitive totals, or none if either domain has no item."""
sa = [min(v, MAX_ALGORITHM_SCORE) for k, v in items.items() if k.startswith(SOCIAL_AFFECT) and v is not None]
rrb = [min(v, MAX_ALGORITHM_SCORE) for k, v in items.items()
if k.startswith(RESTRICTED_REPETITIVE) and v is not None]
if not sa or not rrb:
return None
return sum(sa), sum(rrb)
class ModuleScorer(ABC):
module: ClassVar[str]
@abstractmethod
def severity(self, total: int, *, age_months: float | None, algorithm: str | None) -> tuple[int | None, str | None]:
"""The CSS and the classification of a total, each empty if it can't be given."""
SCORERS: dict[str, ModuleScorer] = {}
def register(cls: type[ModuleScorer]) -> type[ModuleScorer]:
SCORERS[cls.module] = cls()
return cls
def _css(total: int, cut_points: tuple[int, ...]) -> int:
return 1 + sum(total >= c for c in cut_points)
class TableScorer(ModuleScorer):
"""A module whose CSS reads a cut-point row chosen by the language level and the age group."""
# (algorithm, under five years) -> cut points; `None` matches any.
tables: ClassVar[dict[tuple[str | None, bool | None], tuple[int, ...]]]
def severity(self, total, *, age_months, algorithm):
under_five = None if age_months is None else age_months < FIVE_YEARS
for key in ((algorithm, under_five), (algorithm, None), (None, under_five), (None, None)):
if key in self.tables:
css = _css(total, self.tables[key])
return css, classify_css(css)
return None, None
@register
class ModuleOne(TableScorer):
module = "MODULO_1"
tables = {
("Pocas o ninguna palabra", True): (4, 7, 11, 14, 16, 18, 20, 22, 24),
("Pocas o ninguna palabra", False): (6, 9, 12, 15, 17, 19, 21, 23, 25),
("Algunas palabras", True): (3, 5, 8, 10, 12, 14, 16, 18, 20),
("Algunas palabras", False): (4, 6, 9, 11, 13, 15, 17, 19, 21),
}
@register
class ModuleTwo(TableScorer):
module = "MODULO_2"
tables = {
(None, True): (3, 5, 7, 9, 10, 12, 14, 16, 18),
(None, False): (3, 6, 8, 10, 11, 13, 15, 17, 19),
}
@register
class ModuleThree(TableScorer):
module = "MODULO_3"
tables = {(None, None): (2, 4, 7, 8, 9, 11, 13, 15, 17)}
@register
class Toddler(ModuleScorer):
"""Ranges of concern by age band instead of a CSS: the lowest total of the mild-to-moderate and of the severe
range, for 12 to 20 months and for 21 to 30."""
module = "TODDLER"
bands = ((20, (10, 16)), (30, (8, 14)))
def severity(self, total, *, age_months, algorithm):
if age_months is None:
return None, None
mild, severe = next((cuts for limit, cuts in self.bands if age_months <= limit), self.bands[-1][1])
if total >= severe:
return None, CONCERN_SEVERE
return None, CONCERN_MILD_MODERATE if total >= mild else NO_SPECTRUM
def score(module: str | None, items: Mapping[str, int | None], *, age_months: float | None = None,
algorithm: str | None = None) -> Ados2Score | None:
"""The score of an evaluation, or none when its module isn't one the library knows or it has no items in a
domain. `age_months` is the child's age at the evaluation."""
scorer = SCORERS.get(module or "")
given = totals(items)
if scorer is None or given is None:
return None
sa, rrb = given
css, classification = scorer.severity(sa + rrb, age_months=age_months, algorithm=algorithm)
return Ados2Score(sa, rrb, sa + rrb, css, classification)