Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,27 @@ jobs:
- name: Stop container
if: always()
run: docker rm -f chapkit-ci
- name: Start container from the MLproject
run: docker run -d --name chapkit-ci-mlproject -p 8000:8000 chapkit-ghr-model:ci chapkit mlproject run . --host 0.0.0.0 --port 8000
- name: Wait for /health (MLproject)
run: |
for i in $(seq 1 60); do
if curl -fsS http://localhost:8000/health | grep -q '"healthy"'; then
echo "Service healthy after ${i} attempt(s)"
exit 0
fi
sleep 2
done
echo "Service did not become healthy within 120s"
exit 1
- name: Run chapkit test against the MLproject service
run: uv run chapkit test --url http://localhost:8000 --rows 400 --predict-rows 200 --timeout 1200 --verbose
# Real data with geometry, and checks the config reached the scripts.
- name: Run API smoke test against the MLproject service
run: python3 tools/api_smoke.py http://localhost:8000
- name: MLproject container logs on failure
if: failure()
run: docker logs chapkit-ci-mlproject
- name: Stop MLproject container
if: always()
run: docker rm -f chapkit-ci-mlproject
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ RUN --mount=type=cache,target=/root/.cache/uv \
ARG GIT_REVISION=""
ENV GIT_REVISION=${GIT_REVISION}

COPY main.py ./
COPY main.py MLproject ./
COPY scripts/ ./scripts/

# The two chmods are load-bearing: INLA's binaries ship 0744 (predict fails with
Expand Down
159 changes: 159 additions & 0 deletions MLproject
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
# Generated from main.py by `chapkit mlproject export` -- do not edit by hand.
# Regenerate with `chapkit mlproject export main.py`; add --check to fail when it is stale.

