diff --git a/.conda/meta.yaml b/.conda/meta.yaml index 424506ff2..3f4a5a52b 100644 --- a/.conda/meta.yaml +++ b/.conda/meta.yaml @@ -69,6 +69,8 @@ test: source_files: - tests - pyproject.toml + - .github/scripts + - docs/examples/fcma/FCMA_script imports: - brainiak commands: diff --git a/.github/DELLA_RUNNER.md b/.github/DELLA_RUNNER.md new file mode 100644 index 000000000..e42941153 --- /dev/null +++ b/.github/DELLA_RUNNER.md @@ -0,0 +1,396 @@ +# BrainIAK tests on della-rse + +This is a proposed setup, not an installed runner. The manual workflow builds +and runs tests directly on della-rse, which is permitted for this CI workload. +The runner runs as a systemd user service under your account. Tests use the +direct launcher's CPU affinity, timeouts, and sampled memory budgets. No SLURM +allocation or CPU-controller delegation is required. No GPU is used. + +The previous `.github/workflows/della_notebooks.yml` was introduced by +`92793e0` (October 2023) and removed by `5321d4a` (November 2024). It ran on pull +requests and used `salloc -t 03:00:00 -N 1 -n 16`. This replacement uses manual +suite selection and a bounded local launcher instead. + +The [della-rse guide](https://github.com/PrincetonUniversity/della-rse) +recommends systemd for automatic restart and cgroups for resource control. +This setup follows its [systemd instructions](https://github.com/PrincetonUniversity/della-rse/blob/main/systemd.md) +and provides a ready-to-copy user service in `della-runner.service`. +On December 2, 2026, a read-only SSH check confirmed `Linger=yes` for +`dmturner` on della-rse. Once the runner is installed and its user service is +enabled, it can remain available after logout and start at boot without an +open login session. Enabling lingering was an additional setup recommendation; +the Della guide does not explicitly mention it. + +## Read-only inspection on October 7–8, 2026 + +SSH works with `ssh -o BatchMode=no della-rse`. The host runs RHEL 9.8. +`gcc/11 openmpi/gcc/4.1.6` loads successfully. System Python 3.9.25 is available. +Open MPI's local `isolated`, `self`, and `vader` components +were verified with `ompi_info` without launching MPI ranks on Della. +The launcher uses Python's standard library; tests run +with uv-managed Python 3.12. `/etc/profile.d/modules.sh` exists. +`~/.local/bin/uv` exists (0.12.10) but is absent from the noninteractive PATH; +the systemd service adds it explicitly. + +The scratch root already exists and contains an old runner named `della8`, +configured for `brainiak/brainiak`, under `actions-runner/`. No Runner.Listener +process or GitHub runner user service was found. Leave this installation alone +when provisioning the new runner. The repository runner API returned no +currently registered runners, so its saved registration appears stale. +The old `brainiak-example-data/` holds about 16 GiB. Non-smoke runs link known +input files from that cache instead of downloading them again. Source scripts +and notebooks are refreshed separately. At inspection the scratch filesystem +reported 98% usage, so retain this reuse and check capacity before large runs. + +At this inspection, user lingering was disabled and the user service manager +delegated only `memory pids`. The prepared service does not require +CPU-controller delegation. No remote files were created or changed, and no +remote tests were run during inspection. + +## Read-only recheck on December 2, 2026 + +SSH with `BatchMode=no` works. The scratch root is writable by `dmturner`; +the shared filesystem reports 86% usage and about 5.8 TiB available (this is +filesystem capacity, not a user or group quota check). All seven input files +listed for cache reuse, excluding the optional fMRI archive, are present and +nonempty. The old `actions-runner/` directory remains in place. + +`gcc/11 openmpi/gcc/4.1.6` still loads; Python 3.9.25 and +`~/.local/bin/uv` 0.12.10 are available. The user manager reports `Linger=yes`. +There is no installed `della-runner.service` or `actions.runner.*` user unit, +and no runner listener, worker, or test supervisor was found for this account. + +The session allows 64 logical CPUs. Load averages were approximately +57/56/48 when checked, so review current load before starting the smoke test. +No remote directories were created, service settings changed, or tests run. + +Before publishing the PR, the branch was updated with `master`'s dependency +security updates, and boto3 was aligned with the newer locked botocore. +All 18 focused launcher, notebook harness, example-mask, and MPI teardown +regressions passed using the isolated file layout declared by the conda test +recipe. The synthetic IEM notebook also passed locally with the updated +dependencies. The full notebook results below are from October and have not +yet been repeated with the refreshed lock or on Della. + +## Storage and resources + +The user service unit is installed in `~/.config/systemd/user/`, and systemd +captures service output in the user journal. Runner state, work and generated +test data belong under +`/scratch/gpfs/CSES/dmturner/brainiak_tests/`: + +| Path | Contents | +| --- | --- | +| `actions-runner-brainiak/` | New runner installation, registration and diagnostic logs | +| `_work/` | Actions checkout, builds, and runner temporary files | +| `runs/-/` | Launcher log, resource settings, pytest reports, temporary and Jupyter files | +| `notebooks/` | Copied notebooks, reusable datasets, executed notebooks | +| `brainiak-example-data/` | Existing data cache; known inputs are linked, not modified | +| `cache/`, `python/`, `venv/` | uv cache, managed Python, locked test environment | +| `tmp/` | Temporary files for the runner | + +Scratch is not archival storage. A lost cache can be recreated. GitHub retains +uploaded reports for 14 days. + +Only one workflow runs at a time across branches. A filesystem lock also +protects shared caches from a second launcher. There is no scheduled run or +parallel matrix. BLAS, OpenMP, and TensorFlow threads are limited to one. +Build parallelism is limited to the selected CPU count. + +| Suite | Tests | CPU affinity | RSS budget | Wall time | +| --- | --- | --- | --- | --- | +| `smoke` (default) | Synthetic IEM notebook; no notebook downloads | 1 CPU | 8 GiB | 20 minutes | +| `notebooks` | All documentation notebooks | 2 CPUs | 32 GiB | 3 hours | +| `unit` | Package tests, including MPI tests | 2 CPUs | 32 GiB | 3 hours | +| `all` | Unit tests followed by enabled notebooks | 2 CPUs | 32 GiB | 3 hours total | + +The launcher sets inherited Linux CPU affinity and lowers scheduling priority +with `nice`. By default it takes the first one or two CPUs in its allowed set; +set `DELLA_CPUS` to a comma-separated pair of logical CPU IDs to select another +pair. This does not reserve those CPUs, so choose IDs with other node users in +mind. MPI uses at most two ranks on localhost, with Open MPI rebinding disabled +to preserve inherited affinity. No batch scheduler or remote MPI hosts are used. + +The launcher samples the aggregate resident memory of its descendants every +250 ms and stops the run if the budget is exceeded. Shared pages may be counted +more than once, and brief overshoots are possible. This is a memory guard, +**not a kernel-enforced cgroup memory limit**. Programs can change their own +CPU affinity; these controls are intended for trusted CI code. +The launcher bounds total installation/test time independently of the Actions +job's 4-hour timeout and disables core dumps. Its limits and sampled peak RSS +are recorded in `reports/limits.json` and `reports/run.log`. + +These are initial budgets to validate on Della. BrainIAK is rebuilt each run +to avoid stale native extensions in the reused environment. Enabled notebooks +run serially. Review the first runs' memory usage and timing before changing +budgets. + +## Provisioning (not performed by preparing this branch) + +1. Verify access, modules, and available disk space: + + ```bash + ssh -o BatchMode=no della-rse + hostname + module load gcc/11 openmpi/gcc/4.1.6 + command -v python3 systemctl mpicc mpiexec + df -h /scratch/gpfs/CSES/dmturner/brainiak_tests + ``` + +2. Configure a GitHub environment called `della` with these variables: + + - `DELLA_MODULES`: `gcc/11 openmpi/gcc/4.1.6`, verified above. + - `DELLA_CPUS`: optional comma-separated CPU IDs, e.g. `2,3`. Use at least + two IDs to support every suite; leave empty for the default selection. + + Limit environment deployment branches to trusted branches, initially + `master`. Configure required reviewers if maintainers want a per-run gate. + A manual dispatch tests the selected branch's exact workflow commit; there + is no arbitrary checkout-ref input. The workflow must reach the default + branch before it appears in the Actions manual-run UI. + +3. Before registering a runner for this public repository, review + [GitHub's self-hosted runner security guidance](https://docs.github.com/en/actions/concepts/runners/self-hosted-runners) + and repository Actions policies. The manual trigger, labels, read-only + token, and environment gate reduce exposure but do **not** isolate an + account or prevent another workflow from targeting the runner. Require + approval for outside-contributor workflows; do not approve unreviewed fork + code onto the node. Where available, restrict the runner group to this + workflow. Prefer a dedicated service account as the della-rse guide + recommends, with access to the required scratch path. + +4. When ready to provision, create the new directories inside the existing + scratch root. Preserve its existing contents: + + ```bash + umask 077 + export BRAINIAK_TEST_ROOT=/scratch/gpfs/CSES/dmturner/brainiak_tests + mkdir -p "$BRAINIAK_TEST_ROOT"/{actions-runner-brainiak,_work,tmp,cache} + cd "$BRAINIAK_TEST_ROOT/actions-runner-brainiak" + ``` + + Install the Linux x64 GitHub Actions runner here using the current download + and checksum instructions at **Settings → Actions → Runners → New + self-hosted runner**. Register it using the short-lived token from that page: + + ```bash + ./config.sh --url https://github.com/brainiak/brainiak \ + --name brainiak-della-rse --labels brainiak-della \ + --work /scratch/gpfs/CSES/dmturner/brainiak_tests/_work + ``` + + Enter the token at the prompt; do not save it in the repo. Install one runner + only. Tools needed: Bash, Git, Python 3.9+, systemd, `uv`, compiler/Open MPI + modules, `curl`, `wget`, and `tar`. `uv sync --locked` builds BrainIAK and + mpi4py against the module environment with Python 3.12. If compiler/MPI + modules change, stop the runner and recreate the venv and clear the cached + mpi4py build before the next run. + +5. From a checkout of this branch on della-rse, install and start the user + service. The runner and scratch directories from step 4 must already exist: + + ```bash + mkdir -p ~/.config/systemd/user + cp .github/della-runner.service ~/.config/systemd/user/della-runner.service + systemctl --user daemon-reload + systemctl --user enable --now della-runner.service + systemctl --user status della-runner.service + ``` + + The service sets the scratch paths, adds `~/.local/bin` to `PATH`, lowers + scheduling priority, and restarts the listener if it exits. Resource + controls for builds and tests remain in `della-run.py`; the service does + not require CPU-controller delegation. + + `enable --now` starts the runner immediately and enables it for future + user-manager starts. With lingering now enabled for this account, the user + manager persists after logout and starts at boot. A login session no longer + needs to remain open for the runner. + + View logs or restart the service with: + + ```bash + journalctl --user -u della-runner.service -f + systemctl --user restart della-runner.service + ``` + + Cancel any active workflow and let cleanup finish before restarting or + stopping the service. Stop and disable it when no longer needed: + + ```bash + systemctl --user disable --now della-runner.service + ``` + +6. Manually dispatch **Della tests → smoke** and inspect the reports before + trying `notebooks` or `all`. The smoke run exercises installation and an + actual notebook kernel. The `unit` suite also validates two-rank Open MPI + execution on the node. + +## Notebook behavior and local validation + +All eleven documentation notebooks are enabled. Notebook tests remain opt-in +for ordinary pytest runs. The notebook suite +includes FCMA's two-rank MPI subprocesses, so it uses two CPUs even though +notebooks execute serially and numerical-library threads are limited to one. + +The harness finds notebooks relative to the repository, uses the `python3` +kernel from the test environment, and runs each notebook from its directory. +An explicit work directory keeps downloaded and generated files out of the +checkout. Download scripts are run only for selected, enabled notebooks; they +reuse complete files and fail on HTTP/download errors. A failed transfer uses +a `.part` file. A failed notebook saves its partial execution beside the copied +source as `*.executed.ipynb`. The cached notebook directories must not be used +by concurrent pytest processes. Source notebooks/fixtures are refreshed each +run, while datasets and generated output remain until removed by the operator. + +FCMA downloads its original simulated data from a pinned BrainIAK Aperture +revision. Its mask generation uses nibabel and includes the highest-ranked +voxel (rank zero), without requiring FSL. MPI subprocess output is saved in +the executed notebook, and failed subprocesses fail the test. + +HTFA uses the notebook's existing debug configuration (three subjects per +condition, ten factors, three local/global iterations). CI refits the model +on every run and refreshes the animations. SRM uses its original full dataset +and analysis. Their input archives are approximately 2.7 GiB and 9.3 GiB, +respectively; extraction needs additional storage. Reuse the old SRM archive +via the cache link above. The notebooks do not require a multi-rank Jupyter +kernel. + +The real-time notebook downloads a pinned rt-cloud revision into its work +directory. The managed checkout binds HTTP to loopback and stores its data +cache under that directory. It needs free local ports 8889 and 12345. CI runs +all 200 synthetic DICOM volumes through the real RPC service and classifier, +without the interactive two-second pacing. Browser controls and iframe +rendering are not tested. Each run creates a fresh `simdata-*` directory; +include these directories in periodic scratch cleanup. See the +[real-time instructions](../docs/examples/real-time/README_INSTRUCTIONS.md). + +For local execution (using a local temp path, not Della scratch): + +```bash +uv sync --locked --extra dev --extra matnormal --extra examples +# Install a local MPI runtime if one is not already available. +# On Linux, either build mpi4py against system MPI as CI does, or for local +# validation only: uv pip install mpich +.venv/bin/python -m ipykernel install --sys-prefix --name python3 +export OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 +export TF_NUM_INTRAOP_THREADS=1 TF_NUM_INTEROP_THREADS=1 +export CUDA_VISIBLE_DEVICES=-1 +.venv/bin/python -m pytest tests/test_notebooks.py --enable_notebook_tests \ + -k iem_synthetic_RF --notebook-workdir /tmp/brainiak-notebooks +``` + +Omit `-k` to run all enabled notebooks, including dataset downloads. Use +`--notebook-timeout` to bound individual cells (3600 seconds by default and on +Della, allowing time for HTFA fitting). The launcher still bounds the entire +suite to three hours. `--junitxml` respects the requested destination. Run ordinary unit +tests with `PATH="$PWD/.venv/bin:$PATH" .venv/bin/python -m pytest tests -m 'not notebook'`. + +## Cancellation and cleanup + +The local launcher handles SIGINT, SIGTERM and SIGHUP. On completion, +cancellation, timeout, or excess sampled RSS it terminates its descendants, +including detached notebook kernels. Linux child subreaping keeps orphaned +kernels attached to the supervisor for cleanup; processes that ignore SIGTERM +are killed after a short grace period. Test failures propagate to Actions. + +A forcibly killed supervisor cannot run cleanup. After a runner crash or +SIGKILL, inspect your remaining test processes before restarting; terminate +only processes belonging to that run. GitHub's normal orphan-process cleanup +is an additional backstop when its worker remains alive. The systemd service's +`KillMode=control-group` also cleans up all remaining workers and kernels when +the service stops, including processes in separate sessions. + +Periodically inspect scratch usage with `du -sh` and, with the runner stopped +and no tests remaining, remove old `runs/` directories after retaining needed +reports. Keep `notebooks/` datasets for reuse; remove that directory to force +a clean notebook run. No workflow automatically deletes other runs or scratch +contents. + +## Local validation on October 7, 2026 + +Validated with Python 3.12, the locked dev/matnormal/examples dependencies, +MPICH from the local `mpich` wheel, and one thread per numerical library: + +- Full unit run: **206 passed**, 11 notebook cases deselected. This exposed + and then verified the fix for the MPI plugin's parent fixture teardown. +- Earlier focused regression run: **13 passed** for the original SLURM + launcher and notebook harness. The direct launcher is validated separately + below. +- All **six enabled notebooks passed**, combining the broad run with + individual reruns. Five notebook skips remained at that point. + +| Notebook | Successful execution time (approximately) | +| --- | --- | +| Synthetic IEM | 6 seconds | +| IEM with experimental data | 29 seconds | +| fMRI simulation | 4 minutes 35 seconds | +| ISC | 4 minutes 12 seconds | +| BRSA | 16 minutes | +| Event segmentation | 14 minutes 27 seconds | + +The first broad run used a 300-second per-cell limit, which was too short for +BRSA and event segmentation; both passed with the workflow's 1800-second +limit. ISC's slow public download was stopped and the existing Della archive +was copied locally for its successful rerun. The existing fMRI NIfTI file was +also copied locally, avoiding its much larger archive. These were read-only +transfers, not remote test runs. + +`actionlint`, ShellCheck, flake8, mypy, reStructuredText lint, notebook-format +validation, and `git diff --check` passed. Offline checks also verified data +cache reuse, archive extraction, and download failure propagation. No workflow +was dispatched, no runner was registered or started, and no SLURM job was +submitted. These results precede the switch to direct execution on della-rse. + +## Direct launcher validation on October 8, 2026 + +- Launcher and notebook harness regression tests: **16 passed**. They exercise + actual inherited affinity, all four resource profiles, exit status, cache + locking, CPU selection, timeout, memory termination, and cleanup of an + orphaned kernel that creates its own session and ignores SIGTERM. +- Synthetic IEM notebook through the direct supervisor: **passed**, with + approximately 0.95 GiB peak sampled aggregate RSS, restricted to one CPU. +- Two local Open MPI 4.1.8 ranks through the same supervisor and MPI wrapper: + **passed** a collective communication check; both retained the selected + two-CPU affinity. This used a separate temporary local environment, leaving + the repository test environment unchanged. +- `actionlint`, ShellCheck, flake8, mypy, reStructuredText lint, and + `git diff --check`: **passed**. +- Restored systemd user service: **passed** local `systemd-analyze --user + verify`, substituting a local placeholder executable because the Della + runner path does not exist on the workstation. This checks the unit without + installing or starting a service. + +No runner was installed or started on Della. The site-specific build and test +environment still needs its first smoke run, followed by `unit` to validate +the site's Open MPI 4.1.6 build. + +## Previously disabled notebooks: local validation on October 8, 2026 + +The five remaining skips were removed after local execution with Python 3.12 +and the locked dependencies. The six previously enabled notebooks retain the +October 7 results above; the entire eleven-notebook suite was not rerun as one +job for this change. + +| Notebook | Validation | +| --- | --- | +| FCMA | Full notebook passed with MPICH and with Open MPI 4.1.8; the latter took about 9 minutes on two CPUs. Includes eight voxel-selection folds and 24 classification runs. | +| Matrix-normal | Three complete executions passed; the two-CPU launcher run took about 90 seconds. | +| Real-time rt-cloud | Complete 200-volume experiment passed, including RPC startup, data generation, training and classification; about 77 seconds through the launcher. | +| SRM | Full 40-subject notebook passed through the launcher in about 4 minutes 15 seconds, including archive extraction. | +| HTFA | Fresh fitting completed in 27 minutes 15 seconds. After fixing a nodes-only plotting error, the full notebook passed in about 2 minutes using that freshly fitted model, including both kinds of animation. CI always refits. | + +FCMA, Matrix-normal, rt-cloud, and SRM were exercised with local Open MPI +through the direct supervisor, using two CPUs and a 32 GiB sampled RSS budget. +HTFA was exercised with local MPICH and one numerical-library thread. +Executed notebooks and datasets are under `/tmp/brainiak-notebooks/` on the +workstation. SRM's 9.3 GiB archive was copied from the existing Della cache; +this was a read-only transfer. HTFA's data was downloaded from its public +source. No remote tests were run and no remote configuration was changed. + +The focused runner, notebook harness, and FCMA mask regressions passed +**17 tests**. Notebook-format validation, flake8, mypy, reStructuredText lint, +ShellCheck, actionlint, locked dependency validation, and `git diff --check` +passed. The release-note draft was checked with +`towncrier build --version=100 --draft`; `run-checks.sh` still uses an obsolete +top-level Towncrier invocation. diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml new file mode 100644 index 000000000..207d18b70 --- /dev/null +++ b/.github/actionlint.yaml @@ -0,0 +1,3 @@ +self-hosted-runner: + labels: + - brainiak-della diff --git a/.github/della-runner.service b/.github/della-runner.service new file mode 100644 index 000000000..ebdeaedd3 --- /dev/null +++ b/.github/della-runner.service @@ -0,0 +1,23 @@ +[Unit] +Description=BrainIAK GitHub Actions runner on della-rse +After=network.target + +[Service] +ExecStart=/scratch/gpfs/CSES/dmturner/brainiak_tests/actions-runner-brainiak/run.sh +WorkingDirectory=/scratch/gpfs/CSES/dmturner/brainiak_tests/actions-runner-brainiak +Environment=BRAINIAK_TEST_ROOT=/scratch/gpfs/CSES/dmturner/brainiak_tests +Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin +Environment=TMPDIR=/scratch/gpfs/CSES/dmturner/brainiak_tests/tmp +Environment=XDG_CACHE_HOME=/scratch/gpfs/CSES/dmturner/brainiak_tests/cache +UMask=0077 +Restart=always +RestartSec=10 +# Stop all workers and notebook kernels when the service is stopped. +KillMode=control-group +TimeoutStopSec=90 +Nice=10 +# della-run.py applies CPU affinity, timeouts and sampled memory budgets. +# No CPU delegation or lingering checks are needed to start this service. + +[Install] +WantedBy=default.target diff --git a/.github/scripts/della-mpiexec.sh b/.github/scripts/della-mpiexec.sh new file mode 100755 index 000000000..241ae5cec --- /dev/null +++ b/.github/scripts/della-mpiexec.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# pytest's MPI plugin appends -n and the Python command. +# Keep MPI on this node and preserve the launcher's inherited CPU affinity. +set -euo pipefail +: "${BRAINIAK_TEST_CPUS:?Run through della-run.py}" +if [[ ${1:-} != -n || ! ${2:-} =~ ^[12]$ || $2 -gt $BRAINIAK_TEST_CPUS ]]; then + echo 'Della MPI tests must request at most two local ranks' >&2 + exit 2 +fi +# The verified module is Open MPI. Disable scheduler discovery and network +# transports: both ranks communicate locally, without a SLURM allocation. +exec mpiexec --host "localhost:$BRAINIAK_TEST_CPUS" --bind-to none \ + --mca ras ^slurm --mca plm isolated --mca pml ob1 --mca btl self,vader "$@" diff --git a/.github/scripts/della-run.py b/.github/scripts/della-run.py new file mode 100644 index 000000000..45f356d64 --- /dev/null +++ b/.github/scripts/della-run.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python3 +"""Supervise one local Della test run using only Python's standard library. + +CPU affinity is inherited by builds, MPI ranks and notebook kernels. Aggregate +RSS is sampled, so the memory budget is a termination threshold, not a cgroup +hard limit. Linux subreaping lets cleanup find orphaned notebook kernels, +including those that create their own sessions. +""" + +import argparse +import ctypes +import fcntl +import json +import logging +import os +from pathlib import Path +import resource +import signal +import subprocess +import time + + +# CPUs, RSS budget in GiB, wall time in seconds (including installation). +PROFILES = { + "smoke": (1, 8, 20 * 60), + "notebooks": (2, 32, 3 * 60 * 60), + "unit": (2, 32, 3 * 60 * 60), + "all": (2, 32, 3 * 60 * 60), +} +LOG = logging.getLogger("della-run") + + +def descendants(parent): + """Find descendants, including children launched from worker threads.""" + found = set() + pending = [parent] + while pending: + pid = pending.pop() + for children in Path(f"/proc/{pid}/task").glob("*/children"): + try: + pids = {int(value) for value in children.read_text().split()} + except (FileNotFoundError, ProcessLookupError): + continue + pending.extend(pids - found) + found.update(pids) + return found + + +def send(pid, signum): + try: + os.kill(pid, signum) + except ProcessLookupError: + pass + + +def cleanup(): + """Terminate our descendants, including kernels in separate sessions.""" + parent = os.getpid() + pids = descendants(parent) + for pid in pids: + send(pid, signal.SIGTERM) + deadline = time.monotonic() + 2 + while descendants(parent) and time.monotonic() < deadline: + # Reap adopted children, including any command already waited by Popen. + try: + while os.waitpid(-1, os.WNOHANG)[0]: + pass + except ChildProcessError: + return + time.sleep(0.05) + # Stop parents before the final scan so they cannot spawn more children. + stopped = set() + while True: + remaining = descendants(parent) - stopped + if not remaining: + break + for pid in remaining: + send(pid, signal.SIGSTOP) + stopped.update(remaining) + for pid in stopped: + send(pid, signal.SIGKILL) + deadline = time.monotonic() + 1 + while time.monotonic() < deadline: + try: + if not os.waitpid(-1, os.WNOHANG)[0]: + time.sleep(0.05) + except ChildProcessError: + break + + +def supervise(command, *, cpus, memory_bytes, wall_seconds, env): + """Return the command status, 124 for timeout, or 137 for excess RSS.""" + # PR_SET_CHILD_SUBREAPER: detached descendants reparent here, not to init. + libc = ctypes.CDLL(None, use_errno=True) + if libc.prctl(36, 1, 0, 0, 0) != 0: + raise OSError(ctypes.get_errno(), "Cannot enable child subreaping") + os.sched_setaffinity(0, cpus) + os.nice(10) + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + interrupted = 0 + + def stop(signum, _frame): + nonlocal interrupted + interrupted = 128 + signum + + for signum in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP): + signal.signal(signum, stop) + deadline = time.monotonic() + wall_seconds + peak_rss = 0 + page_size = os.sysconf("SC_PAGE_SIZE") + try: + process = subprocess.Popen(command, env=env, start_new_session=True) + while True: + if interrupted: + return interrupted + status = process.poll() + if status is not None: + return status if status >= 0 else 128 - status + if time.monotonic() >= deadline: + LOG.error("Wall time limit exceeded") + return 124 + rss = 0 + for pid in descendants(os.getpid()): + try: + rss += int(Path(f"/proc/{pid}/statm").read_text() + .split()[1]) * page_size + except (FileNotFoundError, ProcessLookupError): + continue + peak_rss = max(peak_rss, rss) + if rss > memory_bytes: + LOG.error("Memory budget exceeded: %.2f GiB", rss / 2**30) + return 137 + time.sleep(0.25) + finally: + cleanup() + LOG.info("Peak sampled aggregate RSS: %.2f GiB", peak_rss / 2**30) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("suite", choices=PROFILES, nargs="?", default="smoke") + args = parser.parse_args() + logging.basicConfig(level=logging.INFO, + format="%(levelname)s: %(message)s") + root = Path(os.environ["BRAINIAK_TEST_ROOT"]).resolve(strict=True) + run_id = os.environ["GITHUB_RUN_ID"] + attempt = os.environ["GITHUB_RUN_ATTEMPT"] + if not run_id.isdecimal() or not attempt.isdecimal(): + parser.error("Run ID and attempt must be numeric") + count, gib, seconds = PROFILES[args.suite] + available = os.sched_getaffinity(0) + requested = os.environ.get("DELLA_CPUS", "") + try: + candidates = ({int(cpu) for cpu in requested.split(",")} if requested + else available) + except ValueError: + parser.error("DELLA_CPUS must be comma-separated numeric CPU IDs") + if not candidates <= available or len(candidates) < count: + parser.error("DELLA_CPUS must provide enough CPUs in current affinity") + cpus = sorted(candidates)[:count] + + # Acquire before creating reports or touching the shared environment/cache. + with (root / "run.lock").open("w") as lock: + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + LOG.error("Another Della test run holds the lock") + return 1 + run_dir = root / "runs" / f"{run_id}-{attempt}" + reports = run_dir / "reports" + reports.mkdir(parents=True, exist_ok=True) + logging.getLogger().addHandler( + logging.FileHandler(reports / "run.log")) + (reports / "limits.json").write_text(json.dumps({ + "suite": args.suite, "cpus": cpus, + "rss_budget_gib": gib, "wall_seconds": seconds, + }, indent=2) + "\n") + env = dict(os.environ, BRAINIAK_RUN_DIR=str(run_dir), + BRAINIAK_TEST_CPUS=str(count)) + script = Path(__file__).with_name("della-test.sh") + LOG.info("Running %s on CPUs %s; RSS budget %s GiB; timeout %ss", + args.suite, cpus, gib, seconds) + result = supervise(["bash", str(script), args.suite], cpus=cpus, + memory_bytes=gib * 2**30, wall_seconds=seconds, + env=env) + LOG.info("Test command exit status: %s", result) + return result + + +if __name__ == "__main__": + os.umask(0o077) + raise SystemExit(main()) diff --git a/.github/scripts/della-test.sh b/.github/scripts/della-test.sh new file mode 100755 index 000000000..62066559f --- /dev/null +++ b/.github/scripts/della-test.sh @@ -0,0 +1,88 @@ +#!/usr/bin/env bash +# Run through della-run.py to bound local builds and tests. +set -euo pipefail +umask 077 +: "${BRAINIAK_TEST_CPUS:?Run through della-run.py}" +: "${BRAINIAK_TEST_ROOT:?}" +: "${BRAINIAK_RUN_DIR:?}" +: "${DELLA_MODULES:?Set compiler and MPI modules for the current Della system}" + +# Noninteractive shells do not automatically initialize environment modules. +# shellcheck source=/dev/null +source /etc/profile.d/modules.sh +module purge +read -r -a modules <<< "$DELLA_MODULES" +module load "${modules[@]}" +command -v uv mpicc mpiexec +export MPICC +MPICC=$(command -v mpicc) + +export TMPDIR="$BRAINIAK_RUN_DIR/tmp" +export XDG_CACHE_HOME="$BRAINIAK_TEST_ROOT/cache" +export UV_CACHE_DIR="$XDG_CACHE_HOME/uv" +export UV_PYTHON_INSTALL_DIR="$BRAINIAK_TEST_ROOT/python" +export UV_PROJECT_ENVIRONMENT="$BRAINIAK_TEST_ROOT/venv" +export UV_PYTHON=3.12 +export UV_LINK_MODE=copy +export JUPYTER_CONFIG_DIR="$BRAINIAK_RUN_DIR/jupyter/config" +export JUPYTER_DATA_DIR="$BRAINIAK_RUN_DIR/jupyter/data" +export JUPYTER_RUNTIME_DIR="$BRAINIAK_RUN_DIR/jupyter/runtime" +export IPYTHONDIR="$BRAINIAK_RUN_DIR/ipython" +export MPLCONFIGDIR="$BRAINIAK_RUN_DIR/matplotlib" +export NUMBA_CACHE_DIR="$BRAINIAK_TEST_ROOT/cache/numba" +export NILEARN_DATA="$BRAINIAK_TEST_ROOT/notebooks/nilearn_data" +export CUDA_VISIBLE_DEVICES=-1 +export OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 +export NUMEXPR_NUM_THREADS=1 TF_NUM_INTRAOP_THREADS=1 TF_NUM_INTEROP_THREADS=1 +export CMAKE_BUILD_PARALLEL_LEVEL="$BRAINIAK_TEST_CPUS" UV_CONCURRENT_BUILDS=1 +export BRAINIAK_MPIEXEC="$GITHUB_WORKSPACE/.github/scripts/della-mpiexec.sh" +mkdir -p "$TMPDIR" "$XDG_CACHE_HOME" "$JUPYTER_RUNTIME_DIR" + +uv sync --locked --extra dev --extra matnormal --extra examples \ + --no-binary-package mpi4py --reinstall-package brainiak +python="$UV_PROJECT_ENVIRONMENT/bin/python" +export PATH="$UV_PROJECT_ENVIRONMENT/bin:$PATH" +"$python" -m ipykernel install --sys-prefix --name python3 +"$python" -c 'import brainiak; from mpi4py import MPI; print(brainiak.__version__); print(MPI.Get_library_version())' + +suite=${1:-smoke} +status=0 +if [[ "$suite" == unit || "$suite" == all ]]; then + "$python" -m pytest -v tests -m 'not notebook' \ + --mpiexec="$GITHUB_WORKSPACE/.github/scripts/della-mpiexec.sh" \ + --basetemp="$TMPDIR/pytest-unit" \ + --junitxml="$BRAINIAK_RUN_DIR/reports/unit.xml" \ + > "$BRAINIAK_RUN_DIR/reports/unit.log" 2>&1 || status=1 +fi +if [[ "$suite" == smoke || "$suite" == notebooks || "$suite" == all ]]; then + if [[ "$suite" != smoke ]]; then + # Reuse the existing 2025 data cache without copying gigabytes or + # overwriting its scripts. Link only known, nonempty input files. + for dataset in \ + eventseg/Sherlock_AG_movie.npy eventseg/Sherlock_AG_recall.npy \ + fmrisim/Corr_MVPA_archive.tar.gz \ + fmrisim/Corr_MVPA/Participant_01_rest_run01.nii \ + iem/RademakerEtAl2019_WM_S05_avgTime.npz \ + iem/AL61_Bilat-V1_attnContrast.mat \ + isc/brainiak-aperture-isc-data.tgz \ + srm/brainiak-aperture-srm-data.tgz; do + cached="$BRAINIAK_TEST_ROOT/brainiak-example-data/$dataset" + target="$BRAINIAK_TEST_ROOT/notebooks/$dataset" + if [[ -s "$cached" && ! -e "$target" && ! -L "$target" ]]; then + mkdir -p "$(dirname "$target")" + ln -s "$cached" "$target" + fi + done + fi + selection=() + if [[ "$suite" == smoke ]]; then + selection=(-k iem_synthetic_RF) + fi + "$python" -m pytest -v tests/test_notebooks.py --enable_notebook_tests \ + "${selection[@]}" --notebook-timeout=3600 \ + --notebook-workdir="$BRAINIAK_TEST_ROOT/notebooks" \ + --basetemp="$TMPDIR/pytest-notebooks" \ + --junitxml="$BRAINIAK_RUN_DIR/reports/notebooks.xml" \ + > "$BRAINIAK_RUN_DIR/reports/notebooks.log" 2>&1 || status=1 +fi +exit "$status" diff --git a/.github/workflows/della_notebooks.yml b/.github/workflows/della_notebooks.yml new file mode 100644 index 000000000..c6ed54b63 --- /dev/null +++ b/.github/workflows/della_notebooks.yml @@ -0,0 +1,65 @@ +name: Della tests + +# Only trusted repository code should reach a cluster account. In particular, +# do not add pull_request or pull_request_target triggers to this workflow. +on: + workflow_dispatch: + inputs: + suite: + description: Tests to run (smoke needs no notebook datasets) + type: choice + default: smoke + options: + - smoke + - notebooks + - unit + - all + +permissions: + contents: read + +concurrency: + group: brainiak-della + cancel-in-progress: false + +jobs: + tests: + if: github.repository == 'brainiak/brainiak' + runs-on: [self-hosted, Linux, X64, brainiak-della] + environment: della + timeout-minutes: 240 + env: + BRAINIAK_TEST_ROOT: /scratch/gpfs/CSES/dmturner/brainiak_tests + DELLA_MODULES: ${{ vars.DELLA_MODULES }} + DELLA_CPUS: ${{ vars.DELLA_CPUS }} + TEST_SUITE: ${{ inputs.suite }} + defaults: + run: + shell: bash + steps: + - name: Verify runner storage before checkout + working-directory: /scratch/gpfs/CSES/dmturner/brainiak_tests + run: | + case "$(realpath "$GITHUB_WORKSPACE")" in + "$BRAINIAK_TEST_ROOT"/*) ;; + *) echo 'Runner work directory must be under BRAINIAK_TEST_ROOT' >&2; exit 1 ;; + esac + command -v python3 uv + test -n "$DELLA_MODULES" || { echo 'Set the della environment variable DELLA_MODULES' >&2; exit 1; } + + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Build and test on della-rse + run: python3 .github/scripts/della-run.py "$TEST_SUITE" + + - name: Upload test reports + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: della-${{ inputs.suite }}-${{ github.run_id }}-${{ github.run_attempt }} + path: /scratch/gpfs/CSES/dmturner/brainiak_tests/runs/${{ github.run_id }}-${{ github.run_attempt }}/reports/ + if-no-files-found: warn + retention-days: 14 diff --git a/.gitignore b/.gitignore index ed3378a61..87e921493 100644 --- a/.gitignore +++ b/.gitignore @@ -39,6 +39,7 @@ examples/data htmlcov .idea .ipynb_checkpoints +*.executed.ipynb junit-*.xml __pycache__ .DS_Store diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 7c8fce90a..8a6c50fc3 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -249,6 +249,13 @@ You can run ``./run-tests.sh`` to run all the unit tests, or you can use the ``py.test `` command to run your tests only, at a more granular level. +Notebook tests are opt-in: use ``python -m pytest tests/test_notebooks.py +--enable_notebook_tests``. The `Della runner setup guide`_ describes the +manual della-rse workflow, scratch storage, and local notebook test options. + +.. _Della runner setup guide: + https://github.com/brainiak/brainiak/blob/master/.github/DELLA_RUNNER.md + Next to the test results, you will also see a code coverage report. New code should have at least 90% coverage. diff --git a/docs/examples/eventseg/download_data.sh b/docs/examples/eventseg/download_data.sh index 2c7bd5306..a309be0ed 100644 --- a/docs/examples/eventseg/download_data.sh +++ b/docs/examples/eventseg/download_data.sh @@ -1,4 +1,19 @@ -#!/bin/bash +#!/usr/bin/env bash +# Reuse complete downloads and never mistake an interrupted transfer for data. +set -euo pipefail -wget -nc https://ndownloader.figshare.com/files/22927253 -O Sherlock_AG_movie.npy -wget -nc https://ndownloader.figshare.com/files/22927256 -O Sherlock_AG_recall.npy +download() { + local filename=$1 url=$2 + if [[ ! -s "$filename" ]]; then + echo "Downloading $filename" + curl --fail --silent --show-error --location --retry 3 \ + --connect-timeout 30 --max-time 600 \ + "$url" --output "$filename.part" + mv "$filename.part" "$filename" + fi +} + +download Sherlock_AG_movie.npy \ + https://ndownloader.figshare.com/files/22927253 +download Sherlock_AG_recall.npy \ + https://ndownloader.figshare.com/files/22927256 diff --git a/docs/examples/fcma/FCMA_demo.ipynb b/docs/examples/fcma/FCMA_demo.ipynb index 728a5ba1c..b8f42a9d3 100644 --- a/docs/examples/fcma/FCMA_demo.ipynb +++ b/docs/examples/fcma/FCMA_demo.ipynb @@ -99,7 +99,10 @@ "import os, glob, subprocess\n", "import seaborn as sns\n", "import networkx as nx\n", - "import matplotlib.pyplot as plt\n" + "import matplotlib.pyplot as plt\n", + "\n", + "# Download the original simulated data if needed.\n", + "subprocess.run([\"bash\", \"download_data.sh\"], check=True)\n" ] }, { @@ -337,10 +340,26 @@ } ], "source": [ - "# Use subprocess to run a python script with MPI. This should work on a cluster or local computer. \n", + "# CI supplies a launcher that restricts MPI to this node and two ranks.\n", + "mpi_launcher = os.environ.get('BRAINIAK_MPIEXEC', 'mpiexec')\n", + "\n", + "def run_mpi(arguments):\n", + " # Open MPI adds singleton runtime state to the native process environment.\n", + " # Pass Python's environment explicitly so the new job starts independently.\n", + " result = subprocess.run(\n", + " [mpi_launcher, '-n', '2', sys.executable, *arguments],\n", + " env=os.environ.copy(), stdout=subprocess.PIPE,\n", + " stderr=subprocess.STDOUT, text=True,\n", + " )\n", + " print(result.stdout)\n", + " result.check_returncode()\n", + "\n", "for left_sid in range(num_subjs):\n", - " subprocess.run(f\"mpirun -np 2 python3 ./FCMA_script/fcma_voxel_selection_cv.py {data_dir} {suffix} {mask_file} {epoch_file} {left_sid} {output_dir}\", shell = True)\n", - " print(f\"Subject {left_sid} done\")" + " run_mpi([\n", + " './FCMA_script/fcma_voxel_selection_cv.py', data_dir, suffix,\n", + " mask_file, epoch_file, str(left_sid), output_dir,\n", + " ])\n", + " print(f\"Subject {left_sid} done\")\n" ] }, { @@ -419,11 +438,13 @@ "metadata": {}, "outputs": [], "source": [ - "# make top n masks\n", - "for n in [10,20,30]:\n", - " top_n = 'top_' + str(n)\n", - " #subprocess.run(\"module load fsl\", shell = True)\n", - " subprocess.run(f\"bash ./FCMA_script/make_top_voxel_mask.sh {output_dir} {n} {os.path.join(output_dir, top_n)}\", shell = True)" + "# Select exactly N voxels, including the highest-ranked voxel (rank zero).\n", + "# Nibabel performs the mask operations, so FSL is not required.\n", + "for n in [10, 20, 30]:\n", + " subprocess.run([\n", + " sys.executable, './FCMA_script/make_top_voxel_mask.py',\n", + " output_dir, str(n), os.path.join(output_dir, f'top_{n}'), mask_file,\n", + " ], check=True)\n" ] }, { @@ -625,15 +646,20 @@ } ], "source": [ - "# run classification for each left out subject for each top-n-mask size\n", - "for n, left_sid in product([10,20,30],range(8)):\n", - " \n", + "# Start fresh so rerunning this cell does not append duplicate results.\n", + "for n in [10, 20, 30]:\n", + " result_file = os.path.join(output_dir, f'top_{n}', 'classify_result.txt')\n", + " if os.path.exists(result_file):\n", + " os.remove(result_file)\n", + "\n", + "for n, left_sid in product([10, 20, 30], range(num_subjs)):\n", " top_n_mask_file_path = os.path.join(output_dir, f'top_{n}', f'fc_no{left_sid}_result_seq_top{n}.nii.gz')\n", " results_path = os.path.join(output_dir, f'top_{n}')\n", - " \n", - " subprocess.run(f\"mpirun -np 2 python3 ./FCMA_script/fcma_classify.py {data_dir} {suffix} {top_n_mask_file_path} {epoch_file} {left_sid} {results_path}\", shell = True) \n", - " \n", - " print(f\"Left out subject {left_sid}, Top {n} voxel mask, Classification done\")" + " run_mpi([\n", + " './FCMA_script/fcma_classify.py', data_dir, suffix,\n", + " top_n_mask_file_path, epoch_file, str(left_sid), results_path,\n", + " ])\n", + " print(f\"Left out subject {left_sid}, Top {n} voxel mask, Classification done\")\n" ] }, { @@ -908,7 +934,7 @@ ], "source": [ "# Load in the data \n", - "epoch_data = raw_data[0] # Just load a single subject and a single epoch\n", + "epoch_data = raw_data[0].copy() # Just load a single subject and a single epoch\n", "mask_top_n_file = os.path.join(output_dir, 'top_30/fc_no0_result_seq_top30.nii.gz')\n", "mask_top_n_nii = nib.load(mask_top_n_file) # Load the mask that leaves that participant out\n", "mask_top_n = mask_top_n_nii.get_fdata()\n", diff --git a/docs/examples/fcma/FCMA_script/fcma_voxel_selection_cv.py b/docs/examples/fcma/FCMA_script/fcma_voxel_selection_cv.py index edeb2b5eb..858cdfa81 100644 --- a/docs/examples/fcma/FCMA_script/fcma_voxel_selection_cv.py +++ b/docs/examples/fcma/FCMA_script/fcma_voxel_selection_cv.py @@ -94,8 +94,8 @@ # Preset the volumes score_volume = np.zeros(mask.shape, dtype=np.float32) score = np.zeros(len(results), dtype=np.float32) - seq_volume = np.zeros(mask.shape, dtype=np.int) - seq = np.zeros(len(results), dtype=np.int) + seq_volume = np.zeros(mask.shape, dtype=np.int32) + seq = np.zeros(len(results), dtype=np.int32) # Write a text document of the voxel selection results with open(file_str + 'result_list.txt', 'w') as fp: diff --git a/docs/examples/fcma/FCMA_script/make_top_voxel_mask.py b/docs/examples/fcma/FCMA_script/make_top_voxel_mask.py new file mode 100644 index 000000000..8848edc3a --- /dev/null +++ b/docs/examples/fcma/FCMA_script/make_top_voxel_mask.py @@ -0,0 +1,46 @@ +"""Create exactly N selected voxels per fold, without requiring FSL.""" + +import argparse +from pathlib import Path + +import nibabel as nib +import numpy as np + + +def make_masks(input_dir, voxel_number, output_dir, brain_mask_file): + """Select zero-based ranks inside the brain mask, including rank zero.""" + if voxel_number < 1: + raise ValueError("voxel_number must be positive") + brain_mask = nib.load(brain_mask_file).get_fdata().astype(bool) + paths = sorted(Path(input_dir).glob("*_seq.nii.gz")) + if not paths: + raise ValueError("No voxel selection results found") + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + masks = [] + for path in paths: + image = nib.load(path) + ranks = image.get_fdata() + selected = brain_mask & (ranks >= 0) & (ranks < voxel_number) + if selected.sum() != voxel_number: + raise ValueError(f"{path}: expected exactly {voxel_number} voxels") + masks.append(selected.astype(np.uint8)) + prefix = path.name.removesuffix(".nii.gz") + nib.save(nib.Nifti1Image(masks[-1], image.affine), + output_dir / f"{prefix}_top{voxel_number}.nii.gz") + stacked = np.stack(masks, axis=-1) + nib.save(nib.Nifti1Image(stacked, image.affine), + output_dir / f"all_top{voxel_number}.nii.gz") + nib.save(nib.Nifti1Image(stacked.mean(axis=-1), image.affine), + output_dir / f"prop_top{voxel_number}.nii.gz") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("input_dir") + parser.add_argument("voxel_number", type=int) + parser.add_argument("output_dir") + parser.add_argument("brain_mask") + args = parser.parse_args() + make_masks(args.input_dir, args.voxel_number, args.output_dir, + args.brain_mask) diff --git a/docs/examples/fcma/FCMA_script/make_top_voxel_mask.sh b/docs/examples/fcma/FCMA_script/make_top_voxel_mask.sh index 916102e9e..53bfd9769 100644 --- a/docs/examples/fcma/FCMA_script/make_top_voxel_mask.sh +++ b/docs/examples/fcma/FCMA_script/make_top_voxel_mask.sh @@ -1,35 +1,6 @@ -#!/bin/bash -i -# -# Takes in a results directory from fcma analysis and a certain number of voxels to threshold for a mask as input - -#You will need to load fsl module/conda for your cluster -#source ../setup_environment.sh - - -# Take inputs -input_dir=$1 # What is the path to thedata? -voxel_number=$2 # What voxel threshold would you like to set -output_dir=$3 # Where do you want to put the data - -# Create output_dir -if [ ! -d ${output_dir} ]; then - mkdir ${output_dir} -fi - -# Iterate through each volume in the fcma directory -for file in ${input_dir}/*_seq.nii.gz -do - # Preprocess the file name - fbase=$(basename "$file") - pref="${fbase%%.*}" - - # Create the voxel mask - fslmaths $file -uthr $voxel_number -bin ${output_dir}/${pref}_top${voxel_number}.nii.gz - -done - -# Concatenate all of the masks from each volume -fslmerge -t ${output_dir}/all_top${voxel_number} ${output_dir}/fc_no*top${voxel_number}.nii.gz - -# Create a probability map of each voxel being included across participants -fslmaths ${output_dir}/all_top${voxel_number} -Tmean ${output_dir}/prop_top${voxel_number} -odt float +#!/usr/bin/env bash +# Backward-compatible entry point; mask construction no longer requires FSL. +set -euo pipefail +script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +exec python3 "$script_dir/make_top_voxel_mask.py" "$1" "$2" "$3" \ + "${4:-$script_dir/../sim_info/full_mask.nii.gz}" diff --git a/docs/examples/fcma/download_data.sh b/docs/examples/fcma/download_data.sh new file mode 100644 index 000000000..cf681d31d --- /dev/null +++ b/docs/examples/fcma/download_data.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Original simulated example data, pinned to a BrainIAK Aperture revision. +set -euo pipefail +base=https://raw.githubusercontent.com/brainiak/brainiak-aperture/78f29d66db8230400ea426517dc588c05e8ba38b/notebooks/fcma +mkdir -p simulated_data sim_info +files=(simulated_data/sim_epoch_file.npy sim_info/full_mask.nii.gz + sim_info/ROI_A_mpfc.nii.gz sim_info/ROI_B_precuenus.nii.gz) +for subject in {0..7}; do + files+=("simulated_data/sub_${subject}_sim_dat.nii.gz") +done +for file in "${files[@]}"; do + if [[ ! -s "$file" ]]; then + curl --fail --location --retry 3 --connect-timeout 30 --max-time 600 \ + "$base/$file" --output "$file.part" + mv "$file.part" "$file" + fi +done diff --git a/docs/examples/fmrisim/download_data.sh b/docs/examples/fmrisim/download_data.sh index a06b09626..caa7b6c0b 100644 --- a/docs/examples/fmrisim/download_data.sh +++ b/docs/examples/fmrisim/download_data.sh @@ -1,8 +1,31 @@ -#!/bin/bash +#!/usr/bin/env bash +# Reuse complete downloads and never mistake an interrupted transfer for data. +set -euo pipefail -# Download the archive containing the example data if we don't have it already -wget -nc https://dataspace.princeton.edu/bitstream/88435/dsp01dn39x4181/2/Corr_MVPA_archive.tar.gz +# The notebook needs only this 63 MiB member of the multi-gigabyte archive. +if [[ -s Corr_MVPA/Participant_01_rest_run01.nii ]]; then + exit 0 +fi -# If the file doesn't exist, we need to extract it. -test ! -e Corr_MVPA && tar xzkvf Corr_MVPA_archive.tar.gz Corr_MVPA_Data_dataspace/Participant_01_rest_run01.nii && mv Corr_MVPA_Data_dataspace Corr_MVPA +download() { + local filename=$1 url=$2 + if [[ ! -s "$filename" ]]; then + echo "Downloading $filename" + curl --fail --silent --show-error --location --retry 3 \ + --connect-timeout 30 --max-time 600 \ + "$url" --output "$filename.part" + mv "$filename.part" "$filename" + fi +} +download Corr_MVPA_archive.tar.gz \ + https://dataspace.princeton.edu/bitstream/88435/dsp01dn39x4181/2/Corr_MVPA_archive.tar.gz + +if [[ ! -s Corr_MVPA/Participant_01_rest_run01.nii ]]; then + mkdir -p Corr_MVPA + tar -xOzf Corr_MVPA_archive.tar.gz \ + Corr_MVPA_Data_dataspace/Participant_01_rest_run01.nii \ + > Corr_MVPA/Participant_01_rest_run01.nii.part + mv Corr_MVPA/Participant_01_rest_run01.nii.part \ + Corr_MVPA/Participant_01_rest_run01.nii +fi diff --git a/docs/examples/htfa/download_data.sh b/docs/examples/htfa/download_data.sh index e27488346..ebfc9c664 100644 --- a/docs/examples/htfa/download_data.sh +++ b/docs/examples/htfa/download_data.sh @@ -1,16 +1,17 @@ -#!/bin/bash - -if [ -d "data/" ]; then - echo "Skipping download of data for HTFA notebook, already present" -else - mkdir data - wget --save-cookies cookies.txt --keep-session-cookies --no-check-certificate -q \ - "https://docs.google.com/uc?export=download&id=1IBA39ZZjeGS1u_DvZdiw1AZZQMS3K5q0" -O- \ - | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p' > confirm - wget --load-cookies cookies.txt --no-check-certificate -q \ - "https://docs.google.com/uc?export=download&confirm="$(cat confirm)"&id=1IBA39ZZjeGS1u_DvZdiw1AZZQMS3K5q0" -O data/pieman.zip - rm cookies.txt confirm - unzip data/pieman.zip -d data/ - rm data/pieman.zip +#!/usr/bin/env bash +set -euo pipefail +mkdir -p data +if [[ ! -f data/Pieman2/.extracted ]]; then + if [[ ! -s data/pieman.zip ]]; then + curl --fail --location --retry 3 --connect-timeout 30 --max-time 900 \ + 'https://drive.usercontent.google.com/download?id=1IBA39ZZjeGS1u_DvZdiw1AZZQMS3K5q0&export=download&confirm=t' \ + --output data/pieman.zip.part + mv data/pieman.zip.part data/pieman.zip + fi + python3 - <<'PY' +from zipfile import ZipFile +with ZipFile('data/pieman.zip') as archive: + archive.extractall('data') +PY + touch data/Pieman2/.extracted fi - diff --git a/docs/examples/htfa/helpers.py b/docs/examples/htfa/helpers.py index 87ab3ebff..50bf34303 100644 --- a/docs/examples/htfa/helpers.py +++ b/docs/examples/htfa/helpers.py @@ -2,9 +2,9 @@ import pandas as pd import nibabel as nib import nilearn as nl -from nilearn.input_data import NiftiMasker +from nilearn.maskers import NiftiMasker import nilearn.plotting as niplot -import matplotlib as mlab +from matplotlib.animation import FuncAnimation import matplotlib.pyplot as plt import holoviews as hv import timecorr as tc @@ -124,7 +124,10 @@ def plot_nodes(htfa, n_timepoints, cmap='Spectral', global_scale=100, local_scal scales = np.repeat(np.hstack([np.array(global_scale), np.array(htfa.n_subj*[local_scale])]), htfa.K) sizes = widths.T * scales - return nl.plotting.plot_connectome(np.eye(htfa.K * (1 + htfa.n_subj)), centers, node_color=colors, node_size=sizes) + # This plot contains nodes only; there are no edge values for a colorbar. + return nl.plotting.plot_connectome( + np.eye(htfa.K * (1 + htfa.n_subj)), centers, + node_color=colors, node_size=sizes, colorbar=False) def nii2cmu(nifti_file, mask_file=None): @@ -275,7 +278,7 @@ def get_im(fname): plt.axis('off') return plt.imshow(plt.imread(fname), animated=True) - ani = mlab.animation.FuncAnimation(fig, get_im, fnames, interval=50) + ani = FuncAnimation(fig, get_im, fnames, interval=50) return ani @@ -324,4 +327,4 @@ def animate_chord(x, cthresh=0.05): hv.output(max_frames=x.shape[0]) renderer = hv.renderer('bokeh') - return hv.HoloMap({t: mat2chord(tc.vec2mat(x[t, :]), cthresh=cthresh) for t in range(x.shape[0])}, kdims='Time (TRs)') \ No newline at end of file + return hv.HoloMap({t: mat2chord(tc.vec2mat(x[t, :]), cthresh=cthresh) for t in range(x.shape[0])}, kdims='Time (TRs)') diff --git a/docs/examples/htfa/htfa.ipynb b/docs/examples/htfa/htfa.ipynb index 6397836da..a1f582dc5 100644 --- a/docs/examples/htfa/htfa.ipynb +++ b/docs/examples/htfa/htfa.ipynb @@ -62,6 +62,8 @@ "source": [ "# Getting started\n", "\n", + "With BrainIAK and its `examples` dependencies installed locally, run `bash download_data.sh` from this notebook's folder before executing the cells. Automated notebook tests handle this download and keep data in the selected work directory.\n", + "\n", "The easiest way to run this notebook is to download and install [Docker](https://www.docker.com/) on your local machine, and then build the Docker image in this folder. That will install the necessary toolboxes and dependencies, and will also download the data you'll be analyzing. Follow the [instructions for your platform](https://www.docker.com/) to download and install Docker, and then start the Docker Desktop application.\n", "\n", "After you've installed Docker, to build the docker image, just navigate to this folder and run:\n", @@ -1715,16 +1717,16 @@ "metadata": {}, "outputs": [], "source": [ - "# Look for the data in /data/ (if running in docker) or in local directory for notebook (data/)\n", - "if os.path.exists('/data'):\n", - " data_path = '/data/'\n", - "elif os.path.exists('data'):\n", + "# Prefer data beside the notebook so CI keeps all files in its work directory.\n", + "if os.path.isdir('data/Pieman2'):\n", " data_path = 'data/'\n", + "elif os.path.isdir('/data/Pieman2') and os.environ.get('BRAINIAK_NOTEBOOK_TEST') != '1':\n", + " data_path = '/data/'\n", "else:\n", " raise ValueError(\"Could not find dataset\")\n", "\n", - "intact = lsdir(os.path.join(data_path, 'Pieman2/sub-*/func/*intact*.nii.gz'))\n", - "scrambled = lsdir(os.path.join(data_path, 'Pieman2/sub-*/func/*word*.nii.gz'))\n", + "intact = sorted(lsdir(os.path.join(data_path, 'Pieman2/sub-*/func/*intact*.nii.gz')))\n", + "scrambled = sorted(lsdir(os.path.join(data_path, 'Pieman2/sub-*/func/*word*.nii.gz')))\n", "\n", "if debug_mode:\n", " intact = intact[:3]\n", @@ -1817,7 +1819,8 @@ " os.makedirs(savedir)\n", "htfa_fname = os.path.join(savedir, 'htfa_' + opts2str(params) + '.pkl')\n", "\n", - "if not os.path.exists(htfa_fname): \n", + "# CI refits the model so a cached pickle cannot hide fitting regressions.\n", + "if not os.path.exists(htfa_fname) or os.environ.get('BRAINIAK_NOTEBOOK_TEST') == '1': \n", " # fit HTFA to htfa_data and save result\n", " htfa.fit([x['Z'] for x in htfa_data], [x['R'] for x in htfa_data])\n", " pkl.dump(htfa2dict(htfa), open(htfa_fname, 'wb'))\n", @@ -2387,8 +2390,8 @@ "# intact\n", "global_centers, global_widths = global_params(htfa)\n", "\n", - "intact_ani = animate_connectome(global_centers, intact_disfc[:max_frames, :], cthresh=cthresh, figdir='intact_frames')\n", - "HTML(intact_ani.to_html5_video())" + "intact_ani = animate_connectome(global_centers, intact_disfc[:max_frames, :], cthresh=cthresh, figdir='intact_frames', force_refresh=True)\n", + "HTML(intact_ani.to_jshtml())" ] }, { @@ -2728,8 +2731,8 @@ ], "source": [ "# scrambled\n", - "scrambled_ani = animate_connectome(global_centers, scrambled_disfc[:max_frames, :], cthresh=cthresh, figdir='scrambled_frames')\n", - "HTML(scrambled_ani.to_html5_video())" + "scrambled_ani = animate_connectome(global_centers, scrambled_disfc[:max_frames, :], cthresh=cthresh, figdir='scrambled_frames', force_refresh=True)\n", + "HTML(scrambled_ani.to_jshtml())" ] }, { diff --git a/docs/examples/iem/download_data.sh b/docs/examples/iem/download_data.sh index 22d762141..fcd01544a 100644 --- a/docs/examples/iem/download_data.sh +++ b/docs/examples/iem/download_data.sh @@ -1,4 +1,19 @@ -#!/bin/bash +#!/usr/bin/env bash +# Reuse complete downloads and never mistake an interrupted transfer for data. +set -euo pipefail -wget -nc https://zenodo.org/record/4950267/files/RademakerEtAl2019_WM_S05_avgTime.npz -wget -nc https://zenodo.org/record/4950267/files/AL61_Bilat-V1_attnContrast.mat +download() { + local filename=$1 url=$2 + if [[ ! -s "$filename" ]]; then + echo "Downloading $filename" + curl --fail --silent --show-error --location --retry 3 \ + --connect-timeout 30 --max-time 600 \ + "$url" --output "$filename.part" + mv "$filename.part" "$filename" + fi +} + +download RademakerEtAl2019_WM_S05_avgTime.npz \ + https://zenodo.org/records/4950267/files/RademakerEtAl2019_WM_S05_avgTime.npz +download AL61_Bilat-V1_attnContrast.mat \ + https://zenodo.org/records/4950267/files/AL61_Bilat-V1_attnContrast.mat diff --git a/docs/examples/iem_synthetic_RF/iem_example_synthetic_RF_data.ipynb b/docs/examples/iem_synthetic_RF/iem_example_synthetic_RF_data.ipynb index a9a214825..8d0bb9f53 100644 --- a/docs/examples/iem_synthetic_RF/iem_example_synthetic_RF_data.ipynb +++ b/docs/examples/iem_synthetic_RF/iem_example_synthetic_RF_data.ipynb @@ -78,7 +78,7 @@ " voxel_tuning = np.linspace(range_start, range_stop, n_voxels+1)\n", " voxel_tuning = voxel_tuning[0:-1]\n", " voxel_tuning = np.floor(voxel_tuning).astype(int)\n", - " gaussian = scipy.signal.gaussian(feature_resolution, 15)\n", + " gaussian = scipy.signal.windows.gaussian(feature_resolution, 15)\n", " voxel_RFs = np.zeros((n_voxels, feature_resolution))\n", " for i in range(0, n_voxels):\n", " voxel_RFs[i, :] = np.roll(gaussian, voxel_tuning[i] - ((feature_resolution//2)-1))\n", diff --git a/docs/examples/isc/download_data.sh b/docs/examples/isc/download_data.sh index 96d9f77bb..a48f2b81f 100644 --- a/docs/examples/isc/download_data.sh +++ b/docs/examples/isc/download_data.sh @@ -1,4 +1,17 @@ -#!/bin/bash +#!/usr/bin/env bash +# Reuse complete downloads and never mistake an interrupted transfer for data. +set -euo pipefail -# Download the data, the python notebook handles extraction and -wget -nc https://zenodo.org/record/4300904/files/brainiak-aperture-isc-data.tgz +download() { + local filename=$1 url=$2 + if [[ ! -s "$filename" ]]; then + echo "Downloading $filename" + curl --fail --silent --show-error --location --retry 3 \ + --connect-timeout 30 --max-time 600 \ + "$url" --output "$filename.part" + mv "$filename.part" "$filename" + fi +} + +download brainiak-aperture-isc-data.tgz \ + https://zenodo.org/records/4300904/files/brainiak-aperture-isc-data.tgz diff --git a/docs/examples/real-time/README_INSTRUCTIONS.md b/docs/examples/real-time/README_INSTRUCTIONS.md index 766c1b1ee..c9d46e7ce 100644 --- a/docs/examples/real-time/README_INSTRUCTIONS.md +++ b/docs/examples/real-time/README_INSTRUCTIONS.md @@ -1,32 +1,48 @@ -# Set Up Instructions for the Real-Time fMRI Cloud-Based Framework - -Here are instructions you have to follow in order to implement our real-time fMRI cloud-based framework when running the [rtcloud_notebook jupyter notebook](https://github.com/brainiak/brainiak-aperture/blob/master/notebooks/real-time/rtcloud_notebook.ipynb). There are some things that you have to set up only once, whereas there are other things you have to do every time before you launch and run the jupyter notebook. - -## Things to do once -Before you can run this notebook, you will have to take the following steps to set up our software framework: - -1. Clone the [brainiak aperture repo](https://github.com/brainiak/brainiak-aperture.git) and the [rtcloud framework repo](https://github.com/brainiak/rt-cloud.git). The location of the repositories do not matter but you should make a note of the paths. -2. Follow [Step 1](https://github.com/brainiak/rt-cloud#step-1-install-mini-conda-and-nodejs) of the installation instructions for the rtcloud framework: Check to see if you have conda, Node.js, and NPM installed. Install these packages if necessary. -3. Create a conda environment that will be specific for the rtcloud framework and activate it: - + `cd /PATH_TO_RTCLOUD/rt-cloud` - + `conda env create -f environment.yml` - + `conda activate rtcloud` -4. Install and build node module dependencies. - + `cd /PATH_TO_RTCLOUD/rt-cloud/web` - + `npm install` - + `npm run build` - -## Things to do every time -Here are the things that you have to do every time before you launch and run this jupyter notebook: - -1. Activate the conda environment for the rtcloud framework: - + `conda activate rtcloud` -2. On the command line, create a global variable to the full path for the rtcloud framework repo. You must do this in order to use the functions we have created for the framework. And don't forget the forward slash "/" at the end. - + `export RTCLOUD_PATH=/PATH_TO_RTCLOUD/rt-cloud/` - + Double check that you did this correctly by typing the following command, which should print the *full* path to the rtcloud framework folder: `ECHO $RTCLOUD_PATH` - -## Common Issues - -- If you get a blank blue screen when you open the localhost with the web server, then you forgot to follow Step 4 above. -- The `/tmp/notebook-simdata` folder is in your root directory. To get there, do `cd /tmp`. You want to delete this `notebook-simdata` folder whenever you want to similate the synthetic data being produced in real-time. -- If `rtCommon` can't be found, then you forgot to run Step 2 of "Things to do every time" above. +# Running the real-time fMRI notebook + +From a BrainIAK checkout, install the example and notebook-test dependencies: + +```bash +uv sync --locked --extra dev --extra matnormal --extra examples +.venv/bin/jupyter notebook docs/examples/real-time/rtcloud_notebook.ipynb +``` + +The notebook runs `download_data.sh` to fetch rt-cloud revision +`00762e7d19dd34ad4df8d1172364f0ad2c1c0dbf` into a local `rt-cloud/` directory. +The script adapts that private copy to bind HTTP only to loopback and to store +its OpenNeuro cache beside the notebook. To use an existing compatible checkout, +set `RTCLOUD_PATH`; that checkout is used without modification. + +The project server needs free localhost ports **8889** (HTTP) and **12345** +(RPC). Restart the notebook kernel between experiments to release its RPC +service. The final cell shuts down the web server and waits for the generator; +background generation failures are reported as notebook errors. + +The notebook generates 200 synthetic DICOM volumes and trains/tests a classifier +through the real rt-cloud RPC interfaces. The synthetic DICOM files contain the +simulator's voxel array but lack scanner geometry, so the example reads them +with pydicom directly. The synthetic ROI is the union of the simulator's two +packaged masks. `dcm2niix` remains necessary for the script's real scanner-data +path, which is not exercised by this tutorial. + +Each run stores its synthetic data in a fresh `simdata-*` directory beside the +notebook. Remove old directories after keeping any required results. When +running pytest with `--notebook-workdir`, all of this data and the rt-cloud +checkout stay under that work directory. + +For automated execution: + +```bash +.venv/bin/python -m pytest tests/test_notebooks.py --enable_notebook_tests \ + -k rtcloud --notebook-workdir /path/to/notebook-cache +``` + +The harness sets `BRAINIAK_NOTEBOOK_TEST=1`, which disables the two-second +real-time pacing while retaining all 200 volumes and the full classification +analysis. It checks RPC/server startup, data generation and classification; +iframe rendering and browser controls require an interactive browser. + +To use those browser controls, install Node.js/npm and build rt-cloud's web +assets with `npm install` and `npm run build` in `rt-cloud/web`, following the +[rt-cloud installation guide](https://github.com/brainiak/rt-cloud#tutorial-rtcloud-installation--usage). +Then open `http://127.0.0.1:8889` and use the demonstration login (`test`/`test`). diff --git a/docs/examples/real-time/download_data.sh b/docs/examples/real-time/download_data.sh new file mode 100644 index 000000000..4e92266ce --- /dev/null +++ b/docs/examples/real-time/download_data.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# Fetch a reproducible rt-cloud checkout for this standalone tutorial. +set -euo pipefail +if [[ -n "${RTCLOUD_PATH:-}" ]]; then + test -f "$RTCLOUD_PATH/rtCommon/projectServer.py" + exit +fi +revision=00762e7d19dd34ad4df8d1172364f0ad2c1c0dbf +if [[ -d rt-cloud ]]; then + if [[ -f rt-cloud/.brainiak-revision ]] && \ + [[ $(cat rt-cloud/.brainiak-revision) == "$revision-notebook1" ]]; then + exit + fi + echo 'Existing rt-cloud directory: set RTCLOUD_PATH to use your own checkout' >&2 + exit 1 +fi +curl --fail --silent --show-error --location --retry 3 \ + --connect-timeout 30 --max-time 600 \ + "https://codeload.github.com/brainiak/rt-cloud/tar.gz/$revision" \ + --output rt-cloud.tar.gz.part +stage=$(mktemp -d rt-cloud.XXXXXX) +trap 'rm -rf "$stage"' EXIT +tar -xzf rt-cloud.tar.gz.part -C "$stage" --strip-components=1 +# The pinned upstream demo binds HTTP on every interface and hard-codes an +# OpenNeuro cache outside the notebook directory. Adapt only this private copy +# to loopback and the notebook's storage; no analysis code is modified. +python3 - "$stage" <<'PY' +from pathlib import Path +import sys +root = Path(sys.argv[1]) / 'rtCommon' +changes = { + 'webServer.py': ( + 'Web.httpServer.listen(Web.httpPort)', + 'Web.httpServer.listen(Web.httpPort, address="127.0.0.1")'), + 'bidsInterface.py': ( + 'OpenNeuroCache(cachePath="/tmp/openneuro")', + 'OpenNeuroCache(cachePath=os.path.join(os.getcwd(), "openneuro-cache"))'), +} +for name, (before, after) in changes.items(): + path = root / name + source = path.read_text() + if source.count(before) != 1: + raise RuntimeError(f'Unexpected rt-cloud source: {name}') + path.write_text(source.replace(before, after)) +PY +printf '%s\n' "$revision-notebook1" > "$stage/.brainiak-revision" +mv "$stage" rt-cloud +rm rt-cloud.tar.gz.part diff --git a/docs/examples/real-time/rtcloud_notebook.ipynb b/docs/examples/real-time/rtcloud_notebook.ipynb index 93b0f3858..260823513 100644 --- a/docs/examples/real-time/rtcloud_notebook.ipynb +++ b/docs/examples/real-time/rtcloud_notebook.ipynb @@ -31,21 +31,15 @@ "\n", "## Before Running This Notebook \n", "\n", - "Before you are able to run this notebook, you have to complete the installation instructions found in the accompanying [instructions README](https://github.com/brainiak/brainiak-aperture/blob/master/notebooks/real-time/README_INSTRUCTIONS.md). **Also, remember that you have to complete the following steps every time before you are able to run this notebook:**\n", - "\n", - "1. Activate the conda environment for the rtcloud framework:\n", - "```\n", - "conda activate rtcloud\n", - "```\n", - "2. On the command line, create a global variable to the full path for the rtcloud framework repo. You must do this in order to use the functions we have created for the framework. And don't forget the forward slash \"/\" at the end.\n", - "```\n", - "export RTCLOUD_PATH=/PATH_TO_RTCLOUD/rt-cloud/\n", - "```\n", - "Double check that you did this correctly by typing the following command. \n", - "```\n", - "ECHO $RTCLOUD_PATH\n", - "```\n", - "This should print the *full* path to the rtcloud framework folder." + "Install BrainIAK's `examples` dependencies and follow the accompanying\n", + "[setup instructions](README_INSTRUCTIONS.md). The first cell downloads a pinned\n", + "rt-cloud revision beside this notebook. If you already have a compatible\n", + "checkout, set `RTCLOUD_PATH` to use it instead.\n", + "\n", + "The managed checkout serves HTTP only on `127.0.0.1:8889`; its RPC service uses\n", + "localhost port 12345. Both ports must be free. The optional browser interface\n", + "requires rt-cloud's JavaScript build; the final cell runs the same experiment\n", + "through RPC without browser interaction.\n" ] }, { @@ -54,13 +48,14 @@ "metadata": {}, "outputs": [], "source": [ - "# If rt-cloud repo is present in local directory and RTCLOUD_PATH is not already set, \n", - "# then set RTCLOUD_PATH to the local repo.\n", + "# Fetch the tested rt-cloud revision unless RTCLOUD_PATH is supplied.\n", "import os\n", - "if 'RTCLOUD_PATH' not in os.environ and os.path.exists('rt-cloud'):\n", - " os.environ['RTCLOUD_PATH'] = os.path.abspath('rt-cloud')\n", - "\n", - "!echo $RTCLOUD_PATH" + "import subprocess\n", + "subprocess.run(['bash', 'download_data.sh'], check=True)\n", + "os.environ.setdefault('RTCLOUD_PATH', os.path.abspath('rt-cloud'))\n", + "# inotify expects DEBUG to be a numeric flag.\n", + "os.environ['DEBUG'] = '0'\n", + "print(os.environ['RTCLOUD_PATH'])\n" ] }, { @@ -81,6 +76,9 @@ "#---- Import the necessary python modules\n", "import sys\n", "import threading\n", + "import tempfile\n", + "import time\n", + "from concurrent.futures import ThreadPoolExecutor\n", "import argparse\n", "import toml\n", "\n", @@ -111,7 +109,10 @@ "\n", "#---- Declare the total number of TRs (timepoints) you want to generate, and how many should be training\n", "num_TRs = 200\n", - "num_training = 100" + "num_training = 100\n", + "# Keep generated data beside the notebook, including during scratch-based CI.\n", + "outdir = tempfile.mkdtemp(prefix='simdata-', dir=path_to_notebook)\n", + "automated = os.environ.get('BRAINIAK_NOTEBOOK_TEST') == '1'\n" ] }, { @@ -139,7 +140,7 @@ " 'isSynthetic' : True, # are we using synthetic data?\n", " 'numSynthetic' : num_TRs, # total number of synthetic TRs\n", " 'numTrainingTRs' : num_training, # number of TRs used for training the classifier\n", - " 'imgDir' : '/tmp/notebook-simdata', # location of synthetic TRs\n", + " 'imgDir' : outdir, # location of synthetic TRs\n", " \n", " 'subjectNum' : 101, # subject number\n", " 'subjectDay' : 1, # study day (relevant if multi-day study)\n", @@ -179,39 +180,35 @@ "args.port = 8889\n", "\n", "\n", - "#---- Start the project server\n", - "def runProjectServer(args):\n", - " projectServer = ProjectServer(args)\n", - " projectServer.start()\n", - "\n", - "\n", - "try:\n", - " project_thread = threading.Thread(name='projectServer', \n", - " target=runProjectServer,\n", - " args=(args,))\n", - " project_thread.setDaemon(True)\n", - " project_thread.start()\n", - "except RuntimeError as err:\n", - " # ignore event loop already running error\n", - " if str(err) != 'This event loop is already running':\n", - " raise" + "#---- Start the project server and wait for RPC readiness.\n", + "# Keep the instance so the final cell can shut down the web server.\n", + "import socket\n", + "for port in (args.port, 12345):\n", + " with socket.socket() as sock:\n", + " sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n", + " sock.bind(('127.0.0.1', port)) # Fail before touching an occupied port.\n", + "project_server = ProjectServer(args)\n", + "project_thread = threading.Thread(\n", + " name='projectServer', target=project_server.start, daemon=True)\n", + "project_thread.start()\n", + "deadline = time.monotonic() + 30\n", + "while True:\n", + " try:\n", + " with socket.create_connection(('127.0.0.1', 12345), timeout=1):\n", + " break\n", + " except OSError:\n", + " if time.monotonic() > deadline:\n", + " raise TimeoutError('rt-cloud RPC server did not start')\n", + " time.sleep(0.1)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "***\n", - "\n", - "**IMPORTANT:**\n", - "\n", - "You can only run this cell to start the projectInterface web server only once or else you will get the following runtime error: \n", - "```\n", - "Web Server already running\n", - "```\n", - "If you want to re-start the web server, you have to first SHUT DOWN the kernel. Instructions for doing this can be found [here](https://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/execute.html#close-a-notebook-kernel-shut-down).\n", - "\n", - "***" + "The notebook starts its own local project server and waits for the RPC service.\n", + "The final cell stops the web server; shutting down the kernel also releases the RPC service.\n", + "Restart the kernel before starting another experiment.\n" ] }, { @@ -229,38 +226,34 @@ "metadata": {}, "outputs": [], "source": [ - "#---- Set up the parameters for the synthetic data generator\n", - "\n", - "sim_settings = sim.default_settings\n", + "# Generate the full 200-TR experiment; CI omits only the two-second pacing.\n", + "sim_settings = sim.default_settings.copy()\n", "sim_settings['save_dicom'] = True\n", - "sim_settings['save_realtime'] = True\n", + "sim_settings['save_realtime'] = not automated\n", "sim_settings['numTRs'] = num_TRs\n", "sim_settings['different_ROIs'] = True\n", "sim_settings['scale_percentage'] = 1\n", "\n", - "outdir = '/tmp/notebook-simdata'\n", - "if not os.path.exists(outdir):\n", - " os.makedirs(outdir)\n", - "\n", - "#---- Run sim.generate_data(outdir, sim_settings) as a thread\n", - "\n", - "syndata_thread = threading.Thread(name='syndata', \n", - " target=sim.generate_data, \n", - " args=(outdir, sim_settings))\n", - "syndata_thread.setDaemon(True)\n", - "syndata_thread.start()" + "# Futures propagate generator errors instead of losing them in a thread.\n", + "executor = ThreadPoolExecutor(max_workers=1)\n", + "syndata_future = executor.submit(sim.generate_data, outdir, sim_settings)\n", + "# Wait for the first image (noise generation precedes streaming).\n", + "deadline = time.monotonic() + 300\n", + "while not os.path.exists(os.path.join(outdir, 'rt_000.dcm')):\n", + " if syndata_future.done():\n", + " syndata_future.result()\n", + " if time.monotonic() > deadline:\n", + " raise TimeoutError('Synthetic data generation did not start')\n", + " time.sleep(0.1)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "***\n", - "**IMPORTANT:**\n", - "\n", - "You can only run this cell to generate the synthetic data in \"real-time\" once unless you delete the data that you have already created. Otherwise, all the data (which is found in the `/tmp/notebook-simdata` folder) will be automatically available when you open the web server, instead of having the File Watcher wait for incoming data one TR at a time.\n", - "\n", - "***" + "Each execution creates a new `simdata-*` directory beside the notebook.\n", + "This prevents old images from being mistaken for a new scanning run.\n", + "After keeping any results you need, remove old simulation directories to reclaim space.\n" ] }, { @@ -311,9 +304,15 @@ "metadata": {}, "outputs": [], "source": [ - "# Run the classification script directly by importing the scripts main function.\n", + "# Run the complete classifier through the rt-cloud RPC service.\n", "from sample import main\n", - "main(['-c', configFile])" + "try:\n", + " accuracy = main(['-c', configFile])\n", + " syndata_future.result(timeout=600)\n", + " assert 0 <= accuracy <= 1\n", + "finally:\n", + " executor.shutdown(wait=True)\n", + " project_server.stop()\n" ] }, { diff --git a/docs/examples/real-time/sample.py b/docs/examples/real-time/sample.py index ea30233b0..c8b715c2f 100644 --- a/docs/examples/real-time/sample.py +++ b/docs/examples/real-time/sample.py @@ -30,7 +30,7 @@ import numpy as np import nibabel as nib import scipy.io as sio -from nilearn.input_data import NiftiMasker +from nilearn.maskers import NiftiMasker from sklearn import preprocessing from sklearn import svm import nilearn @@ -67,7 +67,7 @@ def doRuns(cfg, dataInterface, subjInterface, webInterface): to a subjectService running on the presentation computer to provide feedback to the subject (and optionally get their response). OUTPUT: - None. + Classification accuracy on the held-out synthetic volumes. """ # variables we'll use throughout @@ -132,20 +132,38 @@ def doRuns(cfg, dataInterface, subjInterface, webInterface): # We can use the 'convertDicomFileToNifti' function with dicomData as # input to get the data in NifTi format - base, ext = os.path.splitext(fileName) - assert ext == '.dcm' - niftiFilename = base + '.nii' - convertDicomFileToNifti(fileName, niftiFilename) - niftiObject = readNifti(niftiFilename) - + if dicomData is None: + raise TimeoutError(f"No complete DICOM received: {fileName}") + if cfg.isSynthetic: + # fmrisim stores the complete synthetic 3-D array in pixel_array; + # its minimal DICOM header is not a scanner geometry description. + # Preserve the simulator's voxel order instead of using dcm2niix. + niftiObject = nib.Nifti1Image( + dicomData.pixel_array.astype(np.float32), np.eye(4)) + else: + base, ext = os.path.splitext(fileName) + assert ext == '.dcm' + niftiFilename = base + '.nii' + convertDicomFileToNifti(fileName, niftiFilename) + niftiObject = readNifti(niftiFilename) + # declare various things if it's the first TR if this_TR == 0: - # load the labels and mask labels = np.load(os.path.join(cfg.imgDir, 'labels.npy')) - print(os.path.join(cfg.imgDir, 'labels.npy')) - ROI_nib = nib.load(os.path.join(currPath,'ROI_mask.nii.gz')) - ROI_mask = np.array(ROI_nib.dataobj) - mask_nib = nib.Nifti1Image(ROI_mask.T, affine=niftiObject.affine) + if cfg.isSynthetic: + from importlib.resources import files + import gzip + masks = [] + for name in ['ROI_A.nii.gz', 'ROI_B.nii.gz']: + resource = files('brainiak').joinpath( + 'utils/sim_parameters', name) + masks.append(nib.Nifti1Image.from_bytes( + gzip.decompress(resource.read_bytes())).get_fdata()) + ROI_mask = np.logical_or(*masks).astype(np.uint8) + else: + ROI_nib = nib.load(os.path.join(currPath, 'ROI_mask.nii.gz')) + ROI_mask = np.array(ROI_nib.dataobj).T + mask_nib = nib.Nifti1Image(ROI_mask, affine=niftiObject.affine) # declare the number of TRs we will shift the data to account for the hemodynamic lag num_shiftTRs = 3 # shift the labels to account for hemodynamic lag @@ -190,12 +208,12 @@ def doRuns(cfg, dataInterface, subjInterface, webInterface): if shifted_labels[this_TR] != 0: prediction = clf.predict(scaler.transform(preprocessed_data[this_TR,:].reshape(1,-1))) print(f'Plotting classifier prediction for TR {this_TR}: {prediction}') - webInterface.plotDataPoint(runNum, int(this_TR), float(prediction)) + webInterface.plotDataPoint(runNum, int(this_TR), float(prediction.item())) # To send feedback for the subject at the presentation computer use # the subjInterface as shown below. For this demo there is no # presentation computer so we won't actually it. - # subjInterface.setResult(runNum, int(this_TR), float(prediction)) + # subjInterface.setResult(runNum, int(this_TR), float(prediction.item())) else: print(f'Skipping classification because it is a rest trial') @@ -216,7 +234,7 @@ def doRuns(cfg, dataInterface, subjInterface, webInterface): "###################################################################################\n" "REAL-TIME EXPERIMENT COMPLETE!") - return + return accuracy_score def main(argv=None): """ @@ -269,9 +287,8 @@ def main(argv=None): # feedback to the subject (and optionally get their response). # [4] webInterface - this allows updating information on the experimenter webpage. # For example to plot data points, or update status messages. - doRuns(cfg, dataInterface, subjInterface, webInterface) + return doRuns(cfg, dataInterface, subjInterface, webInterface) - return 0 if __name__ == "__main__": diff --git a/docs/examples/requirements-examples.txt b/docs/examples/requirements-examples.txt index 6001164e5..6f5741945 100644 --- a/docs/examples/requirements-examples.txt +++ b/docs/examples/requirements-examples.txt @@ -7,6 +7,7 @@ seaborn holoviews pyOpenSSL awscli +boto3 bcrypt indexed_gzip inflect diff --git a/docs/examples/srm/SRM.ipynb b/docs/examples/srm/SRM.ipynb index 0def4d3ae..ee0a0e55a 100644 --- a/docs/examples/srm/SRM.ipynb +++ b/docs/examples/srm/SRM.ipynb @@ -93,9 +93,9 @@ } ], "source": [ - "# Download and extract example data from Zenodo\n", - "!wget -nc https://zenodo.org/record/4300825/files/brainiak-aperture-srm-data.tgz\n", - "!tar --skip-old-files -xzf brainiak-aperture-srm-data.tgz\n" + "# Download and extract example data, reusing complete local files.\n", + "import subprocess\n", + "subprocess.run(['bash', 'download_data.sh'], check=True)\n" ] }, { diff --git a/docs/examples/srm/download_data.sh b/docs/examples/srm/download_data.sh index f2374820b..466f2fd29 100644 --- a/docs/examples/srm/download_data.sh +++ b/docs/examples/srm/download_data.sh @@ -1,3 +1,12 @@ -#!/bin/bash - -wget -nc https://zenodo.org/record/4300825/files/brainiak-aperture-srm-data.tgz +#!/usr/bin/env bash +set -euo pipefail +archive=brainiak-aperture-srm-data.tgz +if [[ ! -s "$archive" ]]; then + curl --fail --location --retry 3 --connect-timeout 30 --max-time 3600 \ + "https://zenodo.org/records/4300825/files/$archive" --output "$archive.part" + mv "$archive.part" "$archive" +fi +if [[ ! -f brainiak-aperture-srm-data/.extracted ]]; then + tar -xzf "$archive" + touch brainiak-aperture-srm-data/.extracted +fi diff --git a/docs/newsfragments/+notebook-examples.bugfix.rst b/docs/newsfragments/+notebook-examples.bugfix.rst new file mode 100644 index 000000000..95bef0740 --- /dev/null +++ b/docs/newsfragments/+notebook-examples.bugfix.rst @@ -0,0 +1,5 @@ +Repair the FCMA, HTFA, SRM, and real-time notebook examples for automated +execution, including reproducible data downloads, current dependency APIs, +MPI subprocess error reporting, and the synthetic real-time data path. +FCMA now selects exactly the requested number of voxels, including rank zero, +without requiring FSL. diff --git a/pyproject.toml b/pyproject.toml index 9cfd856f9..9981fcc09 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -122,7 +122,8 @@ examples = [ "wsaccel", "inotify", "pybids", - "watchdog" + "watchdog", + "boto3", ] all=['brainiak[dev,matnormal,examples]'] diff --git a/tests/conftest.py b/tests/conftest.py index f76452096..22f0efb4b 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -12,7 +12,9 @@ def pytest_configure(config): - config.option.xmlpath = "junit-{}.xml".format(MPI.COMM_WORLD.Get_rank()) + # Honour an explicit report destination, e.g. a scratch directory in CI. + if not config.option.xmlpath: + config.option.xmlpath = f"junit-{MPI.COMM_WORLD.Get_rank()}.xml" def pytest_addoption(parser): @@ -24,6 +26,15 @@ def pytest_addoption(parser): help="Enable tests for Jupyter notebook examples in docs/examples. " "These can take a long time and are disabled by default.", ) + parser.addoption( + "--notebook-workdir", + help="Copy notebooks here before executing. Reuses datasets; " + "do not share this directory between concurrent pytest processes.", + ) + parser.addoption( + "--notebook-timeout", type=int, default=3600, + help="Maximum execution time per notebook cell, in seconds.", + ) def pytest_collection_modifyitems(config, items): diff --git a/tests/pytest_mpiexec_plugin.py b/tests/pytest_mpiexec_plugin.py index b82f60438..f3ee3c208 100644 --- a/tests/pytest_mpiexec_plugin.py +++ b/tests/pytest_mpiexec_plugin.py @@ -91,7 +91,7 @@ def pytest_unconfigure(config): reporter.close() -def mpi_runtest_protocol(item): +def mpi_runtest_protocol(item, nextitem): """The runtest protocol for mpi tests Runs the test in an mpiexec subprocess @@ -105,6 +105,18 @@ def mpi_runtest_protocol(item): if call.excinfo: report = hook.pytest_runtest_makereport(item=item, call=call) hook.pytest_runtest_logreport(report=report) + # A preceding ordinary test may have left module/session fixtures active + # because its next item was this MPI test. Advance the parent's teardown + # state too, even though the MPI test itself ran in child processes. + if item.session.shouldfail or item.session.shouldstop: + nextitem = None + # Do not call the item's teardown hooks: its setup hooks (including + # pytest's logging/capture setup) were only run in the child processes. + teardown = pytest.CallInfo.from_call( + partial(item.session._setupstate.teardown_exact, nextitem), "teardown") + if teardown.excinfo: + report = hook.pytest_runtest_makereport(item=item, call=teardown) + hook.pytest_runtest_logreport(report=report) hook.pytest_runtest_logfinish(nodeid=item.nodeid, location=item.location) @@ -118,7 +130,7 @@ def pytest_runtest_protocol(item, nextitem): mpi_mark = item.get_closest_marker(MPI_MARKER_NAME) if not mpi_mark: return - mpi_runtest_protocol(item) + mpi_runtest_protocol(item, nextitem) return True diff --git a/tests/test_della_runner.py b/tests/test_della_runner.py new file mode 100644 index 000000000..ab6b61ebb --- /dev/null +++ b/tests/test_della_runner.py @@ -0,0 +1,181 @@ +"""Exercise the direct Della launcher locally, without datasets or SSH.""" + +import json +import os +from pathlib import Path +import shlex +import signal +import subprocess +import sys +import time + +import pytest + + +LAUNCHER = (Path(__file__).resolve().parents[1] + / ".github/scripts/della-run.py") +MPI_WRAPPER = LAUNCHER.with_name("della-mpiexec.sh") +pytestmark = pytest.mark.skipif(sys.platform != "linux", + reason="Della launcher uses Linux /proc") + + +@pytest.fixture +def runner(tmp_path): + launcher = tmp_path / "della-run.py" + launcher.write_text(LAUNCHER.read_text()) + script = tmp_path / "della-test.sh" + script.write_text(f"exec {shlex.quote(sys.executable)} " + f"{shlex.quote(str(tmp_path / 'child.py'))}\n") + (tmp_path / "child.py").write_text(''' +import json, os, pathlib, resource, sys +root = pathlib.Path(os.environ['BRAINIAK_TEST_ROOT']) +(root / 'child.json').write_text(json.dumps({ + 'cpus': sorted(os.sched_getaffinity(0)), + 'count': os.environ['BRAINIAK_TEST_CPUS'], + 'nice': os.nice(0), + 'core_limit': resource.getrlimit(resource.RLIMIT_CORE), +})) +sys.exit(int(os.environ.get('TEST_STATUS', '0'))) +''') + env = dict(os.environ, BRAINIAK_TEST_ROOT=str(tmp_path), + GITHUB_RUN_ID="123", GITHUB_RUN_ATTEMPT="2", DELLA_CPUS="") + return launcher, env + + +@pytest.mark.parametrize("status", [0, 7]) +@pytest.mark.parametrize("suite,count,gib,seconds", [ + ("smoke", 1, 8, 1200), + ("notebooks", 2, 32, 10800), + ("unit", 2, 32, 10800), + ("all", 2, 32, 10800), +]) +def test_exit_status_and_limits(runner, status, suite, count, gib, seconds): + launcher, env = runner + if len(os.sched_getaffinity(0)) < count: + pytest.skip("Not enough local CPUs for this profile") + env["TEST_STATUS"] = str(status) + result = subprocess.run([sys.executable, str(launcher), suite], env=env, + capture_output=True, text=True, timeout=10) + assert result.returncode == status, result.stderr + root = launcher.parent + child = json.loads((root / "child.json").read_text()) + limits = json.loads((root / "runs/123-2/reports/limits.json").read_text()) + assert child["cpus"] == limits["cpus"] + assert len(child["cpus"]) == count + assert child["count"] == str(count) + assert child["nice"] >= 10 + assert child["core_limit"] == [0, 0] + assert limits["rss_budget_gib"] == gib + assert limits["wall_seconds"] == seconds + + +def wait_for_file(path, process): + deadline = time.monotonic() + 5 + while not path.exists(): + assert process.poll() is None, process.communicate() + assert time.monotonic() < deadline, f"Child did not create {path}" + time.sleep(0.02) + + +def test_cancel_reaps_detached_kernel_and_releases_lock(runner): + launcher, env = runner + root = launcher.parent + # Orphan a detached kernel that ignores SIGTERM to exercise SIGKILL. + kernel = ("import os, pathlib, signal, time; " + "signal.signal(signal.SIGTERM, signal.SIG_IGN); " + f"pathlib.Path({str(root / 'kernel.pid')!r})" + ".write_text(str(os.getpid())); time.sleep(60)") + spawner = ("import subprocess, sys; " + f"subprocess.Popen([sys.executable, '-c', {kernel!r}], " + "start_new_session=True)") + (root / "child.py").write_text( + "import subprocess, sys, time\n" + f"subprocess.run([sys.executable, '-c', {spawner!r}], check=True)\n" + "time.sleep(60)\n") + process = subprocess.Popen([sys.executable, str(launcher), "smoke"], + env=env, stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + kernel_pid = None + try: + wait_for_file(root / "kernel.pid", process) + kernel_pid = int((root / "kernel.pid").read_text()) + second = subprocess.run([sys.executable, str(launcher), "smoke"], + env=env, capture_output=True, timeout=5) + assert second.returncode == 1 + assert b"holds the lock" in second.stderr + process.send_signal(signal.SIGTERM) + process.communicate(timeout=8) + assert process.returncode == 143 + assert not Path(f"/proc/{kernel_pid}").exists() + (root / "child.py").write_text("pass\n") + retry = subprocess.run([sys.executable, str(launcher), "smoke"], + env=env, capture_output=True, timeout=5) + assert retry.returncode == 0, retry.stderr + finally: + if process.poll() is None: + process.kill() + process.wait() + if kernel_pid and Path(f"/proc/{kernel_pid}").exists(): + os.kill(kernel_pid, signal.SIGKILL) + + +@pytest.mark.parametrize("memory_bytes,wall_seconds,status", [ + (1024**3, 2, 124), + (16 * 1024**2, 10, 137), +]) +def test_timeout_and_memory_guard( + tmp_path, memory_bytes, wall_seconds, status): + child = ("import os, pathlib, time; " + "data = bytearray(32 * 1024**2); " + f"pathlib.Path({str(tmp_path / 'pid')!r})" + ".write_text(str(os.getpid())); time.sleep(60)") + command = [sys.executable, "-c", child] + supervisor = ( + "import os, runpy; " + f"run = runpy.run_path({str(LAUNCHER)!r}); " + f"raise SystemExit(run['supervise']({command!r}, " + "cpus=[min(os.sched_getaffinity(0))], " + f"memory_bytes={memory_bytes}, wall_seconds={wall_seconds}, " + "env=os.environ))") + result = subprocess.run([sys.executable, "-c", supervisor], + capture_output=True, text=True, timeout=8) + assert result.returncode == status, result.stderr + pid = int((tmp_path / "pid").read_text()) + assert not Path(f"/proc/{pid}").exists() + + +def test_explicit_cpu_selection(runner): + launcher, env = runner + selected = max(os.sched_getaffinity(0)) + env["DELLA_CPUS"] = str(selected) + result = subprocess.run([sys.executable, str(launcher), "smoke"], + env=env, capture_output=True, timeout=5) + assert result.returncode == 0, result.stderr + child = json.loads((launcher.parent / "child.json").read_text()) + assert child["cpus"] == [selected] + for invalid in (str(selected + 1), "not-a-cpu"): + env["DELLA_CPUS"] = invalid + result = subprocess.run([sys.executable, str(launcher), "smoke"], + env=env, capture_output=True, timeout=5) + assert result.returncode == 2 + + +def test_mpi_stays_local_and_rejects_excess_ranks(tmp_path): + fake_mpi = tmp_path / "mpiexec" + fake_mpi.write_text(f"#!{sys.executable}\n" + "import json, sys\n" + "print(json.dumps(sys.argv[1:]))\n") + fake_mpi.chmod(0o755) + env = dict(os.environ, PATH=f"{tmp_path}:{os.environ['PATH']}", + BRAINIAK_TEST_CPUS="2") + result = subprocess.run(["bash", str(MPI_WRAPPER), "-n", "2", "python"], + env=env, capture_output=True, text=True, timeout=5) + assert result.returncode == 0, result.stderr + args = json.loads(result.stdout) + assert args[args.index("--host") + 1] == "localhost:2" + assert args[args.index("--bind-to") + 1] == "none" + assert args[-3:] == ["-n", "2", "python"] + for count in ("3", "64", ""): + result = subprocess.run(["bash", str(MPI_WRAPPER), "-n", count], + env=env, capture_output=True, timeout=5) + assert result.returncode == 2 diff --git a/tests/test_mpi_plugin.py b/tests/test_mpi_plugin.py new file mode 100644 index 000000000..e7a028306 --- /dev/null +++ b/tests/test_mpi_plugin.py @@ -0,0 +1,48 @@ +"""Parent fixtures must be torn down across ordinary/MPI test boundaries.""" + +import os +from pathlib import Path +import subprocess +import sys + + +def test_teardown_after_mpi_item(tmp_path): + (tmp_path / "conftest.py").write_text(''' +from tests import pytest_mpiexec_plugin as plugin + +# Exercise the parent's protocol without requiring an MPI launch. Child +# execution/report replay does not touch the parent's fixture stack. +def pytest_configure(config): + plugin.mpi_runtest = lambda item: None +''') + (tmp_path / "test_first.py").write_text(''' +import pytest +from pathlib import Path + +@pytest.fixture(scope="module", autouse=True) +def resource(): + yield + Path("finalized").touch() + +def test_local(): + pass + +@pytest.mark.mpiexec(n=2) +def test_mpi(): + pass +''') + (tmp_path / "test_next.py").write_text(''' +from pathlib import Path + +def test_after_mpi(): + assert Path("finalized").exists() +''') + repo = Path(__file__).resolve().parents[1] + env = dict(os.environ, PYTHONPATH=str(repo)) + result = subprocess.run( + [sys.executable, "-m", "pytest", "-p", "tests.pytest_mpiexec_plugin", + "-q", "test_first.py", "test_next.py"], + cwd=tmp_path, env=env, capture_output=True, text=True, timeout=30, + ) + assert result.returncode == 0, result.stdout + result.stderr + assert "2 passed" in result.stdout diff --git a/tests/test_notebook_examples.py b/tests/test_notebook_examples.py new file mode 100644 index 000000000..2f95a7e1e --- /dev/null +++ b/tests/test_notebook_examples.py @@ -0,0 +1,38 @@ +"""Regression checks for algorithms used by the documentation notebooks.""" + +from pathlib import Path +import runpy + +import nibabel as nib +import numpy as np +import pytest + + +EXAMPLES = Path(__file__).resolve().parents[1] / 'docs/examples' + + +def test_fcma_top_voxels_include_rank_zero_and_exclude_background(tmp_path): + make_masks = runpy.run_path(str( + EXAMPLES / 'fcma/FCMA_script/make_top_voxel_mask.py'))['make_masks'] + affine = np.diag([2., 3., 4., 1.]) + # Background and the best voxel both contain zero in FCMA's rank image. + mask = np.array([0, 1, 1, 1, 0, 1], dtype=np.uint8).reshape(2, 3, 1) + mask_path = tmp_path / 'mask.nii.gz' + nib.save(nib.Nifti1Image(mask, affine), mask_path) + for fold, values in enumerate([[0, 0, 1, 2, 0, 3], [0, 3, 2, 1, 0, 0]]): + ranks = np.array(values, dtype=np.int32).reshape(mask.shape) + nib.save(nib.Nifti1Image(ranks, affine), + tmp_path / f'fc_no{fold}_result_seq.nii.gz') + output = tmp_path / 'top_2' + make_masks(tmp_path, 2, output, mask_path) + first = nib.load(output / 'fc_no0_result_seq_top2.nii.gz') + np.testing.assert_array_equal( + first.get_fdata().ravel(), [0, 1, 1, 0, 0, 0]) + np.testing.assert_array_equal(first.affine, affine) + stacked = nib.load(output / 'all_top2.nii.gz').get_fdata() + assert stacked.shape == (2, 3, 1, 2) + np.testing.assert_array_equal(stacked.sum(axis=(0, 1, 2)), [2, 2]) + probability = nib.load(output / 'prop_top2.nii.gz').get_fdata() + np.testing.assert_array_equal(probability.ravel(), [0, .5, .5, .5, 0, .5]) + with pytest.raises(ValueError, match='expected exactly 5 voxels'): + make_masks(tmp_path, 5, output, mask_path) diff --git a/tests/test_notebook_runner.py b/tests/test_notebook_runner.py new file mode 100644 index 000000000..3b475db37 --- /dev/null +++ b/tests/test_notebook_runner.py @@ -0,0 +1,80 @@ +"""Regression checks for notebook discovery, isolation, and failure reports.""" + +from pathlib import Path +from types import SimpleNamespace + +import nbformat +from nbclient.exceptions import CellExecutionError +import pytest + +from tests import test_notebooks as notebooks + + +def test_discovery_outside_repo(tmp_path, monkeypatch): + examples = tmp_path / "examples" + (examples / "iem").mkdir(parents=True) + (examples / "srm").mkdir() + (examples / "real-time/rt-cloud/docs").mkdir(parents=True) + (examples / "iem/.ipynb_checkpoints").mkdir() + for name in ("iem/iem.ipynb", "srm/SRM.ipynb", + "iem/iem.executed.ipynb", + "real-time/rt-cloud/docs/dependency.ipynb", + "iem/.ipynb_checkpoints/iem-checkpoint.ipynb"): + (examples / name).touch() + monkeypatch.setattr(notebooks, "EXAMPLES", examples) + monkeypatch.chdir(tmp_path) + cases = list(notebooks.notebook_cases()) + assert [case.id for case in cases] == ["iem/iem.ipynb", "srm/SRM.ipynb"] + assert all(not case.marks for case in cases) + assert all(Path(case.values[0]).is_absolute() for case in cases) + + +@pytest.mark.parametrize("fail", [False, True]) +def test_kernel_workdir_and_saved_output(tmp_path, monkeypatch, fail): + source = tmp_path / "source" + example = source / "example" + example.mkdir(parents=True) + path = example / "example.ipynb" + (example / "fixture.txt").write_text("fixture") + code = ( + "from pathlib import Path\n" + "assert Path('fixture.txt').read_text() == 'fixture'\n" + "Path('generated.txt').write_text('result')\n" + + ("raise ValueError('expected failure')" if fail else "print('ok')") + ) + nb = nbformat.v4.new_notebook( + cells=[nbformat.v4.new_code_cell(code), nbformat.v4.new_code_cell( + "print('fresh')", execution_count=42, + outputs=[nbformat.v4.new_output( + "stream", name="stdout", text="stale output")])], + metadata={"kernelspec": { + "name": "nonexistent-contributor-kernel", + "display_name": "Old local kernel", "language": "python", + }}, + ) + nbformat.write(nb, path) + original = path.read_bytes() + workdir = tmp_path / "work" + options = {"--notebook-workdir": str(workdir), "--notebook-timeout": 30} + request = SimpleNamespace(config=SimpleNamespace(getoption=options.get)) + monkeypatch.setattr(notebooks, "EXAMPLES", source) + cwd = Path.cwd() + with monkeypatch.context() as execution_patch: + if fail: + with pytest.raises(CellExecutionError, match="expected failure"): + notebooks.test_notebook(path, request, execution_patch) + else: + notebooks.test_notebook(path, request, execution_patch) + assert Path.cwd() == cwd + assert path.read_bytes() == original + assert not (example / "generated.txt").exists() + assert (workdir / "example/generated.txt").read_text() == "result" + executed = nbformat.read(workdir / "example/example.executed.ipynb", 4) + assert executed.cells[0].execution_count == 1 + assert executed.cells[0].outputs[-1].output_type == ( + "error" if fail else "stream") + if fail: + assert executed.cells[1].execution_count is None + assert executed.cells[1].outputs == [] + else: + assert executed.cells[1].outputs[0].text == "fresh\n" diff --git a/tests/test_notebooks.py b/tests/test_notebooks.py index 34634a515..592ac5ae3 100644 --- a/tests/test_notebooks.py +++ b/tests/test_notebooks.py @@ -1,90 +1,64 @@ -import os -import glob -import pytest - -from testbook import testbook - - -nb_files = glob.glob("docs/examples/**/*.ipynb", recursive=True) - -mpi_notebooks = ["htfa", "FCMA", "SRM"] - -nb_tests = [] -for f in nb_files: - # Mark notebooks that need MPI to skip for now, - # we are having some issues on della - if any([nb in f for nb in mpi_notebooks]): - nb_tests.append( - pytest.param( - f, - marks=pytest.mark.skip( - "notebooks that require MPI are WIP on della" - ), - ) - ) - elif "rtcloud" in f: - nb_tests.append( - pytest.param( - f, marks=pytest.mark.skip("rtcloud is failing on della") - ) - ) - elif "Matrix-normal" in f: - nb_tests.append( - pytest.param( - f, - marks=pytest.mark.skip( - "Matrix-normal notebook is flaky, disabled for now" - ), - ) - ) - else: - nb_tests.append(f) # type: ignore - +"""Execute documentation notebooks, optionally in a separate directory.""" -# Helper function to mark specific notebooks as expected failure. -def mark_xfail(nb, **kwargs): - nb_index = None - for i, nb_file in enumerate(nb_files): - if nb in nb_file: - nb_index = i - - if nb_index is None: - raise ValueError( - f"Cannot set notebook {nb} to xfail because it could not be found" - ) - - nb_files[nb_index] = pytest.param(nb, marks=pytest.mark.xfail(**kwargs)) - - -# mark_xfail('rtcloud_notebook.ipynb', -# reason="Needs to have a web server installed, " -# "will probably need to run this in " -# "singularity on della") +from pathlib import Path +import shutil +import subprocess +import nbformat +import pytest +from testbook import testbook -@pytest.fixture(autouse=True) -def chdir_back_to_root(): - """ - This fixture sets up and tears down state before each example is run. - Certain examples require that they are run from the local directory in - which they reside. This changes directory. It reverses this after the - test finishes. - """ - # Get the current directory before running the test - cwd = os.getcwd() +EXAMPLES = Path(__file__).resolve().parents[1] / "docs" / "examples" - yield - # After the test, we need chdir back to root of the repo - os.chdir(cwd) +def notebook_cases(): + for path in sorted(EXAMPLES.rglob("*.ipynb")): + if (".ipynb_checkpoints" in path.parts + or "rt-cloud" in path.relative_to(EXAMPLES).parts + or path.name.endswith(".executed.ipynb")): + continue + relative = path.relative_to(EXAMPLES) + yield pytest.param(path, id=relative.as_posix()) @pytest.mark.notebook -@pytest.mark.parametrize("notebook_file", nb_tests) -def test_notebook(notebook_file): - - os.chdir(os.path.dirname(notebook_file)) - - with testbook(os.path.basename(notebook_file), execute=True, timeout=3600): - pass +@pytest.mark.parametrize("notebook_file", list(notebook_cases())) +def test_notebook(notebook_file, request, monkeypatch): + work_root = request.config.getoption("--notebook-workdir") + if work_root: + # Keep relative fixtures beside their notebook. Reusing this directory + # also reuses downloads; callers must serialize access to it. + workdir = (Path(work_root).resolve() + / notebook_file.parent.relative_to(EXAMPLES)) + if workdir != notebook_file.parent: + shutil.copytree(notebook_file.parent, workdir, dirs_exist_ok=True, + ignore=shutil.ignore_patterns( + ".ipynb_checkpoints", "*.executed.ipynb")) + else: + workdir = notebook_file.parent + + monkeypatch.chdir(workdir) + # Keep interactive examples unattended while retaining their full analyses. + monkeypatch.setenv("BRAINIAK_NOTEBOOK_TEST", "1") + download = workdir / "download_data.sh" + if download.exists(): + subprocess.run(["bash", str(download)], check=True, timeout=3600) + + # Ignore kernelspec names saved from a contributor's local environment. + # The runner installs python3's kernelspec in the test environment. + notebook = nbformat.read(workdir / notebook_file.name, as_version=4) + for cell in notebook.cells: + if cell.cell_type == "code": + cell.outputs = [] + cell.execution_count = None + cell.metadata.pop("execution", None) + with testbook(notebook, kernel_name="python3", + timeout=request.config.getoption( + "--notebook-timeout")) as tb: + try: + tb.execute() + finally: + # Include partially executed notebooks when a cell fails. + output = workdir / (notebook_file.stem + ".executed.ipynb") + nbformat.write(tb.nb, output) diff --git a/uv.lock b/uv.lock index 2772c3566..26aebed0b 100644 --- a/uv.lock +++ b/uv.lock @@ -338,6 +338,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f6/a8/877f306720bc114c612579c5af36bcb359026b83d051226945499b306b1a/bokeh-3.8.2-py3-none-any.whl", hash = "sha256:5e2c0d84f75acb25d60efb9e4d2f434a791c4639b47d685534194c4e07bd0111", size = 7207131, upload-time = "2026-01-06T00:20:04.917Z" }, ] +[[package]] +name = "boto3" +version = "1.43.28" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "botocore" }, + { name = "jmespath" }, + { name = "s3transfer" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/4e/f2/a976b2a81d8dc7ff675f4b614367a185727061130184a28da0f53f446b97/boto3-1.43.28.tar.gz", hash = "sha256:8391fdcc4d8e1d4e0bf96575a7e5610964a4d401dafa4dccb0a5bade8dd3fbb0", size = 113202, upload-time = "2026-06-11T19:29:01.464Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c3/a5/47db150ea6380f11569b87d3ad064e3c929e5abe227a549d472fab6f5f3a/boto3-1.43.28-py3-none-any.whl", hash = "sha256:4fe6df2163aea02b561eca0d685e2f41a059d71f03721a3e79c3b522e79a3b56", size = 140536, upload-time = "2026-06-11T19:29:00.143Z" }, +] + [[package]] name = "botocore" version = "1.43.28" @@ -376,6 +390,7 @@ dependencies = [ all = [ { name = "awscli" }, { name = "bcrypt" }, + { name = "boto3" }, { name = "coverage" }, { name = "flake8" }, { name = "flake8-print" }, @@ -440,6 +455,7 @@ dev = [ examples = [ { name = "awscli" }, { name = "bcrypt" }, + { name = "boto3" }, { name = "holoviews" }, { name = "indexed-gzip" }, { name = "inflect" }, @@ -479,6 +495,7 @@ matnormal = [ requires-dist = [ { name = "awscli", marker = "extra == 'examples'" }, { name = "bcrypt", marker = "extra == 'examples'" }, + { name = "boto3", marker = "extra == 'examples'" }, { name = "brainiak", extras = ["dev", "examples", "matnormal"], marker = "extra == 'all'" }, { name = "coverage", marker = "extra == 'dev'" }, { name = "flake8", marker = "extra == 'dev'" },