Compare commits

...

28 Commits

Author SHA1 Message Date
alberto 8f7f7cc694 Merge pull request 'Preview of one EDF and its ADOS-2 report: notes and pointer (#213)' (#214) from feature/tea-eeg-analysis into dev 2026-11-23 12:28:13 -06:00
ulises 71adac469e ISSSTELEON pointer: results of one EDF and its ADOS-2 report without storing them (#213)
selective-ci / selective-ci (pull_request) Failing after 4s
2026-11-23 12:27:38 -06:00
ulises b1a2b21fac Preview of one EDF and its ADOS-2 report: route in the architecture notes (#213) 2026-11-23 12:27:38 -06:00
alberto 7fe574c5dc Merge pull request 'TEA EEG from the app: manual-deploy flow, 10-pod Dask cluster, plan (#211)' (#212) from feature/tea-eeg-analysis into dev 2026-11-23 09:38:40 -06:00
ulises 0b4a1ccb87 ISSSTELEON pointer: TEA EEG in Gobernanza (#211)
selective-ci / selective-ci (pull_request) Failing after 4s
2026-11-23 09:35:52 -06:00
ulises 5ce450a36a TEA EEG from the app: manual-deploy README and settings, one 10-pod Dask cluster, worker build checks the Python patch, rule on the 5310 stack (#211) 2026-11-23 09:35:52 -06:00
ulises 7f8232be5d dev-data pointer: merge with dev (#184) 2026-11-23 09:35:52 -06:00
Roberto Treviño Cervantes 6f0897afcb CaMa demo: Trazabilidad loaded from the precomputed history 2026-11-23 03:37:27 -06:00
Roberto Treviño Cervantes 678aef8f1f Merge dev 2026-11-23 01:33:42 -06:00
Roberto Treviño Cervantes f28c75c600 CaMa demo patients and how to reach them; plan status after the redeploy from dev; ISSSTELEON pin 2026-11-23 01:33:22 -06:00
Roberto Treviño Cervantes 9e946b9a97 Plan: owner's decisions on the CaMa redeploy data and the survival model 2026-11-22 23:37:40 -06:00
Roberto Treviño Cervantes d4e3baa838 Plan: how to get the CaMa models and the example patients 2026-11-22 23:35:26 -06:00
Roberto Treviño Cervantes a5c19a7d21 Plan: CaMa consolidation into dev and a clean redeploy from dev 2026-11-22 23:24:44 -06:00
alberto 3c84918b85 Merge pull request 'ADOS-2 scoring by the platform: open items and pointers (#184)' (#209) from feature/tea-eeg-analysis into dev
Reviewed-on: #209
2026-11-22 22:12:45 -06:00
ulises ec91a234b8 ISSSTELEON pointer: WebApp merge (#184)
selective-ci / selective-ci (pull_request) Failing after 5s
2026-11-22 22:11:41 -06:00
ulises d7c5635641 ADOS-2 scoring by the platform: open items, submodule pointers (#184)
selective-ci / selective-ci (pull_request) Failing after 4s
2026-11-22 22:01:54 -06:00
ulises e1f0d251e1 ADOS-2 items read from the evaluation PDF: ISSSTELEON and dev-data (#184) 2026-11-22 12:10:28 -06:00
ulises 03c4a7f77b ISSSTELEON rebased onto dev with the CaCu indicators integration; open item on the CaCu risk index date migration over existing views (#184) 2026-11-22 09:53:26 -06:00
ulises d4d75a3245 TEA ADOS-2 association and EEG zones: submodules, new EEG baselines bundle, cluster image with bokeh, open items (#184) 2026-11-21 23:18:40 -06:00
ulises 3295d6d8b1 manual-deploy: TEA section for training the EEG age baselines on the Dask cluster and loading them in a second deployment (#184) 2026-11-21 20:54:10 -06:00
alberto 21062d6ad3 manual-deploy: the exported EEG baselines bundle the deployment imports (#184) 2026-11-21 20:54:10 -06:00
alberto b6eb3c836b manual-deploy: ports, EDF folder and Dask scheduler address, and the EEG baselines import log (#184) 2026-11-21 20:54:10 -06:00
AlbertoPMDM fd583a630b manual-deploy: deployment A trains on the k3s Dask cluster, the simulated hospital takes the real EDFs (#184) 2026-11-21 20:54:10 -06:00
AlbertoPMDM 5f9d61cf96 plans: TEA EEG analysis on the Dask cluster, what the first runs showed and the tasks that follow (#184) 2026-11-21 20:54:10 -06:00
AlbertoPMDM 3b76b07fb5 dask-cluster: sync-reference checks each copied file by size, so files left by an earlier sync don't fail it (#184) 2026-11-21 20:54:10 -06:00
AlbertoPMDM e428b490e4 dask-cluster: image with only the tea library and models at the platform's versions, dask worker/scheduler commands, HTTP sync of the reference folder (#184) 2026-11-21 20:54:10 -06:00
AlbertoPMDM cb399a8006 dask-cluster: Kubernetes Dask image and cluster for the TEA EEG baselines, reading reference EDFs from a local folder (#184) 2026-11-21 20:54:10 -06:00
roberto 05872352f3 Merge pull request 'Pin ISSSTELEON and dev-data with the TEA age norm and ADOS-2 relation' (#196) from integration/tea-eeg-analysis-into-dev into dev
Reviewed-on: #196
2026-11-21 15:38:12 -06:00
44 changed files with 1865 additions and 8 deletions
+7 -1
View File
@@ -70,6 +70,12 @@ read only when a task points there (§5).
describe the change in their own terms. The link goes the other way:
each WorkingNarrative issue cites the commits and pull requests that
resolve it.
13. **The deployment on port 5310 is not touched.** Its containers
(`sitio-b-*`), volumes (`sitio-b_*`) and images (`sitio-b/*`) hold the
analysed real-data deployment: no `up`, `down`, `restart`, `recreate`,
`load`, import, promote or analysis, and no `docker exec` that writes.
Reading its API (GET requests) is fine. New deployments use another
project name, ports and subnet.
---
@@ -142,7 +148,7 @@ Databases: four independent ones (`CACU_`, `CAMA_`, `TEA_`,
one baseline generated from the models, verified upgrade/downgrade/upgrade
on SQLite, MySQL 8, PostgreSQL 16 and SQL Server 2022; older revisions are
gone, so a database stamped with them must start fresh):
- tea `a3e1c7b90d12` -> `f2b6d1e8c934` -> `6d772e9a342f` and `a7d3c9e5b160` -> `b9e4d2c71a05` (the join) -> `16bf0b0ee3e4` (EEG analysis outputs, `eeg_criterio`) -> `c4306f438b3a` (the four old criterion columns dropped);
- tea `a3e1c7b90d12` -> `f2b6d1e8c934` -> `6d772e9a342f` and `a7d3c9e5b160` -> `b9e4d2c71a05` (the join) -> `16bf0b0ee3e4` (EEG analysis outputs, `eeg_criterio`) -> `c4306f438b3a` (the four old criterion columns dropped) -> `41694156d3a1` (ADOS-2 association tables) and `c3f6a9e42d53` (risk index date) -> `e8c2a5d47f13` (their join) -> `98dadd777ffd` (`eeg_metrica_zona`);
cacu `b4f2d8c01e23` -> `f89e1f081998`; cama `c5a3e9d12f34` -> `f82b64f43abd` (`cat_sistema_fuente`,
`cat_mapeo`); governance `d6b4f0e23a45` -> `e7c5a1f34b56`. The TEA chain and the join verified
upgrade/downgrade/upgrade on SQLite only.
+4
View File
@@ -0,0 +1,4 @@
# Written by build.sh on every build.
requirements.lock
constraints.txt
.image
+35
View File
@@ -0,0 +1,35 @@
# syntax=docker/dockerfile:1.7
# Dask scheduler and workers for ISSSTELEON's TEA EEG batches (age baselines, EEG analysis). Build it with
# ./build.sh, which writes requirements.lock and passes the ISSSTELEON checkout as the `isssteleon` build context.
#
# Only what the workers run: the tea library and the models package its tasks come from, with their dependencies
# at the versions of the platform's lockfile (ISSSTELEON/WebApi/uv.lock). The same base as the platform's image,
# so Python is the one distributed's version check expects.
FROM python:3.12-slim
COPY --from=ghcr.io/astral-sh/uv:0.13.1 /uv /bin/uv
# One BLAS thread per worker process, as the platform's own local cluster does.
ENV OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 \
UV_SYSTEM_PYTHON=1 UV_NO_CACHE=1
COPY requirements.lock /opt/isssteleon/requirements.lock
RUN uv pip install -r /opt/isssteleon/requirements.lock
# The workers unpickle models.tea.eeg tasks, which import models, tea, core and persistance.
COPY --from=isssteleon Core /opt/isssteleon/Core
COPY --from=isssteleon Persistance /opt/isssteleon/Persistance
COPY --from=isssteleon Extraction /opt/isssteleon/Extraction
COPY --from=isssteleon models /opt/isssteleon/models
RUN uv pip install --no-deps \
/opt/isssteleon/Core /opt/isssteleon/Persistance /opt/isssteleon/Extraction \
/opt/isssteleon/models/libs/tea /opt/isssteleon/models \
&& python -c "import models.tea.eeg.train, models.tea.eeg.analyze, models.eeg_analysis, tea, distributed; print('distributed', distributed.__version__)"
COPY versions.py /opt/isssteleon/versions.py
RUN useradd --uid 10001 --create-home dask
USER dask
WORKDIR /home/dask
ARG ISSSTELEON_COMMIT=unknown
LABEL org.opencontainers.image.title="isssteleon-dask" isssteleon.commit=$ISSSTELEON_COMMIT
+97
View File
@@ -0,0 +1,97 @@
# Dask cluster for the TEA EEG batches
A Kubernetes Dask cluster (dask-operator `DaskCluster`) that runs ISSSTELEON's TEA EEG work: training the age
baselines on a local reference folder and, if the deployment points at it, the EEG analysis. The image holds only
what those tasks run: the `tea` library and the `models` package, with their dependencies.
| File | What it is |
|---|---|
| `Dockerfile` | the scheduler and worker image |
| `build.sh` | resolves `requirements.lock` against the platform's lockfile, builds, checks versions, pushes |
| `cluster.yaml` | the `isssteleon-eeg` DaskCluster: 10 worker pods (one per machine) x 4 processes, NodePorts 30786 and 30787 |
| `loader.yaml`, `sync-reference.sh` | copy a local EDF folder into the `eeg-data` volume the workers read |
| `deploy.sh` | applies the cluster with the built image and prints the scheduler address |
| `versions.py` | the versions `build.sh` compares between this image and the platform's |
## Why the image is built this way
The platform submits the jobs from its `webapi` container and connects with distributed's version check, which
refuses a scheduler or workers whose dask, distributed, cloudpickle, msgpack, tornado or Python differ. The
workers also unpickle tasks such as `models.tea.eeg.analyze.reference`, which import `models`, `tea`, `core` and
`persistance`. So:
- **The platform's base image**, `python:3.12-slim`, so Python is the one the platform runs.
- **ISSSTELEON's packages** (`Core`, `Persistance`, `Extraction`, `models`, `models/libs/tea`) from the checkout
you build from, which must be the commit the deployment runs. The image tag carries it
(`dask:isssteleon-<commit>`).
- **Their dependencies at the platform's exact versions**: `build.sh` exports `ISSSTELEON/WebApi/uv.lock` as
constraints and resolves the five packages against it, plus bokeh for the scheduler's dashboard. Nothing else is
installed: no S3 client (the workers read local folders), no notebooks, no OCR binaries.
- It runs as an unprivileged user (uid 10001). The loader pod runs as root to write the volume.
## Before the first build
- `uv`, Docker with BuildKit, and `kubectl` pointing at the cluster, which runs the dask-operator.
- The ISSSTELEON checkout next to this folder (`../ISSSTELEON`, submodules checked out), at the deployment's commit.
- Docker on this machine allowed to push to `192.168.20.18:5000` (an `insecure-registries` entry if it is
plain HTTP), and the cluster's nodes allowed to pull from it.
- A `PersistentVolumeClaim` named `eeg-data` that every node can mount: `ReadWriteMany`, since the loader writes
it while workers on several nodes read it.
- The platform's deployment built once (`docker compose up --build -d` in `../manual-deploy`), so `build.sh` can
compare versions with its image.
## Build, load the reference folder, deploy
```sh
cd dask-cluster
./build.sh # resolve, build, compare with the platform, push
```
Put the ages table inside the folder first. Its columns are `archivo` (file name only) and `edad_meses` or
`edad_anos`. Without one, ages come from each EDF's header. For Helsinki HK1K, whose headers have no birth date:
```sh
cp ~/datos/edades-helsinki.csv ~/datos/helsinki/edades.csv
./sync-reference.sh ~/datos/helsinki helsinki # -> /referencia/helsinki on every worker
./deploy.sh # prints DASK_SCHEDULER_ADDRESS=tcp://<node>:30786
```
## Train on the cluster
From `../manual-deploy`, with the address `deploy.sh` printed. The folder is mounted at the same path the
workers see, so the same command also works without the cluster (drop the `-e`):
```sh
docker compose run --rm \
-e DASK_SCHEDULER_ADDRESS=tcp://<node>:30786 \
--entrypoint /app/WebApi/.venv/bin/python \
-v "$HOME/datos/helsinki:/referencia/helsinki:ro" \
webapi -m models run tea eeg --train --environment prod \
--reference-dir /referencia/helsinki --reference-ages /referencia/helsinki/edades.csv \
--reference-name sitio-a --line-hz 50
```
The listing and every study's measurement run on the workers, which read the files from the volume. Training each
baseline on the measured features runs in the `webapi` container and registers in the deployment's MLflow.
Follow it on the dashboard (`http://<node>:30787/status`).
To send the deployment's EEG analysis to the cluster too, set `DASK_SCHEDULER_ADDRESS` in `../manual-deploy/.env`
and restart `webapi` and `indicadores`. Each EDF's bytes travel with its task, so the analysis needs no volume.
## Keep it in step
- **Rebuild after any change to ISSSTELEON** (models, tea, Core, Persistance, the WebApi lockfile), then
`./deploy.sh` again. An image from another commit is refused by the version check or runs old code.
- `./deploy.sh --delete` removes the cluster. The volume and its folders stay.
- Scale with `kubectl scale daskcluster isssteleon-eeg --replicas N` or by editing `replicas`.
## If something fails
| What you see | What to do |
|---|---|
| `ValueError: Mismatched versions found` on the client | the image was built from another ISSSTELEON commit than the deployment: rebuild |
| `no folder /referencia/<name>` from a worker | the folder wasn't synced, or `--reference-dir` names another one: `./sync-reference.sh` |
| `KeyError: 'posterior_rhythm_hz'` while training | no study had an age in 16 to 36 months: check the ages table is in the folder and passed with `--reference-ages` |
| Worker pods `Pending` | not enough memory or CPU per node for 22Gi and 5 CPUs, or the claim can't attach on several nodes |
| `ErrImagePull` | the nodes can't pull from `192.168.20.18:5000` |
| `build.sh` stops on `versions differ` | the platform's image is older or newer than the checkout: rebuild the deployment, or check out its commit |
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env bash
# Builds the Dask image for ISSSTELEON's EEG batches and pushes it to the cluster's registry: the tea library and the
# models package, with their dependencies at the platform's locked versions.
#
# ./build.sh resolve, build, compare with the platform's webapi image, push
# ./build.sh --no-push the same without pushing
# ./build.sh --resolve-only only write requirements.lock
#
# Environment:
# ISSSTELEON_DIR the ISSSTELEON checkout the platform runs (default: ../ISSSTELEON)
# REGISTRY where the image goes (default: 192.168.20.18:5000)
# WEBAPI_IMAGE the platform's image to compare versions with (default: <COMPOSE_PROJECT_NAME>/webapi:local
# from ../manual-deploy/.env); the comparison is skipped if that image isn't on this machine
#
# Writes requirements.lock, constraints.txt and .image (the tag deploy.sh applies).
set -euo pipefail
cd "$(dirname "$0")"
mode=${1:-push}
ISSSTELEON_DIR=$(realpath "${ISSSTELEON_DIR:-../ISSSTELEON}")
REGISTRY=${REGISTRY:-192.168.20.18:5000}
LOCAL_PACKAGES=(Core Persistance Extraction models/libs/tea models)
for p in "${LOCAL_PACKAGES[@]}"; do
[[ -f "$ISSSTELEON_DIR/$p/pyproject.toml" ]] || { echo "no $p in $ISSSTELEON_DIR (ISSSTELEON_DIR, submodules checked out?)" >&2; exit 1; }
done
commit=$(git -C "$ISSSTELEON_DIR" rev-parse --short HEAD)
if [[ -n "$(git -C "$ISSSTELEON_DIR" status --porcelain --untracked-files=no)" ]]; then
echo "warning: $ISSSTELEON_DIR has uncommitted changes; the image gets them, its tag says $commit-dirty" >&2
commit="$commit-dirty"
fi
echo "== constraints from $ISSSTELEON_DIR/WebApi/uv.lock"
(cd "$ISSSTELEON_DIR/WebApi" && uv export --frozen --no-dev --no-hashes --no-emit-project) \
| grep -v '^-e ' > constraints.txt
echo "== requirements.lock"
input=$(mktemp --suffix=.in)
trap 'rm -f "$input"' EXIT
for p in "${LOCAL_PACKAGES[@]}"; do echo "$ISSSTELEON_DIR/$p"; done > "$input"
# bokeh serves the scheduler's dashboard (port 8787); without it the status page is empty.
echo "bokeh>=3.1" >> "$input"
uv pip compile "$input" --python-version 3.12 --no-header --quiet \
--constraint constraints.txt \
--no-emit-package core --no-emit-package persistance --no-emit-package extraction \
--no-emit-package tea --no-emit-package models \
-o requirements.lock
grep -E '^(dask|distributed|bokeh|numpy|pandas|mne|yasa)==' requirements.lock | tr '\n' ' '; echo
[[ "$mode" == "--resolve-only" ]] && exit 0
image="$REGISTRY/dask:isssteleon-$commit"
echo "== building $image"
docker build --build-context isssteleon="$ISSSTELEON_DIR" --build-arg ISSSTELEON_COMMIT="$commit" -t "$image" .
if [[ -z "${WEBAPI_IMAGE:-}" && -f ../manual-deploy/.env ]]; then
project=$(sed -n 's/^COMPOSE_PROJECT_NAME=//p' ../manual-deploy/.env | tail -1)
[[ -n "$project" ]] && WEBAPI_IMAGE="$project/webapi:local"
fi
if [[ -n "${WEBAPI_IMAGE:-}" ]] && docker image inspect "$WEBAPI_IMAGE" >/dev/null 2>&1; then
echo "== versions against $WEBAPI_IMAGE"
ours=$(docker run --rm "$image" python /opt/isssteleon/versions.py | tail -1)
theirs=$(docker run --rm -i --entrypoint /app/WebApi/.venv/bin/python "$WEBAPI_IMAGE" - < versions.py | tail -1)
python3 - "$ours" "$theirs" <<'EOF'
import json, sys
ours, theirs = (json.loads(a) for a in sys.argv[1:])
bad = []
for k in sorted(set(ours) | set(theirs)):
a, b = ours.get(k), theirs.get(k)
if k == "python":
if a != b:
bad.append(f"python {a} here, {b} in the platform (distributed refuses even a patch difference: "
"rebuild the platform with `docker compose build --pull`, then this image the same day)")
elif a != b:
bad.append(f"{k} {a} here, {b} in the platform")
if bad:
sys.exit("versions differ from the platform:\n " + "\n ".join(bad))
print("same versions as the platform")
EOF
else
echo "warning: no platform image to compare with (WEBAPI_IMAGE); build the deployment first to check" >&2
fi
echo "$image" > .image
if [[ "$mode" == "--no-push" ]]; then
echo "built $image (not pushed)"
exit 0
fi
echo "== pushing $image"
docker push "$image"
echo "pushed $image; next: ./sync-reference.sh <folder> <name>, then ./deploy.sh"
+59
View File
@@ -0,0 +1,59 @@
# The Dask cluster for ISSSTELEON's TEA EEG batches. Apply it with ./deploy.sh, which fills in __IMAGE__.
#
# Workers read reference EDFs from the eeg-data volume, mounted read-only at /referencia: a cohort uploaded with
# `./sync-reference.sh <folder> <name>` is /referencia/<name>, the path given to --reference-dir. The volume is
# shared by every worker on every node, so the claim must be ReadWriteMany (or ReadOnlyMany once loaded).
#
# Its own name and NodePorts, so it runs next to other Dask clusters.
apiVersion: kubernetes.dask.org/v1
kind: DaskCluster
metadata:
name: isssteleon-eeg
spec:
worker:
replicas: 10
spec:
topologySpreadConstraints:
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
dask.org/cluster-name: isssteleon-eeg
dask.org/component: worker
containers:
- name: worker
image: __IMAGE__
# One pod per machine (the spread constraint above), 4 worker processes per pod, one thread each, at the
# 4.25 GiB a study needs; 4 x 4.25 GiB fits in 19Gi. To go to 5 per pod, use 22Gi and 5 CPUs.
args: [dask, worker, --name, $(DASK_WORKER_NAME), --nworkers, "4", --nthreads, "1", --memory-limit, 4.25GiB]
resources:
requests: {memory: 19Gi, cpu: "4"}
limits: {memory: 19Gi}
env:
- name: NODE_NAME
valueFrom:
fieldRef: {fieldPath: spec.nodeName}
volumeMounts:
- {name: referencia, mountPath: /referencia, readOnly: true}
volumes:
- name: referencia
persistentVolumeClaim: {claimName: eeg-data, readOnly: true}
scheduler:
spec:
containers:
- name: scheduler
# The same image as the workers: the platform checks the scheduler's versions too.
image: __IMAGE__
args: [dask, scheduler]
ports:
- {name: tcp-comm, containerPort: 8786}
- {name: http-dashboard, containerPort: 8787}
service:
type: NodePort
selector:
dask.org/cluster-name: isssteleon-eeg
dask.org/component: scheduler
ports:
- {name: tcp-comm, port: 8786, targetPort: tcp-comm, nodePort: 30786}
- {name: http-dashboard, port: 8787, targetPort: http-dashboard, nodePort: 30787}
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env bash
# Applies cluster.yaml with the image ./build.sh pushed, waits for the scheduler and prints the address the
# platform uses.
#
# ./deploy.sh create or update the cluster
# ./deploy.sh --delete remove it
set -euo pipefail
cd "$(dirname "$0")"
name=isssteleon-eeg
if [[ "${1:-}" == "--delete" ]]; then
kubectl delete daskcluster "$name"
exit 0
fi
IMAGE=${IMAGE:-$(cat .image 2>/dev/null || true)}
[[ -n "$IMAGE" ]] || { echo "no image: run ./build.sh first, or set IMAGE" >&2; exit 1; }
sed "s#__IMAGE__#$IMAGE#g" cluster.yaml | kubectl apply -f -
selector="dask.org/cluster-name=$name,dask.org/component=scheduler"
for _ in $(seq 60); do
kubectl get pod -l "$selector" -o name 2>/dev/null | grep -q . && break
sleep 5
done
kubectl wait --for=condition=Ready pod -l "$selector" --timeout=600s
node=$(kubectl get nodes -o jsonpath='{.items[0].status.addresses[?(@.type=="InternalIP")].address}')
port=$(kubectl get service "$name-scheduler" -o jsonpath='{.spec.ports[?(@.name=="tcp-comm")].nodePort}' 2>/dev/null || echo 30786)
dashboard=$(kubectl get service "$name-scheduler" -o jsonpath='{.spec.ports[?(@.name=="http-dashboard")].nodePort}' 2>/dev/null || echo 30787)
echo
echo "scheduler: DASK_SCHEDULER_ADDRESS=tcp://$node:${port:-30786}"
echo "dashboard: http://$node:${dashboard:-30787}/status"
echo "workers: kubectl get pods -l dask.org/cluster-name=$name,dask.org/component=worker"
+22
View File
@@ -0,0 +1,22 @@
# A short-lived pod with the eeg-data volume mounted read-write, so sync-reference.sh can copy a local folder
# into it. sync-reference.sh fills in __IMAGE__ and deletes the pod when the copy is done.
apiVersion: v1
kind: Pod
metadata:
name: isssteleon-eeg-loader
labels: {app: isssteleon-eeg-loader}
spec:
restartPolicy: Never
containers:
- name: loader
image: __IMAGE__
# The image runs as an unprivileged user; root here so it can write wherever the volume's owner allows.
securityContext: {runAsUser: 0}
command: [sleep, "86400"]
resources:
requests: {memory: 256Mi, cpu: "250m"}
volumeMounts:
- {name: referencia, mountPath: /referencia}
volumes:
- name: referencia
persistentVolumeClaim: {claimName: eeg-data}
+150
View File
@@ -0,0 +1,150 @@
#!/usr/bin/env bash
# Copies a local folder of reference EDFs into the eeg-data volume, where every worker reads it at
# /referencia/<name>. Put the ages table (`archivo`, `edad_meses` or `edad_anos`) inside the folder first.
#
# ./sync-reference.sh ~/datos/helsinki helsinki
#
# Files already there with the same name are overwritten; nothing is deleted, and files left there by an earlier
# sync don't affect the check, which compares each file of the local folder with its copy. Uses the image in
# .image (or IMAGE) for the short-lived loader pod, so the cluster needs no other image.
set -euo pipefail
cd "$(dirname "$0")"
folder=${1:?usage: sync-reference.sh <local folder> <name>}
name=${2:?usage: sync-reference.sh <local folder> <name>}
[[ -d "$folder" ]] || { echo "no folder $folder" >&2; exit 1; }
[[ "$name" =~ ^[A-Za-z0-9._-]+$ ]] || { echo "name: letters, digits, dot, dash or underscore only" >&2; exit 1; }
IMAGE=${IMAGE:-$(cat .image 2>/dev/null || true)}
[[ -n "$IMAGE" ]] || { echo "no image: run ./build.sh first, or set IMAGE" >&2; exit 1; }
pod=isssteleon-eeg-loader
local_count=$(find "$folder" -type f -iname '*.edf' | wc -l)
[[ "$local_count" -gt 0 ]] || { echo "no .edf files under $folder" >&2; exit 1; }
find "$folder" -maxdepth 1 -iname '*.csv' | grep -q . || echo "warning: no .csv in $folder: ages will come from the EDF headers" >&2
sed "s#__IMAGE__#$IMAGE#g" loader.yaml | kubectl apply -f -
trap 'rm -f "${server:-}" "${manifest:-}" "${expected:-}"; kill "${server_pid:-}" 2>/dev/null || true; kubectl delete pod "$pod" --wait=false >/dev/null 2>&1 || true' EXIT
kubectl wait --for=condition=Ready "pod/$pod" --timeout=600s
echo "== copying $local_count EDF files from $folder to /referencia/$name"
kubectl exec "$pod" -- mkdir -p "/referencia/$name"
# The bulk data flows over HTTP from this machine: the API server's exec stream is dropped
# mid-transfer often enough that piping a large folder through kubectl exec never finishes.
server=$(mktemp --suffix=.py)
manifest=$(mktemp)
cat > "$server" <<'EOF'
import http.server, pathlib, sys
folder = pathlib.Path(sys.argv[1]).resolve()
manifest = pathlib.Path(sys.argv[2]).read_bytes()
class Handler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=str(folder), **kwargs)
def do_GET(self):
if self.path == "/__manifest":
self.send_response(200)
self.send_header("Content-Length", str(len(manifest)))
self.end_headers()
self.wfile.write(manifest)
return
super().do_GET()
http.server.ThreadingHTTPServer(("0.0.0.0", int(sys.argv[3])), Handler).serve_forever()
EOF
find "$folder" -type f -printf '%P\0' > "$manifest"
port=${SYNC_PORT:-18777}
python3 "$server" "$folder" "$manifest" "$port" >/dev/null 2>&1 &
server_pid=$!
cluster=$(kubectl config view -o jsonpath='{.contexts[?(@.name=="'"$(kubectl config current-context)"'")].context.cluster}')
api=$(kubectl config view -o jsonpath='{.clusters[?(@.name=="'"$cluster"'")].cluster.server}')
api_host=${api#http://}; api_host=${api_host#https://}; api_host=${api_host%%:*}
host_ip=${SYNC_HOST_IP:-$(ip -4 route get "$api_host" | awk '{for (i = 1; i < NF; i++) if ($i == "src") {print $(i + 1); exit}}')}
[[ -n "$host_ip" ]] || { echo "no host IP the pod can reach; set SYNC_HOST_IP" >&2; exit 1; }
python3 -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:$port/__manifest', timeout=5)" \
|| { echo "the local HTTP server did not start (is port $port busy?)" >&2; exit 1; }
for attempt in $(seq 1 3); do
if kubectl exec -i "$pod" -- python3 - "/referencia/$name" "http://$host_ip:$port" <<'EOF'; then
import concurrent.futures, pathlib, sys, urllib.parse, urllib.request
dest, base = sys.argv[1], sys.argv[2]
names = [n for n in urllib.request.urlopen(base + "/__manifest", timeout=30).read().decode().split("\0") if n]
def fetch(name):
target = pathlib.Path(dest, name)
target.parent.mkdir(parents=True, exist_ok=True)
url = base + "/" + urllib.parse.quote(name)
error = None
for _ in range(5):
try:
with urllib.request.urlopen(url, timeout=300) as response, open(target, "wb") as out:
while True:
block = response.read(1 << 20)
if not block:
break
out.write(block)
return name, None
except Exception as exc: # the next attempt rewrites the file
error = exc
return name, error
failed = []
with concurrent.futures.ThreadPoolExecutor(8) as pool:
for i, (name, error) in enumerate(pool.map(fetch, names), 1):
if error is not None:
failed.append(name)
if i % 100 == 0:
print(f"{i}/{len(names)}", flush=True)
if failed:
print("failed: " + ", ".join(failed))
sys.exit(1)
print(f"downloaded {len(names)} files")
EOF
break
fi
if [[ $attempt == 3 ]]; then
echo "the download keeps failing" >&2
exit 1
fi
echo "download lost its exec stream, retrying" >&2
done
kill "$server_pid" 2>/dev/null || true
server_pid=
# The workers run as an unprivileged user.
kubectl exec "$pod" -- chmod -R a+rX "/referencia/$name"
# Each local file against its copy, by size: a missing or truncated file fails the sync by name.
expected=$(mktemp)
find "$folder" -type f -printf '%s\t%P\0' > "$expected"
check='
import os, sys
dest, edfs, bad = sys.argv[1], 0, []
for record in sys.stdin.buffer.read().decode().split("\0"):
if not record:
continue
size, name = record.split("\t", 1)
path = os.path.join(dest, name)
got = os.path.getsize(path) if os.path.isfile(path) else None
if got != int(size):
bad.append(f"{name}: missing" if got is None else f"{name}: {got} of {size} bytes")
elif name.lower().endswith(".edf"):
edfs += 1
print(edfs)
print("\n".join(bad))
sys.exit(1 if bad else 0)
'
if ! report=$(kubectl exec -i "$pod" -- python3 -c "$check" "/referencia/$name" < "$expected"); then
echo "these files did not arrive whole:" >&2
tail -n +2 <<< "$report" | head -20 >&2
exit 1
fi
echo "copied: $(head -1 <<< "$report") of $local_count EDF files to /referencia/$name, each at its local size"
echo "train with: --reference-dir /referencia/$name$(find "$folder" -maxdepth 1 -iname '*.csv' -printf ' --reference-ages /referencia/'"$name"'/%f' -quit)"
+20
View File
@@ -0,0 +1,20 @@
"""Prints, as JSON, the versions distributed's version check compares and the ones the EEG numbers depend on.
build.sh runs it in this image and in the platform's webapi image and refuses to push when they differ.
"""
import json
import platform
from importlib.metadata import PackageNotFoundError, version
PACKAGES = ("dask", "distributed", "msgpack", "cloudpickle", "tornado", "toolz", "lz4",
"numpy", "pandas", "scipy", "scikit-learn", "mne", "yasa", "antropy", "meegkit", "fooof", "tea")
def _version(name: str) -> str | None:
try:
return version(name)
except PackageNotFoundError:
return None
print(json.dumps({"python": platform.python_version(), **{p: _version(p) for p in PACKAGES}}, sort_keys=True))
+20
View File
@@ -117,3 +117,23 @@ build, isolated from the server, for development experiments.
opened from a version).
- Only `.ipynb` (nbformat 4) is accepted. Open items in
`docs/ledgers/open-items.md`.
### TEA EEG training and analysis
- `models/models/tea/eeg/model.py` uses `EEG_ANALYSIS_CLUSTER` to select
the runner that measures reference studies. It accepts `auto`, `local`,
`remote`, and `sync`, and falls back to `auto` for `off` or an
unrecognised value. Auto uses `DASK_SCHEDULER_ADDRESS` when configured.
- `python -m models tea analyze --ids 12,34` reanalyses the specified EEGs
regardless of pending status. `--ids` takes comma-separated database
EEG IDs and is mutually exclusive with `--all` and `--limit`.
- `tea.pipeline.cluster_status.ClusterStatus` reports the effective mode
and remote health, including scheduler reachability, worker count,
version compatibility, dashboard status, and reference volume visibility
for the requested cohort.
- `tea.pipeline.run_monitor.RunMonitor` publishes the current phase, counts,
elapsed time, ETA, and recent samples during training and analysis. Dask
runs include task counts and worker CPU and memory. When `RUN_PROGRESS_DIR`
is set, the monitor atomically replaces `progress.json` in that directory.
See the [WebApi routes and detached job lifecycle](webapi.md#tea-eeg-governance).
+35
View File
@@ -61,3 +61,38 @@ Moved from `AGENTS.md` on 2026-11-03.
- WebApp: the flow editor's "Reglas" tab (`connect/components/mapping-rules`)
sets document columns, derived fields and the catalog fallback, and shows
the mapped preview.
### TEA EEG governance
The Gobernanza **TEA · EEG** panel uses these new and extended endpoints.
| Method | Path | Purpose |
|---|---|---|
| GET | `/governance/tea/cluster` | Check the selected cluster mode, scheduler, versions, workers, dashboard, and optional reference cohort. |
| GET | `/governance/tea/reference-cohorts` | List cohorts under `TEA_REFERENCE_ROOT`. |
| POST | `/governance/tea/reference-cohorts/<name>/files` | Upload one EDF or `edades.csv` as multipart `file`. |
| POST | `/governance/model-versions/tea/eeg/train-jobs` | Start training with optional cohort, line frequency, promotion, and cluster settings. |
| GET | `/governance/tea/baselines/export` | Download the baseline ZIP with SHA-256 and version count headers. |
| POST | `/governance/tea/baselines/import` | Import a multipart baseline ZIP and return its hash and imported versions. |
| POST | `/governance/tea/eeg/analyze-jobs` | Start analysis for pending EEGs or select a limit, all EEGs, or explicit IDs. |
| GET | `/governance/tea/eeg/analyze-jobs` | List analysis jobs, newest first. |
| GET | `/governance/tea/eeg/analyze-jobs/<id>` | Read analysis job state and its summary when available. |
| GET | `/governance/tea/jobs/<kind>/<job_id>/progress` | Read the latest training or analysis sample. Returns 404 before the first sample. |
| GET | `/governance/tea/baselines/<scenario>/<version>/metrics` | List metrics with a baseline age curve. |
| GET | `/governance/tea/baselines/<scenario>/<version>/curve` | Read the age percentiles for the requested `metric`. |
| GET | `/governance/tea/eeg` | List EEGs with pagination and analysis status. |
| GET | `/governance/tea/eeg/<eeg_id>/metrics` | Read study age, validity, metric values, z-scores, and outliers. |
| POST | `/governance/tea/eeg/upload` | Validate and import one EDF via the import pipeline, with an optional patient ID. |
| POST | `/governance/tea/eeg/preview` | Analyse one EDF (`edf`) and an optional ADOS-2 PDF (`ados2`) in memory and answer a patient-summary bundle with notices; nothing is stored. |
| GET | `/governance/tea/eeg/summary` | Count EEGs, metrics, outliers, and FHIR view rows. |
| POST | `/reportes/indicadores/tea/recalcular` | Queue a TEA indicator cycle. The contract specifies an optional cluster choice. The current handler queues the cycle using the service configuration. |
Reports, checks, promotion, and training job status use the existing governance
routes. The cluster health endpoint uses the models-side `ClusterStatus`
probe and accepts scheduler addresses from `DASK_SCHEDULER_ADDRESS` and
`TEA_DASK_SCHEDULERS`.
`WebApi/webapi/detached_jobs.py` launches training and analysis as subprocesses
in their own sessions. It records job metadata, stdout, stderr, and exit status
in the job directory and passes that directory to the child as
`RUN_PROGRESS_DIR`. The progress endpoint reads `progress.json` there.
+42
View File
@@ -254,3 +254,45 @@ Left open by steps 0 and 1 (the library at `models/libs/tea` @ `9cef555`; the sc
outside the platform (`cohort.source = referencia`, the hash of its listing) satisfies ML-03 for these versions
(`registry.checks`). Promotion still needs the three reports (MLD-01, MLD-01b, MLD-03), which is where the domain
expert's validation goes; `TEA_ALTERACIONES_VALIDADAS` stays a separate switch in the WebApi.
### TEA: ADOS-2 association, zones and the library's spike and spindle changes (2026-11-21)
- The ADOS-2 association (`tea.associations.ados2`, `models tea relate-ados2`, the cycle's `relate_ados2`) writes
every version unvalidated (`rel_validado` 0). Who validates a version, and how the panel shows an unvalidated one,
is the domain expert's decision. On the 62 real EDFs only the ADOS-2 rows were invented, so the associations
there say nothing.
- Legacy `ados2_association` scores only the rows it was fitted on (the research code keeps only those
probabilities); the platform runs modern, which scores any row.
- Spike densities use a count reference (`CountRate`: the reference's aggregate rate and its negative-binomial
dispersion, z from the child's mid-p tail in its own minutes). That method, and the 0.05 cut for `outside`, need
the domain expert's review, like the other baselines.
- Every biomarker module changed version (spikes 0.4.0, spindles 0.2.0, the rest 0.2.0 for the `outside` change),
so every EEG is analysed again, and the baselines must be retrained and promoted with their reports before the
next load. The cluster's image must come from the same ISSSTELEON commit as the deployment
(`dask-cluster/build.sh`; it now adds bokeh for the dashboard).
- `tea_ados2_reactivos.puntaje_algoritmo` now counts 7, 8 and 9 as 0 (the ADOS-2 algorithm's rule), which changes
the domain totals everywhere it is read, not only in the association view. To confirm with the owner.
- A child with two ADOS-2 on the same first date duplicates its rows in `tea_paciente_relacion_ados2`, as before.
- Spindle per-electrode and per-zone densities exist only for the channels the detector searches (no T3-T6, O1,
O2), so `spindle_zone_temporal_*` and `spindle_zone_occipital` are NaN by design.
- Not ported (outside the brief): per-candidate `origen_estado` / `motivo_puerta` from `picos_eventos`, inherited
per-electrode spike densities, and `ventana_de_candidatos`.
- WebApi's suite has 13 failures on this machine that need tesseract, pymssql and the notebook runner; unrelated to
this change.
- The previous deployment's run reported that `models run tea eeg --promote` fails for the EEG baselines ("no such
model"); not looked at here.
- CaCu migration `a1d4e7c20b31` (risk index date, from `dev`) fails on an existing SQLite database that already has
the dbt views: the batch rebuild of `evaluacion_riesgo` stops at `error in view cacu_riesgo_vigilancia: no such
table: main.evaluacion_riesgo`. A fresh database is fine; any SQLite installation upgrading with the views built
hits it. Seen on the manual deployment A (2026-11-22), which was restarted from an empty volume.
- ADOS-2 CSS and classification are now computed by the platform (`tea.scoring`, `models tea score-ados2`, the
cycle's `score_ados2`, `ADOS2_SCORING=off` to skip), and the hospital no longer sends module, algorithm, CSS or
classification (dev-data takes module and algorithm from the PDF through the document source). Open:
- the CSS cut points in `tea/scoring/ados2.py` are approximate, written from memory of the calibrated severity
tables, not transcribed from the manual; they must be replaced with the licensed values (they are data);
- the total is the sum of the items present, so an item read as `S/D` lowers it; the expected items per module and
algorithm are not checked;
- Toddler gets a range of concern and no CSS, and dev-data writes no PDF for a Toddler ADOS-2, so those children
have no module, items or classification after the load;
- the document import was not run end to end with `ado_modulo` and `ado_algoritmo` in the mapping (unit tests
only); Module 2 prints no algorithm, so its `ado_algoritmo` stays empty.
+15 -5
View File
@@ -5,18 +5,18 @@
# --- Project ---
# Prefix of every container, network, volume and image. Change it (and the
# ports) to run a second copy next to this one.
COMPOSE_PROJECT_NAME=isssteleon-manual
COMPOSE_PROJECT_NAME=sitio-a
# --- Published ports ---
# Address the ports bind to: 0.0.0.0 for every interface, 127.0.0.1 for this
# machine only.
BIND_ADDRESS=0.0.0.0
# The application (nginx: pages and proxy to the API). Open this one.
WEBAPP_PORT=5210
WEBAPP_PORT=5310
# The API, direct.
WEBAPI_PORT=5211
WEBAPI_PORT=5311
# The simulated hospital's MySQL (user/password hospital/hospital).
HOSPITAL_PORT=5212
HOSPITAL_PORT=5312
# --- Simulated hospital contents ---
# Patients generated per project, the generator's seed and reference date.
@@ -30,7 +30,17 @@ TEA_ALTERACIONES_VALIDADAS=1
# child (after the N synthetic ones), a confirmed autism case whose only EEG
# carries that file. Empty: only the synthetic EDFs. Changing it needs
# `docker compose down -v` (a populated hospital is left alone).
EDF_CARPETA=
EDF_CARPETA=/home/milk/datos/edf
DASK_SCHEDULER_ADDRESS=tcp://10.0.10.41:30786
# Gobernanza > TEA · EEG: the dashboard port and worker count the cluster card checks.
TEA_DASK_DASHBOARD_PORT=30787
TEA_DASK_EXPECTED_WORKERS=40
# Folder (in the container) holding one subfolder per reference cohort, and the host folder mounted there.
TEA_REFERENCE_ROOT=/referencia
REFERENCIA_CARPETA=../manual-deploy/referencia
# The indicator cycle leaves the EEGs unanalysed until the baselines are in production: upload them in
# Gobernanza > TEA · EEG, promote, then analyse there. Set to auto to analyse in the cycle as before.
EEG_ANALYSIS_CLUSTER=off
# --- Patient-level views ---
# Any value turns on the routes that return one patient's data (the follow-up
+274
View File
@@ -114,6 +114,280 @@ Things to know:
- **A change in `Transformation` needs a rebuild** (`up --build -d`) and a
recomputation, as above.
## TEA from the app
The whole baseline flow runs from **Gobernanza → TEA · EEG** in the web app: check the cluster, train the
seven EEG age baselines (or upload a `baselines.zip`), attach the reports, promote, analyse the EEGs and read the
result. No shell is needed after the deployment is up and loaded. The command-line version of the same flow is in
the next section; use it when the app can't do a step.
### The state `load` leaves
With the settings below, `up` and `load` leave the platform with the hospital's TEA children and their EEGs
**unanalysed**: no baseline is in production and the indicator cycle skips the EEG analysis
(`EEG_ANALYSIS_CLUSTER=off`). Resultado shows `EEGs 62, Analizados 0`. Nothing else is needed before the app steps.
```sh
docker compose up --build -d # hospital populated with the real EDFs in EDF_CARPETA
docker compose run --rm --build load # every `rechazadas` must be 0
```
Settings in `.env` (the template is `ISSSTELEON/dist/.env.ejemplo`):
| Setting | Value here | Purpose |
|---|---|---|
| `EDF_CARPETA` | absolute path of the real EDFs | each file becomes one TEA child (see "TEA EEGs from real EDF files"); the `N` synthetic children are left out |
| `DASK_SCHEDULER_ADDRESS` | `tcp://<host>:<port>` | where Remoto runs; empty means no cluster |
| `TEA_DASK_EXPECTED_WORKERS` | `40` | the worker count the cluster card compares with |
| `TEA_DASK_DASHBOARD_PORT` | `30787` | port of the Dask dashboard on the scheduler's host; `TEA_DASK_DASHBOARD_URL` replaces the whole address |
| `TEA_DASK_SCHEDULERS` | optional | extra scheduler addresses the card may check, besides `DASK_SCHEDULER_ADDRESS` |
| `TEA_REFERENCE_ROOT` | `/referencia` | folder in the `webapi` container with one subfolder per reference cohort, for local training and uploads |
| `REFERENCIA_CARPETA` | `../manual-deploy/referencia` | host folder mounted at `/referencia` (relative paths resolve from `../ISSSTELEON`) |
| `EEG_ANALYSIS_CLUSTER` | `off` | `off` leaves the EEG analysis out of the indicator cycle, so the EEGs wait for the baselines. `auto` analyses in the cycle on the cluster (or locally with no scheduler); `local`, `remote` and `sync` force a mode |
| `TEA_REFERENCE_NAME` | optional | default cohort name for a training request that gives none |
Remote runs need the **platform and worker images built the same day** from the same checkout, with the same
Python: Dask refuses a worker whose Python differs even by a patch. Build the platform with
`docker compose build --pull`, then the worker image (`../dask-cluster/build.sh`) and `./deploy.sh`; `build.sh`
stops with that advice when the two differ.
### The steps
| Step | What to do | What you see |
|---|---|---|
| **Clúster** | Pick Auto, Local, Remoto or Sync; the choice applies to Entrenar and Analizar. With Remoto press **Verificar**. | Scheduler, workers (`40 de 40`), versions (`Cliente y trabajadores coinciden`), dashboard, and a button that opens the Dask dashboard. |
| **Datos de referencia** | Only for training on this machine (Local or Sync): upload a cohort's EDFs and its `edades.csv`, or see the cohorts already in `TEA_REFERENCE_ROOT`. | One row per cohort with its EDF count and whether it has ages. |
| **Entrenar** | *Remoto*: type the cohort's path **on the cluster** (`/referencia/helsinki`) and its ages table (`/referencia/helsinki/edades.csv`); choose 50 or 60 Hz. *Local*: pick an uploaded cohort. Leave **Promover al terminar** unticked (promotion needs the reports). Press **Entrenar**. | The run monitor: phase, `done/total`, ETA, CPU and RAM per worker, task counts, and a history. Seven `eeg-*` versions appear when it ends (`223 estudios` on 40 workers took 3 min 16 s). |
| **Líneas base** | **Exportar** downloads `baselines.zip`. **Importar** takes a zip from your computer instead of training, for example `baselines/baselines.zip`. Importing the same versions twice is refused. | The imported versions, or a clear message when they already exist. Wait for it to finish before the next step. |
| **Reportes** | Enter the technical validation, clinical validation and interpretability addresses and apply them to the versions. At least one address is required. | `Reportes aplicados a 7 de 7 versiones.` |
| **Promover** | **Promover todas**. A version missing its reports shows the checks that failed. | `Promovidas 7 de 7.` Promotion applies to the next analysis without restarting anything. |
| **Verificar línea base** | Pick a scenario, version and metric to see its p5–p95 age curve and overlay analysed EEGs. A cohort too small to have curves says so. | The curve and, once EEGs are analysed, where each study falls. |
| **Analizar** | Choose **Pendientes**, **Primeros N** or **EEGs elegidos**, then **Analizar**. **Subir EDF** adds a new study first. Then **Ejecutar ciclo de indicadores** to rebuild the indicator views from the new metrics. | The run monitor again, then `Válidos`, `No válidos`, `Fallidos`. |
| **Resultado** | **Actualizar**. | EEGs, analysed, valid, metrics, metrics with z, high and low, and the FHIR view rows; the state of the TEA indicator cycle. |
Things to know:
- **Every step reads the versions again when you open it**, so a zip imported in Líneas base shows up in Reportes
without reloading the page.
- **Remote training reads the cluster's volume.** The files must already be at `/referencia/<name>` on the workers
(`../dask-cluster/sync-reference.sh <folder> <name>`, step K2). Uploads in Datos de referencia reach only this
machine, so they serve Local and Sync runs.
- **Analysing on Remoto sends the EDFs to the workers**; the monitor may print a harmless Dask warning about the
size of the task graph.
- **A cohort with fewer than about 30 studies per age bin has no curves** and its metrics carry no z; use the
full reference cohort for real results.
- **To go back to analysing inside the cycle**, set `EEG_ANALYSIS_CLUSTER=auto`, recreate `webapi` and
`indicadores`, and ask for a cycle in Analizar. EEGs already analysed without baselines are not re-analysed:
choose **EEGs elegidos** for them.
What still needs the host: building and pushing the worker image (K1), copying reference data to the cluster (K2),
deploying or deleting the cluster (K3), and the dev-data `poblar` and `load` jobs, which fill the simulated hospital
and import it.
## TEA from the command line: EEG age baselines on a Dask cluster
Two copies of this deployment, built from the same folder: **A** (project
`sitio-a`, the one in `.env`) trains the seven EEG age baselines on the Dask
cluster and exports them; **B** (project `sitio-b`) runs the simulated
hospital with the real EDFs, imports and promotes the baselines, then loads.
B's indicator cycle analyses the EEGs on the cluster by itself. Both use the
same ports, so only one runs at a time.
The commands below use these placeholders:
| Placeholder | What it is |
|---|---|
| `<referencia>` | folder of training EDFs plus `edades.csv`, the ages table |
| `<edf>` | folder of EDFs for B's simulated hospital |
| `<scheduler>` | the Dask scheduler, `tcp://<host>:<port>`; its dashboard is at `http://<host>:<port>/status` |
| `$API` | `http://localhost:<WEBAPI_PORT>` |
| `$PY` | `/app/WebApi/.venv/bin/python`, the Python inside the platform image (its entrypoint ignores other commands) |
Set the two variables in the shell first, for example
`API=http://localhost:5210 PY=/app/WebApi/.venv/bin/python`.
Each deployment keeps its data in the volume `<project>_webapi_data`, mounted
at `/data` (`/data/tea.db`, `/data/mlflow.db`). The cluster scripts are in
`../dask-cluster`; its README explains how the worker image is built.
### Once: settings
The containers read their environment from `.env`, shared by A and B. It
needs:
```sh
EDF_CARPETA=<edf>
TEA_ALTERACIONES_VALIDADAS=1
DASK_SCHEDULER_ADDRESS=<scheduler>
```
With the scheduler set, training, the indicator cycle and any manual analysis
run on the cluster, and a TEA cycle needs the cluster up. To run without it,
remove that line and recreate `webapi` and `indicadores`. A also puts the EDF
children in its hospital; that doesn't matter, A is never loaded.
### K. The cluster
```sh
kubectl get daskclusters # Running
curl -s http://<host>:<dashboard-port>/json/counts.json # the expected number of workers
```
Only after a change to ISSSTELEON or to the training data:
```sh
cd ../dask-cluster
WEBAPI_IMAGE=sitio-a/webapi:local ./build.sh # K1: rebuild and push the worker image
./sync-reference.sh <referencia> <name> # K2: copy the training data to the cluster volume
./deploy.sh # K3: start or update the cluster
```
- **K1** must print the same versions as the platform, Python's patch included.
Rebuild the deployments from the same ISSSTELEON commit with
`docker compose build --pull`, and this image the same day, or the version
check refuses the workers. `build.sh` writes the image tag to `.image`, which `deploy.sh`
and `sync-reference.sh` read.
- **K2** puts the files at `/referencia/<name>` in every worker and ends with
`copied: n of n EDF files`, each at its local size; a missing or truncated
file fails it by name. The pod downloads from this machine over HTTP while
it runs, open to the LAN: fine for public reference data, not for patient
EEGs.
### A. Train and export
```sh
docker compose -p sitio-b down # A1: B down, A up
docker compose up -d
until curl -sf $API/health >/dev/null; do sleep 5; done
docker compose exec webapi printenv DASK_SCHEDULER_ADDRESS # <scheduler>
```
```sh
# A2: train the seven baselines on the cluster
docker compose run --rm --entrypoint $PY -v <referencia>:/referencia/<name>:ro \
webapi -m models run tea eeg --train --environment prod \
--reference-dir /referencia/<name> --reference-ages /referencia/<name>/edades.csv \
--reference-name sitio-a --line-hz 50
```
Seven lines, `eeg-…: trained, version N` (or `already trained`). The studies
show on the cluster dashboard while it runs. For a run from scratch, use
`docker compose down -v` in A1; it deletes A's MLflow and data.
```sh
# A3: export, then stop A
mkdir -p baselines
docker compose run --rm --entrypoint $PY -v "$PWD/baselines:/salida" \
webapi -m models tea export-baselines --out /salida/baselines.zip --environment prod
sha256sum baselines/baselines.zip
docker compose down
```
It prints the seven versions and `written: /salida/baselines.zip (sha256 …)`,
the same hash `sha256sum` shows. `down` without `-v` keeps A's MLflow.
### B. Import, promote, load
Every command is `docker compose -p sitio-b`. The baselines must be in
production before `load`.
```sh
docker compose down # B1: A down, B from empty
docker compose -p sitio-b down -v # deletes B's data, never A's
```
```sh
# B2: build, then start, as two steps: in one go it can run the machine out of memory
docker compose -p sitio-b build
docker compose -p sitio-b up -d
until curl -sf $API/health >/dev/null; do sleep 5; done
docker compose -p sitio-b exec webapi printenv DASK_SCHEDULER_ADDRESS
docker compose -p sitio-b logs poblar | head -3 # EDF de /edf: n archivos ...
```
```sh
# B3: import the baselines
docker compose -p sitio-b run --rm -T --entrypoint $PY -v "$PWD/baselines:/salida:ro" \
webapi -m models tea import-baselines /salida/baselines.zip | tee baselines/import-b.txt
```
Seven lines, `eeg-…: imported as version 1`.
```sh
# B4: attach the three reports to each version
sed -nE 's/^([a-z0-9-]+): .* version ([0-9]+)$/\1 \2/p' baselines/import-b.txt |
while read scenario version; do
curl -s -o /dev/null -w "$scenario $version: %{http_code}\n" -X PATCH -H 'Content-Type: application/json' \
-d '{"technical_validation_report_uri": "file:///pendiente/tecnico.pdf",
"clinical_validation_report_uri": "file:///pendiente/clinico.pdf",
"interpretability_report_uri": "file:///pendiente/interpretabilidad.pdf"}' \
"$API/governance/model-versions/tea/$scenario/$version/reports"
done
```
Seven `200` lines. These URIs are placeholders for a test deployment; on a
real installation they point at the domain expert's documents.
```sh
# B5: promote the baselines
docker compose -p sitio-b run --rm --entrypoint $PY webapi -m models run tea eeg --promote --environment prod
```
Seven lines, `version 1 promoted`.
```sh
# B6: load, and let the cycle analyse on the cluster
docker compose -p sitio-b run --rm --build load
docker compose -p sitio-b logs -f indicadores | grep --line-buffered -E 'analyze_eeg|tea: |ERROR'
```
Every `rechazadas` is 0. Then `analyze_eeg: … elementos` while the dashboard
shows the batches, and `tea: ok` when the views are built. This needs
`EEG_ANALYSIS_CLUSTER=auto` in `.env`; with `off` (the default for the app
flow) the cycle leaves the EEGs unanalysed and `analyze_eeg` never appears.
```sh
# B7: check the result
docker compose -p sitio-b exec -T webapi $PY -c "
import sqlite3; c = sqlite3.connect('file:/data/tea.db?mode=ro', uri=True)
print('analysed EEGs, metrics, with z, high, low:', c.execute('select count(distinct met_eeg_id), count(*), sum(met_z is not null), sum(met_fuera = 1), sum(met_fuera = -1) from eeg_metrica').fetchone())
for t in ('tea_paciente_eegs', 'tea_paciente_eeg_metricas'): print(t, c.execute(f'select count(*) from {t}').fetchone()[0])"
```
Most analysed EEGs should have metrics with a z; `H` and `L` in TEA's patient
summary are metrics above or below the age curve (`N/A` are the validation
criteria). In the app, TEA's patient summary shows each metric against its
curve.
### Tear down
```sh
docker compose -p sitio-b down # -v also deletes B's data
(cd ../dask-cluster && ./deploy.sh --delete) # frees the nodes; the training data stays on the volume
```
Before the next TEA load without the cluster, remove `DASK_SCHEDULER_ADDRESS`
from `.env`.
### If something fails
| What you see | Why, and what to do |
|---|---|
| `port is already allocated` on `up` | The other deployment is still up: `docker compose down` (A) or `docker compose -p sitio-b down` (B). |
| `printenv DASK_SCHEDULER_ADDRESS` prints nothing | The line isn't in `.env`, or the container started before it was added. Fix `.env` and recreate `webapi` and `indicadores`. |
| `poblar` says `Sin archivos EDF` | `EDF_CARPETA` is empty. Fix `.env`, then B1 and B2. |
| No alterations in the app after B6 | `curl -s $API/reportes/indicadores`: `en_curso` means the cycle is still running; `error` means read the `indicadores` logs. `TEA_ALTERACIONES_VALIDADAS` must be 1. |
| Metrics without z after the load | The baselines weren't in production when the cycle analysed. Run B5, then `... run --rm --entrypoint $PY webapi -m models tea analyze --all` and request a fresh cycle with `POST /reportes/indicadores/tea/recalcular`. |
| `ValueError: Mismatched versions found` | The worker image comes from another ISSSTELEON commit than the deployment's, or from a Python with another patch number (`python 3.12.15` against `3.12.16`). Rebuild the platform with `docker compose build --pull`, then K1 and K3 the same day. |
| `all predefined address pools have been fully subnetted` | Docker has no free network left because of the other projects on the machine. Remove one you don't need, or give this project a subnet in an extra Compose file, `networks: {default: {ipam: {config: [{subnet: 10.240.77.0/24}]}}}`, any range that `docker network ls` and `ip route` don't use, and add it with `-f docker-compose.yml -f <file>`. |
| `table _alembic_tmp_latest_metrics already exists` | The first start was interrupted while MLflow migrated its database. `down -v` and start again, and wait for `health` before the first request. |
| The cycle or training hangs at the start | The container can't reach the scheduler, or the cluster is down. Check K. |
| `no folder /referencia/<name>` from a worker | The training data isn't on the volume. K2. |
| `KeyError: 'posterior_rhythm_hz'` | No study had an age: `edades.csv` missing from `<referencia>` or not passed with `--reference-ages`. |
| `not promoted, missing: MLD-…` | A report is missing on that version. B4. |
| The machine freezes during B2 | Out of memory. A down, other programs closed, `build` and `up -d` separately. |
| `load` refuses a batch | B wasn't empty. B1 and B2 again. |
## Generate the test documents
```sh
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
eeg-gradient: imported as version 1
eeg-posterior-rhythm: imported as version 1
eeg-spikes: imported as version 1
eeg-spindle-topography-n2: imported as version 1
eeg-spindle-topography-n3: imported as version 1
eeg-spindles-n2: imported as version 1
eeg-spindles-n3: imported as version 1
+4
View File
@@ -56,6 +56,10 @@ services:
--api http://webapp \
--hospital "mysql+pymysql://hospital:hospital@hospital:3306/$$database"
done
echo
echo "Loaded. TEA's EEGs are not analysed until their baselines are in production:"
echo "open the app, Gobernanza > TEA · EEG, train or import baselines.zip, attach the reports,"
echo "promote, then Analizar. README.md, \"TEA from the app\"."
# One-shot: writes the test PDFs of the same patients the hospital holds
# (same seed and reference date) into ./documentos. It needs neither the
+2
View File
@@ -13,6 +13,8 @@ x-api: &api
services:
webapi:
<<: *api
volumes:
- "${REFERENCIA_CARPETA:-./referencia}:/referencia"
ports: !override
- "${BIND_ADDRESS:-0.0.0.0}:${WEBAPI_PORT:-25050}:5000"
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

@@ -0,0 +1,94 @@
# CaMa demo: patients and how to reach them
Stack: **http://10.0.10.41:18122** (`cama-dev`, built from `dev` at ISSSTELEON `3743ea6`). Log in, choose **Cáncer de mama**, open the **Análisis de riesgos** tab.
## The patient for Luis's figure: 44574
Luis's reference: `luis-HER2-ge60-III-IV-referencia.png` (subgroup "HER2+ · ≥60 años · estadio III–IV (Alto)", from his stage 05).
- **44574** belongs only to that scenario. Her card opens on it with no menu and draws the same graph in Plotly: title with n and deaths, Kaplan-Meier with its Greenwood band, Weibull, fractional Weibull, and the LR + HBN combined diamonds with bootstrap intervals at 6, 12 and 18 months, over 0 to 24 months.
- **How to reach her:** Análisis de riesgos → Fecha de corte 23/11/2026, Ventana 3 meses, BI-RADS 4B, Grupo de edad 60 a 69 años, Resultado de la biopsia Carcinoma invasor → Consultar → **page 1, row 8**.
- **The numbers are the platform's data, not his file:** SEER as imported, with diagnoses placed in the recruitment window and follow-up cut at 2026-11-21. That gives n = 970, deaths = 227 and diamonds 0.899 / 0.835 / 0.786, against his n = 1,142, deaths = 308 and 0.865 / 0.803 / 0.740. Screenshot: `08-44574-supervivencia.jpg`; the list row: `07-lista-44574.jpg`.
- **Backups for the same scenario:** 121232 (only that scenario; page 1, row 39 with BI-RADS 5 and 60 a 69) and 37346 (post-treatment, that scenario first plus the recurrence panel; see below).
## How to find a patient
1. In **Análisis de riesgos**, set **Fecha de corte = 23/11/2026**. Don't leave the default: the default is today, and on another day the 3-month window moves and the rows shift.
2. **Ventana de meses = 3 meses**, **Registros por página = 50**.
3. Set the filters in the patient's row below, leave the others on **Todos**, and press **Consultar**.
4. The list is sorted by latest mammogram, then by ID. Go to the page, count down to the row, and click the patient's ID to open her card.
5. Scroll down the card:
- **Riesgo de muerte → Análisis de supervivencia** has the survival figure.
- For a post-treatment patient, **Pronóstico y recomendaciones → Análisis de recurrencia** comes first, above it, with its **Factores de riesgo** by horizon.
- **Regresar** goes back to the list with the filters kept.
The figures are Plotly, drawn from Luis's models over the data ingested in the platform:
- **Survival** (SEER pipeline, stage 05):
- Kaplan-Meier with the Greenwood 95 % band;
- Weibull and fractional Weibull fitted on the scenario's deaths;
- the LR + HBN combined points with their bootstrap 95 % intervals at 6, 12 and 18 months.
- **Recurrence** (METABRIC / SCAN-B):
- Kaplan-Meier with its Greenwood band, plus both Weibulls;
- the combined points with bootstrap intervals at 12, 36 and 60 months.
A patient in several scenarios gets a menu; the first one is her default.
## Survival: patients in observation (diagnosed, no treatment yet)
All have **Escenario clínico: En observación**, **Resultado de la biopsia = Carcinoma invasor**, status "Diagnóstico confirmado, sin tratamiento registrado" and priority **Alta**.
| Patient | BI-RADS | Grupo de edad | Page | Row | Rows in list | Survival scenarios | Recurrence |
|---|---|---|---|---|---|---|---|
| **44574** | BI-RADS 4B | 60 a 69 años | 1 | 8 | 108 | only **HER2+ · ≥60 años · estadio III–IV (Alto)**, Luis's reference figure | none (not post-treatment) |
| 121232 | BI-RADS 5 | 60 a 69 años | 1 | 39 | 377 | only HER2+ · ≥60 años · estadio III–IV (Alto) | none |
| 6622 | BI-RADS 5 | 70 años o más | 1 | 41 | 429 | menu: HER2+ · ≥60 · III–IV (Alto), Estadio IV | none |
| 16104 | BI-RADS 5 | 40 a 49 años | 1 | 24 | 175 | menu: < 45 años, Jóvenes (<45) · HER2− | none |
| 29617 | BI-RADS 5 | 50 a 59 años | 2 | 15 | 243 | menu: Estadio I, Triple negativo (HR−/HER2−) · estadio 0–II | none |
| 128524 | BI-RADS 5 | 60 a 69 años | 2 | 21 | 377 | only Estadio I | none |
| 102589 | BI-RADS 4C | 70 años o más | 1 | 15 | 120 | only ≥ 75 años | none |
| 67164 | BI-RADS 4A | 50 a 59 años | 1 | 1 | 96 | **Toda la cohorte** (no stage recorded, so no scenario) | none |
44574's figure on this stack: n = 970, deaths = 227; combined points 0.899 / 0.835 / 0.786 at 6 / 12 / 18 months; Kaplan-Meier 0.904 / 0.830 / 0.770.
## Recurrence: post-treatment patients (survival and recurrence)
Set **Escenario clínico = Post-tratamiento** plus the filters below; leave **Resultado de la biopsia = Todos**. All are "Diagnóstico confirmado, en tratamiento", priority **Baja**. Their card shows both panels: **Análisis de recurrencia** (under Pronóstico y recomendaciones, with its cohort and scenario menu and its **Factores de riesgo** by horizon) and, below it, **Análisis de supervivencia**.
| Patient | BI-RADS | Grupo de edad | Page | Row | Rows in list | Recurrence scenarios (cohort) | Survival scenarios |
|---|---|---|---|---|---|---|---|
| **37346** | BI-RADS 4A | 60 a 69 años | 1 | 4 | 26 | Grado 3 (SCAN-B) | menu: **HER2+ · ≥60 · III–IV (Alto)**, Estadio IV |
| 82947 | BI-RADS 6 | 50 a 59 años | 1 | 1 | 103 | Grado 3 (SCAN-B) | menu: HER2+ · <60 · 0–II (Bajo), Estadio I, HER2+ · 0–II · cirugía conservadora |
| 9582 | BI-RADS 4A | Menores de 40 años | 1 | 1 | 9 | menu: < 45 años (METABRIC), < 45 años (SCAN-B) | menu of 6, starting with Estadio I and < 45 años |
| 52291 | BI-RADS 5 | 70 años o más | 1 | 3 | 139 | menu: ≥ 75 años (METABRIC), Grado 3 (SCAN-B), ≥ 75 años (SCAN-B) | only ≥ 75 años |
| 69458 | BI-RADS 5 | 50 a 59 años | 1 | 1 | 69 | menu: Tumor >50 mm (METABRIC), Grado 3 (SCAN-B), Tumor >50 mm (SCAN-B) | Toda la cohorte |
| 19445 | BI-RADS 5 | Menores de 40 años | 1 | 1 | 16 | menu of 5: < 45 años and Tumor >50 mm (METABRIC); Grado 3, < 45 años and Tumor >50 mm (SCAN-B) | only < 45 años |
## Before the demo
- **Open the stack once, about 15 minutes before:**
- **Análisis de riesgos** with any filter: after a restart of the API the first list takes 3 to 5 minutes, because it builds the follow-up cohort; later ones take seconds.
- One patient card: the first card loads the model's members.
- **Indicadores** loads in under a second; its answers are computed by the indicators cycle.
- **Trazabilidad** shows every month (or semester) since 2000. Its answers were computed ahead on the server for this data, so it draws in about 10 to 20 seconds. The data only fills the last few years, so pick **Semestral** or a recent range in **Periodos a mostrar** before showing it. Screenshot: `09-trazabilidad.jpg`.
- **Don't import data or restart the `indicadores` service before the demo.** A new load starts a recalculation of about 40 minutes, and the history has to be computed again.
## If something looks off
- **Screens slow, or briefly failing:** an import or a restart of the `indicadores` service starts a recalculation of about 40 minutes. The stack is set so a restart alone doesn't start one (`INDICADORES_AL_INICIAR=0`).
- **The rows moved:** check that Fecha de corte is 23/11/2026.
- **"El modelo todavía no tiene la supervivencia de este escenario":** the cycle hasn't finished the scenario points yet. It only shows for "Toda la cohorte" right after a new build.
## Screenshots
All taken on this stack on 2026-11-23.
1. `01-filtros-37346.jpg`: the filters set for 37346 (Fecha de corte 23/11/2026, 3 meses, BI-RADS 4A, 60 a 69 años, Post-tratamiento).
2. `02-lista-37346-fila4.jpg`: the list, with 37346 on row 4.
3. `03-ficha-37346.jpg`: her card's header: status, priority, days from mammogram to diagnosis, mammogram and histopathology.
4. `04-37346-recurrencia.jpg`: recurrence, Grado 3 (SCAN-B): Kaplan-Meier with its Greenwood band, both Weibulls and the combined points at 12, 36 and 60 months.
5. `05-37346-factores-y-supervivencia.jpg`: the scenario's risk factors at 60 months, and the start of the survival panel with her two-scenario menu.
6. `06-37346-supervivencia.jpg`: her survival figure (HER2+ · ≥60 años · estadio III–IV).
7. `07-lista-44574.jpg`: 44574 in the list (BI-RADS 4B, 60 a 69 años, Carcinoma invasor).
8. `08-44574-supervivencia.jpg`: 44574's figure, the one to put next to Luis's `luis-HER2-ge60-III-IV-referencia.png`.
9. `09-trazabilidad.jpg`: Trazabilidad loaded, monthly, all 323 months.
Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

+239
View File
@@ -0,0 +1,239 @@
# CaMa survival and recurrence: from the consolidation branch to `dev`, and a clean redeploy
Written 2026-11-22 at the end of the session that built the consolidation. The next session starts here.
## 1. What the owner wants (non-negotiable)
- **Both CaMa models are exactly Luis's.**
- Survival is his SEER pipeline: stages 01–06, LR+HBN including stage and treatments, his stage-05 subgroup curves and points (`models/cama/seer_survival`).
- Recurrence is his METABRIC/SCAN-B scripts: prep, modeling, factors and calculator (`models/cama/recurrence`).
- No substitute estimator, no pasted images, no numbers made up in the code.
- **Everything runs from data ingested into the platform DB.**
- SEER, METABRIC and SCAN-B go in through the import (UI or `/imports/commit`).
- Synthetic fill (dates, pathways, treatments, recent patients) is allowed for the demo.
- Models never train from bundled CSV/TSV/JSON.
- **The dashboard draws Plotly figures from his models' outputs over the ingested data.**
- The clinical scenario comes from the patient's own data.
- There is a menu only when she fits several scenarios.
- **Scope is CaMa.** TEA and CaCu belong to other people. Only the PDF's shared tab rename ("Análisis de riesgos → Seguimiento") touches every domain.
- **Commits:** one-line subjects, with no Co-Authored-By trailer.
- **Schema:** database agnostic, never edit a migration, no new tables or columns without the owner's OK.
## 2. Where things are
**Branches:** `consolidation/cama-survival-recurrence` is pushed in ISSSTELEON, models, WebApi and WebApp; push was over HTTP with the org token, since SSH keys are refused. Heads at the end of the session:
| Repo | Head | Commits beyond `origin/dev` | `dev` commits it lacks |
|---|---|---|---|
| ISSSTELEON | `60f550c` | 13 | 10 |
| models | `706f751` | 10 | 11 |
| WebApi | `3248324` | 9 | 13 |
| WebApp | `7ab2567` | 7 | 26 |
`dev` moved on during the session, so the first task is merging it back in.
What the branch does, by area:
- **Recurrence:**
- Trains on the total cohort (`cama/cohorte_total`) indexed at the first invasive biopsy: patients whose `pac_fuente` is METABRIC or SCANB, recoded by the dictionary in `recurrence/cohorts.toml`.
- Its bundled TSVs, `source.py` and `steps.py` are removed.
- `cohort_import.py` writes the import files from Luis's TSVs, with `--diagnosis-from`, `--spread-days` and `--censor` to place the diagnoses in the platform's recruitment window and stop follow-up at a given day.
- The patient import schema regained 12 fields the merge had dropped (`pac_fuente`, `pac_pam50`, ...); they exist in Core and in a migration.
- **Survival:**
- `models/cama/survival` (the registered scenario) runs Luis's six stages over the DB members inside training (`development.py`) and publishes his tables and figures.
- The live figure (`live.curves`) draws:
- the Kaplan-Meier, plus Weibull and fractional Weibull fitted on the scenario's own deaths, as in his stage 05;
- his model's points and bootstrap intervals for the scenario.
- The points come from `refresh_subgroups`, run by the indicators cycle over each new build (stages 01 and 05, about 16 minutes on 130k patients). Until that has run, the figure uses the points the version published when it trained.
- Ulises's second survival scenario (`seer_survival` as a model and `/cama/supervivencia`) is retired; the `seer_survival` package stays as Luis's pipeline.
- **Patient card:**
- The survival and recurrence panels show the patient's own scenarios.
- The follow-up row carries a provisional status, priority and mammogram-to-diagnosis days (`webapi/cama_follow_up/listing.py`). Those are demo rules, pending Luis.
- The "Seguimiento" tab rename applies to all domains, as the labels PDF asks.
- **Speed:**
- The live models' labelled members are saved once per build and version (`INDICADORES_DIR/modelos/*.parquet`) and each API worker loads them at start (`WEBAPI_PRECALENTAR_MODELOS=1` in the Dockerfile).
- The CaMa follow-up cohort is cached by revision.
- **dbt:**
- `cama_window.cutoff` moves to 2026-12-31.
- A treatment encounter after the malignant diagnosis counts as post-treatment evidence.
- **Migrations:** a no-op revision `e3b8a6d29f71` joins the two CaMa heads.
**Server** (10.0.10.41, user `admon`; the `cama-trabajo` stack on port 18121):
- **Data** in `~/cama-trabajo/datos`, with backups beside it: `cama-antes-del-corrimiento.db`, `cama-antes-de-rutas.db`, `cama-antes-de-externas.db`, `cama-antes-de-noviembre.db`.
- **Images** are built from `~/cama-consolidado/src`, a copy updated by tarballs, not a git checkout.
- **Models in production:**
- `cama-survival` v3, trained on DB build 3.
- `cama-recurrence` v2, trained on DB build 4.
- Both were **force-promoted** with the alias set directly, because the MLD-01, MLD-01b and MLD-03 reports don't exist.
- **The last two commits are not deployed:** `refresh_subgroups` (WebApi `3248324`, models `706f751`).
- **An indicators cycle was in progress** when the session ended. It was loading 2,000 synthetic patients with mammograms from 2026-11-02 to 11-21, imported through `/imports/commit`.
- **Leftover containers:** `cama-trabajo-survival` and `cama-trabajo-recurrence` (one-off training runs, now exited).
**Data on the server, how it got there** (scripts in `scripts/` here):
- **Imported through `/imports/commit`:**
- METABRIC 2,380 and SCAN-B 8,847 patients (`cargar_externas.py`, from `cohort_import.py` with `--diagnosis-from 2018-01-01 --spread-days 540 --censor 2026-11-21`).
- 2,000 recent screenings (`cargar_nov.py`).
- **The SEER patients (129,562) came with the earlier deploy and were reshaped directly in SQLite:**
- dates shifted to end by 2026-11-21 (`shift.py`);
- pathways built: biopsy order linked to its mammogram, diagnosis note, treatments (`pathway.py`);
- treatments added for 2026 patients (`treatments.py`).
- These scripts write silver and bronze tables directly, which breaks "everything through the import". Redo them as import files for the clean deploy (task 4).
## 3. Tasks for the next session
### Task 1. Merge `dev` into the consolidation branches
1. In each repo, fetch `dev` over HTTP (`git fetch http://10.0.10.41:3000/ISSSTELEON/<repo>.git '+refs/heads/*:refs/remotes/origin/*'`) and merge `origin/dev` into `consolidation/cama-survival-recurrence`.
2. Order: models, WebApi and WebApp first, then ISSSTELEON with its pins.
3. Resolve conflicts keeping the CaMa work of this branch and `dev`'s everything else. Don't touch TEA or CaCu changes beyond what `dev` has.
4. Check the CaMa migration chain still has one head per domain. If `dev` added CaMa revisions, add a new merge revision; never edit one.
5. Test baselines to compare against. Failures that already existed are not new work, but compare the lists:
- **models** (`uv run pytest -q`): 12 failed, 1 error before this work; the errors seen in TEA and cohort-build tests came from runs overlapping.
- **WebApi** (`uv run pytest -q`): 29 failed, all already failing.
- **WebApi CaMa follow-up tests:** need a compiled manifest: `cd Transformation && uv run --no-sync dbt compile --profiles-dir . --profile cacu --target sqlite --no-introspect --target-path /tmp/dbtc`, then run with `DBT_MANIFEST=/tmp/dbtc/manifest.json`. 37 pass.
- **WebApp** (`npx ng test --watch=false`): 1,881 pass.
6. Push the consolidation branches; that needs the owner's OK each time. Then merge into `dev` only when the owner says so.
**Done when:** the consolidation branches contain `dev` and the test failure lists are no longer than the baselines.
### Task 2. Finish and verify the cycle-computed scenario points
- `development.subgroup_points` (stages 01 and 05 over the current members) has not run end to end. Its test took over 10 minutes because stage 05 gives each subgroup's fractional fit up to 180 seconds (`ks_sub_max_seconds`).
- Add a way to pass the survival budgets (`ks_max_seconds`, `ks_sub_max_seconds`, `n_boot`, `n_boot_sub`) through `[config.desarrollo]`, so the test can use small ones. Then write the test (template in `docs/testing.md`).
- On the server, after deploy, check:
- `INDICADORES_DIR/modelos/cama-survival-v<v>-armado<b>-subgrupos.json` appears after a cycle;
- `/cama/modelo/curvas/consulta` for "HER2+ · ≥60 años · estadio III–IV (Alto)" returns its points.
- Reference values on build 8: n 970, deaths 227, COMB 0.900 / 0.834 / 0.784.
**Done when:** a cycle writes the subgroups file and the figure draws its points.
### Task 3. Replace dev's survival estimator with Luis's stage-04 models (decided 2026-11-22: option a)
The registered `cama/survival` still holds dev's `IntervalSurvival`, an LR+HBN on age, histologic type, grade, ER, PR, HER2, Ki-67 and size, without stage. It is used for:
- placing a patient in her scenarios;
- the points of "Toda la cohorte", when she is in none: about 16% of patients, mostly recent diagnoses with no stage recorded yet.
Per §1 the model should be Luis's. Options:
- **(a)** Register his stage-04 models as the saved model and score from them.
- **(b)** Keep `IntervalSurvival` only for membership and use his stage-05 cohort points (`curva_supervivencia_puntos_LR_HBN.csv`, currently not published as a table) for "Toda la cohorte".
**Done when:** the owner has chosen and the choice is implemented.
**Status (2026-11-23):**
- Done: the figure no longer uses `IntervalSurvival`. Every point it draws, "Toda la cohorte" included, is Luis's stage 05: `subgrupos_puntos` and the cohort table, now published as `cohorte_puntos` and recomputed by the cycle's `refresh_subgroups` (models `674bdc4`, WebApi `1048175`, WebApp `069cc45`).
- Placement never used a model: it reads the patient's age, subtype, stage and surgery (`live.scenario_masks`).
- Deferred by the owner: registering the stage-04 LR and HBN as the saved model. They are binary mortality classifiers on the balanced cohort and give no 6/12/18-month points, so they change nothing on screen; doing it means a retrain of about 1 h 40 min.
### Task 4. Synthetic fill through the import only (later; does not block the redeploy: start from the copied server data, task 5)
1. Rewrite what `shift.py`, `pathway.py` and `treatments.py` did as import files posted to `/imports/commit`:
- mammograms (`cama.Mastografia`);
- biopsies (`cama.BiopsiaMama`);
- notes with the diagnosis, specialty and stage (`cama.NotaMedica`);
- treatments (`cama.TratamientoMama`);
- follow-up (`cama.SeguimientoMama`).
2. **Known gap:** the import doesn't link a biopsy order to the mammogram that led to it (silver `procedimiento.padre_id`); `pathway.py` set it by hand. Fix it as a platform feature: the import can take the mammogram's id or order number. No new columns without the owner.
3. Stage should be filled for diagnosed patients, so they land in a scenario.
**Done when:** a fresh database filled only through the import gives the same screens.
### Task 5. Clean redeploy from `dev` on the server
1. After task 1 is merged into `dev`, build `isssteleon/webapi` and `isssteleon/webapp` from a git checkout of `dev`, not the tarball copy, under a new tag.
2. Copy `~/cama-trabajo/datos` (all domain DBs, `governance.db`, `mlflow.db`, `mlflow-artefactos/`, `cohorts/`, `indicadores/`) into the new stack's data dir and run `alembic upgrade head` (decided 2026-11-22), so the patients and the example IDs stay the same. Rebuilding from scratch (steps 3–4) only once task 4 exists.
3. Load, in order, through the import:
- SEER (`models/cama/seer_survival/seer_import.py`);
- METABRIC and SCAN-B (`cohort_import.py` with the placement flags above, censor = yesterday);
- the synthetic pathway files from task 4.
4. Let the indicators cycle run.
5. Train from the database, one-off containers with `--entrypoint uv` and the stack's env file (the image's entrypoint starts gunicorn otherwise):
- survival: `models run cama survival --export --source dbt --manifest /app/Transformation/target/manifest.json --environment prod --train` (about 1 h 40 min; stage 04 is 70 min);
- recurrence: `models run cama recurrence --export --source dbt --manifest ... --environment prod --train` (about 1 h 20 min).
6. Promote: write the MLD reports so the gate passes, or force the alias only with the owner's OK, saying so.
7. Run a cycle or `webapi.model_analysis.warm('cama')` to leave the members file, then restart the API.
8. Check the screens:
- Seguimiento list up to yesterday;
- patient header (status, priority, days);
- Histopatología card;
- the BI-RADS × histopathology and diagnosis-time indicators;
- survival and recurrence panels for patients in one scenario and in several. Examples on the current data: 44574, 6622, 16104 and 128524.
**Done when:** the screens above work on the new stack.
### Task 6. Open items for the owner and Luis
- Provisional CaMa status and priority rules (`listing.py`, `ESTATUS` and `_prioridad`).
- Figure labels, title and axes: Luis said he would define them.
- "Recomendaciones" is still "no disponibles".
- MLD-01, MLD-01b and MLD-03 reports for both models.
- Whether the CaMa follow-up list needs a search by patient id. It has none: patients are found by filters.
## 4. How to get the CaMa models the way the owner established
**Survival** (`models/cama/survival`, Luis's pipeline in `models/cama/seer_survival`):
1. **Load SEER through the import.**
- `python -m models.cama.seer_survival.seer_import RECODED.csv OUT_DIR` writes one CSV per bronze entity.
- Post them to `/imports/commit` (`scripts/cargar_externas.py` shows the payload) or load them through "Conectar datos".
- SEER has no calendar dates. Place the diagnoses in the recruitment window, and keep every date on or before yesterday.
2. **Fill what SEER lacks for the demo** through the import as well: mammograms with BI-RADS 4–6, the biopsy order and report, a diagnosis note with stage, and treatments within a year. Stage is what puts a patient in Luis's scenarios.
3. **Let the indicators cycle run.** It builds silver, the views and the `cama/cohorte_total` build.
4. **Train from the database:** `models run cama survival --export --source dbt --manifest $DBT_MANIFEST --environment prod --train`.
- This runs Luis's six stages over the members, with stage and treatments.
- It publishes his tables and figures in `analisis/desarrollo.json`.
- About 1 h 40 min.
5. **Promote:** with the MLD reports, or by setting the alias with the owner's OK.
6. **The dashboard's survival panel** (`/cama/modelo/escenarios` and `/cama/modelo/curvas/consulta`):
- It shows the patient's own scenarios.
- The Plotly figure has the Kaplan-Meier of the scenario's members, and the Weibull and fractional Weibull fitted on their deaths (his stage 05).
- The diamonds and intervals are his model's points for the scenario: from the cycle's `refresh_subgroups` over the current build, or the version's `subgrupos_puntos` until it has run.
- **Check:** the figure must match his stage-05 PNG for the same scenario. On build 8: n 970, deaths 227, diamonds 0.900 / 0.834 / 0.784, Kaplan-Meier 0.904 / 0.830 / 0.770 at 6/12/18 months.
**Recurrence** (`models/cama/recurrence`, Luis's METABRIC/SCAN-B scripts):
1. **Load METABRIC and SCAN-B through the import:**
- `python -m models.cama.recurrence.cohort_import metabric brca_metabric_clinical_data.tsv OUT --diagnosis-from 2018-01-01 --spread-days 540 --censor <yesterday>`, and the same with `scanb scanb_clinical_metadata.txt`.
- Post the ten CSVs with `scripts/cargar_externas.py BASE OUT`. The files are in Luis's folder; they are not in the repo.
- Each patient carries `pac_fuente` (METABRIC or SCANB), which is how each cohort finds its patients.
2. **Let the cycle run, then train:** `models run cama recurrence --export --source dbt --manifest $DBT_MANIFEST --environment prod --train`, about 1 h 20 min.
3. **Promote** as above.
4. **The recurrence panel** (`/cama/modelo/recurrencia?paciente=`):
- It shows the patient's own scenarios (both cohorts, labelled), and a menu only when she is in several.
- The Plotly figure is his calculator's record: Kaplan-Meier and Greenwood band, both Weibulls, and the combined points with bootstrap intervals at 12/36/60 months.
- It shows only for post-treatment patients.
**Running one-off training containers:** use `--entrypoint uv` with the stack's env file and `-w /app/WebApi`; otherwise the image's entrypoint starts gunicorn.
## 5. Example patients on the current server data (cut-off 2026-11-23)
In the Seguimiento tab, leave "Fecha de corte" as it is and set the filters below. Rows are sorted by latest mammogram, then by ID, 50 per page.
| Patient | Ventana | BI-RADS | Grupo de edad | Biopsia | Where | Survival panel shows |
|---|---|---|---|---|---|---|
| 44574 | 3 meses | 4B | 60 a 69 | Carcinoma invasor | page 1, row 8 | only "HER2+ · ≥60 años · estadio III–IV (Alto)", Luis's figure |
| 121232 | 3 meses | 5 | 60 a 69 | Carcinoma invasor | page 1, row 39 | only that same scenario |
| 6622 | 3 meses | 5 | 70 o más | Carcinoma invasor | page 1, row 41 | menu: that scenario and "Estadio IV" |
| 16104 | 3 meses | 5 | 40 a 49 | Carcinoma invasor | page 1, row 24 | menu: "< 45 años", "Jóvenes (<45) · HER2−" |
| 29617 | 3 meses | 5 | 50 a 59 | Carcinoma invasor | page 2, row 15 | menu: "Estadio I", "Triple negativo · estadio 0–II" |
| 128524 | 3 meses | 5 | 60 a 69 | Carcinoma invasor | page 2, row 21 | only "Estadio I" |
| 102589 | 3 meses | 4C | 70 o más | Carcinoma invasor | page 1, row 15 | only "≥ 75 años" |
| 67164 | 3 meses | 4A | 50 a 59 | Carcinoma invasor | — | "Toda la cohorte": no stage recorded, so no scenario |
- All of them are "En observación", with status "Diagnóstico confirmado, sin tratamiento registrado", priority "Alta" and about 30 days from mammogram to diagnosis.
- None is post-treatment, so their recurrence panel doesn't show. Use the "Escenario clínico: Post-tratamiento" filter to find patients with one.
- After a clean redeploy the IDs change. Find equivalents with the same filters, or query the members file: `pd.read_parquet(INDICADORES_DIR/modelos/cama-survival-*.parquet)` with `models.cama.survival.live.scenario_masks`.
## 6. Things that cost time this session
- **SSH:** to Gitea it's refused; use HTTP with the org token for pushes.
- **Server access:**
- SSH to the server is intermittently refused or times out; retry.
- The server can drop off the VPN; check the route (`route -n get 10.0.10.41`).
- **SQLite views:** the indicators worker drops and recreates the views while it runs, so requests can fail transiently.
- **The cohort build is slow:** reading it from the views takes about 6 minutes on 140k patients (`KitBuild.frame`). Never do it per request.
- **IDs:** check synthetic `pac_id_hospital` values against existing ones; 8-digit ids collided.
@@ -0,0 +1,32 @@
"""Loads the METABRIC and SCAN-B import files through the same endpoints "Conectar datos" calls.
Usage: python3 cargar_externas.py BASE_URL FOLDER"""
import base64, csv, json, sys, urllib.error, urllib.request
from pathlib import Path
BASE, FOLDER = sys.argv[1], Path(sys.argv[2])
ORDER = [("pacientes", "cama.Paciente"), ("biopsias", "cama.BiopsiaMama"), ("notas", "cama.NotaMedica"),
("tratamientos", "cama.TratamientoMama"), ("seguimientos", "cama.SeguimientoMama")]
def call(path, body):
req = urllib.request.Request(BASE + path, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}, method="POST")
try:
with urllib.request.urlopen(req, timeout=3600) as r:
return r.status, json.load(r)
except urllib.error.HTTPError as e:
return e.code, json.loads(e.read() or b"{}")
for cohort in ("metabric", "scanb"):
sources = []
for name, target in ORDER:
path = FOLDER / f"{cohort}_{name}.csv"
header = next(csv.reader(path.open(encoding="utf-8")))
sources.append({"label": path.name, "source_type": "csv", "target": target,
"column_mapping": {c: c for c in header},
"payload": {"file_base64": base64.b64encode(path.read_bytes()).decode()}})
status, result = call("/imports/commit", {"sources": sources, "on_conflict": "reject"})
print(f"{cohort}: HTTP {status}", result.get("error", ""))
for r in result.get("results", []):
print(f" {r['target']:24} total={r['total']} creadas={r['created']} rechazadas={r['rejected']} vinculos={r.get('linked')}")
print(f" audit_id={result.get('audit_id')} recalculo={result.get('indicadores_en_recalculo')}")
@@ -0,0 +1,17 @@
"""Loads new patients and their mammograms through the import, as "Conectar datos" does. Usage: python3 cargar_nov.py BASE FOLDER"""
import base64, csv, json, sys, urllib.error, urllib.request
from pathlib import Path
BASE, FOLDER = sys.argv[1], Path(sys.argv[2])
sources = []
for name, target in (("pacientes", "cama.Paciente"), ("mastografias", "cama.Mastografia")):
path = FOLDER / f"{name}.csv"; header = next(csv.reader(path.open(encoding="utf-8")))
sources.append({"label": path.name, "source_type": "csv", "target": target, "column_mapping": {c: c for c in header},
"payload": {"file_base64": base64.b64encode(path.read_bytes()).decode()}})
req = urllib.request.Request(BASE + "/imports/commit", data=json.dumps({"sources": sources, "on_conflict": "reject"}).encode(),
headers={"Content-Type": "application/json"}, method="POST")
try:
with urllib.request.urlopen(req, timeout=3600) as r: status, result = r.status, json.load(r)
except urllib.error.HTTPError as e: status, result = e.code, json.loads(e.read() or b"{}")
print("HTTP", status, result.get("error", ""))
for r in result.get("results", []): print(f" {r['target']:20} total={r['total']} creadas={r['created']} rechazadas={r['rejected']}")
print("recalculo", result.get("indicadores_en_recalculo"))
@@ -0,0 +1,71 @@
import sqlite3, time
DB = "/home/admon/cama-trabajo/datos/cama.db"
Y = "2026-11-21"
c = sqlite3.connect(DB, timeout=300)
print("sqlite", sqlite3.sqlite_version, flush=True)
t = time.time()
def run(label, sql):
n = c.execute(sql).rowcount
print(label, n, round(time.time() - t), flush=True); return n
H = "((a.pac_id * 2654435761) % 1000003)"
c.executescript(f"""
drop table if exists temp.ruta;
create temp table ruta as
select r.pac_id,
r.procedimiento_id as bx_reporte, r.padre_id as bx_orden, r.fecha as d,
date(r.fecha, '-' || (20 + {H.replace('a.', 'r.')} % 20) || ' days') as toma
from procedimiento r where r.estudio_id = 'biopsia' and r.clase = 'reporte';
create index temp.ruta_pac on ruta(pac_id);
alter table temp.ruta add column reporte_mast text;
alter table temp.ruta add column orden text;
alter table temp.ruta add column bx_toma text;
update temp.ruta set reporte_mast = date(toma, '+' || (1 + ((pac_id * 2654435761) % 1000003) % 7) || ' days'),
bx_toma = date(d, '-' || (2 + ((pac_id * 2654435761) % 1000003) % 4) || ' days');
update temp.ruta set orden = date(bx_toma, '-' || (1 + ((pac_id * 2654435761) % 1000003) % 3) || ' days');
""")
print("rutas", c.execute("select count(*), sum(orden <= reporte_mast) from temp.ruta").fetchone())
# mammogram toma, its report and its parts
run("mast toma", "update procedimiento set fecha = (select toma from temp.ruta r where r.pac_id = procedimiento.pac_id) where estudio_id='mastografia' and clase='toma'")
run("mast reporte/parte", "update procedimiento set fecha = (select reporte_mast from temp.ruta r where r.pac_id = procedimiento.pac_id) where estudio_id='mastografia' and clase in ('reporte','parte')")
# biopsy order (linked to the mammogram that led to it) and sample
run("bx orden", """update procedimiento set fecha = (select orden from temp.ruta r where r.pac_id = procedimiento.pac_id),
padre_id = (select t.procedimiento_id from procedimiento t where t.pac_id = procedimiento.pac_id and t.estudio_id='mastografia' and t.clase='toma')
where estudio_id='biopsia' and clase='orden'""")
run("bx toma", "update procedimiento set fecha = (select bx_toma from temp.ruta r where r.pac_id = procedimiento.pac_id) where estudio_id='biopsia' and clase='toma'")
# bronze, so a reload says the same
run("bronze mast", "update mastografia set mast_fecha_toma = (select toma from temp.ruta r where r.pac_id = mastografia.pac_id), mast_fecha_reporte = (select reporte_mast from temp.ruta r where r.pac_id = mastografia.pac_id)")
run("bronze bx", "update biopsiamama set bx_fecha_solicitud = (select orden from temp.ruta r where r.pac_id = biopsiamama.pac_id), mast_id = (select m.mast_id from mastografia m where m.pac_id = biopsiamama.pac_id)")
# the first note becomes the diagnosis: oncologic surgery, a C50 code from the tumour's site
c.executescript("""
drop table if exists temp.nota1;
create temp table nota1 as select pac_id, min(procedimiento_id) as procedimiento_id from procedimiento where estudio_id='nota_medica' and clase='encuentro' group by pac_id;
create index temp.nota1_p on nota1(procedimiento_id);
""")
run("nota fecha", "update procedimiento set fecha = (select date(d, '+' || (3 + ((pac_id * 2654435761) % 1000003) % 10) || ' days') from temp.ruta r where r.pac_id = procedimiento.pac_id) where procedimiento_id in (select procedimiento_id from temp.nota1)")
c.executescript("""
drop table if exists temp.sitio;
create temp table sitio as
select p.pac_id, min(replace(o.valor_id, '.', '')) as cie
from observacion_clinica o join procedimiento p on p.procedimiento_id = o.procedimiento_id
where o.resultado_id = 'biopsia.localizacion' and o.valor_id like 'C50%' group by p.pac_id;
create index temp.sitio_p on sitio(pac_id);
""")
run("nota cie", "update observacion_clinica set valor_texto = coalesce((select cie from temp.sitio s where s.pac_id = observacion_clinica.pac_id), 'C509') where resultado_id = 'nota_medica.diagnostico' and procedimiento_id in (select procedimiento_id from temp.nota1)")
run("nota especialidad", "update observacion_clinica set valor_id = 'CIRUGIA_ONCOLOGICA', valor_fuente = 'CIRUGIA_ONCOLOGICA' where resultado_id = 'nota_medica.especialidad' and procedimiento_id in (select procedimiento_id from temp.nota1)")
run("bronze nota", """update notamedica set nm_fecha = (select p.fecha from procedimiento p where p.fuente_tabla='notamedica' and p.fuente_id = cast(notamedica.nm_id as text)),
nm_especialidad = 'CIRUGIA_ONCOLOGICA', nm_cie_codigo = 'C509'
where cast(nm_id as text) in (select p.fuente_id from procedimiento p join temp.nota1 n on n.procedimiento_id = p.procedimiento_id)""")
# treatments after the diagnosis, and none that has not happened yet
for estudio, base, span in (("cirugia", 21, 40), ("quimioterapia", 45, 60), ("radioterapia", 90, 90)):
run(estudio, f"update procedimiento set fecha = (select date(d, '+' || ({base} + ((pac_id * 2654435761) % 1000003) % {span}) || ' days') from temp.ruta r where r.pac_id = procedimiento.pac_id) where estudio_id = '{estudio}'")
run("bronze trat", "update tratamientomama set trat_fecha = (select p.fecha from procedimiento p where p.fuente_tabla='tratamientomama' and p.fuente_id = cast(tratamientomama.trat_id as text))")
future = f"select procedimiento_id from procedimiento where fecha > '{Y}'"
run("future obs", f"delete from observacion_clinica where procedimiento_id in ({future})")
run("future trat", f"delete from tratamientomama where trat_fecha > '{Y}'")
run("future notes", f"delete from notamedica where nm_fecha > '{Y}'")
run("future procs", f"delete from procedimiento where fecha > '{Y}'")
c.commit()
for q in ["select clase, estudio_id, min(fecha), max(fecha), count(*) from procedimiento where estudio_id in ('mastografia','biopsia','cirugia') group by 1,2",
"select count(*) from procedimiento o join procedimiento t on t.procedimiento_id = o.padre_id where o.estudio_id='biopsia' and o.clase='orden' and t.clase='toma'"]:
print(c.execute(q).fetchall())
print("done", round(time.time() - t))
@@ -0,0 +1,19 @@
import pickle
from models.io.registry import registry, PRODUCTION_ALIAS, registered_name, PromotionBlocked
from models.io.tracking import TrainingRun
with open("/data/seer_survival.pkl", "rb") as handle:
model = pickle.load(handle)
print(type(model))
run = TrainingRun(domain="cama", scenario="seer_survival", environment="PROD", cohorte_armado_id=2)
run.log_model(model, requirements=["scikit-learn", "numpy", "pandas", "scipy", "statsmodels", "pgmpy", "cloudpickle", "mpmath"])
version = registry.register_run(run.finish(hyperparameters={"origen": "seer_survival.pkl"}))
print("registered", version)
try:
registry.promote("cama", "seer_survival", version)
print("promoted through the gate")
except PromotionBlocked as blocked:
print("gate:", [(c.name, c.passed) for c in blocked.checks] if hasattr(blocked, "checks") else blocked)
registry.client.set_registered_model_alias(registered_name("cama", "seer_survival"), PRODUCTION_ALIAS, version)
print("alias set directly")
print(registry.resolve("cama", "seer_survival"))
+36
View File
@@ -0,0 +1,36 @@
import sqlite3, time
DB = "/home/admon/cama-trabajo/datos/cama.db"
Y = "2026-11-21"
OFF = "(875 + ((pac_id * 48271) % 365))"
c = sqlite3.connect(DB, timeout=120)
c.execute("pragma journal_mode=wal")
t = time.time()
def shift(table, *cols, where=""):
sets = ", ".join(f"{col} = date({col}, '+' || {OFF} || ' days')" for col in cols)
n = c.execute(f"update {table} set {sets} {where}").rowcount
print(table, cols, n, round(time.time() - t))
shift("biopsiamama", "bx_fecha_solicitud", "bx_fecha_reporte")
shift("mastografia", "mast_fecha_toma", "mast_fecha_reporte")
shift("notamedica", "nm_fecha")
shift("paciente", "pac_fecha_nacimiento", "pac_fecha_defuncion")
shift("persona", "fecha_nacimiento", "fecha_defuncion")
shift("periodo_observacion", "fecha_inicio")
shift("procedimiento", "fecha")
shift("tratamientomama", "trat_fecha")
shift("observacion_clinica", "valor_fecha", where="where valor_fecha is not null")
shift("cohorte_miembro", "fecha_indice")
# Nothing after yesterday: a later death is not known yet, a later visit or treatment has not happened.
print("deaths cleared", c.execute(f"update persona set fecha_defuncion = null where fecha_defuncion > '{Y}'").rowcount,
c.execute(f"update paciente set pac_fecha_defuncion = null where pac_fecha_defuncion > '{Y}'").rowcount)
future = f"select procedimiento_id from procedimiento where fecha > '{Y}'"
print("future obs", c.execute(f"delete from observacion_clinica where procedimiento_id in ({future})").rowcount)
print("future children", c.execute(f"update procedimiento set padre_id = null where padre_id in ({future})").rowcount)
print("future procs", c.execute(f"delete from procedimiento where fecha > '{Y}'").rowcount)
print("future notes", c.execute(f"delete from notamedica where nm_fecha > '{Y}'").rowcount)
print("future treatments", c.execute(f"delete from tratamientomama where trat_fecha > '{Y}'").rowcount)
c.commit()
for q in ["select min(fecha), max(fecha) from procedimiento where estudio_id='mastografia'",
"select min(fecha), max(fecha), count(*) from procedimiento",
"select count(fecha_defuncion), max(fecha_defuncion) from persona"]:
print(q, c.execute(q).fetchone())
print("done", round(time.time() - t))
@@ -0,0 +1,44 @@
import sqlite3, time
DB = "/home/admon/cama-trabajo/datos/cama.db"
Y = "2026-11-21"
c = sqlite3.connect(DB, timeout=300)
t = time.time()
rows = c.execute("""
select r.pac_id, r.fecha, r.carga_id, p.pac_id_hospital,
(select o.valor_id from observacion_clinica o where o.procedimiento_id = r.procedimiento_id and o.resultado_id = 'biopsia.lateralidad')
from procedimiento r join paciente p on p.pac_id = r.pac_id
where r.estudio_id = 'biopsia' and r.clase = 'reporte' and r.fecha >= '2026-01-01'
and not exists (select 1 from procedimiento x where x.pac_id = r.pac_id and x.estudio_id in ('cirugia', 'quimioterapia', 'radioterapia'))
""").fetchall()
print("patients without treatment", len(rows), flush=True)
trat_id = c.execute("select max(trat_id) from tratamientomama").fetchone()[0]
proc_id = c.execute("select max(procedimiento_id) from procedimiento").fetchone()[0]
obs_id = c.execute("select max(observacion_id) from observacion_clinica").fetchone()[0]
trats, procs, obs = [], [], []
def add(pac, hosp, carga, estudio, fecha, detalle, lateralidad, results):
global trat_id, proc_id, obs_id
trat_id += 1; proc_id += 1
trats.append((trat_id, pac, hosp, estudio, fecha, detalle, lateralidad))
procs.append((proc_id, "tratamientomama", str(trat_id), carga, pac, estudio, "encuentro", fecha))
for resultado, valor in results:
obs_id += 1
obs.append((obs_id, proc_id, carga, pac, resultado, valor, valor))
for pac, d, carga, hosp, lat in rows:
h = (pac * 2654435761) % 1000003
lat = lat or ("IZQUIERDA" if h % 2 else "DERECHA")
def when(base, span):
f = c.execute("select date(?, ?)", (d, f"+{base + h % span} days")).fetchone()[0]
return f if f <= Y else None
if h % 100 < 85 and (f := when(21, 40)):
tipo = "SEGMENTECTOMIA" if h % 100 < 55 else "MASTECTOMIA_TOTAL"
add(pac, hosp, carga, "cirugia", f, tipo, lat, [("cirugia.tipo_cirugia", tipo), ("cirugia.lateralidad", lat)])
if (h // 7) % 100 < 60 and (f := when(90, 90)):
add(pac, hosp, carga, "radioterapia", f, "ADYUVANTE", lat, [("radioterapia.intencion", "ADYUVANTE")])
if (h // 13) % 100 < 35 and (f := when(45, 60)):
add(pac, hosp, carga, "quimioterapia", f, "ADYUVANTE", lat, [("quimioterapia.intencion", "ADYUVANTE")])
c.executemany("insert into tratamientomama (trat_id, pac_id, pac_id_hospital, trat_tipo, trat_fecha, trat_detalle, trat_lateralidad) values (?,?,?,?,?,?,?)", trats)
c.executemany("insert into procedimiento (procedimiento_id, fuente_tabla, fuente_id, carga_id, pac_id, estudio_id, clase, fecha) values (?,?,?,?,?,?,?,?)", procs)
c.executemany("insert into observacion_clinica (observacion_id, procedimiento_id, carga_id, pac_id, resultado_id, valor_id, valor_fuente) values (?,?,?,?,?,?,?)", obs)
c.commit()
print("inserted", len(trats), len(procs), len(obs), round(time.time() - t), flush=True)
print(c.execute("select substr(fecha,1,7), estudio_id, count(*) from procedimiento where estudio_id in ('cirugia','radioterapia','quimioterapia') and fecha >= '2026-06' group by 1,2").fetchall())
+77
View File
@@ -0,0 +1,77 @@
# TEA EEG analysis on the Dask cluster: what the first runs showed
The age baselines are trained on site and shipped as a bundle (#184), and the platform sends its EEG batches to
the k3s Dask cluster in `dask-cluster/` when `DASK_SCHEDULER_ADDRESS` is set. Two manual deployments tested the
whole procedure on 2026-11-20: A (`sitio-a`) trained the seven baselines on Helsinki HK1K (223 studies aged 16
to 36 months) and exported them; B (`sitio-b`) imported and promoted them and loaded dev-data with 62 real EDFs,
and its indicator cycle analysed them on the cluster (5 pods, 25 workers). The procedure is the runbook "TEA
Cluster Run"; the cluster's files are `dask-cluster/` on `feature/tea-eeg-analysis`.
It works end to end. This plan collects what the runs showed should change.
---
## 1. The analysis doesn't keep the cluster busy
The cycle analysed the 62 EEGs in 404 s. Each EEG takes 30 to 80 s on a worker, so 25 workers should need about
2.5 to 3 minutes. The completion times show why it took 6.7:
| Batch | EEGs | Done (s after start) |
|---|---|---|
| 1 | 16 | 32 - 114 |
| 2 | 16 | 148 - 209 |
| 3 | 16 | 249 - 301 |
| 4 | 14 | 334 - 403 |
`models.eeg_analysis.analyze_pending` (`models/models/eeg_analysis.py`, the batch loop at the end) reads 16 EDFs
from the database, hands them to `tea.pipeline.dask_runner.run` as one graph and waits for all 16 before
reading the next ones. So:
- **9 of 25 workers are idle the whole run**: a batch never has more than 16 tasks.
- **Each batch waits for its slowest recording**, and workers go idle as the fast ones finish.
- **Each batch spends about 30 s before its first result.** The EDF bytes are arguments of `dask.delayed`
calls, so they are pickled into the graph: 427 to 528 MiB per batch ("Sending large graph" from
`distributed/client.py`), held by the scheduler and sent again to the workers.
**Design.** The runner keeps a bounded number of studies in flight (about one per worker thread) and submits the
next as soon as one finishes (`client.submit` and `as_completed`). Large arguments go out of band with
`client.scatter`, so the graph holds only their keys. `analyze_pending` reads each EDF only when its study is
submitted, so the client never holds more than the studies in flight. Synchronous and local-cluster runs keep
working as they do. Target: the 62 EEGs in under 4 minutes on 25 workers, with no large-graph warning.
## 2. Two runs analyse the same EEGs
`analyze_pending` builds its pending list once, before the first batch. After a `load`, the indicator cycle
listed all 62 EEGs as pending and kept analysing them on the laptop's single local worker while a manual run on
the cluster had already analysed them; the patient views stayed empty until the worker was restarted. With the
scheduler in `.env` the cycle itself uses the cluster, which removes the manual run, but two analyses can still
overlap (a cycle and `POST /governance/eeg/run`, or two cycles). Each study should be re-checked against the
current plan, versions and baselines just before it is submitted and skipped if another run finished it.
## 3. Findings from the 43 / 19 result
Investigated read-only on B. The 19 rejected EEGs fail on properties of the recordings, checked against the
EDFs: `clean-windows` below 60% (17), `triage-level` (10), `internal-coverage` below 0.90 from `BAD_ACQ_SKIP`
gaps (3), `usable-scalp` below 12 with every channel saturated (1); one EEG can fail several. The dev-data header
rewrite caused none. The 43 valid EEGs carry deviations against the promoted baselines. What remains:
- **Zero spikes on a flat baseline.** When a child has 0 spikes and the curve is 0 at that age
(p5 = median = p95 = 0), z is 0/0 and stored as null (7 rows on B), the same as "not computed"
(`libs/tea/src/tea/biomarkers/spikes/_baseline.py`, `z_y_posicion`; each biomarker has its own `_baseline.py` with the same function). The convention is a clinical decision.
- **The 60% clean-windows gate.** 8 of the 19 rejections score 45 to 54% clean windows and are triaged usable
for bipolar analyses, yet fail the single gate (`libs/tea/src/tea/validation/rules.py`, `min_clean_pct`).
Whether that is intended for screening is for the clinical lead.
- **MLflow's type-hint warning** on every analysis: `predict` of the library's pyfunc models has no type hints
(`libs/tea/src/tea/serving/model_code/biomarker_model.py`, `plan_model.py`). Harmless; the hints remove it.
## 4. Loading the training data is slow
`dask-cluster/sync-reference.sh` copies at about 10 MB/s. Measured from a worker pod: laptop to pod 106 MiB/s,
reads from the `eeg-data` NFS volume (`192.168.20.10:/srv/nfs/data`) 95 MiB/s. Writes to the volume were not
measured; a synchronous NFS export or the server's disk are the likely limit. With the reference folder trimmed
to the 223 studies in range (1.9 GB) a sync takes about 3 minutes, so this is not urgent.
## What is out of scope
The Dask cluster's own configuration (worker count, memory per study) and the platform's validation thresholds
themselves. Tasks are in [`tasks.md`](tasks.md).
+94
View File
@@ -0,0 +1,94 @@
# Tasks: TEA EEG analysis on the Dask cluster
What [`plan.md`](plan.md) proposes, in the forms of `docs/process.md` §2. The `tea` library is its own repository
(`alberto/tea`, the `models/libs/tea` submodule); a change there is released as a new version and locked by
`models` and the WebApi.
---
## C1. EEG batches keep the cluster busy
Goal: `dev` analyses EEGs on the cluster with every worker busy and no EDF bytes in the task graph.
Description: The runner, its caller and the version lock change together: the new runner alone isn't used, and the caller alone needs the runner. Done when: on the manual deployment with the 62 EDFs and 25 workers, the cycle after a `load` analyses them in under 4 minutes, with no "Sending large graph" warning in the `indicadores` log, and the same 43 valid / 19 not valid as before.
Tasks: T1, T2, T3, T4
Branch: feature/tea-eeg-analysis
Depends on: none
Labels: type/feature priority/p2-normal area/models status/ready
## T1. A streaming Dask runner in the tea library
Goal: `tea.pipeline.dask_runner.run` keeps a bounded number of studies in flight and sends large arguments out of band.
Description: `run` gains a limit of studies in flight (default: the cluster's worker threads) and submits each study with `client.submit`, feeding the next one from `as_completed` as each finishes; `on_result` and `on_error` keep their meaning and order of calls per study. Arguments over a size threshold (EDF bytes) go through `client.scatter` so the task holds only their key. The synchronous scheduler keeps running one study at a time in the process. It doesn't change what a study computes. Done when: a test on a `LocalCluster` shows no more than the limit in flight and every result delivered; a test with a 50 MB argument raises no large-graph warning (warnings captured); the library's existing tests pass.
Context: `plan.md` §1; `models/libs/tea/src/tea/pipeline/dask_runner.py`, `core.py`
Depends on: none
Approval: none
Labels: type/feature priority/p2-normal area/models status/ready model/standard review/light size/m agent-ok
Part of: C1
## T2. analyze_pending streams its studies
Goal: `models.eeg_analysis.analyze_pending` reads each EDF only when its study is submitted and uses the streaming runner.
Description: The fixed batches of 16 go; the studies are handed to the runner as a lazy sequence, so the client holds only the studies in flight. `batch` becomes the limit in flight, defaulting to the runner's. The summary, the rows written and the governance `ExtractionRun` per EEG don't change. Done when: tests with a stub `measure_fn` show every pending EEG written once, at most the limit read from the database at a time, and the same summary as the batched version for the same input.
Context: `plan.md` §1; `models/models/eeg_analysis.py`
Depends on: T1
Approval: none
Labels: type/refactor priority/p2-normal area/models status/ready model/standard review/light size/m agent-ok
Part of: C1
## T3. Skip EEGs another run finished
Goal: Two analyses running at once don't analyse the same EEG twice.
Description: Just before a study is submitted, `analyze_pending` checks again that the EEG is still pending under the current plan, versions and baselines (`pending_ids`' rule) and skips it if not; the summary counts the skipped ones. Done when: a test starts a run over three EEGs, marks one as analysed with the current plan between submissions, and sees it skipped and counted.
Context: `plan.md` §2; `models/models/eeg_analysis.py` (`pending_ids`, `analyze_pending`)
Depends on: T2
Approval: none
Labels: type/bug priority/p2-normal area/models status/ready model/standard review/light size/s agent-ok
Part of: C1
## T4. Release the runner and rebuild the worker image
Goal: The platform and the cluster run the new library version.
Description: `tea` gets a new version with T1; `models` and the WebApi lock it; `dask-cluster/build.sh` builds and pushes the worker image from that commit and `deploy.sh` rolls the cluster. Done when: `build.sh` reports "same versions as the platform" with the new `tea` version, and C1's criterion holds on the manual deployment.
Context: `dask-cluster/README.md`; runbook "TEA Cluster Run" (steps K1, K3, B1 to B7)
Depends on: T1, T2, T3
Approval: pushing the image and the branches (permission per action)
Labels: type/chore priority/p2-normal area/infra status/ready model/small review/light size/s agent-ok
Part of: C1
## D1. Decisions for the clinical lead (`human-only`)
| Id | What is decided |
|---|---|
| D1.1 | The deviation of a metric whose value equals a flat baseline curve (0 spikes where p5 = median = p95 = 0): z = 0 and within range, or not evaluable, or another convention (`plan.md` §3) |
| D1.2 | Whether an EEG with 45 to 54% clean windows, triaged usable for bipolar analyses, is rejected by the single 60% gate (`plan.md` §3) |
Shared labels: `type/spike`, `priority/p2-normal`, `area/models`, `status/ready`, `review/domain-expert`,
`size/s`, `human-only`.
## T5. Apply the flat-curve convention
Goal: A metric equal to a flat baseline curve gets the deviation D1.1 decides, distinguishable from "not computed".
Description: `z_y_posicion` of the spikes biomarker (and of any other whose curve can be flat) returns the decided z and position instead of 0/0; the analysis stores it in `met_z` and `met_fuera`. Done when: a test with value 0 on a curve of zeros gets the decided values, and a test with a missing value still gets null.
Context: `plan.md` §3; `models/libs/tea/src/tea/biomarkers/spikes/_baseline.py` (one `_baseline.py` per biomarker)
Depends on: D1.1
Approval: the convention (D1.1)
Labels: type/bug priority/p2-normal area/models status/blocked model/standard review/required size/s agent-ok
Part of: standalone
## T6. Type hints on the library's pyfunc models
Goal: Loading a baseline no longer warns about missing type hints.
Description: `predict` of the biomarker and plan pyfunc models gets pandas type hints for its input and output. Done when: loading a registered baseline raises no MLflow type-hint warning (warnings captured in a test) and predictions are unchanged.
Context: `plan.md` §3; `models/libs/tea/src/tea/serving/model_code/biomarker_model.py`, `plan_model.py`
Depends on: none
Approval: none
Labels: type/chore priority/p3-low area/models status/ready model/small review/none size/s agent-ok
Part of: standalone
## T7. Find what limits writes to the eeg-data volume
Goal: Know why `sync-reference.sh` copies at 10 MB/s on a gigabit path.
Description: From a pod with `eeg-data` mounted read-write, time writing 1 GiB to a scratch folder as one stream and as 8 parallel streams, then read the NFS export's options and the server's disk throughput. It changes nothing on the server. Done when: the limit is named with its measurement (export option, disk, or network to `192.168.20.10`), the scratch folder is removed, and the recommendation is recorded in `plan.md` §4.
Context: `plan.md` §4; `dask-cluster/sync-reference.sh`, `loader.yaml`
Depends on: none
Approval: writing a scratch folder on the shared volume
Labels: type/spike priority/p3-low area/infra status/ready model/standard review/light size/s agent-ok
Part of: standalone
---
## Issue numbers
Not posted to Gitea yet.
+149
View File
@@ -0,0 +1,149 @@
# TEA EEG in Gobernanza: API contracts
Fixed before any delegate writes code. Backend (`models`, `WebApi`) and frontend (`WebApp`) both work from this file.
All paths are under the WebApi root; all bodies are JSON unless marked multipart. Error bodies keep the existing
`{"error": "<message>"}` shape. User-facing strings in the UI are Spanish; API identifiers are English except existing
ones (`estado`, `codigo`, `salida`, `error`, `iniciado`, which the job states already use).
## Shared types
```ts
type ClusterMode = 'auto' | 'local' | 'remote' | 'sync';
interface ClusterChoice { mode: ClusterMode; scheduler?: string } // scheduler only meaningful for 'remote'
type JobState = 'en_curso' | 'completado' | 'entrenado_sin_promover' | 'fallido' | 'interrumpido';
```
`remote` without a scheduler (none given and `DASK_SCHEDULER_ADDRESS` unset) answers 400.
## 1. Cluster health
`GET /governance/tea/cluster?mode=<ClusterMode>&scheduler=<addr>` (both optional)
```ts
interface ClusterStatus {
mode: ClusterMode; // effective mode after resolving 'auto'
scheduler: string | null;
reachable: boolean;
workers: number | null;
expected_workers: number | null; // TEA_DASK_EXPECTED_WORKERS
versions_ok: boolean | null;
version_error: string | null;
dashboard_ok: boolean | null;
dashboard_url: string | null; // TEA_DASK_DASHBOARD_URL, else http://<scheduler host>:TEA_DASK_DASHBOARD_PORT/status
reference: { name: string; edfs: number } | null; // seen from a worker; null when not checked
latency_ms: number | null;
error: string | null;
}
```
`scheduler` must equal `DASK_SCHEDULER_ADDRESS` or be in `TEA_DASK_SCHEDULERS` (comma list); otherwise 400.
Local mode reports `reachable: true`, `workers` of the local cluster is not started (null), `dashboard_*` null.
## 2. Reference cohorts
`GET /governance/tea/reference-cohorts` -> `ReferenceCohort[]`
```ts
interface ReferenceCohort { name: string; edfs: number; size_bytes: number; has_ages: boolean; path: string }
```
`POST /governance/tea/reference-cohorts/<name>/files` multipart, field `file` (one `.edf`, or `edades.csv`) ->
`201 {name, file, size_bytes}`. Name matches `[A-Za-z0-9._-]{1,64}`; other extensions 400; path escapes 400.
Root is `TEA_REFERENCE_ROOT` (unset -> the endpoints answer 503 `{"error": ...}`).
## 3. Training with parameters
`POST /governance/model-versions/tea/eeg/train-jobs` (existing route, body now optional)
```ts
interface TeaTrainBody {
reference_name?: string; // cohort folder under TEA_REFERENCE_ROOT, or a label for cluster data
reference_dir?: string; // absolute; must be inside TEA_REFERENCE_ROOT unless cluster.mode is remote
reference_ages?: string;
line_hz?: number; // 50 | 60, default 60
promote?: boolean; // default true (existing behaviour)
cluster?: ClusterChoice;
}
```
Body fields override `TEA_REFERENCE_*`. Response and states are the existing job object plus
`cluster: ClusterChoice | null`. 409 when one is running, as today.
## 4. Baseline bundle
`GET /governance/tea/baselines/export?environment=prod&production=0` -> `application/zip`, headers
`Content-Disposition: attachment; filename=baselines.zip`, `X-Baselines-Sha256: <hex>`, `X-Baselines-Versions: <n>`.
`POST /governance/tea/baselines/import` multipart, field `file` ->
```ts
interface BaselineImport { sha256: string; imported: { scenario: string; version: number }[] }
```
`BundleError` -> 400 (bad zip) or 409 (already imported / conflicting).
## 5. Analysis jobs
`POST /governance/tea/eeg/analyze-jobs`
```ts
interface AnalyzeBody { all?: boolean; limit?: number; ids?: number[]; cluster?: ClusterChoice }
```
-> `202 AnalyzeJob`; `409` if one runs. `GET /governance/tea/eeg/analyze-jobs` -> `AnalyzeJob[]` (newest first),
`GET /governance/tea/eeg/analyze-jobs/<id>` -> `AnalyzeJob`.
```ts
interface AnalyzeJob {
id: string; iniciado: string; estado: JobState; codigo: number | null; salida: string; error: string;
cluster: ClusterChoice | null; ids: number[] | null; summary: AnalyzeSummary | null; // summary once finished
}
interface AnalyzeSummary { pending: number; valid: number; not_valid: number; failed: number }
```
`ids` given -> those EEGs are re-analysed regardless of pending state; unknown id -> 404 at start.
## 6. Run progress (training and analysis, local or remote cluster)
`GET /governance/tea/jobs/<kind>/<job_id>/progress`, `kind` is `train` or `analyze`. 404 before the first sample.
```ts
interface RunProgress {
updated_at: string; // ISO UTC; the UI treats > 10 s old as 'sin señal' while the job is en_curso
phase: string; // 'midiendo' | 'ajustando' | 'registrando' | 'analizando' | ...
done: number; total: number; // studies or EEGs, in the measuring phase
elapsed_s: number;
eta_s: number | null; // null until a rate exists
tasks: { processing: number; waiting: number; memory: number; erred: number } | null;
cluster: { mode: ClusterMode; scheduler: string | null; workers: WorkerSample[]; cpu_pct: number; memory_pct: number } | null;
history: { t: number; done: number; cpu_pct: number; memory_pct: number }[]; // last 120 samples, t = seconds since start
}
interface WorkerSample { name: string; cpu_pct: number; memory_bytes: number; memory_limit: number | null; executing: number; threads: number }
```
`GET /governance/tea/jobs/<kind>/<job_id>/progress` for a job that is not Dask-based returns `cluster: null`, `tasks: null`.
## 7. Baseline check
`GET /governance/tea/baselines/<scenario>/<version>/curve?metric=<name>` ->
```ts
interface BaselineCurve { scenario: string; version: number; metric: string; edad_meses: number[]; p5: number[]; p25: number[]; mediana: number[]; p75: number[]; p95: number[] }
```
`GET /governance/tea/baselines/<scenario>/<version>/metrics` -> `string[]` (the metric names that have a curve).
`GET /governance/tea/eeg/<eeg_id>/metrics` -> `EegMetrics`:
```ts
interface EegMetrics { eeg_id: number; valid: boolean | null; level: string | null; age_months: number | null;
metrics: { name: string; value: number; z: number | null; outside: -1 | 0 | 1 | null; model: string | null }[] }
```
`GET /governance/tea/eeg` -> `{ id: number; lab_id: string | null; patient_id: number | null; study_date: string | null; valid: boolean | null; analysed: boolean }[]`
(paged: `?limit=200&offset=0`), used for the ticked-list in the analyze step.
## 8. EDF upload
`POST /governance/tea/eeg/upload` multipart: `file` (one `.edf`), optional form field `patient_id` (integer).
-> `201 { eeg_id: number; lab_id: string | null; created: boolean }`. Invalid EDF (MNE cannot open it) -> 400.
Goes through the existing import pipeline (`tea.Eeg`, upsert on `eeg_id_registro_laboratorio`); no new tables.
## 9. Result summary
`GET /governance/tea/eeg/summary` ->
```ts
interface EegSummary { eegs: number; analysed: number; valid: number; not_valid: number; failed: number;
metrics: number; metrics_with_z: number; high: number; low: number;
fhir_eegs: number; fhir_metrics: number } // tea_paciente_eegs / tea_paciente_eeg_metricas
```
## 10. Indicator cycle (existing, plus an optional body)
`POST /reportes/indicadores/tea/recalcular` body `{ cluster?: ClusterChoice }` (optional); `GET /reportes/indicadores`
unchanged (`en_curso | ok | error`...).
## Existing endpoints the UI reuses unchanged
`GET /governance/scenarios`, `GET /governance/training-jobs[/<id>]`, `GET /governance/model-versions?domain=tea`,
`PATCH /governance/model-versions/tea/<scenario>/<version>/reports`, `POST .../promote`, `GET .../checks`.
+75
View File
@@ -0,0 +1,75 @@
# TEA EEG in Gobernanza: tasks
Composite plan. Contracts: `contracts.md`. Each task fits one session and lands on `dev` of its submodule.
Owner: C = Claude, X = Codex, K = Kimi. Order is top to bottom; tasks marked (par) can run in parallel with the previous one.
| # | Task | Repo | Owner | Notes |
|---|---|---|---|---|
| 1 | Detached-job base, training body, cluster choice in `training_jobs.py` | WebApi | X | `start(domain, scenario, body)`; `--cluster`/`--reference-name` in `models run` |
| 2 | Reference cohorts store and endpoints | WebApi | X | `TEA_REFERENCE_ROOT` |
| 3 | Baselines export / import endpoints | WebApi | X | reuses `models/tea/eeg/bundle.py` |
| 4 | Cluster health (`ClusterStatus`) | models, WebApi | X | local cluster in tests |
| 5 | `RunMonitor` and progress endpoint | models, WebApi | C | |
| 6 | Analyze jobs with `ids` | models, WebApi | X | `pending_ids(ids=...)` |
| 7 | EDF upload (`EdfIntake`) after spike | WebApi | C | spike: import commit column mapping |
| 7 | (spike result) | | | `commit_sources([{kind: "edf", target: "tea.Eeg", file_base64, options: {file_name}, column_mapping: {id_registro_laboratorio: eeg_id_registro_laboratorio, fecha_estudio: eeg_fecha_estudio, canales: eeg_canales, duracion_min: eeg_duracion_min, estudio: eeg_estudio}, defaults: {eeg_pac_id}}], on_conflict="upsert")` in `webapi/imports/services/import_service.py`; the connector's `paciente` column is not mapped |
| 8 | Baseline curve / EEG metrics / EEG list / summary endpoints | WebApi | X | |
| 9 | UI scaffolding: tab, stepper, API service, types, `ClusterSelector` | WebApp | K (par with 1) | |
| 10 | UI: cohorts, train, baselines, reports, promote steps | WebApp | K | |
| 11 | UI: `RunMonitorComponent`, analyze, upload, baseline check, result | WebApp | K | after 5-8 |
| 12 | TEA notebook templates | models | C | deferred; spike: does the TEA flow fit `/experiments`? |
| 13 | Docs: README (manual-deploy), `dist/`, `docs/architecture` | all | K | |
| 14 | Restart-free promote check | models, WebApi | C | verify caching first |
## Status (2026-11-22)
| # | State |
|---|---|
| 1 training body and cluster choice | done, tested (+ `EEG_ANALYSIS_CLUSTER` honoured by `models run tea eeg`) |
| 2, 3 cohorts, baselines zip | done, tested |
| 4 cluster health | done, tested; probed against the real schedulers 10.0.10.41:30886 (25 workers) and :30786 (20 workers) |
| 5 run monitor | done, tested (`RUN_PROGRESS_DIR`, `progress.json`, `GET .../jobs/<kind>/<id>/progress`) |
| 6 analyze jobs with ids | done, tested |
| 7 EDF upload | done, tested (`webapi/tea/edf_intake.py`, `POST /governance/tea/eeg/upload`) |
| 8 curves, EEG list/metrics, summary | done, tested |
| 9 UI scaffolding | done, 31 governance specs pass, build ok |
| 10 UI steps (cohorts, train, baselines, reports, promote) | done (Kimi; scenario prefix fixed to `eeg-`) |
| 11 UI monitor card, analyze, upload, baseline check, result | done (Codex), 60 governance specs pass, build ok |
| 12 TEA notebook templates | deferred; spike pending |
| 13 docs | written (README section, dist settings, architecture); recalcular with a cluster choice added in WebApi (`recomputation.py`, `reports.py`) |
| 14 restart-free promote | no change needed: `analyze_pending` builds its `Baselines` per call, so each cycle resolves production anew; only an in-flight cycle keeps the old set |
## End-to-end run (2026-11-23, API only, one local Dask worker, 8 synthetic 4-minute EDFs)
Deployment A trained the seven baselines (job state, progress, ETA, CPU/RAM of the single worker all reported) and exported
`baselines.zip` (sha256 header equals the file's). Deployment B imported it (409 on a repeat, 400 on garbage), took the three
report URIs, promoted all seven, accepted two uploaded EDFs, analysed them by UUID id (2 valid, 0 failed), and answered the
result summary and EEG metrics; the indicator cycle ran with a cluster choice (`ok`). Not covered: the Angular UI in a browser,
a remote-cluster run, and a baseline curve (an 8-study cohort has no age bin with the 30 effective studies a curve needs).
Found and fixed during the run: 2-minute EDFs are not valid studies (use 4 minutes or more); EEG ids are UUID strings, so
`ids` (CLI, API, UI) now takes opaque ids; `TEA_LOCAL_WORKERS` caps a local cluster; the recalculate route now carries the
cluster choice. Open: the monitor keeps the last CPU/RAM/task figures after the cluster closes (they should clear).
## Cluster (2026-11-23)
Both DaskClusters (`test`, `isssteleon-eeg`) were deleted and `isssteleon-eeg` recreated from `dask-cluster/cluster.yaml`:
10 pods (one per k3s-w1..w10) x 4 workers = 40, scheduler NodePort 30786, dashboard 30787, image unchanged.
## Browser run (2026-11-23, headless Chromium, one local worker)
Driven through the UI: cluster check per mode, cohort list, training from a chosen cohort with the live monitor, baselines
export (download) and duplicate import (clear 409 message), reports, promote (7 of 7), baseline check, EDF upload,
analysis by selection (1 valid) and the result step. Found and fixed: a cohort name was never resolved to its folder
(training failed), report fields could be applied blank, RAM readings were unrounded, and a finished training said it was
promoted. Not covered: a remote-cluster run, a baseline curve, the notebook button (shows "Próximamente").
## Remote run and final deployment (2026-11-23)
Platform image rebuilt with `--pull` so its Python (3.12.16) equals the workers'; the worker image was rebuilt from the same
checkout and the cluster rolled onto it. In a throwaway project the app trained the seven baselines on the cluster from
`/referencia/helsinki` (223 studies, 40 workers, 3 min 16 s), exported the zip, promoted, and analysed three real EDFs on
the cluster (3 valid, 9 metrics with z). The existing `manual-deploy/baselines/baselines.zip` also imported, got its reports
and promoted 7 of 7 through the app. Found and fixed: the training form had no ages-table field for cluster-side folders,
and the reports and promote steps kept the version list read when the page opened.
Deployment B (`sitio-b`) was recreated: 62 real EDFs loaded, EEGs unanalysed, no baselines, cycle analysis off.