name: chapkit_ghr_model
version: 0.1.5
target: disease_cases
supported_period_type: month
required_covariates:
- population
allow_free_additional_continuous_covariates: true
requires_geo: false
min_prediction_periods: 1
max_prediction_periods: 12
meta_data:
display_name: GHRmodel (chapkit)
description: Bayesian hierarchical spatio-temporal model for climate-sensitive disease, built on R-INLA.
Wraps BSC's GHRmodel package (dhis2-workflow branch), running a single user-specified model configuration
with configurable spatial, seasonal and interannual random effects and lagged/rolling climate covariates.
author: Global Health Resilience group, BSC (wrapped for CHAP by HISP Centre)
author_note: Wraps BSC's GHRmodel without modifying it. The wrapper is maintained by HISP Centre; BSC
does not support this service.
author_assessed_status: red
contact_email: morten@dhis2.org
organization: Barcelona Supercomputing Center
organization_logo_url: https://www.bsc.es/sites/default/files/public/bscw2/content/about-bsc/bsc-logo.png
citation_info: 'Lowe R, Lee SA, O''Reilly KM et al. (2021) Combined effects of hydrometeorological hazards
and urbanisation on dengue risk in Brazil: a spatiotemporal modelling study. The Lancet Planetary
Health. https://doi.org/10.1016/S2542-5196(20)30292-8'
config_format: flat
user_options:
additional_continuous_covariates:
type: array
items:
type: string
default:
- rainfall
- mean_temperature
description: Continuous covariates to include as fixed effects.
re_spatial:
type: string
enum:
- bym2
- none
default: bym2
description: How risk varies between areas. 'bym2' (Besag-York-Mollie) lets neighbouring areas share
information via the adjacency graph, plus an unstructured per-area term; 'none' omits the effect.
Requires geometry, and is forced to 'none' when none is supplied.
re_seasonal:
type: string
enum:
- rw1
- rw2
- none
default: rw1
description: How risk varies within the year, as a cycle (December wraps to January). 'rw1' is a random
walk that smooths the level between consecutive periods; 'rw2' smooths the slope instead, giving
a gentler, more curved seasonal shape; 'none' omits the effect.
re_interannual:
type: string
enum:
- iid
- rw1
- rw2
- none
default: iid
description: How risk varies between years. 'iid' treats each year as independent, which handles year-to-year
shocks but cannot extrapolate a trend to an unseen year; 'rw1' and 'rw2' assume consecutive years
are related and carry a trend forward; 'none' omits the effect.
priors:
type: string
default: 0.5:0.01
description: How much the random effects are allowed to vary, as penalised-complexity priors. Each
'U:alpha' pair reads as 'the probability that this effect's standard deviation exceeds U is alpha',
so '0.5:0.01' says values above 0.5 are unlikely and keeps the effect conservative. Separate pairs
with semicolons. The forecast uses the first pair; the selection report searches all of them. BSC's
Laos demo uses '0.5:0.01;1:0.01'.
roll_mean:
type: string
default: mean_temperature:3
description: Rolling-mean windows per covariate, encoded as 'name:w1,w2;name2:w3'. Window 1 means
no rolling. Empty string disables. Matches select_fe()'s roll_mean.
roll_sum:
type: string
default: rainfall:3
description: Rolling-sum windows per covariate, same encoding as roll_mean. Conventionally used for
precipitation.
lag:
type: string
default: mean_temperature:1;rainfall:1
description: Lags in periods per covariate, same encoding. Lag 0 means no lag. Multiple values put
several lagged terms in the one model.
nl:
type: string
default: ''
description: Non-linear (random walk) covariate effects, encoded 'name:n' where n is the number of
basis knots. Empty string means all effects linear.
standardize:
type: boolean
default: true
description: Centre and scale covariates before fitting. Aids INLA convergence.
family:
type: string
enum:
- nbinomial
- poisson
default: nbinomial
description: INLA likelihood family. 'nbinomial' handles overdispersed counts; 'poisson' assumes mean
equals variance. These are the only two families GHRmodel's posterior sampler supports.
offset:
type: string
default: population
description: Offset column, entering the linear predictor as log(offset). Empty string disables. Modelling
rates rather than counts.
offset_scale:
type: number
default: 10000.0
description: Divide the offset by this before fitting. BSC's own pipeline notes population should
be divided by a constant (they use 10,000) to help INLA converge. Set to 1 to disable.
n_samples:
type: integer
default: 1000
description: Posterior predictive draws per forecast row.
nthreads:
type: integer
default: 4
description: INLA compute threads.
emit_re_selection_report:
type: boolean
default: false
description: 'Run BSC''s select_re() random-effect search during training and save its HTML comparison
report into the training artifact. Covers the random-effect stage only, not select_fe(). Expensive:
fits many candidate models. Does not affect the forecast.'
report_re_spatial:
type: string
default: bym2
description: Comma-separated spatial effects for the report search. Forced to 'none' when no geometry
is supplied.
report_re_seasonal:
type: string
default: rw1,rw2
description: Comma-separated seasonal effects for the selection report search.
report_re_interannual:
type: string
default: iid,rw1,rw2
description: Comma-separated interannual effects for the selection report search.
entry_points:
train:
parameters:
train_data: path
polygons: path
command: Rscript scripts/train.R --data {train_data} --geo {polygons}
predict:
parameters:
historic_data: path
future_data: path
polygons: path
out_file: path
command: Rscript scripts/predict.R --historic {historic_data} --future {future_data} --geo {polygons}
--output {out_file}
26 changes: 24 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
.PHONY: help build run run-ghcr lint test-unit test-local test-api test-contract serve-test stop-test clean
.PHONY: help build run run-ghcr lint mlproject test-mlproject test-unit test-local test-api test-contract serve-test stop-test clean

IMAGE ?= chapkit-ghr-model:latest
GHCR_IMAGE ?= ghcr.io/chap-models/chapkit_ghr_model:latest
Expand All @@ -18,7 +18,9 @@ help:
@echo " test-contract chapkit's own end-to-end contract test (synthetic data)"
@echo " test-api Train + predict as real jobs over the API, real geo data"
@echo " stop-test Stop the detached test service"
@echo " lint Run ruff format check + lint"
@echo " mlproject Regenerate MLproject from main.py"
@echo " test-mlproject test-contract + test-api against chapkit mlproject run"
@echo " lint Run ruff format check + lint, and check MLproject is up to date"
@echo " clean Remove local image and test outputs"

build:
Expand Down Expand Up @@ -91,6 +93,26 @@ lint:
@uv run ruff format --check .
@echo ">>> Ruff lint"
@uv run ruff check .
@echo ">>> MLproject check"
@uv run chapkit mlproject export --check

mlproject:
@uv run chapkit mlproject export

test-mlproject: build
@docker rm -f chapkit-ghr-model-mlproject >/dev/null 2>&1 || true
@docker run -d --platform linux/amd64 -p $(TEST_PORT):8000 \
--name chapkit-ghr-model-mlproject $(IMAGE) \
chapkit mlproject run . --host 0.0.0.0 --port 8000 >/dev/null
@echo ">>> Waiting for $(TEST_URL)/health"
@for i in $$(seq 1 40); do \
if curl -fsS $(TEST_URL)/health >/dev/null 2>&1; then echo " healthy"; break; fi; \
if [ $$i = 40 ]; then echo " service did not become healthy"; docker logs chapkit-ghr-model-mlproject; exit 1; fi; \
sleep 3; \
done
@uv run chapkit test --url $(TEST_URL) --rows 400 --predict-rows 200 --timeout 1200 --verbose \
&& python3 tools/api_smoke.py $(TEST_URL); \
status=$$?; docker rm -f chapkit-ghr-model-mlproject >/dev/null; exit $$status

clean:
@docker rmi -f $(IMAGE) 2>/dev/null || true
Expand Down
42 changes: 42 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ does exactly that, with `on.exit()` cleanup so the globals do not leak.

```
main.py chapkit service definition and config schema
MLproject the same model as an MLproject, generated from main.py by `chapkit mlproject export`
scripts/ what the runner invokes, and nothing else
lib.R shared wrapper helpers
train.R train entry point: validate + placeholder (no-op)
Expand All @@ -88,6 +89,7 @@ make test-unit # unit checks for the helpers in scripts/lib.R
make test-local # run train.R + predict.R directly against example_data
make test-contract # chapkit's own contract test (synthetic data, no geo)
make test-api # train + predict as real API jobs, with real geometry
make test-mlproject # test-contract + test-api against `chapkit mlproject run`
```

Or run the prebuilt image from GHCR (once published):
Expand All @@ -96,6 +98,45 @@ Or run the prebuilt image from GHCR (once published):
docker compose -f compose.ghcr.yml up # service on :8000
```

## Running from the MLproject

`MLproject` describes the same model for `chapkit mlproject run` and
`chap eval --run-config.as-chapkit`: the same service info, config options and
defaults, and train/predict commands. It is generated from `main.py` by
`chapkit mlproject export`, so `main.py` stays the source of truth: edit it and
run `make mlproject`. `make lint` (and so CI) runs `chapkit mlproject export
--check`, which fails when the file is stale or when `chapkit mlproject run`
would read it as a different service.

Export warns about one setting an MLproject cannot carry: `main.py` registers
with a 15s keepalive. Pass `--keepalive-interval 15` to `chapkit mlproject run`
to keep it when the service registers with chap-core.

The commands need R with INLA and GHRmodel, so the MLproject declares no
environment; the service image provides one, and has the MLproject in `/work`:

```bash
docker run --rm --platform linux/amd64 -p 8000:8000 \
ghcr.io/chap-models/chapkit_ghr_model:latest \
chapkit mlproject run . --host 0.0.0.0 --port 8000
```

`make test-mlproject` does this and runs the contract and API smoke tests against it.
Point `chap eval --model-name http://localhost:8000` at the running service, or
use `chap eval --run-config.as-chapkit` directly on a machine that has R,
INLA and GHRmodel installed.

The MLproject sets `meta_data.config_format: flat`, so `chapkit mlproject run`
(chapkit 2.4.0 or later) writes the same flat `config.yml` as `main.py`.
chap-core requires 2.4.0 for `--run-config.as-chapkit` since
dhis2-chap/chap-core#737. Older chapkit, as in chap-core installs from before
that, ignores the key and nests the model options under `user_option_values`;
`read_config()` in `scripts/lib.R` accepts both layouts.

Chap's own MLproject runners (`docker_env` and friends) are not supported:
they write the config under another file name, passed as `{model_config}`,
which the scripts do not read.

## Configuration

| Field | Default | Notes |
Expand Down Expand Up @@ -304,6 +345,7 @@ Error: Configured covariate(s) not present in the data: rainfall
| `make test-local` | train + predict directly against the fixture |
| `make test-contract` | chapkit's contract test; supplies no geometry, so it also covers the spatial-effect-disabled path |
| `make test-api` | real train and predict jobs over REST with geometry, returning 33 rows x 100 samples |
| `make test-mlproject` | `test-contract` and `test-api` against the service `chapkit mlproject run` builds from `MLproject` |

## Equivalence with BSC's reference pipeline

Expand Down
6 changes: 5 additions & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ class GHRModelConfig(BaseConfig):
info = MLServiceInfo(
id="chapkit-ghr-model",
display_name="GHRmodel (chapkit)",
version="0.1.4",
version="0.1.5",
description=(
"Bayesian hierarchical spatio-temporal model for climate-sensitive disease, "
"built on R-INLA. Wraps BSC's GHRmodel package (dhis2-workflow branch), running "
Expand All @@ -211,6 +211,10 @@ class GHRModelConfig(BaseConfig):
),
model_metadata=ModelMetadata(
author="Global Health Resilience group, BSC (wrapped for CHAP by HISP Centre)",
author_note=(
"Wraps BSC's GHRmodel without modifying it. The wrapper is maintained by HISP Centre; "
"BSC does not support this service."
),
author_assessed_status=AssessedStatus.red,
# Wrapper maintainer, not BSC: they authored the model but don't support this service.
contact_email="morten@dhis2.org",
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ version = "0.1.0"
description = "ML service wrapping BSC's GHRmodel (dhis2-workflow) for CHAP"
requires-python = ">=3.13"
dependencies = [
"chapkit>=2.2.0,<3",
"chapkit>=2.4.0,<3",
"pandas>=2.3.3",
]

Expand Down
6 changes: 6 additions & 0 deletions scripts/lib.R
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ opt_path <- function(p) {

read_config <- function(path = "config.yml") {
cfg <- if (file.exists(path)) yaml.load_file(path) else list()
# chapkit before 2.4.0 nests the model options under user_option_values.
nested <- cfg$user_option_values
if (is.list(nested)) {
cfg$user_option_values <- NULL
cfg[names(nested)] <- nested
}
# Defaults mirror GHRModelConfig in main.py so the scripts stay runnable
# standalone (outside chapkit) for debugging.
defaults <- list(
Expand Down
24 changes: 24 additions & 0 deletions tools/test_lib.R
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,30 @@ g <- build_graph(geo, c("VN-SG", "VN-57"))
check("neighbours despite invalid s2 geometry", as.vector(g), c(0, 1, 1, 0))
check("s2 setting restored", sf::sf_use_s2(), TRUE)

cat("\n== config layouts ==\n")
# main.py and chapkit >= 2.4.0 write config.yml flat; older `chapkit mlproject run`
# nests the model options under user_option_values. Both must give the same config.
cfg_file <- tempfile(fileext = ".yml")
writeLines(c("prediction_periods: 2", "n_samples: 100", "roll_sum: ''"), cfg_file)
flat <- read_config(cfg_file)
check("flat: option read", flat$n_samples, 100L)
check("flat: empty string kept", flat$roll_sum, "")
check("flat: missing option defaulted", flat$family, "nbinomial")
writeLines(c(
"prediction_periods: 2",
"additional_continuous_covariates: [pdsi]",
"user_option_values:",
" n_samples: 100",
" roll_sum: ''"
), cfg_file)
nested <- read_config(cfg_file)
check("nested: option hoisted", nested$n_samples, 100L)
check("nested: empty string kept", nested$roll_sum, "")
check("nested: top-level kept", nested$additional_continuous_covariates, "pdsi")
check("nested: missing option defaulted", nested$family, "nbinomial")
check("nested: user_option_values removed", is.null(nested$user_option_values), TRUE)
unlink(cfg_file)

cat("\n")
if (fails > 0) {
cat("FAILED:", fails, "check(s)\n")
Expand Down
Loading
Loading