diff --git a/.dockerignore b/.dockerignore index a8e1783..052d78a 100644 --- a/.dockerignore +++ b/.dockerignore @@ -5,3 +5,9 @@ __pycache__ *.pyd env .dockerignore +# Not needed in the image (and secrets must not be baked in) +scenarios/.streamlit +.streamlit/secrets.toml +OasisPiWind +certs +tests diff --git a/.env.scenarios b/.env.scenarios new file mode 100644 index 0000000..f7f25d1 --- /dev/null +++ b/.env.scenarios @@ -0,0 +1,85 @@ +# ============================================================================ +# PUBLIC SCENARIOS DEMO CONFIGURATION +# ============================================================================ +# Credential-free Scenarios app (scenarios_app.py): visitors run pre-loaded +# scenarios against pre-loaded exposure and view the results. No uploads, no +# public API. Deploy with: +# +# cp .env.scenarios .env # then change every CHANGE_ME value below +# ./install.sh +# +# The demo uses simple auth with a service account that only the UI and its +# setup/prune services use; visitors never log in. +# ============================================================================ + +# Public demo: Scenarios app only, no public API/database ports (docker-compose.public.yml) +OASIS_PUBLIC_DEMO=true +MODEL_SET=scenarios +# Directory holding the scenario model data (cloned by get-scenarios.sh if missing) +SCENARIOS_PATH=/home/ubuntu/Scenarios +# Bundled analysis settings used when the platform has no settings template +UI_DEFAULTS=./scenarios/defaults +# Days to keep visitors' runs (showcase runs are always kept) +OASIS_PRUNE_DAYS=7 +# Per scenario worker: tasks at a time and memory cap (13 workers share the host) +OASIS_WORKER_CONCURRENCY=1 +OASIS_WORKER_MEM_LIMIT=6g +# Set to get a Let's Encrypt certificate for OASIS_UI_HOSTNAME (must be public) +OASIS_ACME_EMAIL= + +# Project Configuration +COMPOSE_PROJECT_NAME=oasisscenarios +OASIS_DEBUG=0 + +# Docker socket path (Docker Desktop uses ~/.docker/desktop/docker.sock) +# Standard Docker: /var/run/docker.sock +DOCKER_SOCK=/var/run/docker.sock + +# Hostname Configuration +OASIS_UI_HOSTNAME=oasislmf-scenarios.com +OASIS_PROTOCOL=https + +# Authentication Type +API_AUTH_TYPE=simple +OASIS_SERVER_ALLOWED_OIDC_AUTH_PROVIDERS=keycloak,authentik + +# Simple Auth Credentials +OASIS_ADMIN_USER=admin +OASIS_ADMIN_PASS=CHANGE_ME + +# Image Versions +SERVER_IMG=coreoasis/api_server +VERS_API=2.5.9 +WORKER_IMG=coreoasis/model_worker +VERS_WORKER=2.5.9 +PYTHONUI_IMG=coreoasis/oasispythonui_app +VERS_UI=latest +VERS_PIWIND=2.5.9 + +# Database Configuration +OASIS_SERVER_DB_HOST=server-db +OASIS_SERVER_DB_PORT=5432 +OASIS_SERVER_DB_NAME=oasis +OASIS_SERVER_DB_USER=oasis +OASIS_SERVER_DB_PASS=CHANGE_ME + +OASIS_CELERY_DB_HOST=celery-db +OASIS_CELERY_DB_PORT=5432 +OASIS_CELERY_DB_NAME=celery +OASIS_CELERY_DB_USER=celery +OASIS_CELERY_DB_PASS=CHANGE_ME + +# Broker & Channel Layer +RABBITMQ_DEFAULT_USER=rabbit +RABBITMQ_DEFAULT_PASS=CHANGE_ME +OASIS_CELERY_BROKER_URL=amqp://rabbit:CHANGE_ME@broker:5672 +REDIS_HOST=channel-layer +REDIS_PORT=6379 +OASIS_SERVER_CHANNEL_LAYER_SSL=false + +# Advanced Configuration +OASIS_PORTFOLIO_UPLOAD_VALIDATION=0 +OASIS_OASISLMF_VERSION= +OASIS_ODS_VERSION= +OASIS_ODM_VERSION= +OASIS_OED_SCHEMA_INFO= diff --git a/.github/workflows/scenarios-ui-docker.yml b/.github/workflows/scenarios-ui-docker.yml deleted file mode 100644 index 53ee9a9..0000000 --- a/.github/workflows/scenarios-ui-docker.yml +++ /dev/null @@ -1,42 +0,0 @@ -name: Docker Scenarios UI CI - -on: - workflow_dispatch: - inputs: - docker_push: - required: true - default: 'false' - type: string - workflow_call: - inputs: - docker_push: - required: true - default: 'false' - type: string - -env: - DOCKER_PUSH: 'false' - -jobs: - build-push: - runs-on: ubuntu-latest - steps: - - name: Set inputs - run: | - [[ -z "${{ inputs.docker_push }}" ]] || echo "DOCKER_PUSH=${{ inputs.docker_push }}" >> $GITHUB_ENV - - name: Login to Docker Hub - if: env.DOCKER_PUSH == 'true' - uses: docker/login-action@v3 - with: - username: ${{ vars.DOCKERHUB_USERNAME }} - password: ${{ secrets.DOCKERHUB_TOKEN }} - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v3 - - name: show docker push - run: echo "docker_push=${{env.DOCKER_PUSH}}" - - name: Build and push - uses: docker/build-push-action@v6 - with: - push: ${{ env.DOCKER_PUSH }} - tags: coreoasis/oasis_scenarios:latest - file: ./oasisui_st_app.Dockerfile diff --git a/README.md b/README.md index ef6cc14..5723136 100644 --- a/README.md +++ b/README.md @@ -14,8 +14,10 @@ The standard UI (`ui-config.json`) has three pages: Analysis settings are edited with controls generated from the ODS-tools analysis and model settings schemas, and validated before they are saved. -The Scenarios UI (`scenarios/ui-config.json`) is configured separately and adds -the `/scenarios`, `/comparison` and `/scenariosGuide` pages. +A separate, credential-free **Scenarios app** (`scenarios_app.py`) is for the +public demo: visitors run pre-loaded disaster scenarios against pre-loaded +exposure and explore the results, but cannot upload anything. See +[Public Scenarios demo](#public-scenarios-demo). Which pages appear in the sidebar is controlled by the UI config file. @@ -167,7 +169,7 @@ or set `MODEL_SET` in `.env` so a bare `./install.sh` deploys it: ```bash ./install.sh -m piwind # default: the PiWind demo model -./install.sh -m scenarios # PiWind plus the public scenario models +./install.sh -m scenarios # the public disaster scenario models ``` Model sets shipped in this repository: @@ -175,7 +177,7 @@ Model sets shipped in this repository: | File | Contents | |------|----------| | `docker-compose.models.piwind.yml` | A `model-registration` one-shot and `piwind-worker`, with model data from `./OasisPiWind/`. | -| `docker-compose.models.scenarios.yml` | `piwind-worker` plus the scenario workers (Impact Forecasting, JBA, ARA, IPE), with model data from `${SCENARIOS_PATH}`. | +| `docker-compose.models.scenarios.yml` | `piwind-worker` plus the scenario workers (Impact Forecasting, JBA, ARA, IPE), with model data from `${SCENARIOS_PATH}`, and a `scenarios-setup` one-shot that loads the scenario portfolios, settings templates and showcase runs. | Because the split is by filename, adding a model set means dropping two new files into the root directory — no edits to `docker-compose.yml`, `install.sh` @@ -314,7 +316,73 @@ docker compose logs -f # UI logs - The `.env` templates and `users.yaml` files ship with **demo credentials**. Change all passwords before any non-local deployment. -## Public Demo +## Public Scenarios demo -The public site is at https://ui.oasislmf-scenarios.com/ -Default scenarios in the tool are processed/hosted at https://github.com/OasisLMF/Scenarios +The public site is at https://oasislmf-scenarios.com/. Its scenarios are +published in https://github.com/OasisLMF/Scenarios. + +The demo runs the **Scenarios app** (`scenarios_app.py`, pages in +`scenarios_ui/`), not the standard UI. It is credential free: the app uses a +service account for everyone, and visitors can: + +- **Run a scenario** - choose a scenario, check the exposure it runs against, + choose the number of samples and a loss breakdown, run it and explore the + results. +- **Showcase** - explore pre-computed results without waiting. +- **Compare** - put two runs (showcase or their own) side by side. +- **Guide** - how loss models work and how to read the results. + +Visitors only see their own runs (identified by the `?v=` id in the URL) and the +showcase runs. They cannot upload exposure, and the standard UI's pages are not +part of the app. Limits are set in the `scenarios` section of +`scenarios/ui-config.json`: + +| Setting | Default | Description | +|---------|---------|-------------| +| `max_samples` | 50 | Maximum number of samples per run | +| `default_samples` | 10 | Initial number of samples | +| `max_active_runs_per_visitor` | 2 | Runs one visitor can have in progress | +| `max_active_runs` | 10 | Runs in progress across all visitors before new runs wait | +| `showcase_tag` | `[showcase]` | Name tag marking showcase runs | + +`model_map` in the same file lists which pre-loaded portfolios each scenario +model can be run against. + +### Deploying + +```bash +cp .env.scenarios .env # set every CHANGE_ME value, SCENARIOS_PATH and the hostname +./install.sh # or ./install.sh --yes for an unattended redeploy +``` + +With `OASIS_PUBLIC_DEMO=true`, `install.sh` adds `docker-compose.public.yml`: + +- the UI runs the Scenarios app; +- only Traefik's http/https ports are published - the API, websocket, databases + and broker have no host ports and no public routes; +- a `scenarios-prune` service deletes visitors' runs older than + `OASIS_PRUNE_DAYS` (showcase runs are kept). + +The installer refuses to deploy a public demo while `.env` still contains +`CHANGE_ME` placeholders. Set `OASIS_ACME_EMAIL` to get a Let's Encrypt +certificate for `OASIS_UI_HOSTNAME` (`docker-compose.acme.yml`; the hostname +must resolve to the server and port 80 must be reachable). + +The `scenarios-setup` service runs on every deploy and is idempotent: it adds +missing portfolios (`scenarios/portfolios.json`), updates the settings templates +(`scenarios/a_settings.json`) and starts a showcase run for any scenario that +doesn't have one (`scripts/add_showcase_analyses.py`). + +The **Docker Scenarios UI CD** workflow deploys to the hosted server by running +`scenarios/deploy_scenarios_ui.sh` there, which uses `install.sh`. The server's +`.env` must be a configured copy of `.env.scenarios`. + +To run the Scenarios app locally against an existing platform: + +```bash +OASIS_UI_CONFIG=scenarios/ui-config.json streamlit run scenarios_app.py +``` + +The UI and setup scripts take the service account from +`OASIS_SERVICE_USERNAME_OR_ID` / `OASIS_SERVICE_PASSWORD_OR_SECRET` (set by +`install.sh` from `.env`), falling back to `.streamlit/secrets.toml`. diff --git a/app.py b/app.py index 0cb042b..eab3137 100644 --- a/app.py +++ b/app.py @@ -3,6 +3,7 @@ get_auth_type, exchange_session_token ) import streamlit as st +from modules.credentials import service_client_kwargs from modules.client import ClientInterface from modules.nav import SidebarNav from oasis_data_manager.errors import OasisException @@ -45,10 +46,7 @@ if ui_config.skip_login: with st.spinner("Loading platform..."): - if auth_type != 'simple': - client_interface = ClientInterface(auth_type="oidc", client_id=st.secrets["client_id"], client_secret=st.secrets["client_secret"]) - else: - client_interface = ClientInterface(auth_type="simple", username=st.secrets["user"], password=st.secrets["password"]) + client_interface = ClientInterface(**service_client_kwargs()) st.session_state["client"] = client_interface.client cols = st.columns([0.1, 0.8, 0.1]) diff --git a/deploy-scenarios.sh b/deploy-scenarios.sh deleted file mode 100755 index ff857fe..0000000 --- a/deploy-scenarios.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash -export $(grep -v '^#' .env | xargs) - -# Pull the latest images -set +e -docker pull ${WORKER_IMG-coreoasis/model_worker}:${VERS_WORKER:-latest} -docker pull ${SERVER_IMG-coreoasis/api_server}:${VERS_API:-latest} -docker pull ${SCENARIOS_UI_IMG-coreoasis/oasis_scenarios}:${VERS_API:-latest} -set -e - -# Update -docker compose -f oasis-scenarios-platform.yml up -d -docker compose -f oasis-scenarios-ui.yml up -d diff --git a/docker-compose.acme.yml b/docker-compose.acme.yml new file mode 100644 index 0000000..0c43f4b --- /dev/null +++ b/docker-compose.acme.yml @@ -0,0 +1,33 @@ +# ============================================================================ +# Let's Encrypt certificates for a public hostname +# ============================================================================ +# Added by install.sh when OASIS_ACME_EMAIL is set. Traefik obtains and renews +# a certificate for OASIS_UI_HOSTNAME using the HTTP challenge, so the hostname +# must resolve to this machine and port 80 must be reachable from the internet. +# Without it, certs/ui.crt (scripts/generate-certs.sh) is served instead. +# ============================================================================ + +volumes: + letsencrypt-data: + +services: + traefik: + command: + - "--providers.docker=true" + - "--providers.docker.exposedbydefault=false" + - "--entrypoints.web.address=:80" + - "--entrypoints.websecure.address=:443" + - "--providers.file.directory=/etc/traefik/dynamic" + - "--providers.file.watch=true" + - "--ping=true" + - "--api.insecure=true" + - "--certificatesresolvers.letsencrypt.acme.email=${OASIS_ACME_EMAIL}" + - "--certificatesresolvers.letsencrypt.acme.storage=/letsencrypt/acme.json" + - "--certificatesresolvers.letsencrypt.acme.httpchallenge.entrypoint=web" + volumes: + - letsencrypt-data:/letsencrypt + + pythonui: + labels: + - "traefik.http.routers.pythonui-secure.tls.certresolver=letsencrypt" + - "traefik.http.routers.pythonui-secure.tls.domains[0].main=${OASIS_UI_HOSTNAME}" diff --git a/docker-compose.models.scenarios.yml b/docker-compose.models.scenarios.yml index 4764777..b24f588 100644 --- a/docker-compose.models.scenarios.yml +++ b/docker-compose.models.scenarios.yml @@ -1,9 +1,10 @@ # ============================================================================ -# PiWind demo model +# Public scenario models # ============================================================================ -# The default model set, loaded by install.sh (MODEL_COMPOSE=piwind, or -# --models piwind). Always used together with docker-compose.yml, which -# provides the server, databases, broker and the filestore volume. +# The scenarios model set (install.sh -m scenarios): one worker per disaster +# scenario, with model data from ${SCENARIOS_PATH}. Always used together with +# docker-compose.yml, which provides the server, databases, broker and the +# filestore volume. # x-shared-env: &worker-env @@ -18,6 +19,10 @@ x-shared-env: &worker-env # Where workers report events completed, shown as run progress in the UI OASIS_ANALYSIS_STATUS_URL: http://server:8000/analysis-status/ + # One task at a time per worker (Celery defaults to one process per CPU, and + # with 13 workers that alone uses a lot of memory) + OASIS_CELERY_CONCURRENCY: ${OASIS_WORKER_CONCURRENCY:-1} + # Authentication configuration OASIS_SERVER_API_AUTH_TYPE: ${API_AUTH_TYPE:-simple} OASIS_SERVER_ALLOWED_OIDC_AUTH_PROVIDERS: ${OASIS_SERVER_ALLOWED_OIDC_AUTH_PROVIDERS} @@ -63,6 +68,9 @@ x-shared-env: &worker-env x-worker: &worker restart: always image: ${WORKER_IMG:-coreoasis/model_worker}:${VERS_WORKER:-latest} + # Cap each worker so a run that outgrows it is killed inside its container + # rather than exhausting the host's memory + mem_limit: ${OASIS_WORKER_MEM_LIMIT:-6g} depends_on: server: condition: service_healthy @@ -73,18 +81,6 @@ x-worker: &worker services: - piwind-worker: - <<: *worker - environment: - <<: *worker-env - OASIS_MODEL_SUPPLIER_ID: OasisLMF - OASIS_MODEL_ID: PiWind - OASIS_MODEL_VERSION_ID: 'v2' - OASIS_RUN_MODE: v2 - volumes: - - ./OasisPiWind/:/home/worker/model - - filestore-data:/shared-fs:rw - maeq-worker: <<: *worker environment: @@ -250,3 +246,25 @@ services: volumes: - ${SCENARIOS_PATH}/IPE/FranceHail/:/home/worker/model - filestore-data:/shared-fs:rw + + # Loads the scenario portfolios, settings templates and showcase analyses + # (scripts/scenarios_setup.sh). Idempotent, so it runs on every deploy. + scenarios-setup: + image: ${PYTHONUI_IMG:-coreoasis/oasispythonui_app}:${VERS_UI:-latest} + restart: "no" + entrypoint: ["bash", "scripts/scenarios_setup.sh"] + environment: + - API_URL=http://server:8000 + - API_AUTH_TYPE=${API_AUTH_TYPE:-simple} + - OASIS_SERVICE_USERNAME_OR_ID=${OASIS_SERVICE_USERNAME_OR_ID:-} + - OASIS_SERVICE_PASSWORD_OR_SECRET=${OASIS_SERVICE_PASSWORD_OR_SECRET:-} + - SCENARIOS_UI_CONFIG=scenarios/ui-config.json + # Number of model workers in this file: setup waits for all to register + - SCENARIOS_MIN_MODELS=13 + volumes: + # Portfolio paths in scenarios/portfolios.json are relative to /usr/src/app + - ${SCENARIOS_PATH}:/usr/src/Scenarios:ro + - ${UI_STREAMLIT:-./.streamlit/}:/usr/src/app/.streamlit:ro + depends_on: + server: + condition: service_healthy diff --git a/docker-compose.public.yml b/docker-compose.public.yml new file mode 100644 index 0000000..6103409 --- /dev/null +++ b/docker-compose.public.yml @@ -0,0 +1,70 @@ +# ============================================================================ +# Public, credential-free Scenarios demo +# ============================================================================ +# Added by install.sh when OASIS_PUBLIC_DEMO=true (see .env.scenarios). Use +# with the scenarios model set and simple auth. +# +# - The UI runs the Scenarios app (scenarios_app.py) instead of the standard UI: +# visitors can run pre-loaded scenarios but cannot upload or delete anything. +# - Only Traefik's http/https ports are published. The API, websocket, +# databases and broker have no host ports and no public routes, so the +# platform is only reachable through the UI. +# - Visitors' runs are pruned daily; showcase runs are kept. +# ============================================================================ + +services: + traefik: + ports: !override + - "${OASIS_HTTP_PORT-80}:80" + - "${OASIS_HTTPS_PORT-443}:443" + + server: + ports: !reset [] + labels: + - "traefik.enable=false" + + server-websocket: + ports: !reset [] + labels: + - "traefik.enable=false" + + server-db: + ports: !reset [] + + celery-db: + ports: !reset [] + + broker: + ports: !reset [] + + channel-layer: + ports: !reset [] + + pythonui: + entrypoint: ["streamlit", "run", "scenarios_app.py", "--server.port=8501"] + ports: !reset [] + environment: + - OASIS_UI_CONFIG=/usr/src/app/scenarios/ui-config.json + + # Delete visitors' runs older than OASIS_PRUNE_DAYS (default 7), keeping showcase runs + scenarios-prune: + image: ${PYTHONUI_IMG:-coreoasis/oasispythonui_app}:${VERS_UI:-latest} + restart: always + entrypoint: + - bash + - -c + - | + while true; do + # Credentials come from the environment, so they aren't in the process list + python3 -u scripts/prune_analysis.py --force --days "$${OASIS_PRUNE_DAYS:-7}" \ + --keep-tag "[showcase]" --log INFO + sleep 86400 + done + environment: + - API_URL=http://server:8000 + - OASIS_PRUNE_DAYS=${OASIS_PRUNE_DAYS:-7} + - OASIS_SERVICE_USERNAME_OR_ID=${OASIS_SERVICE_USERNAME_OR_ID:-} + - OASIS_SERVICE_PASSWORD_OR_SECRET=${OASIS_SERVICE_PASSWORD_OR_SECRET:-} + depends_on: + server: + condition: service_healthy diff --git a/docker-compose.ui.yml b/docker-compose.ui.yml index 23a5fbf..8e9f489 100644 --- a/docker-compose.ui.yml +++ b/docker-compose.ui.yml @@ -25,6 +25,9 @@ services: - API_AUTH_TYPE=${API_AUTH_TYPE} - OASIS_HOSTNAME=${OASIS_UI_HOSTNAME} - OASIS_PROTOCOL=${OASIS_PROTOCOL:-http} + # Service account (set by install.sh from .env); falls back to .streamlit/secrets.toml + - OASIS_SERVICE_USERNAME_OR_ID=${OASIS_SERVICE_USERNAME_OR_ID:-} + - OASIS_SERVICE_PASSWORD_OR_SECRET=${OASIS_SERVICE_PASSWORD_OR_SECRET:-} volumes: - ${UI_DEFAULTS:-./defaults/}:/usr/src/app/defaults/ - ${UI_CONFIG:-./ui-config.json}:/usr/src/app/ui-config.json:ro diff --git a/get-scenarios.sh b/get-scenarios.sh index 341ae87..5a005e4 100644 --- a/get-scenarios.sh +++ b/get-scenarios.sh @@ -26,8 +26,6 @@ if [ -z "$SCENARIOS_PATH" ]; then exit 1 fi -# The scenarios set runs PiWind alongside the scenario models -bash "$SCRIPT_DIR/get-piwind.sh" if [ -d "$SCENARIOS_PATH" ]; then echo " -> Scenario models already checked out at $SCENARIOS_PATH" diff --git a/images/IDFlogo_navyreddot_RGB_v1.png b/images/IDFlogo_navyreddot_RGB_v1.png deleted file mode 100644 index 4038e7e..0000000 Binary files a/images/IDFlogo_navyreddot_RGB_v1.png and /dev/null differ diff --git a/images/STguide_10_outputTbl.png b/images/STguide_10_outputTbl.png deleted file mode 100644 index 21ac49d..0000000 Binary files a/images/STguide_10_outputTbl.png and /dev/null differ diff --git a/images/STguide_11_outputTbloption.png b/images/STguide_11_outputTbloption.png deleted file mode 100644 index fe18db8..0000000 Binary files a/images/STguide_11_outputTbloption.png and /dev/null differ diff --git a/images/STguide_1_createAnalysis.png b/images/STguide_1_createAnalysis.png deleted file mode 100644 index becd78b..0000000 Binary files a/images/STguide_1_createAnalysis.png and /dev/null differ diff --git a/images/STguide_2_createAnalysis.png b/images/STguide_2_createAnalysis.png deleted file mode 100644 index 606606f..0000000 Binary files a/images/STguide_2_createAnalysis.png and /dev/null differ diff --git a/images/STguide_3_createAnalysis.png b/images/STguide_3_createAnalysis.png deleted file mode 100644 index 5303073..0000000 Binary files a/images/STguide_3_createAnalysis.png and /dev/null differ diff --git a/images/STguide_4_runAnalysis.png b/images/STguide_4_runAnalysis.png deleted file mode 100644 index bc6f862..0000000 Binary files a/images/STguide_4_runAnalysis.png and /dev/null differ diff --git a/images/STguide_5_runAnalysis_showOutput.png b/images/STguide_5_runAnalysis_showOutput.png deleted file mode 100644 index dde273f..0000000 Binary files a/images/STguide_5_runAnalysis_showOutput.png and /dev/null differ diff --git a/images/STguide_6_Output.png b/images/STguide_6_Output.png deleted file mode 100644 index 15cb39f..0000000 Binary files a/images/STguide_6_Output.png and /dev/null differ diff --git a/images/STguide_7_ResultsSummary.png b/images/STguide_7_ResultsSummary.png deleted file mode 100644 index e1a7aa8..0000000 Binary files a/images/STguide_7_ResultsSummary.png and /dev/null differ diff --git a/images/STguide_8_downloadOption.png b/images/STguide_8_downloadOption.png deleted file mode 100644 index 04f8a7d..0000000 Binary files a/images/STguide_8_downloadOption.png and /dev/null differ diff --git a/images/STguide_9_outputMap.png b/images/STguide_9_outputMap.png deleted file mode 100644 index ff23216..0000000 Binary files a/images/STguide_9_outputMap.png and /dev/null differ diff --git a/install.sh b/install.sh index d2e2a4b..178dc62 100755 --- a/install.sh +++ b/install.sh @@ -17,6 +17,7 @@ MODEL_SET_ARG="" BUILD_UI=false NO_PULL_UI=false UNINSTALL=false +ASSUME_YES=false usage() { cat <<'USAGE' @@ -30,6 +31,7 @@ Usage: ./install.sh [options] --build-ui Rebuild the UI docker container. --no-pull-ui Disable pulling UI docker container. -u, --uninstall Bring the stack down and delete its volumes. + -y, --yes Redeploy over an existing installation without asking. -h, --help Show this message. USAGE } @@ -47,6 +49,7 @@ while [ $# -gt 0 ]; do --build-ui) BUILD_UI=true; shift ;; --no-pull-ui) NO_PULL_UI=true; shift ;; -u|--uninstall) UNINSTALL=true; shift ;; + -y|--yes) ASSUME_YES=true; shift ;; -h|--help) usage; exit 0 ;; *) echo "ERROR: unknown option '$1'" >&2; usage >&2; exit 1 ;; esac @@ -70,6 +73,8 @@ if [ "$UNINSTALL" = true ]; then -f "$SCRIPT_DIR/docker-compose.ui.yml" \ -f "$SCRIPT_DIR/docker-compose.keycloak.yml" \ -f "$SCRIPT_DIR/docker-compose.authentik.yml" \ + -f "$SCRIPT_DIR/docker-compose.public.yml" \ + -f "$SCRIPT_DIR/docker-compose.acme.yml" \ "${MODEL_FILES[@]}" \ down --remove-orphans -v 2>/dev/null # Also try old files in case of migration @@ -229,6 +234,27 @@ elif [ "$API_AUTH_TYPE" = "authentik" ]; then echo " -> Including Authentik services" fi +if [ "${OASIS_PUBLIC_DEMO:-false}" = "true" ]; then + if [ "$API_AUTH_TYPE" != "simple" ]; then + echo "ERROR: OASIS_PUBLIC_DEMO=true requires API_AUTH_TYPE=simple (see .env.scenarios)" + exit 1 + fi + # Settings (not comments) still holding the .env.scenarios placeholder + PLACEHOLDERS=$(grep -v '^[[:space:]]*#' "$SCRIPT_DIR/.env" | grep "CHANGE_ME" | cut -d= -f1) + if [ -n "$PLACEHOLDERS" ]; then + echo "ERROR: .env still contains CHANGE_ME placeholders. Set real passwords before a public deployment:" + echo "$PLACEHOLDERS" | sed 's/^/ /' + exit 1 + fi + COMPOSE_FILES="$COMPOSE_FILES -f $SCRIPT_DIR/docker-compose.public.yml" + echo " -> Public demo: Scenarios app only, no public API or database ports" +fi + +if [ -n "${OASIS_ACME_EMAIL:-}" ]; then + COMPOSE_FILES="$COMPOSE_FILES -f $SCRIPT_DIR/docker-compose.acme.yml" + echo " -> Let's Encrypt certificate for $OASIS_UI_HOSTNAME" +fi + echo " -> Compose files: $COMPOSE_FILES" echo "" @@ -251,7 +277,7 @@ echo "" EXISTING_CONTAINERS=$(docker compose $COMPOSE_FILES ps -q 2>/dev/null | wc -l) -if [ "$EXISTING_CONTAINERS" -gt 0 ]; then +if [ "$EXISTING_CONTAINERS" -gt 0 ] && [ "$ASSUME_YES" != true ]; then MSG="Previous installation detected. Redeploy? (existing data will be preserved)" while true; do read -r -n 1 -p "${MSG} [y/n]: " REPLY @@ -356,8 +382,12 @@ echo " Hostname: $OASIS_UI_HOSTNAME" echo "" echo " Access Points (via Traefik):" echo " UI: ${OASIS_PROTOCOL}://${OASIS_UI_HOSTNAME}/" -echo " API: ${OASIS_PROTOCOL}://${OASIS_UI_HOSTNAME}/api/" -echo " API Docs: ${OASIS_PROTOCOL}://${OASIS_UI_HOSTNAME}/api/swagger/" +if [ "${OASIS_PUBLIC_DEMO:-false}" = "true" ]; then + echo " (public Scenarios demo: the API is not exposed)" +else + echo " API: ${OASIS_PROTOCOL}://${OASIS_UI_HOSTNAME}/api/" + echo " API Docs: ${OASIS_PROTOCOL}://${OASIS_UI_HOSTNAME}/api/swagger/" +fi if [ "$API_AUTH_TYPE" = "keycloak" ]; then echo " Keycloak: ${OASIS_PROTOCOL}://${OASIS_UI_HOSTNAME}/auth/admin/" diff --git a/modules/authorisation.py b/modules/authorisation.py index 5833613..8140f15 100644 --- a/modules/authorisation.py +++ b/modules/authorisation.py @@ -1,10 +1,12 @@ """Module to handle authorisation.""" import os import requests +from oasis_data_manager.errors import OasisException from requests.exceptions import HTTPError from modules.config import retrieve_ui_config import streamlit as st from modules.client import ClientInterface +from modules.credentials import service_client_kwargs import logging logger = logging.getLogger(__name__) @@ -50,13 +52,7 @@ def handle_login(skip_login=False): if skip_login: with st.spinner("Loading platform..."): try: - auth_type = get_auth_type() - if auth_type != 'simple': - st.session_state["client_interface"] = ClientInterface( - auth_type="oidc", client_id=st.secrets["client_id"], client_secret=st.secrets["client_secret"]) - else: - st.session_state["client_interface"] = ClientInterface( - auth_type="simple", username=st.secrets["user"], password=st.secrets["password"]) + st.session_state["client_interface"] = ClientInterface(**service_client_kwargs()) except HTTPError as e: logger.error(e) st.error("Loading platform failed.") @@ -70,16 +66,10 @@ def quiet_login(): if "client_interface" in st.session_state: return - auth_type = get_auth_type() try: - if auth_type != 'simple': - if "client_id" in st.secrets and "client_secret" in st.secrets: - st.session_state["client_interface"] = ClientInterface( - auth_type="oidc", client_id=st.secrets["client_id"], client_secret=st.secrets["client_secret"]) - elif "user" in st.secrets and "password" in st.secrets: - st.session_state["client_interface"] = ClientInterface(auth_type="simple", username=st.secrets["user"], password=st.secrets["password"]) - except HTTPError as e: - logger.error(e) + st.session_state["client_interface"] = ClientInterface(**service_client_kwargs()) + except (HTTPError, OasisException) as e: + logger.error(f'Service login failed: {e}') return diff --git a/modules/config.py b/modules/config.py index c9cec92..3066419 100644 --- a/modules/config.py +++ b/modules/config.py @@ -34,6 +34,9 @@ def __init__(self): self.model_map = config.get('model_map', {}) self.skip_login = config.get('skip_login', False) self.footer = config.get('footer', None) + # Scenarios app settings (run limits, showcase tag, ...): see modules/scenarios.py + self.scenarios = config.get('scenarios', {}) + # Curated scenario details (title, peril, countries, type), keyed by model id def retrieve_ui_config(): diff --git a/modules/credentials.py b/modules/credentials.py new file mode 100644 index 0000000..2cb4133 --- /dev/null +++ b/modules/credentials.py @@ -0,0 +1,46 @@ +"""Credentials for the UI's service account. + +Environment variables set by install.sh take precedence over +`.streamlit/secrets.toml`, so a deployment's credentials only need setting in +`.env`: + +- `API_AUTH_TYPE`: `simple`, or an OIDC provider (`keycloak`, `authentik`) +- `OASIS_SERVICE_USERNAME_OR_ID`: username (simple) or client id (OIDC) +- `OASIS_SERVICE_PASSWORD_OR_SECRET`: password (simple) or client secret (OIDC) +""" +import os + +import streamlit as st + + +def _secret(key, default=None): + try: + return st.secrets.get(key, default) + except Exception: # noqa: BLE001 - no secrets file is fine when env vars are set + return default + + +def service_auth_type(): + """'simple' or 'oidc'.""" + auth = os.environ.get('API_AUTH_TYPE') or _secret('auth_type', 'simple') + return 'simple' if auth == 'simple' else 'oidc' + + +def service_credentials(): + """`(auth_type, id, secret)` for the service account.""" + auth = service_auth_type() + env_id = os.environ.get('OASIS_SERVICE_USERNAME_OR_ID') + env_secret = os.environ.get('OASIS_SERVICE_PASSWORD_OR_SECRET') + if env_id and env_secret: + return auth, env_id, env_secret + if auth == 'simple': + return auth, _secret('user', 'admin'), _secret('password', 'password') + return auth, _secret('client_id', 'oasis-service'), _secret('client_secret', 'serviceNotSoSecret') + + +def service_client_kwargs(): + """Keyword arguments for `ClientInterface` / `APIClient` using the service account.""" + auth, ident, secret = service_credentials() + if auth == 'simple': + return {'auth_type': 'simple', 'username': ident, 'password': secret} + return {'auth_type': 'oidc', 'client_id': ident, 'client_secret': secret} diff --git a/modules/oed.py b/modules/oed.py new file mode 100644 index 0000000..0c8c57e --- /dev/null +++ b/modules/oed.py @@ -0,0 +1,61 @@ +"""OED reference data (peril and country names) from the ods_tools OED spec.""" +import json +import re +from functools import lru_cache +from pathlib import Path + +import ods_tools +import pandas as pd + +# Broad peril families used to filter scenarios, by the first letter of the OED peril code +PERIL_FAMILIES = { + 'Q': 'Earthquake', + 'W': 'Windstorm', + 'O': 'Flood', + 'X': 'Convective storm', + 'Z': 'Winter storm', + 'B': 'Wildfire', + 'V': 'Volcano', +} +# Codes whose family differs from their first letter +PERIL_FAMILY_OVERRIDES = {'XHL': 'Hail', 'XCH': 'Hail', 'ZST': 'Windstorm'} + + +@lru_cache +def oed_spec(): + """The newest OED spec bundled with ods_tools.""" + data = Path(ods_tools.__file__).parent / 'data' + + def version(path): + return tuple(int(v) for v in re.findall(r'\d+', path.stem)) + + latest = max(data.glob('OpenExposureData_*Spec.json'), key=version) + return json.loads(latest.read_text()) + + +def country_name(code): + entry = oed_spec().get('country', {}).get(str(code).upper(), {}) + return entry.get('Name') or str(code) + + +def peril_description(code): + entry = oed_spec().get('perils', {}).get('info', {}).get(str(code).upper(), {}) + return entry.get('Peril Description') or str(code) + + +def peril_family(code): + code = str(code).upper() + return PERIL_FAMILY_OVERRIDES.get(code) or PERIL_FAMILIES.get(code[:1], peril_description(code)) + + +def has_coordinates(locations): + """Whether OED locations have usable coordinates for a map. + + Needs Latitude and Longitude columns with at least two distinct points, + ignoring missing values and 0,0 (which OED files use for "not geocoded"). + """ + if locations is None or not {'Latitude', 'Longitude'} <= set(locations.columns): + return False + coords = locations[['Latitude', 'Longitude']].apply(pd.to_numeric, errors='coerce').dropna() + coords = coords[(coords['Latitude'] != 0) | (coords['Longitude'] != 0)] + return len(coords.drop_duplicates()) > 1 diff --git a/modules/rerun.py b/modules/rerun.py deleted file mode 100644 index 2f409fe..0000000 --- a/modules/rerun.py +++ /dev/null @@ -1,75 +0,0 @@ -import streamlit as st - - -class RefreshHandler: - q_name = "refresh_1" - refresh_bool = "refreshing" - - def __init__(self, client_interface, interval=None): - self.client_interface = client_interface - - if interval is None: - interval = '5s' - - self.interval = interval - - # Set up session state - self.set_up() - - @staticmethod - def start(analysis_id, required_statuses): - RefreshHandler.add_to_queue(analysis_id, required_statuses) - RefreshHandler.set_refresh_bool(True) - st.rerun() - - @staticmethod - def get_queue(): - return st.session_state[RefreshHandler.q_name] - - @staticmethod - def is_refreshing(): - return st.session_state[RefreshHandler.refresh_bool] - - @staticmethod - def set_refresh_bool(state=True): - st.session_state[RefreshHandler.refresh_bool] = state - - @staticmethod - def add_to_queue(analysis_id, required_statuses): - st.session_state[RefreshHandler.q_name].append((analysis_id, required_statuses)) - - @staticmethod - def set_up(): - if RefreshHandler.q_name not in st.session_state: - st.session_state[RefreshHandler.q_name] = [] - if RefreshHandler.refresh_bool not in st.session_state: - st.session_state[RefreshHandler.refresh_bool] = False - - @staticmethod - def queue_empty(): - return len(RefreshHandler.get_queue()) == 0 - - def update_queue(self): - st.session_state[RefreshHandler.q_name] = self.clear_rerun_queue() - - if RefreshHandler.queue_empty() and RefreshHandler.is_refreshing(): - RefreshHandler.set_refresh_bool(False) - st.rerun() - - def run_every(self): - run_every = None - if not RefreshHandler.queue_empty(): - run_every = self.interval - - return run_every - - def clear_rerun_queue(self): - q = self.get_queue() - while True: - if len(q) == 0: - return [] - - id, required_statuses = q.pop(0) - if (self.client_interface.analyses.get(id)['status'] not in required_statuses): - q.insert(0, (id, required_statuses)) - return q diff --git a/modules/scenarios.py b/modules/scenarios.py new file mode 100644 index 0000000..84f2ae5 --- /dev/null +++ b/modules/scenarios.py @@ -0,0 +1,180 @@ +"""Shared logic for the public Scenarios app (`scenarios_app.py`). + +The Scenarios app is credential free: every visitor uses the same service +account, so analyses are attributed to a visitor by a tag in the analysis +name. Visitors see their own runs plus a curated set of showcase runs +(tagged `[showcase]`), and runs are limited by the `scenarios` section of the +UI config. +""" +import re +import uuid +from dataclasses import dataclass + +import streamlit as st + +from modules.oed import country_name, peril_family +from modules.status import IN_PROGRESS_STATUSES, is_active # noqa: F401 - re-exported + +VISITOR_PARAM = 'v' +_VISITOR_KEY = 'scenarios_visitor_id' +_TAG_PATTERN = re.compile(r'\s*\[(showcase|v:[0-9a-f]+)\]\s*$') + +IN_PROGRESS = IN_PROGRESS_STATUSES + +# Group-by choices offered to visitors, as (label, OED field) +GROUP_BY_OPTIONS = [('Portfolio', 'PortNumber'), ('Country', 'CountryCode'), ('Location', 'LocNumber')] + + +@dataclass +class ScenarioLimits: + """Run limits for the public Scenarios app (`scenarios` in the UI config).""" + + max_samples: int = 50 + default_samples: int = 10 + max_active_runs_per_visitor: int = 2 + max_active_runs: int = 3 + processes_per_run: int = 2 + showcase_tag: str = '[showcase]' + + @classmethod + def from_config(cls, ui_config): + settings = getattr(ui_config, 'scenarios', {}) or {} + known = {k: v for k, v in settings.items() if k in cls.__dataclass_fields__} + limits = cls(**known) + limits.default_samples = min(limits.default_samples, limits.max_samples) + return limits + + +def limit_processes(settings, processes): + """Cap the model processes a run uses (oasislmf computation settings). + + oasislmf defaults to one process per CPU for both the lookup and the loss + calculation, so several concurrent runs on one host can exhaust its memory. + Values already set in the settings (e.g. by the template) are kept. + """ + if processes and processes > 0: + computation = settings.setdefault('computation_settings', {}) + computation.setdefault('kernel_num_processes', processes) + computation.setdefault('lookup_num_processes', processes) + return settings + + +def visitor_id(): + """This visitor's id, kept in the URL (`?v=...`) so it survives reloads. + + Page navigation clears query parameters, so the id is also kept in the + session and written back to the URL on every page. + """ + vid = st.query_params.get(VISITOR_PARAM) or st.session_state.get(_VISITOR_KEY) + if not vid or not re.fullmatch(r'[0-9a-f]{12}', str(vid)): + vid = uuid.uuid4().hex[:12] + st.session_state[_VISITOR_KEY] = vid + if st.query_params.get(VISITOR_PARAM) != vid: + st.query_params[VISITOR_PARAM] = vid + return vid + + +def visitor_tag(vid): + return f'[v:{vid}]' + + +def tagged_name(name, tag): + return f'{name} {tag}' + + +def display_name(name): + """Analysis name without its visitor/showcase tag.""" + return _TAG_PATTERN.sub('', name or '') + + +def is_showcase(analysis, limits): + return (analysis.get('name') or '').endswith(limits.showcase_tag) + + +def visitor_analyses(analyses, vid): + tag = visitor_tag(vid) + return [a for a in analyses if (a.get('name') or '').endswith(tag)] + + +def showcase_analyses(analyses, limits, models=None, ui_config=None): + """Showcase runs, limited to configured scenario models when `models` and `ui_config` are given. + + Runs left over from scenarios since removed from the config are then not shown. + """ + runs = [a for a in analyses if is_showcase(a, limits)] + if models is not None and ui_config is not None: + configured = {m['id'] for m in models if m.get('model_id') in (ui_config.model_map or {})} + runs = [a for a in runs if a.get('model') in configured] + return runs + + +def run_blocked_reason(analyses, vid, limits): + """Why a new run can't start right now (None if it can).""" + active = [a for a in analyses if is_active(a)] + mine = [a for a in visitor_analyses(active, vid)] + if len(mine) >= limits.max_active_runs_per_visitor: + return (f'You already have {len(mine)} run(s) in progress. ' + 'Wait for one to finish before starting another.') + if len(active) >= limits.max_active_runs: + return 'The service is busy running other analyses. Please try again in a few minutes.' + return None + + +def scenario_portfolios(model, portfolios, ui_config): + """Portfolios offered for a scenario model (from the config's `model_map`).""" + names = (ui_config.model_map or {}).get(model.get('model_id')) + if names is None: + return [] + by_name = {p['name']: p for p in portfolios} + return [by_name[n] for n in names if n in by_name] + + +def scenario_models(models, portfolios, ui_config): + """Models that have at least one configured portfolio available.""" + return [m for m in models if scenario_portfolios(m, portfolios, ui_config)] + + +def _column(df, name): + """Column `name` of an OED DataFrame, matched case-insensitively (or None).""" + match = next((c for c in df.columns if c.lower() == name.lower()), None) + return df[match] if match is not None else None + + +def scenario_catalogue(models, portfolios, ui_config, settings_for, locations_for=None): + """Scenarios to browse, with title, peril, countries, provider and description. + + The title and description come from the model's settings; the peril and + countries from the scenario's first portfolio (`locations_for(portfolio)` + returns its location DataFrame), using OED peril and country names. + + Args: + models: model records from the API. + portfolios: portfolio records from the API. + ui_config: UI config with `model_map`. + settings_for: callable returning a model's settings (for name and description). + locations_for: optional callable returning a portfolio's location DataFrame. + """ + catalogue = [] + for model in scenario_models(models, portfolios, ui_config): + settings = settings_for(model) or {} + countries, peril = None, None + if locations_for is not None: + locations = locations_for(scenario_portfolios(model, portfolios, ui_config)[0]) + if locations is not None: + codes = _column(locations, 'CountryCode') + if codes is not None: + countries = sorted(codes.dropna().astype(str).unique()) + covered = _column(locations, 'LocPerilsCovered') + if covered is not None: + perils = {c for value in covered.dropna().astype(str).unique() for c in value.split(';')} + peril = ', '.join(sorted({peril_family(c) for c in perils if c})) + + catalogue.append({ + 'id': model['id'], + 'title': settings.get('name') or model['model_id'], + 'peril': peril or 'Not specified', + 'countries': [country_name(c) for c in countries or []], + 'provider': model.get('supplier_id') or '', + 'description': settings.get('description') or '', + }) + return sorted(catalogue, key=lambda e: e['title'].lower()) diff --git a/modules/status.py b/modules/status.py new file mode 100644 index 0000000..ef59d46 --- /dev/null +++ b/modules/status.py @@ -0,0 +1,26 @@ +"""Analysis status helpers shared by the standard UI and the Scenarios app.""" +from datetime import datetime, timezone + +IN_PROGRESS_STATUSES = ['INPUTS_GENERATION_QUEUED', 'INPUTS_GENERATION_STARTED', + 'RUN_QUEUED', 'RUN_STARTED'] + +# A generate-and-run reports READY between input generation and the loss run, +# because OasisPlatform's record_input_files always sets READY (it ignores its +# analysis_finish_status argument). A READY analysis updated this recently is +# treated as still running. +READY_GRACE_SECONDS = 120 + + +def is_active(analysis, now=None): + """Whether an analysis is in progress, including the READY gap of a generate-and-run.""" + status = analysis.get('status') + if status in IN_PROGRESS_STATUSES: + return True + if status == 'READY' and analysis.get('modified'): + try: + modified = datetime.fromisoformat(str(analysis['modified']).replace('Z', '+00:00')) + except ValueError: + return False + now = now or datetime.now(timezone.utc) + return (now - modified).total_seconds() < READY_GRACE_SECONDS + return False diff --git a/modules/visualisation.py b/modules/visualisation.py index 66004c4..48d437f 100644 --- a/modules/visualisation.py +++ b/modules/visualisation.py @@ -33,6 +33,19 @@ def has_summary_info(self, perspective, summary_level=None): return self._request_to_summary_info_fname(level, perspective, self.file_prefixes.get(perspective, '')) \ in self.output_file_dict + def has_output(self, perspective, output_type, summary_level=None): + """Whether the output file for `output_type` exists for the selected level and prefix.""" + level = summary_level or self.summary_level(perspective) + prefix = self.file_prefixes.get(perspective, '') + return self._file(self._request_to_fname(level, perspective, output_type, prefix=prefix)) is not None + + def _file(self, csv_name): + """Output file by its `.csv` name, or its `.parquet` equivalent (ORD parquet_format).""" + df = self.output_file_dict.get(csv_name) + if df is None and csv_name.endswith('.csv'): + df = self.output_file_dict.get(csv_name[:-4] + '.parquet') + return df + def fields_available(self, perspective, oed_fields, summary_level=None): """Whether outputs can be broken down by `oed_fields`: either a summary-info file exists, or the outputs already contain the fields @@ -108,15 +121,14 @@ def get(self, summary_level, perspective, output_type, **kwargs): prefix = self.file_prefixes.get(perspective, '') fname = self._request_to_fname(summary_level, perspective, output_type, prefix=prefix, **kwargs) - results = self.output_file_dict.get(fname) + results = self._file(fname) if results is None: logger.error(f'Failed to find output file: {fname}') raise OasisException('Output file not found.') oed_fields = self.oed_fields.get(perspective, None) if oed_fields: - summary_info = self.output_file_dict.get( - self._request_to_summary_info_fname(summary_level, perspective, prefix)) + summary_info = self._file(self._request_to_summary_info_fname(summary_level, perspective, prefix)) results = self.add_oed_fields(results, summary_info, oed_fields) missing = [f for f in oed_fields if f not in results.columns] if missing: diff --git a/oasis-scenarios-platform.yml b/oasis-scenarios-platform.yml deleted file mode 100755 index 96fecba..0000000 --- a/oasis-scenarios-platform.yml +++ /dev/null @@ -1,398 +0,0 @@ -volumes: - server-db-OasisData: - celery-db-OasisData: - filestore-OasisData: -x-shared-env: &shared-env - OASIS_DEBUG: 1 - OASIS_URL_SUB_PATH: 0 - OASIS_CELERY_BROKER_URL: "amqp://rabbit:rabbit@broker:5672" - OASIS_SERVER_DB_HOST: server-db - OASIS_SERVER_DB_PASS: oasis - OASIS_SERVER_DB_USER: oasis - OASIS_SERVER_DB_NAME: oasis - OASIS_SERVER_DB_PORT: 5432 - OASIS_SERVER_CHANNEL_LAYER_HOST: channel-layer - OASIS_SERVER_DB_ENGINE: django.db.backends.postgresql_psycopg2 - OASIS_CELERY_DB_ENGINE: db+postgresql+psycopg2 - OASIS_CELERY_DB_HOST: celery-db - OASIS_CELERY_DB_PASS: password - OASIS_CELERY_DB_USER: celery - OASIS_CELERY_DB_NAME: celery - OASIS_CELERY_DB_PORT: 5432 - OASIS_INPUT_GENERATION_CONTROLLER_QUEUE: task-controller - OASIS_LOSSES_GENERATION_CONTROLLER_QUEUE: task-controller - -x-volumes: &shared-volumes - - filestore-OasisData:/shared-fs:rw -services: - server: - restart: always - image: ${SERVER_IMG:-coreoasis/api_server}:${VERS_API:-latest} - command: ["./wsgi/run-wsgi.sh"] - ports: - - 8000:8000 - - 51970:51970 - links: - - server-db - - celery-db - - broker - environment: - <<: *shared-env - STARTUP_RUN_MIGRATIONS: "true" - OASIS_ADMIN_USER: admin - OASIS_ADMIN_PASS: catmodels - volumes: - - filestore-OasisData:/shared-fs:rw - healthcheck: - test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/healthcheck/')"] - interval: 30s - retries : 10 - start_period: 30s - timeout: 10s - server_websocket: - restart: always - image: ${SERVER_IMG:-coreoasis/api_server}:${VERS_API:-latest} - command: ["./asgi/run-asgi.sh"] - links: - - server-db - - celery-db - - broker - ports: - - 8001:8001 - environment: - <<: *shared-env - volumes: - - filestore-OasisData:/shared-fs:rw - v2-worker-monitor: - restart: always - image: ${SERVER_IMG:-coreoasis/api_server}:${VERS_API:-latest} - command: [celery, -A, 'src.server.oasisapi.celery_app_v2', worker, --loglevel=INFO, -Q, celery-v2] - links: - - server-db - - celery-db - - broker - environment: - <<: *shared-env - volumes: - - filestore-OasisData:/shared-fs:rw - v2-task-controller: - restart: always - image: ${SERVER_IMG:-coreoasis/api_server}:${VERS_API:-latest} - command: [celery, -A, 'src.server.oasisapi.celery_app_v2', worker, --loglevel=INFO, -Q, task-controller] - links: - - server-db - - celery-db - - broker - environment: - <<: *shared-env - volumes: - - filestore-OasisData:/shared-fs:rw - celery-beat_v2: - restart: always - image: ${SERVER_IMG:-coreoasis/api_server}:${VERS_API:-latest} - command: [celery, -A, src.server.oasisapi.celery_app_v2, beat, --loglevel=INFO] - links: - - server-db - - celery-db - - broker - environment: - <<: *shared-env - volumes: *shared-volumes - piwind-worker: - restart: always - image: ${WORKER_IMG:-coreoasis/model_worker}:${VERS_WORKER:-latest} - build: - context: . - dockerfile: Dockerfile.model_worker - links: - - celery-db - - broker:mybroker - environment: - <<: *shared-env - OASIS_MODEL_SUPPLIER_ID: OasisLMF - OASIS_MODEL_ID: PiWind - OASIS_MODEL_VERSION_ID: 'v2' - OASIS_RUN_MODE: v2 - volumes: - - ./OasisPiWind/:/home/worker/model - - filestore-OasisData:/shared-fs:rw - maeq-worker: - restart: always - image: ${WORKER_IMG:-coreoasis/model_worker}:${VERS_WORKER:-latest} - build: - context: . - dockerfile: Dockerfile.model_worker - links: - - celery-db - - broker:mybroker - environment: - <<: *shared-env - OASIS_MODEL_SUPPLIER_ID: Impact Forecasting - OASIS_MODEL_ID: MAEQ - OASIS_MODEL_VERSION_ID: 'v2' - OASIS_RUN_MODE: v2 - volumes: - - filestore-OasisData:/shared-fs:rw - - ${SCENARIOS_PATH}/ImpactForecasting/MAEQ/1.0.0/:/home/worker/model - euws-worker: - restart: always - image: ${WORKER_IMG:-coreoasis/model_worker}:${VERS_WORKER:-latest} - build: - context: . - dockerfile: Dockerfile.model_worker - links: - - celery-db - - broker:mybroker - environment: - <<: *shared-env - OASIS_MODEL_SUPPLIER_ID: Impact Forecasting - OASIS_MODEL_ID: EUWS - OASIS_MODEL_VERSION_ID: 'v2' - OASIS_RUN_MODE: v2 - volumes: - - filestore-OasisData:/shared-fs:rw - - ${SCENARIOS_PATH}/ImpactForecasting/EUWS/1.0.0/:/home/worker/model - treq-worker: - restart: always - image: ${WORKER_IMG:-coreoasis/model_worker}:${VERS_WORKER:-latest} - build: - context: . - dockerfile: Dockerfile.model_worker - links: - - celery-db - - broker:mybroker - environment: - <<: *shared-env - OASIS_MODEL_SUPPLIER_ID: Impact Forecasting - OASIS_MODEL_ID: TREQ - OASIS_MODEL_VERSION_ID: 'v2' - OASIS_RUN_MODE: v2 - volumes: - - filestore-OasisData:/shared-fs:rw - - ${SCENARIOS_PATH}/ImpactForecasting/TREQ/1.0.0/:/home/worker/model - philippines_taiwan_defended-worker: - restart: always - image: ${WORKER_IMG:-coreoasis/model_worker}:${VERS_WORKER:-latest} - build: - context: . - dockerfile: Dockerfile.model_worker - links: - - celery-db - - broker:mybroker - environment: - <<: *shared-env - OASIS_MODEL_SUPPLIER_ID: JBA - OASIS_MODEL_ID: Philippines-Taiwan-Defended - OASIS_MODEL_VERSION_ID: 'v2' - OASIS_RUN_MODE: v2 - OASIS_OASISLMF_CONFIG: /home/worker/model/oasislmf.json - volumes: - - ${SCENARIOS_PATH}/JBA/Philippines-Taiwan/combined-defended/:/home/worker/model - - filestore-OasisData:/shared-fs:rw - philippines_taiwan_undefended-worker: - restart: always - image: ${WORKER_IMG:-coreoasis/model_worker}:${VERS_WORKER:-latest} - build: - context: . - dockerfile: Dockerfile.model_worker - links: - - celery-db - - broker:mybroker - environment: - <<: *shared-env - OASIS_MODEL_SUPPLIER_ID: JBA - OASIS_MODEL_ID: Philippines-Taiwan-Undefended - OASIS_MODEL_VERSION_ID: 'v2' - OASIS_RUN_MODE: v2 - OASIS_OASISLMF_CONFIG: /home/worker/model/oasislmf.json - volumes: - - ${SCENARIOS_PATH}/JBA/Philippines-Taiwan/combined-undefended/:/home/worker/model - - filestore-OasisData:/shared-fs:rw - ghana-E635900-worker: - restart: always - image: ${WORKER_IMG:-coreoasis/model_worker}:${VERS_WORKER:-latest} - build: - context: . - dockerfile: Dockerfile.model_worker - links: - - celery-db - - broker:mybroker - environment: - <<: *shared-env - OASIS_MODEL_SUPPLIER_ID: JBA - OASIS_MODEL_ID: Ghana-E635900 - OASIS_MODEL_VERSION_ID: 'v2' - OASIS_RUN_MODE: v2 - OASIS_OASISLMF_CONFIG: /home/worker/model/oasislmf.json - volumes: - - ${SCENARIOS_PATH}/JBA/Ghana/E635900/combined/:/home/worker/model - - filestore-OasisData:/shared-fs:rw - ghana-E689982-worker: - restart: always - image: ${WORKER_IMG:-coreoasis/model_worker}:${VERS_WORKER:-latest} - build: - context: . - dockerfile: Dockerfile.model_worker - links: - - celery-db - - broker:mybroker - environment: - <<: *shared-env - OASIS_MODEL_SUPPLIER_ID: JBA - OASIS_MODEL_ID: Ghana-E689982 - OASIS_MODEL_VERSION_ID: 'v2' - OASIS_RUN_MODE: v2 - OASIS_OASISLMF_CONFIG: /home/worker/model/oasislmf.json - volumes: - - ${SCENARIOS_PATH}/JBA/Ghana/E689982/combined/:/home/worker/model - - filestore-OasisData:/shared-fs:rw - ghana-E760461-worker: - restart: always - image: ${WORKER_IMG:-coreoasis/model_worker}:${VERS_WORKER:-latest} - build: - context: . - dockerfile: Dockerfile.model_worker - links: - - celery-db - - broker:mybroker - environment: - <<: *shared-env - OASIS_MODEL_SUPPLIER_ID: JBA - OASIS_MODEL_ID: Ghana-E760461 - OASIS_MODEL_VERSION_ID: 'v2' - OASIS_RUN_MODE: v2 - OASIS_OASISLMF_CONFIG: /home/worker/model/oasislmf.json - volumes: - - ${SCENARIOS_PATH}/JBA/Ghana/E760461/combined/:/home/worker/model - - filestore-OasisData:/shared-fs:rw - nepal-E151185-worker: - restart: always - image: ${WORKER_IMG:-coreoasis/model_worker}:${VERS_WORKER:-latest} - build: - context: . - dockerfile: Dockerfile.model_worker - links: - - celery-db - - broker:mybroker - environment: - <<: *shared-env - OASIS_MODEL_SUPPLIER_ID: JBA - OASIS_MODEL_ID: Nepal-E151185 - OASIS_MODEL_VERSION_ID: 'v2' - OASIS_RUN_MODE: v2 - OASIS_OASISLMF_CONFIG: /home/worker/model/oasislmf.json - volumes: - - ${SCENARIOS_PATH}/JBA/Nepal/E151185/combined/:/home/worker/model - - filestore-OasisData:/shared-fs:rw - nepal-E432557-worker: - restart: always - image: ${WORKER_IMG:-coreoasis/model_worker}:${VERS_WORKER:-latest} - build: - context: . - dockerfile: Dockerfile.model_worker - links: - - celery-db - - broker:mybroker - environment: - <<: *shared-env - OASIS_MODEL_SUPPLIER_ID: JBA - OASIS_MODEL_ID: Nepal-E432557 - OASIS_MODEL_VERSION_ID: 'v2' - OASIS_RUN_MODE: v2 - OASIS_OASISLMF_CONFIG: /home/worker/model/oasislmf.json - volumes: - - ${SCENARIOS_PATH}/JBA/Nepal/E432557/combined/:/home/worker/model - - filestore-OasisData:/shared-fs:rw - nepal-E505423-worker: - restart: always - image: ${WORKER_IMG:-coreoasis/model_worker}:${VERS_WORKER:-latest} - build: - context: . - dockerfile: Dockerfile.model_worker - links: - - celery-db - - broker:mybroker - environment: - <<: *shared-env - OASIS_MODEL_SUPPLIER_ID: JBA - OASIS_MODEL_ID: Nepal-E505423 - OASIS_MODEL_VERSION_ID: 'v2' - OASIS_RUN_MODE: v2 - OASIS_OASISLMF_CONFIG: /home/worker/model/oasislmf.json - volumes: - - ${SCENARIOS_PATH}/JBA/Nepal/E505423/combined/:/home/worker/model - - filestore-OasisData:/shared-fs:rw - us_hurricane-worker: - restart: always - image: ${WORKER_IMG:-coreoasis/model_worker}:${VERS_WORKER:-latest} - build: - context: . - dockerfile: Dockerfile.model_worker - links: - - celery-db - - broker:mybroker - environment: - <<: *shared-env - OASIS_MODEL_SUPPLIER_ID: ARA - OASIS_MODEL_ID: US-Hurricane - OASIS_MODEL_VERSION_ID: 'v2' - OASIS_RUN_MODE: v2 - OASIS_OASISLMF_CONFIG: /home/worker/model/oasislmf.json - volumes: - - ${SCENARIOS_PATH}/ARA/US_Hurricane/:/home/worker/model - - filestore-OasisData:/shared-fs:rw - france_hail-worker: - restart: always - image: ${WORKER_IMG:-coreoasis/model_worker}:${VERS_WORKER:-latest} - build: - context: . - dockerfile: Dockerfile.model_worker - links: - - celery-db - - broker:mybroker - environment: - <<: *shared-env - OASIS_MODEL_SUPPLIER_ID: IPE - OASIS_MODEL_ID: France-Hail - OASIS_MODEL_VERSION_ID: 'v2' - OASIS_RUN_MODE: v2 - OASIS_OASISLMF_CONFIG: /home/worker/model/oasislmf.json - volumes: - - ${SCENARIOS_PATH}/IPE/FranceHail/:/home/worker/model - - filestore-OasisData:/shared-fs:rw - server-db: - restart: always - image: postgres - environment: - - POSTGRES_DB=oasis - - POSTGRES_USER=oasis - - POSTGRES_PASSWORD=oasis - volumes: - - server-db-OasisData:/var/lib/postgresql/data:rw - ports: - - 33307:3306 - celery-db: - restart: always - image: postgres - environment: - - POSTGRES_DB=celery - - POSTGRES_USER=celery - - POSTGRES_PASSWORD=password - volumes: - - celery-db-OasisData:/var/lib/postgresql/data:rw - ports: - - 33306:5432 - broker: - restart: always - image: rabbitmq:3.8.14-management - environment: - - RABBITMQ_DEFAULT_USER=rabbit - - RABBITMQ_DEFAULT_PASS=rabbit - ports: - - 5672:5672 - - 15672:15672 - channel-layer: - restart: always - image: redis:5.0.7 - ports: - - 6379:6379 diff --git a/oasis-scenarios-ui.yml b/oasis-scenarios-ui.yml deleted file mode 100644 index 1c3b011..0000000 --- a/oasis-scenarios-ui.yml +++ /dev/null @@ -1,43 +0,0 @@ -services: - streamlit_ui: - restart: always - image: coreoasis/oasis_scenarios:latest - container_name: oasis_st_ui - build: - dockerfile: ./oasisui_st_app.Dockerfile - ports: - - 8501:8501 - environment: - - API_URL=http://server:8000 - volumes: - - ./defaults/:/usr/src/app/defaults/ - - ./scenarios/assets/:/usr/src/app/scenarios/assets/ - - type: bind - source: ./scripts/ - target: /usr/src/app/scripts/ - - type: bind - source: ./.streamlit/config-local.toml - target: /usr/src/app/.streamlit/config.toml - - type: bind - source: ./.streamlit/secrets.toml - target: /usr/src/app/.streamlit/secrets.toml - - type: bind - source: ./scenarios/ui-config.json - target: /usr/src/app/ui-config.json - develop: - watch: - - action: sync - path: ./app.py - target: ./usr/src/app/app.py - - action: sync - path: ./pages/ - target: ./usr/src/app/pages/ - - action: sync - path: ./modules/ - target: ./usr/src/app/modules/ - - action: sync - path: ./scenarios/ui-config.json - target: ./usr/src/app/ui-config.json - - action: sync - path: ./scripts/ - target: ./usr/src/app/scripts/ diff --git a/oasisui_st_app.Dockerfile b/oasisui_st_app.Dockerfile index b21d38f..262ec6f 100644 --- a/oasisui_st_app.Dockerfile +++ b/oasisui_st_app.Dockerfile @@ -23,6 +23,11 @@ COPY ./modules ./modules COPY ./app.py ./app.py COPY ./pages ./pages COPY ./assets/ ./assets +# Scenarios app (run with `streamlit run scenarios_app.py`) and its setup scripts +COPY ./scenarios_app.py ./scenarios_app.py +COPY ./scenarios_ui ./scenarios_ui +COPY ./scenarios ./scenarios +COPY ./scripts ./scripts # Run streamlit EXPOSE 8501 diff --git a/pages/analyses.py b/pages/analyses.py index 6abb05e..7038789 100644 --- a/pages/analyses.py +++ b/pages/analyses.py @@ -12,7 +12,8 @@ from pages.components.common import (ERROR_STATUSES, IN_PROGRESS_STATUSES, MODELS_PAGE, NEW_ANALYSIS_DEFAULTS, PORTFOLIOS_PAGE, SELECTED_ANALYSIS, SELECTED_MODEL, SELECTED_PORTFOLIO, analysis_progress, current_task, - format_status, open_record, selectable_table) + format_status, is_active, open_record, selectable_table, + status_label) from pages.components.data import (analyses_df, analysis_files, analysis_settings, cached_model_settings, model_label, models_df, portfolio_file_df, session_cached) @@ -245,7 +246,7 @@ def edit_settings_view(analysis): portfolio_fields(portfolio)) st.divider() - in_progress = analysis['status'] in IN_PROGRESS_STATUSES + in_progress = is_active(analysis) if in_progress: st.caption(':orange[The analysis is running. Settings can be changed once it finishes.]') elif problems: @@ -308,7 +309,7 @@ def results_tab(analysis, settings): outputs = analysis_files(ci, analysis, 'output_file') inputs = analysis_files(ci, analysis, 'input_file') locations = inputs.get('location.csv', inputs.get('location.parquet')) - render_results(settings, outputs, locations) + render_results(settings, outputs, locations, key=analysis['id']) st.divider() st.markdown('**Output files**') @@ -366,7 +367,7 @@ def analysis_detail(analysis): status = analysis['status'] portfolio = portfolios_by_id.get(analysis['portfolio'], {}) model = models_by_id.get(analysis['model'], {}) - in_progress = status in IN_PROGRESS_STATUSES + in_progress = is_active(analysis) title_col, *btn_cols = st.columns([0.52, 0.12, 0.12, 0.12, 0.12], vertical_alignment='bottom') title_col.subheader(analysis['name']) @@ -491,7 +492,7 @@ def list_view(): height=min(38 + 35 * max(len(table), 1), 400)) snapshot = {a['id']: a['status'] for a in analyses} - any_running = any(s in IN_PROGRESS_STATUSES for s in snapshot.values()) + any_running = any(is_active(a) for a in analyses) @st.fragment(run_every='2s' if any_running else None) def live_status(): @@ -501,11 +502,11 @@ def live_status(): if {a['id']: a['status'] for a in fresh} != snapshot: st.rerun() # A status changed: refresh the whole page for a in fresh: - if a['status'] not in IN_PROGRESS_STATUSES: + if not is_active(a): continue fraction, detail = analysis_progress(a) task = current_task(ci.analyses.sub_tasks(a['id'])) - text = ' · '.join(x for x in [f"**{a['name']}**", format_status(a['status']), task, detail] if x) + text = ' · '.join(x for x in [f"**{a['name']}**", status_label(a), task, detail] if x) st.progress(fraction or 0.0, text=text) live_status() diff --git a/pages/components/common.py b/pages/components/common.py index 92d71c5..6a1d222 100644 --- a/pages/components/common.py +++ b/pages/components/common.py @@ -1,4 +1,5 @@ """File containig some common methods for `pages/`.""" +from modules.status import IN_PROGRESS_STATUSES, is_active # noqa: F401 - re-exported import streamlit as st from urllib.parse import urlparse from pathlib import PurePosixPath @@ -46,8 +47,6 @@ def get_page_path(): 'RUN_ERROR': '❌', } -IN_PROGRESS_STATUSES = ['INPUTS_GENERATION_QUEUED', 'INPUTS_GENERATION_STARTED', - 'RUN_QUEUED', 'RUN_STARTED'] ERROR_STATUSES = ['INPUTS_GENERATION_ERROR', 'RUN_ERROR'] @@ -59,6 +58,13 @@ def format_status(status): return f"{STATUS_ICONS.get(status, '')} {label}".strip() +def status_label(analysis): + """Status label for an analysis, showing the READY gap of a generate-and-run as starting.""" + if analysis.get('status') == 'READY' and is_active(analysis): + return '⏳ Inputs ready, starting run' + return format_status(analysis.get('status')) + + def analysis_progress(analysis): """Progress of a running analysis as `(fraction or None, description)`. diff --git a/pages/components/create.py b/pages/components/create.py deleted file mode 100644 index 477559a..0000000 --- a/pages/components/create.py +++ /dev/null @@ -1,53 +0,0 @@ -"""Analysis creation form used by the Scenarios page.""" -import streamlit as st - -from modules.validation import NameValidation, NotNoneValidation, ValidationError, ValidationGroup - - -def create_analysis_form(portfolios, models): - """Analysis creation form ui component.""" - - def list_empty(lst): - if len(lst) == 0: - return True - if all(e is None for e in lst): - return True - return False - - if list_empty(portfolios) or list_empty(models): - st.info("Ensure portfolios and models are loaded.") - return None - - def format_portfolio(portfolio): - return f"{portfolio['name']}" - - def format_model(model): - if "model_name" in model: - return model['model_name'] - return f"{model['model_id']} {model['run_mode']} {model['supplier_id']}" - - with st.form("create_analysis_form", clear_on_submit=True, enter_to_submit=False): - name = st.text_input("Analysis Name") - - selected_port = 0 if len(portfolios) == 1 else None - portfolio = st.selectbox('Select Portfolio', options=portfolios, - index=selected_port, format_func=format_portfolio) - - selected_model = 0 if len(models) == 1 else None - model = st.selectbox('Select Model', options=models, - index=selected_model, format_func=format_model) - - submitted = st.form_submit_button("Create Analysis") - - if submitted: - val_group = ValidationGroup() - val_group.add_validation(NameValidation('Name'), name) - val_group.add_validation(NotNoneValidation('Portfolio'), portfolio) - val_group.add_validation(NotNoneValidation('Model'), model) - - try: - val_group.validate() - return {'name': name, 'model_id': int(model['id']), 'portfolio_id': int(portfolio['id'])} - except ValidationError as e: - st.error(e) - return None diff --git a/pages/components/data.py b/pages/components/data.py index 0ca4632..5661f6b 100644 --- a/pages/components/data.py +++ b/pages/components/data.py @@ -13,7 +13,7 @@ from requests.exceptions import HTTPError from modules.client import PortfoliosEndpointInterface -from pages.components.common import format_status +from pages.components.common import status_label logger = logging.getLogger(__name__) @@ -148,7 +148,7 @@ def analyses_df(analyses, portfolios, models_frame): 'id': a['id'], 'name': a['name'], 'status': a.get('status'), - 'status_label': format_status(a.get('status')), + 'status_label': status_label(a), 'portfolio': a.get('portfolio'), 'portfolio_name': portfolio_names.get(a.get('portfolio'), f"#{a.get('portfolio')}"), 'model': a.get('model'), diff --git a/pages/components/display.py b/pages/components/display.py index dbe9b6c..0ba4f64 100644 --- a/pages/components/display.py +++ b/pages/components/display.py @@ -247,9 +247,19 @@ def find_zoom_level(lon_range): return 18 return min(max(masked.iloc[0, :].name - 1, 0), 18) - lon_range = locations[self.longitude].max() - locations[self.longitude].min() - - zoom = find_zoom_level(lon_range) + # Frame the map on the locations with a loss (all of them if none have one), ignoring + # missing coordinates and 0,0 ("not geocoded") + lon, lat = locations[self.longitude], locations[self.latitude] + placed = lon.notna() & lat.notna() & ((lon != 0) | (lat != 0)) + framed = locations[placed & (locations[self.weight] > 0)] + if framed.empty: + framed = locations[placed] if placed.any() else locations + lon_min, lon_max = framed[self.longitude].min(), framed[self.longitude].max() + lat_min, lat_max = framed[self.latitude].min(), framed[self.latitude].max() + center = {'lon': (lon_min + lon_max) / 2, 'lat': (lat_min + lat_max) / 2} + + # The map is about twice as wide as it is tall, so a north-south spread needs more room + zoom = find_zoom_level(max(lon_max - lon_min, 2 * (lat_max - lat_min))) format_weight = self.weight if len(format_weight) > 1: @@ -262,6 +272,7 @@ def find_zoom_level(lon_range): color_continuous_scale="YlOrRd", opacity=0.75, zoom=zoom, + center=center, labels={self.weight: format_weight}) fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) fig.update_layout(coloraxis_colorbar=dict( diff --git a/pages/components/exposure.py b/pages/components/exposure.py new file mode 100644 index 0000000..356472a --- /dev/null +++ b/pages/components/exposure.py @@ -0,0 +1,53 @@ +"""Exposure summary for a portfolio's location file: key figures, a map and TIV breakdowns.""" +import streamlit as st + +from pages.components.display import MapView +from pages.components.output import summarise_locations, valid_locations + +TIV_COLUMNS = ['BuildingTIV', 'OtherTIV', 'ContentsTIV', 'BITIV'] +BREAKDOWN_FIELDS = ['CountryCode', 'OccupancyCode', 'ConstructionCode', 'LocPerilsCovered'] + + +def exposure_metrics(locations): + summary = summarise_locations(locations).iloc[0] + cols = st.columns(4) + cols[0].metric('Locations', f"{int(summary['number_locations']):,}") + cols[1].metric('Total TIV', f"{summary['TotalTIV']:,.0f}", + help='Total insured value: building, contents, other and business interruption.') + if 'CountryCode' in locations: + cols[2].metric('Countries', locations['CountryCode'].nunique()) + if 'LocPerilsCovered' in locations: + cols[3].metric('Peril codes', locations['LocPerilsCovered'].nunique()) + + +def exposure_map(locations): + if {'Latitude', 'Longitude', 'BuildingTIV'} <= set(locations.columns) and valid_locations(locations): + MapView(locations, weight='BuildingTIV', map_type='heatmap').display() + elif {'CountryCode', 'BuildingTIV'} <= set(locations.columns): + MapView(locations, weight='BuildingTIV', map_type='choropleth').display() + else: + st.caption('No coordinates or country codes to map.') + + +def exposure_breakdowns(locations): + tiv_cols = [c for c in TIV_COLUMNS if c in locations] + for field in BREAKDOWN_FIELDS: + if field in locations and tiv_cols: + st.markdown(f'**TIV by {field}**') + breakdown = (locations.groupby(field)[tiv_cols].sum() + .assign(Locations=locations.groupby(field).size()) + .sort_values(tiv_cols[0], ascending=False).reset_index()) + st.dataframe(breakdown, hide_index=True, height=200) + + +def exposure_overview(locations, breakdowns=True): + """Key figures, a map and (optionally) TIV breakdowns for a location file.""" + exposure_metrics(locations) + if breakdowns: + map_col, breakdown_col = st.columns([0.6, 0.4]) + with map_col: + exposure_map(locations) + with breakdown_col: + exposure_breakdowns(locations) + else: + exposure_map(locations) diff --git a/pages/components/footer.py b/pages/components/footer.py deleted file mode 100644 index 8a3c69a..0000000 --- a/pages/components/footer.py +++ /dev/null @@ -1,30 +0,0 @@ -from modules.config import retrieve_ui_config -from modules.logging import get_session_logger -import streamlit as st - -from pages.components.common import get_page_path - -logger = get_session_logger() - - -def generate_footer(ui_config=None): - if ui_config is None: - ui_config = retrieve_ui_config() - - if ui_config.footer is None: - return - - assert "path" in ui_config.footer, "No footer path in config." - - try: - with open(ui_config.footer.get("path"), "r") as f: - footer_txt = f.read() - - page_path = get_page_path() - if "pages" in ui_config.footer and page_path in ui_config.footer["pages"]: - logger.info(f"Footer applied to {page_path}.") - st.write('---') - st.caption(footer_txt) - - except FileNotFoundError as _: - logger.error(f"Footer file not found as path {ui_config.footer['path']}") diff --git a/pages/components/output.py b/pages/components/output.py index 6f9da9b..42d632e 100644 --- a/pages/components/output.py +++ b/pages/components/output.py @@ -7,6 +7,7 @@ from pages.components.display import DataframeView, MapView from pages.components.common import PERSPECTIVES_MAP +from modules.oed import has_coordinates logger = logging.getLogger(__name__) @@ -74,6 +75,46 @@ def sample_selector(df, vis, key): return df[df['SampleId'] == choice] +SAMPLE_TYPE_LABELS = {'Sample': 'Sample', 'Analytical': 'Analytical'} + + +def order_sample_types(values): + """Order Analytical/Sample result types so Sample comes first (the default).""" + order = list(SAMPLE_TYPE_LABELS) + return sorted(values, key=lambda v: order.index(v) if v in order else len(order)) + + +def sample_type_selector(df, col, key, label='Results:'): + """Choose Sample (default) or Analytical rows of an output with a type column.""" + if col not in df.columns: + return df + types = order_sample_types(df[col].dropna().unique().tolist()) + if len(types) <= 1: + return df + choice = st.radio(label, options=types, index=0, horizontal=True, key=key, + help='Sample: statistics of the sampled losses. Analytical: the model\'s ' + 'numerically integrated values, which don\'t depend on the number of samples.') + return df[df[col] == choice] + + +ALL_EVENTS = 'All events' + + +def event_selector(df, loss_col, key): + """Choose one event (or all) of an event loss table with several events. + + Events are listed largest loss first; the choice applies to the table and the map. + """ + if 'EventId' not in df.columns or df['EventId'].nunique() <= 1: + return df + totals = df.groupby('EventId', observed=True)[loss_col].sum().sort_values(ascending=False) + options = [ALL_EVENTS] + totals.index.tolist() + choice = st.selectbox('Event:', options, key=key, + format_func=lambda e: e if e == ALL_EVENTS else f'Event {e} (loss {totals[e]:,.0f})', + help='This scenario has more than one event. Show one, or all of them combined.') + return df if choice == ALL_EVENTS else df[df['EventId'] == choice] + + def order_ep_calcs(values): """Order EPCalc codes so full uncertainty comes first, then MeanDR.""" order = list(EP_CALC_LABELS) @@ -627,20 +668,21 @@ def eltcalc_map(map_df, locations, oed_fields=[], map_type=None, st.info("No map to display.") -def valid_locations(loc_df): - """Check if `Latitude` and `Longitude` columns are present - and if they are unique between locations. +def map_type_for(oed_fields, locations): + """How losses grouped by `oed_fields` can be mapped. + + 'heatmap' by location (needs coordinates), 'choropleth' by country, or None. """ - if loc_df is None: - return False - if not set(['Latitude', 'Longitude']).issubset(loc_df.columns): - return False + if 'LocNumber' in oed_fields and valid_locations(locations): + return 'heatmap' + if 'CountryCode' in oed_fields: + return 'choropleth' + return None - lat_long = loc_df[['Latitude', 'Longitude']] - if (lat_long == lat_long.iloc[0]).all(axis=None): - return False - return True +def valid_locations(loc_df): + """Whether locations have usable coordinates for a map (see `modules.oed.has_coordinates`).""" + return has_coordinates(loc_df) @st.fragment @@ -667,10 +709,11 @@ def generate_eltcalc_fragment(perspective, output, oed_fields = output.oed_fields.get(perspective) or [] eltcalc_result = output.get(output.summary_level(perspective), perspective, 'eltcalc') + map_type = map_type_for(oed_fields, locations) tab_names = [] if table: tab_names.append('table') - if map: + if map and map_type: tab_names.append('map') if len(tab_names) == 0: @@ -680,14 +723,6 @@ def generate_eltcalc_fragment(perspective, output, for name, tab in zip(tab_names, tabs): if name == 'map': - assert locations is not None, "Locations required for map view." - map_type = None - - if 'LocNumber' in oed_fields and valid_locations(locations): - map_type = 'heatmap' - elif 'CountryCode' in oed_fields: - map_type = 'choropleth' - with tab: map_df = eltcalc_result[eltcalc_result['type'] == 'Sample'] eltcalc_map(map_df, locations, oed_fields, map_type) @@ -710,12 +745,11 @@ def generate_melt_fragment(p, vis, locations=None): type_col = None if type_col: - types = data_df[type_col].unique() - selected_type = st.radio('Type Filter:', options=types, index=0, horizontal=True, - key=f'melt_{p}_type_filter') - data_df = data_df[data_df[type_col] == selected_type] + data_df = sample_type_selector(data_df, type_col, key=f'melt_{p}_type_filter') + data_df = event_selector(data_df, 'MeanLoss', key=f'melt_{p}_event_filter') - tab_names = ['table', 'map'] + map_type = map_type_for(oed_fields, locations) + tab_names = ['table', 'map'] if map_type else ['table'] with st.container(border=True): tabs = st.tabs([t.title() for t in tab_names]) @@ -732,19 +766,9 @@ def generate_melt_fragment(p, vis, locations=None): if selected is not None and not selected.empty: selected_events = selected['EventId'].tolist() - if locations is None: - with tabs[1]: - st.error("Map view unavailable.") - logger.error("Locations required for Map view") + if map_type is None: return - map_type = None - - if 'LocNumber' in oed_fields and valid_locations(locations): - map_type = 'heatmap' - elif 'CountryCode' in oed_fields: - map_type = 'choropleth' - if selected_events: data_df = data_df[data_df['EventId'].isin(selected_events)] @@ -773,8 +797,10 @@ def generate_qelt_fragment(p, vis, locations=None): key=f'qelt_{p}_quantile_filter') data_df = data_df[data_df['Quantile'] == quantile_filter] + data_df = event_selector(data_df, 'Loss', key=f'qelt_{p}_event_filter') - tab_names = ['table', 'map'] + map_type = map_type_for(oed_fields, locations) + tab_names = ['table', 'map'] if map_type else ['table'] with st.container(border=True): tabs = st.tabs([t.title() for t in tab_names]) @@ -788,19 +814,9 @@ def generate_qelt_fragment(p, vis, locations=None): if selected is not None and not selected.empty: selected_events = selected['EventId'].tolist() - if locations is None: - with tabs[1]: - st.error("Map view unavailable.") - logger.error("Locations required for Map view") + if map_type is None: return - map_type = None - - if 'LocNumber' in oed_fields and valid_locations(locations): - map_type = 'heatmap' - elif 'CountryCode' in oed_fields: - map_type = 'choropleth' - map_df = data_df if selected_events: map_df = data_df[data_df['EventId'].isin(selected_events)] @@ -841,8 +857,10 @@ def generate_selt_fragment(p, vis, locations=None): oed_fields = vis.oed_fields.get(p) or [] data_df = sample_selector(data_df, vis, key=f'selt_{p}_sample_filter') + data_df = event_selector(data_df, 'Loss', key=f'selt_{p}_event_filter') - tab_names = ['table', 'map'] + map_type = map_type_for(oed_fields, locations) + tab_names = ['table', 'map'] if map_type else ['table'] with st.container(border=True): tabs = st.tabs([t.title() for t in tab_names]) @@ -855,18 +873,9 @@ def generate_selt_fragment(p, vis, locations=None): if selected is not None and not selected.empty: selected_events = selected['EventId'].tolist() - if locations is None: - with tabs[1]: - st.error("Map view unavailable.") - logger.error("Locations required for Map view") + if map_type is None: return - map_type = None - if 'LocNumber' in oed_fields and valid_locations(locations): - map_type = 'heatmap' - elif 'CountryCode' in oed_fields: - map_type = 'choropleth' - map_df = data_df if selected_events: map_df = data_df[data_df['EventId'].isin(selected_events)] @@ -886,6 +895,7 @@ def generate_selt_fragment(p, vis, locations=None): @st.fragment def generate_aalcalc_fragment(p, vis): result = vis.get(vis.summary_level(p), p, 'aalcalc') + result = sample_type_selector(result, 'type', key=f'aalcalc_{p}_type_filter') oed_fields = vis.oed_fields.get(p) or [] breakdown_field = None @@ -907,7 +917,7 @@ def generate_aalcalc_fragment(p, vis): result = result.loc[:, group_field + ['mean']] result = result.groupby(group_field, as_index=False).agg({'mean': 'sum'}) - graph = px.bar(result, x='type', y='mean', color=breakdown_field, + graph = px.bar(result, x=breakdown_field or 'type', y='mean', labels={'type': 'Type', 'mean': 'Mean'}, color_discrete_sequence=px.colors.sequential.RdBu) @@ -922,6 +932,7 @@ def generate_alt_fragment(p, vis, output_type='alt_meanonly'): result = vis.get(vis.summary_level(p), p, output_type) type_field = 'SampleType' mean_field = 'MeanLoss' + result = sample_type_selector(result, type_field, key=f'{output_type}_{p}_type_filter') oed_fields = vis.oed_fields.get(p) or [] breakdown_field = None @@ -945,7 +956,7 @@ def generate_alt_fragment(p, vis, output_type='alt_meanonly'): type_formatted = type_field[0] + type_field[1:] mean_formatted = mean_field[0] + mean_field[1:] - graph = px.bar(result, x=type_field, y=mean_field, color=breakdown_field, + graph = px.bar(result, x=breakdown_field or type_field, y=mean_field, labels={type_field: type_formatted, mean_field: mean_formatted}, color_discrete_sequence=px.colors.sequential.RdBu) @@ -1181,7 +1192,12 @@ def format_lec_options(opt): for r in results: values.update(r[col].unique().tolist()) - values = order_ep_calcs(values) if col == 'EPCalc' else sorted(values) + if col == 'EPCalc': + values = order_ep_calcs(values) + elif col in ('type', 'SampleType'): + values = order_sample_types(values) + else: + values = sorted(values) if len(values) > 1: format_map = spec.get('format_map') selected_value = st.radio(spec['label'], options=values, horizontal=True, @@ -1340,10 +1356,7 @@ def generate_pltcalc_fragment(p, vis): elif selected_group: result[selected_group] = result[selected_group].astype(str) - types = result['type'].unique() - selected_type = st.radio('Type filter: ', options=types, index=0, key=f'pltcalc_{p}_type_filter') - - result = result[result['type'] == selected_type] + result = sample_type_selector(result, 'type', key=f'pltcalc_{p}_type_filter') date_cols = { 'year': 'occ_year', @@ -1377,8 +1390,8 @@ def generate_mplt_fragment(p, vis): elif selected_group: result[selected_group] = result[selected_group].astype(str) - types = result['SampleType'].unique() - selected_type = st.radio('Type filter: ', options=types, index=0, horizontal=True, + types = order_sample_types(result['SampleType'].unique().tolist()) + selected_type = st.radio('Results:', options=types, index=0, horizontal=True, key=f'mplt_{p}_type_filter') result = result[result['SampleType'] == selected_type] @@ -1668,8 +1681,8 @@ def generate_aalcalc_comparison_fragment(p, outputs, names=None): breakdown_field_invalid = True breakdown_field = None - types = results[0]['type'].unique() - selected_type = st.radio('Type filter: ', options=types, index=0, horizontal=True, + types = order_sample_types(results[0]['type'].unique().tolist()) + selected_type = st.radio('Results:', options=types, index=0, horizontal=True, key=f'aalcalc_comparison_{p}_type_filter') for i in range(2): @@ -1768,7 +1781,9 @@ def generate_eltcalc_comparison_fragment(perspective, outputs, names=None, results = [o.get(o.summary_level(perspective), perspective, output_type) for o in outputs] oed_fields = shared_oed_fields(perspective, outputs) - options = results[0][filter_col].unique() + options = results[0][filter_col].unique().tolist() + if filter_col in ('type', 'SampleType'): + options = order_sample_types(options) if filter_index < 0: filter_index += len(options) @@ -1806,13 +1821,7 @@ def generate_eltcalc_comparison_fragment(perspective, outputs, names=None, st.info('Locations files not found.') return - map_type = None - - if 'LocNumber' in oed_fields and valid_locations(locations): - map_type = 'heatmap' - elif 'CountryCode' in oed_fields: - map_type = 'choropleth' - + map_type = map_type_for(oed_fields, locations) eltcalc_map(result, locations, oed_fields, map_type=map_type, intensity_col=intensity_col, group_fields=['loc_analysis_id']) @@ -1874,7 +1883,9 @@ def generate_pltcalc_comparison_fragment(p, outputs, names=None, output_type='pl breakdown_field_invalid = True breakdown_field = None - options = results[0][filter_col].unique() + options = results[0][filter_col].unique().tolist() + if filter_col in ('type', 'SampleType'): + options = order_sample_types(options) if filter_index < 0: filter_index += len(options) diff --git a/pages/components/process.py b/pages/components/process.py deleted file mode 100644 index 4f6637d..0000000 --- a/pages/components/process.py +++ /dev/null @@ -1,127 +0,0 @@ -from oasis_data_manager.errors import OasisException -import pandas as pd -from requests.models import HTTPError -import streamlit as st - -from modules.client import ClientInterface -from modules.logging import get_session_logger - -logger = get_session_logger() - - -def number_rows(portfolio_ids, client_interface, filename='location_file', col_name='number_rows'): - data = {'id': [], col_name: []} - for id in portfolio_ids: - file_func = getattr(client_interface.portfolios, f'get_{filename}', None) - if file_func is None: - raise OasisException('Portfolio file endpoint not found.') - - file_df = file_func(id, df=True) - if file_df is None: - data['id'].append(id) - data[col_name].append(None) - continue - - data['id'].append(id) - data[col_name].append(file_df.shape[0]) - return pd.DataFrame(data) - - -def number_locations(portfolio_ids, client_interface): - return number_rows(portfolio_ids, client_interface, filename='location_file', col_name='number_locations') - - -def number_accounts(portfolio_ids, client_interface): - return number_rows(portfolio_ids, client_interface, filename='accounts_file', col_name='number_accounts') - - -def portfolio_files(portfolios): - enriched = portfolios['id'].to_frame() - enriched['contains_location'] = portfolios['location_file.stored'].notna() - enriched['contains_accounts'] = portfolios['accounts_file.stored'].notna() - enriched['contains_ri_info'] = portfolios['reinsurance_info_file.stored'].notna() - enriched['contains_ri_scope'] = portfolios['reinsurance_scope_file.stored'].notna() - return enriched - - -def enrich_portfolios(portfolios, client_interface, - disable=[]): - """Enrich portfolios dataframe with additional columns. Each new column is given a key which can be disabled with the `disable` kwarg. The columns added and keys are listed below: - - 'loc': 'number_locations' - 'acc': 'number_accounts' - 'files': ['contains_location', 'contains_accounts', 'contains_ri_info', 'contains_ri_scope'] - """ - enriched = [] - if 'loc' not in disable: - _n_loc_df = number_locations(portfolios[portfolios['location_file.stored'].notna()]['id'], client_interface) - enriched.append(_n_loc_df.set_index('id')) - if 'acc' not in disable: - _n_acc_df = number_accounts(portfolios[portfolios['accounts_file.stored'].notna()]['id'], client_interface) - _n_acc_df = _n_acc_df.set_index('id') - enriched.append(_n_acc_df) - - if 'files' not in disable: - enriched.append(portfolio_files(portfolios).set_index('id')) - - if enriched: - portfolios = portfolios.set_index('id').join(enriched).reset_index(names='id') - - return portfolios - - -def enrich_analyses_with_portfolios(analyses, portfolios): - portfolios = portfolios[['id', 'name']].rename(columns={'name': 'portfolio_name'}) - analyses = analyses.set_index('portfolio').join(portfolios.set_index('id')).reset_index(names='portfolio') - - return analyses - - -def enrich_analyses_with_models(analyses, models): - cols = ['id', 'model_id', 'supplier_id'] - if 'model_name' in models: - cols += ['model_name'] - models = models[cols].rename(columns={'supplier_id': 'model_supplier'}) - analyses = analyses.set_index('model').join(models.set_index('id')).reset_index(names='model') - - return analyses - - -def enrich_analyses(analyses, portfolios=None, models=None): - # add portfolio names - if portfolios is not None: - analyses = enrich_analyses_with_portfolios(analyses, portfolios) - - # add model names - if models is not None: - analyses = enrich_analyses_with_models(analyses, models) - - return analyses - - -@st.cache_data(ttl="1d", hash_funcs={ClientInterface: lambda ci: ci.client.api.tkn_access}) -def add_model_names_to_models_cached(models: pd.DataFrame, - ci: ClientInterface, - col_name='model_name'): - return add_model_names_to_models(models, ci, col_name) - - -def add_model_names_to_models(models, ci, col_name='model_name'): - """Add the model names to models. Note the model `id` should be the index of the models. - - Args: - models (DataFrame): dataframe containing models endpoint output - ci (ClientInterface): intialised client interface - col_name (str) : column name for model names - """ - models[col_name] = '' - for model_id, _ in models.iterrows(): - try: - models.at[model_id, col_name] = ci.models.settings.get(model_id).get('name', None) - except HTTPError as _: - models.at[model_id, col_name] = None - logger.warning(f'No settings for model_id: {model_id}') - - models[col_name] = models[col_name].fillna(models['model_id']) - - return models diff --git a/pages/components/results.py b/pages/components/results.py index 91179db..b9ee8ca 100644 --- a/pages/components/results.py +++ b/pages/components/results.py @@ -2,7 +2,6 @@ import re import streamlit as st -from oasis_data_manager.errors import OasisException from modules.schemas import PERSPECTIVE_LABELS, PERSPECTIVES from modules.visualisation import OutputInterface @@ -25,45 +24,46 @@ def _sections(summary, locations): ord_settings = summary.get('ord_output', {}) sections = [] - def add(enabled, title, render): + def add(enabled, title, render, output_type=None): if enabled: - sections.append((title, render)) + sections.append((title, render, output_type)) # ORD outputs add(ord_settings.get('elt_sample'), 'Sample event loss table (SELT)', - lambda p, vis: generate_selt_fragment(p, vis, locations=locations)) + lambda p, vis: generate_selt_fragment(p, vis, locations=locations), output_type='elt_sample') add(ord_settings.get('elt_moment'), 'Moment event loss table (MELT)', - lambda p, vis: generate_melt_fragment(p, vis, locations=locations)) + lambda p, vis: generate_melt_fragment(p, vis, locations=locations), output_type='elt_moment') add(ord_settings.get('elt_quantile'), 'Quantile event loss table (QELT)', - lambda p, vis: generate_qelt_fragment(p, vis, locations=locations)) - add(ord_settings.get('plt_sample'), 'Sample period loss table (SPLT)', generate_splt_fragment) - add(ord_settings.get('plt_moment'), 'Moment period loss table (MPLT)', generate_mplt_fragment) - add(ord_settings.get('plt_quantile'), 'Quantile period loss table (QPLT)', generate_qplt_fragment) + lambda p, vis: generate_qelt_fragment(p, vis, locations=locations), output_type='elt_quantile') + add(ord_settings.get('plt_sample'), 'Sample period loss table (SPLT)', generate_splt_fragment, output_type='plt_sample') + add(ord_settings.get('plt_moment'), 'Moment period loss table (MPLT)', generate_mplt_fragment, output_type='plt_moment') + add(ord_settings.get('plt_quantile'), 'Quantile period loss table (QPLT)', generate_qplt_fragment, output_type='plt_quantile') add(ord_settings.get('alt_meanonly'), 'Average loss table, mean only (ALT)', - lambda p, vis: generate_alt_fragment(p, vis, 'alt_meanonly')) + lambda p, vis: generate_alt_fragment(p, vis, 'alt_meanonly'), output_type='alt_meanonly') add(ord_settings.get('alt_period'), 'Period average loss table (PALT)', - lambda p, vis: generate_alt_fragment(p, vis, 'alt_period')) - add(ord_settings.get('alct_convergence'), 'Average loss convergence table (ALCT)', generate_alct_fragment) - add(any(ord_settings.get(e) for e in EPT_FLAGS), 'Exceedance probability table (EPT)', generate_ept_fragment) - add(any(ord_settings.get(e) for e in PSEPT_FLAGS), 'Per-sample EPT (PSEPT)', generate_psept_fragment) + lambda p, vis: generate_alt_fragment(p, vis, 'alt_period'), output_type='alt_period') + add(ord_settings.get('alct_convergence'), 'Average loss convergence table (ALCT)', generate_alct_fragment, output_type='alct_convergence') + add(any(ord_settings.get(e) for e in EPT_FLAGS), 'Exceedance probability table (EPT)', generate_ept_fragment, output_type='ept') + add(any(ord_settings.get(e) for e in PSEPT_FLAGS), 'Per-sample EPT (PSEPT)', generate_psept_fragment, output_type='psept') # Legacy ktools outputs add(summary.get('eltcalc'), 'ELT (legacy)', - lambda p, vis: generate_eltcalc_fragment(p, vis, locations=locations, map=True)) - add(summary.get('aalcalc'), 'AAL (legacy)', generate_aalcalc_fragment) + lambda p, vis: generate_eltcalc_fragment(p, vis, locations=locations, map=True), output_type='eltcalc') + add(summary.get('aalcalc'), 'AAL (legacy)', generate_aalcalc_fragment, output_type='aalcalc') add(summary.get('lec_output'), 'Loss exceedance curve (legacy)', - lambda p, vis: generate_leccalc_fragment(p, vis, summary.get('leccalc'))) - add(summary.get('pltcalc'), 'PLT (legacy)', generate_pltcalc_fragment) + lambda p, vis: generate_leccalc_fragment(p, vis, summary.get('leccalc')), output_type=None) + add(summary.get('pltcalc'), 'PLT (legacy)', generate_pltcalc_fragment, output_type='pltcalc') return sections -def render_results(settings, outputs, locations=None): +def render_results(settings, outputs, locations=None, key=None): """Visualise analysis outputs. Args: settings: the analysis settings used for the run. outputs: `{filename: DataFrame}` from the analysis output file. locations: optional location DataFrame used for maps. + key: identifies the analysis (e.g. its id), so widgets reset when switching analyses. """ if not outputs: st.info('No output files were found for this analysis.') @@ -88,7 +88,7 @@ def render_results(settings, outputs, locations=None): if len(levels) > 1: level_id = st.selectbox( 'Summary level', list(levels), format_func=lambda i: level_label(levels[i]), - key=f'results_level_{p}', + key=f'results_level_{p}' + (f'_{key}' if key is not None else ''), help='Each summary level groups losses differently. Choose which one to view.') else: st.caption(level_label(levels[level_id])) @@ -114,12 +114,13 @@ def render_results(settings, outputs, locations=None): sections = _sections(summary, locations) if not sections: st.info('No outputs were selected for this summary level.') - for i, (title, render) in enumerate(sections): + for i, (title, render, output_type) in enumerate(sections): with st.expander(title, expanded=i == 0): - try: - render(p, vis) - except OasisException: + # Check first: the views are fragments, which show their own errors + if output_type and not vis.has_output(p, output_type): st.info('This output was requested in the settings but the run did not produce it.') + else: + render(p, vis) def level_label(level): diff --git a/pages/portfolios.py b/pages/portfolios.py index f026d61..c9b5b91 100644 --- a/pages/portfolios.py +++ b/pages/portfolios.py @@ -6,8 +6,7 @@ SELECTED_PORTFOLIO, open_record, selectable_table) from pages.components.data import (FILE_TYPES, analyses_df, guess_file_type, models_df, portfolio_file_df, portfolios_df) -from pages.components.display import MapView -from pages.components.output import summarise_locations, valid_locations +from pages.components.exposure import exposure_overview ci = page_setup('Portfolios') @@ -201,33 +200,7 @@ def create_portfolio_dialog(): else: with st.spinner('Loading locations...'): locations = portfolio_file_df(ci, portfolio, 'location_file') - summary = summarise_locations(locations).iloc[0] - - metric_cols = st.columns(4) - metric_cols[0].metric('Locations', f"{int(summary['number_locations']):,}") - metric_cols[1].metric('Total TIV', f"{summary['TotalTIV']:,.0f}") - if 'CountryCode' in locations: - metric_cols[2].metric('Countries', locations['CountryCode'].nunique()) - if 'LocPerilsCovered' in locations: - metric_cols[3].metric('Peril codes', locations['LocPerilsCovered'].nunique()) - - tiv_cols = [c for c in ['BuildingTIV', 'OtherTIV', 'ContentsTIV', 'BITIV'] if c in locations] - map_col, breakdown_col = st.columns([0.6, 0.4]) - with map_col: - if {'Latitude', 'Longitude', 'BuildingTIV'} <= set(locations.columns) and valid_locations(locations): - MapView(locations, weight='BuildingTIV', map_type='heatmap').display() - elif {'CountryCode', 'BuildingTIV'} <= set(locations.columns): - MapView(locations, weight='BuildingTIV', map_type='choropleth').display() - else: - st.caption('No coordinates or country codes to map.') - with breakdown_col: - for field in ['CountryCode', 'OccupancyCode', 'ConstructionCode', 'LocPerilsCovered']: - if field in locations and tiv_cols: - st.markdown(f'**TIV by {field}**') - breakdown = (locations.groupby(field)[tiv_cols].sum() - .assign(Locations=locations.groupby(field).size()) - .sort_values(tiv_cols[0], ascending=False).reset_index()) - st.dataframe(breakdown, hide_index=True, height=200) + exposure_overview(locations) with analyses_tab: diff --git a/pages/scenarios.py b/pages/scenarios.py deleted file mode 100644 index 85388a0..0000000 --- a/pages/scenarios.py +++ /dev/null @@ -1,512 +0,0 @@ -from modules.authorisation import validate_page, handle_login -from oasis_data_manager.errors import OasisException -import tarfile -from io import BytesIO -from pathlib import Path -from requests.exceptions import HTTPError -import streamlit as st -from modules.logging import get_session_logger -from modules.nav import SidebarNav -from modules.config import retrieve_ui_config -from modules.rerun import RefreshHandler -from modules.settings import get_analyses_settings -from pages.components.display import DataframeView, MapView -from pages.components.create import create_analysis_form -from pages.components.footer import generate_footer -from pages.components.output import valid_locations -from modules.validation import KeyInValuesValidation, NotNoneValidation, ValidationGroup, IsNoneValidation -from modules.visualisation import OutputInterface -import time -from json import JSONDecodeError -import json - -from pages.components.output import generate_eltcalc_fragment, generate_leccalc_fragment, generate_pltcalc_fragment, model_summary, summarise_inputs, generate_aalcalc_fragment -from pages.components.output import generate_melt_fragment, generate_qelt_fragment, generate_selt_fragment -from pages.components.output import generate_mplt_fragment, generate_qplt_fragment, generate_splt_fragment -from pages.components.output import generate_alt_fragment, generate_alct_fragment -from pages.components.output import generate_ept_fragment, generate_psept_fragment -from pages.components.process import add_model_names_to_models_cached, enrich_analyses, enrich_portfolios - -logger = get_session_logger() - -########################################################################################## -# Header -########################################################################################## - -ui_config = retrieve_ui_config() -validate_page("Scenarios") - -st.set_page_config( - page_title="Scenarios", - layout="centered" -) - -cols = st.columns([0.1, 0.8, 0.1]) -with cols[1]: - st.image("images/oasis_logo.png") - - -########################################################################################## -# Page -########################################################################################## - -handle_login(ui_config.skip_login) - -SidebarNav() - -client_interface = st.session_state["client_interface"] -client = client_interface.client - -st.markdown("For more information on this tool and usage instructions please refer to the [User Guide](scenariosGuide).") - -'## Create Analysis' -'To begin a scenario impact analysis, select one of the pre-loaded hazard scenarios (footprints) from the list below.' - - -if len(client_interface.portfolios.get()) == 0: - st.error('No Portfolios Found') - st.stop() -if len(client_interface.models.get()) == 0: - st.error('No Models Found') - st.stop() -create_container = st.container(border=True) - -'## Run Analysis' -'New analyses and previously executed analyses are shown in the table below.' -"Previously executed analyses will have a status of 'Run Completed' and the outputs can be viewed by clicking the 'Show Output' button." -"New analyses will have a status of 'New'. The group fields and number of samples analysis settings can be set and the analysis can be executed by clicking on the button 'Run'." -'The ability to group output by country, portfolio and/or location depends on the level of data in the loaded portfolio.' - -run_container = st.container(border=True) - -with create_container: - model_map = ui_config.model_map - - '#### Scenario Selection' - 'Select an event scenarios by clicking the grey box on the left side of the table.' - - models = client_interface.models.get(df=True) - models = models.set_index('id', drop=False) - models = add_model_names_to_models_cached(models, client_interface) - display_cols = ['model_name', 'supplier_id'] - column_config = { - 'model_name': 'Scenarios Footprint', - 'supplier_id': 'Supplier' - } - - model_view = DataframeView(models, selectable='single', display_cols=display_cols, column_config=column_config) - selected_model = model_view.display() - - 'Currently, it is not possible to add your own scenarios directly; please describe any scenario you would like to add as a Github issue [here](https://github.com/OasisLMF/OasisPythonUI/issues).' - - '#### Portfolio Selection' - 'A pre-loaded portfolio of buildings will be shown below, corresponding to the same area as the event footprint selected above.' - 'In the near future, buildings data from the Global Exposure Model will be available to select here.' - "After selecting a combination of scenario and exposure portfolios, click on 'Create Analysis', give it a name, and create the analysis." - 'The Scenario Details button provides a description of the scenario selected.' - 'The Exposure Map button will show the distribution of building TIV (total insured value) in the selected portfolio.' - - # Prepare portfolios data - portfolios = client_interface.portfolios.get(df=True) - - # Find the corresponding portfolios - def filter_valid_rows(df, key, valid_map, filter_col): - if key is None: - return df - - if type(key) is not str: - key = str(key) - - valid_elements = valid_map.get(key, None) - - if valid_elements is None: - return df - - _df = df.loc[df[filter_col].isin(valid_elements)] - return _df - - selected_model_id = selected_model['model_id'] if selected_model is not None else None - if selected_model_id: - portfolios = filter_valid_rows(portfolios, selected_model_id, model_map, "name") - portfolios = enrich_portfolios(portfolios, client_interface, disable=['files']) - - display_cols = ['name', 'number_locations', 'number_accounts'] - portfolios['number_accounts'] = portfolios['number_accounts'].fillna('No accounts file') - - portfolio_view = DataframeView(portfolios, display_cols=display_cols, selectable='single', - column_config=column_config) - selected_portfolio = portfolio_view.display() - else: - st.info("Please select a model.") - selected_portfolio = None - - validations = ValidationGroup() - validations = validations.add_validation(NotNoneValidation("Portfolio"), selected_portfolio) - validations = validations.add_validation(NotNoneValidation("Model"), selected_model) - - enable_popover = validations.is_valid() - msg = validations.get_message() - - # Set up row of buttons - cols = st.columns([0.25, 0.25, 0.25, 0.25]) - - with cols[0]: - with st.popover("Create Analysis", disabled=not enable_popover, help=msg, width='stretch'): - if enable_popover: - resp = create_analysis_form(portfolios=[selected_portfolio.to_dict()], models=[selected_model.to_dict()]) - if resp: - try: - resp = client_interface.create_analysis(resp['portfolio_id'], resp['model_id'], resp['name']) - - st.success('Created analysis.') - time.sleep(0.5) - st.rerun() - except OasisException as e: - st.error(e) - - with cols[1]: - validation = NotNoneValidation("Portfolio") - enable_map_button = validation.is_valid(selected_portfolio) - - if st.button("Exposure Map", disabled=not enable_map_button, - help=validation.get_message(), width='stretch'): - @st.dialog("Locations Map", width='large') - def show_locations_map(): - with st.spinner('Loading map...'): - locations = client_interface.portfolios.endpoint.location_file.get_dataframe(selected_portfolio["id"]) - cols = locations.columns - heatmap_cols = ["Latitude", "Longitude", "BuildingTIV"] - choropleth_cols = ["CountryCode", "BuildingTIV"] - if all([c in cols for c in heatmap_cols]) and valid_locations(locations): - exposure_map = MapView(locations, weight="BuildingTIV", map_type="heatmap") - exposure_map.display() - elif all([c in cols for c in choropleth_cols]): - exposure_map = MapView(locations, weight="BuildingTIV", map_type="choropleth") - exposure_map.display() - else: - st.error('Map cannot be displayed.') - logger.error(f"Map view\n\tData cols: {cols}") - show_locations_map() - - with cols[2]: - validation = NotNoneValidation("Model") - enable_model_details = validation.is_valid(selected_model) - - if st.button("Scenario Details", disabled=not enable_model_details, - help=validation.get_message(), width='stretch'): - try: - model_settings = client_interface.models.settings.get(selected_model['id']) - except HTTPError as e: - logger.error(e) - model_settings = {} - - @st.dialog("Scenario Details", width="large") - def model_details_dialog(): - model_summary(selected_model, model_settings, detail_level="full") - model_details_dialog() - -with run_container: - # Initialise refresh handler - re_handler = RefreshHandler(client_interface) - run_every = re_handler.run_every() - - @st.fragment(run_every=run_every) - def analysis_fragment(): - re_handler.update_queue() - - analyses = client_interface.analyses.get(df=True) - portfolios = client_interface.portfolios.get(df=True) - models = client_interface.models.get(df=True) - models = models.set_index('id', drop=False) - models = add_model_names_to_models_cached(models, client_interface) - - completed_statuses = ['RUN_COMPLETED', 'RUN_CANCELLED', 'RUN_ERROR', 'INPUTS_GENERATION_ERROR'] - running_statuses = ['RUN_QUEUED', 'RUN_STARTED', 'INPUTS_GENERATION_QUEUED', - 'INPUTS_GENERATION_STARTED',] - - running_analyses = analyses[analyses['status'].isin(running_statuses)] - if not re_handler.is_refreshing() and not running_analyses.empty: - for analysis_id in running_analyses['id']: - re_handler.start(analysis_id, completed_statuses) - - valid_statuses = ['NEW', 'INPUTS_GENERATION_QUEUED', - 'INPUTS_GENERATION_STARTED', - 'INPUTS_GENERATION_CANCELLED', - 'INPUTS_GENERATION_ERROR', 'READY', 'RUN_QUEUED', - 'RUN_STARTED', 'RUN_COMPLETED', 'RUN_CANCELLED', - 'RUN_ERROR'] - analyses = analyses[analyses['status'].isin(valid_statuses)] - analyses = enrich_analyses(analyses, portfolios, models).sort_values('id', ascending=False) - - display_cols = ['name', 'status', 'portfolio_name', 'model_name', 'model_supplier'] - - column_config = { - 'name': 'Analysis Name', - 'model_name': 'Scenarios Footprint', - 'supplier_id': 'Supplier' - } - - analyses_view = DataframeView(analyses, display_cols=display_cols, selectable='single', - column_config=column_config) - selected = analyses_view.display() - - # Set subset of analysis settings - st.write("**Analysis Settings:**") - - cols = st.columns([0.5, 0.5]) - - oed_group = cols[0].pills("Group Output by:", - ["Portfolio", "Country", "Location"], selection_mode="multi") - - number_of_samples = cols[1].number_input('Number of Samples per event:', min_value=1, - max_value=1000, value=10) - - group_to_code = { - 'Portfolio': 'PortNumber', - 'Country': 'CountryCode', - 'Location': 'LocNumber' - } - - valid_statuses = ['NEW', 'READY', 'INPUTS_GENERATION_ERROR', 'RUN_CANCELLED', 'RUN_ERROR', 'RUN_COMPLETED'] - validations = ValidationGroup() - validations.add_validation(NotNoneValidation('Analysis'), selected) - validations.add_validation(KeyInValuesValidation('Status'), selected, 'status', valid_statuses) - val = IsNoneValidation() - val.set_message('Analysis already running') - validations.add_validation(val, run_every) - - run_enabled = validations.is_valid() - msg = validations.get_message() - - columns = st.columns([0.25, 0.25, 0.25, 0.25]) - columns = st.columns([0.5, 0.5]) - - run_started = False - with columns[0]: - if st.button('Run', disabled=not run_enabled, help=msg, width='stretch'): - try: - # Load from platform - templates = client_interface.models.setting_templates.get(selected['model']) - template_id = max([t['id'] for t in templates]) - analysis_settings = client_interface.models.setting_templates.get_contents(selected['model'], template_id) - logger.info(f"Loaded analysis settings for model {selected['model']}") - except (OasisException, HTTPError): - model_name_id = client_interface.models.get(selected['model'])['model_id'] - - logger.error(f"Failed to load template from platform for model {model_name_id}") - - # Load from defaults/ - analysis_settings = get_analyses_settings(model_name_id=model_name_id)[0] - - with open(analysis_settings, 'r') as f: - analysis_settings = json.load(f) - - if len(oed_group) > 0: - oed_group_codes = [group_to_code[g] for g in oed_group] - if analysis_settings.get('gul_output', False): - analysis_settings['gul_summaries'][0]['oed_fields'] = oed_group_codes - if analysis_settings.get('il_output', False): - analysis_settings['il_summaries'][0]['oed_fields'] = oed_group_codes - if analysis_settings.get('ri_output', False): - analysis_settings['ri_summaries'][0]['oed_fields'] = oed_group_codes - - analysis_settings['number_of_samples'] = number_of_samples - - try: - # Write group-by fields into the outputs (pytools join-summary-info) - analysis_settings.setdefault('join_summary_info', True) - client_interface.upload_settings(selected['id'], analysis_settings) - except (JSONDecodeError, HTTPError) as e: - logger.error(e) - st.error('Failed to upload settings') - - try: - if selected['status'] in ['NEW', 'INPUTS_GENERATION_ERROR']: - client_interface.generate_and_run(selected['id']) - else: - client_interface.run(selected['id']) - - run_started = True - - except HTTPError as _: - st.error('Starting run failed.') - - if run_started: - st.success("Run started.") - time.sleep(0.5) - run_started = False - re_handler.start(selected['id'], completed_statuses) - - # Download button - @st.dialog("Output", width="large") - def display_outputs(ci, analysis_id, model_id): - st.markdown('# Analysis Summary') - st.markdown('This section summarises the input data for this analysis, including the total values contained in the portfolio, and analysis / output settings.') - input_file = ci.analyses.get_file(analysis_id, 'input_file', df=True) - - if 'location.csv' in input_file: - locations = input_file.get('location.csv') - elif 'location.parquet' in input_file: - locations = input_file.get('location.parquet') - else: - locations = None - a_settings = ci.analyses.settings.get(analysis_id) - model_settings = ci.models.settings.get(model_id) - summarise_inputs(locations, a_settings, model_settings) - - st.markdown('# Results Summary') - st.markdown('This section summarises the results.') - st.markdown('''Ground Up Loss (gul) is the estimated direct cost of damage to the buildings in the selected portfolio due to the selected event scenario. - This is the only loss perspectiev enabled, and no insurance contracts are included in the analysis.''') - st.markdown("Ground Up loss is shown as the event loss ('mean') for all locations and each location if 'group by' LocNumber is selected.") - st.markdown("In addition to the table of mean loss, the spatial distribution is shown under 'map' and a chart shown below.") - st.markdown('Sample results refer to outputs from running no sample - just one realisation of the event; Analytical results refer to running the number of samples (currently defaulting to 10 samples).') - - # Graphs from output - - @st.cache_data(show_spinner="Fetching output data...") - def get_output_file(analysis_id, modified_time): # don't use cache if analysis modified - return ci.analyses.get_file(analysis_id, 'output_file', df=True) - - modified_time = ci.analyses.get(analysis_id).get('modified', None) - results_dict = get_output_file(analysis_id, modified_time) - output_interface = OutputInterface(results_dict) - - for p in ['gul', 'il', 'ri']: - p_oed_fields = a_settings.get(f'{p}_summaries', [{}])[0].get('oed_fields', None) - if p_oed_fields: - output_interface.set_oed_fields(p, p_oed_fields) - - def generate_perspective_visualisation(perspective, summaries_settings): - if summaries_settings[0].get('eltcalc', False): - # st.write("### ELT Output") - we don't need to define ELT versus AAL loss, as this is a single event. - generate_eltcalc_fragment(perspective, output_interface, locations=locations, map=True) - st.write('---') - - if summaries_settings[0].get('aalcalc', False): - # st.write("### AAL Output") - we don't need to define ELT versus AAL loss, as this is a single event. - generate_aalcalc_fragment(perspective, output_interface) - st.write('---') - - if summaries_settings[0].get('lec_output', False): - st.write("### LEC Output") - lec_options = summaries_settings[0].get('leccalc') - generate_leccalc_fragment(perspective, output_interface, lec_options) - st.write('---') - - if summaries_settings[0].get('pltcalc'): - st.write("### PLT Output") - generate_pltcalc_fragment(perspective, output_interface) - st.write('---') - - ord_settings = summaries_settings[0].get('ord_output', {}) - - if ord_settings.get('elt_moment', False): - st.write("### MELT Output") - generate_melt_fragment(perspective, output_interface, locations=locations) - st.write('---') - - if ord_settings.get('elt_quantile', False): - st.write("### QELT Output") - generate_qelt_fragment(perspective, output_interface, locations=locations) - st.write('---') - - if ord_settings.get('elt_sample', False): - st.write("### SELT Output") - generate_selt_fragment(perspective, output_interface, locations=locations) - st.write('---') - - if ord_settings.get('plt_moment', False): - st.write("### MPLT Output") - generate_mplt_fragment(perspective, output_interface) - st.write('---') - - if ord_settings.get('plt_quantile', False): - st.write("### QPLT Output") - generate_qplt_fragment(perspective, output_interface) - st.write('---') - - if ord_settings.get('plt_sample', False): - st.write("### SPLT Output") - generate_splt_fragment(perspective, output_interface) - st.write('---') - - if ord_settings.get('alt_meanonly', False): - st.write("### ALT MeanOnly Output") - generate_alt_fragment(perspective, output_interface, 'alt_meanonly') - st.write('---') - - if ord_settings.get('alt_period', False): - st.write("### PALT Output") - generate_alt_fragment(perspective, output_interface, 'alt_period') - st.write('---') - - if ord_settings.get('alct_convergence', False): - st.write("### ALCT Output") - generate_alct_fragment(perspective, output_interface) - st.write('---') - - ept_settings = [ - 'ept_full_uncertainty_aep', - 'ept_full_uncertainty_oep', - 'ept_mean_sample_aep', - 'ept_mean_sample_oep', - 'ept_per_sample_mean_aep', - 'ept_per_sample_mean_oep' - ] - - if any(ord_settings.get(e, False) for e in ept_settings): - st.write("### EPT Output") - generate_ept_fragment(perspective, output_interface) - st.write('---') - - psept_settings = ['psept_aep', 'psept_oep'] - - if any(ord_settings.get(e, False) for e in psept_settings): - st.write("### PSEPT Output") - generate_psept_fragment(perspective, output_interface) - st.write('---') - - if a_settings['gul_output']: - st.write("## Ground Up Loss") - generate_perspective_visualisation('gul', a_settings['gul_summaries']) - - if a_settings.get('il_output', False): - st.write("## Insured Loss") - generate_perspective_visualisation('il', a_settings['il_summaries']) - - if a_settings.get('ri_output', False): - st.write("## Loss Net of Reinsurance") - generate_perspective_visualisation('ri', a_settings['ri_summaries']) - - fname = f"analysis_{analysis_id}_output.tar.gz" - st.markdown(f"Output File Name: `{fname}`") - fdata = ci.download_output(analysis_id) - - tdata = tarfile.open(fileobj=BytesIO(fdata)) - output_files = [m.name for m in tdata.getmembers() if m.isfile()] - output_files = [Path(p).name for p in output_files] - - st.download_button('Download Results File', - data=fdata, - file_name=fname) - - valid_statuses = ['RUN_COMPLETED'] - validations = ValidationGroup() - validations.add_validation(NotNoneValidation('Analysis'), selected) - validations.add_validation(KeyInValuesValidation('Status'), selected, 'status', valid_statuses) - download_enabled = validations.is_valid() - - with columns[1]: - if st.button("Show Output", width='stretch', disabled=not download_enabled): - display_outputs(client_interface, selected["id"], selected['model']) - - if len(client_interface.analyses.get()) == 0: - st.error("No analyses found.") - generate_footer(ui_config) - st.stop() - analysis_fragment() - if run_every is not None: - st.info('Analysis running.') - -generate_footer(ui_config) diff --git a/pages/scenariosGuide.py b/pages/scenariosGuide.py deleted file mode 100644 index 77ee000..0000000 --- a/pages/scenariosGuide.py +++ /dev/null @@ -1,407 +0,0 @@ -from modules.authorisation import quiet_login, validate_page -import streamlit as st -from modules.nav import SidebarNav -from modules.config import retrieve_ui_config -from pages.components.footer import generate_footer -import logging -import os - - -logger = logging.getLogger(__name__) - -########################################################################################## -# Header -########################################################################################## - -ui_config = retrieve_ui_config() - -validate_page("User Guide") - -st.set_page_config( - page_title="User Guide", - layout="centered" -) - -cols = st.columns([0.1, 0.8, 0.1]) -with cols[1]: - st.image("images/oasis_logo.png") - -########################################################################################## -# Page -########################################################################################## - -SidebarNav(no_client=ui_config.skip_login) - -# Title -st.title("User Guide: Scenario analysis and comparison") - -# Table of Contents -st.header("Table of Contents") -st.markdown(""" -[1. Introduction](#1-introduction)\\ -[2. Getting Started](#2-getting-started)\\ -[3. Understanding the Interface](#3-understanding-the-interface)\\ -[4. Working with Scenarios](#4-working-with-scenarios)\\ -[5. Interpreting Results](#5-interpreting-results)\\ -[6. Scenario Comparison](#6-scenario-comparison)\\ -[7. Troubleshooting](#7-troubleshooting)\\ -[8. Limitations](#8-limitations)\\ -[9. Attributions](#9-attributions)\\ -[10. Disclaimer](#10-disclaimer) -""") - -# Introduction -st.header("1. Introduction") -st.markdown("*[back to top](#table-of-contents)*") -st.markdown(""" -The Oasis Loss Modelling Framework (LMF) Scenarios Tool is a web-based application designed for catastrophe (or disaster) scenario impact analysis. -As part of the open-source Oasis platform, it provides accessible tools to evaluate potential loss from selected disaster event scenarios. -It can be used for demonstrating and conducting stress-testing for insurance regulatory or rating agency purposes, 'what-if' modelling of historical events, or -worst-case scenario modelling of hypothetical events for (re)insurance, government, and academic use. -This tool uses hazard scenarios, or hazard footprints, as well as exposure data and physical vulnerability curves in Oasis formats. -""") - -st.subheader("Key Features") -st.markdown(""" -- Uses the [Oasis LMF](https://oasislmf.org/) open-source platform analytical engine, with no installation or download required and with full transparency of methods -- Web-based interface: Accessible through any modern web browser, free to use -- Standardized data formats: Uses [Open Exposure Data (OED) and Open Results Data (ORD) standards](https://oasislmf.org/open-data-standards) -- Comprehensive modelling: Supports multiple perils and modelling approaches -- Flexible analysis: Monte Carlo simulation with customizable parameters -- Visualization tools: Interactive maps, charts, and reporting capabilities -""") - -st.subheader("Target Users") -st.markdown(""" -- Insurance and reinsurance professionals -- Risk analysts and catastrophe modellers -- Government agencies and public sector organizations -- Academic researchers and students -- Consultants and third-party risk assessment providers -""") - -# Getting Started -st.header("2. Getting Started") -st.markdown("*[back to top](#table-of-contents)*") -st.subheader("System Requirements") -st.markdown(""" -- Modern web browser (Chrome, Firefox, Safari, Edge) -- Stable internet connection -""") - -st.subheader("Accessing the Platform") -st.markdown(""" -1. Navigate to [Oasis LMF Scenarios](https://ui.oasislmf-scenarios.com/scenarios) in your browser -2. No installation or download required -3. Upon first access, you'll be presented with the main dashboard. The interface is designed to be intuitive, but familiarizing yourself -with the key components will enhance your experience. -""") - -# Understanding the Interface -st.header("3. Understanding the Interface") -st.markdown("*[back to top](#table-of-contents)*") - -st.subheader("Scenarios: Analyse individual disaster scenarios") -st.markdown(""" -The Scenarios dashboard provides an overview of your current scenarios and quick access to key functions: -- Scenario Selection: Select scenarios from a default list maintained by Oasis. New scenarios can be added [on request](https://github.com/OasisLMF/Scenarios/issues) -- Portfolio Selection: Select a portfolio of exposure to assess the disaster scenario against. The tool supports built asset data in OED format. THese may be 'flat file' where each location has the same value, or data derived from an exposure model. -- Create analysis: Give the analysis a name, view the distribution of hazard intensity and exposure value. -- Run analysis: Select granularity of loss to analyse: total scenario loss (whole portfolio), per-country breakdown of loss, or per-location loss. -- Output Viewer: Show a summary of the input scenario and exposure and a summary of ground up or economic loss in the form of a table, chart or map. -- Export results: Download the full results. -""") - -st.subheader("Comparison: Compare losses from disaster scenarios") -st.markdown(""" -- Select scenario analyses to compare: Select two analyses that have been run in the [Scenarios](https://ui.oasislmf-scenarios.com/scenarios) page. -- View results: Display and analyse the ground up (economic) loss of the two scenarios side-by-side in table and chart form - for the scenario total and per location. -""") - - -# Working with Scenarios -st.header("4. Working with Scenarios") -st.markdown("*[back to top](#table-of-contents)*") - -st.subheader("Creating a New Scenario") - -st.markdown(""" -**1. Access the Main Dashboard** - - Navigate to [Oasis LMF Scenarios](https://ui.oasislmf-scenarios.com/scenarios) - - Wait for the application to load completely -""") - -# Check if the image file exists -if os.path.exists("images/STguide_1_createAnalysis.png"): - # Display the image - st.image("images/STguide_1_createAnalysis.png") -else: - # Display a warning message - st.warning(f"Image file '{"STguide_1_createAnalysis.png"}' not found. Please check the file path and try again.") - - -st.markdown(""" -**2. Start a New Scenario** - - Select a scenario by checking the box next to the model/supplier table - - Select the portfolio from the list of available exposures for the scenario - - Click the "Create Analysis" button (typically located in the bottom-right corner) -""") - -if os.path.exists("images/STguide_2_createAnalysis.png"): - # Display the image - st.image("images/STguide_2_createAnalysis.png") -else: - # Display a warning message - st.warning(f"Image file '{"STguide_2_createAnalysis.png"}' not found. Please check the file path and try again.") - - -st.markdown(""" -**3. Configure Scenario Details** - - Scenario Name: Enter a descriptive name (e.g., "Ghana Flood 61") - - Portfolio: Select from the available exposure sets for the scenario - - Model: Select from the available model variants - - Vulnerability: In future versions of the tool, the vulnerability functions being applied in the analysis will be shown here (and could be selected). - - Click on “Create Analysis” -""") - -if os.path.exists("images/STguide_3_createAnalysis.png"): - # Display the image - st.image("images/STguide_3_createAnalysis.png") -else: - # Display a warning message - st.warning(f"Image file '{"STguide_3_createAnalysis.png"}' not found. Please check the file path and try again.") - - -st.markdown(""" -**4. Run Analysis** - - Selection: Choose from available analyses. The one that has just been created should have a green “Ready” as its status. Click the check-box next to this. - - Select the level you would like the output losses grouped by - - Portfolio: all locations combined - - Country: split by country - - Location: split by individual location - - Click the “Run” button to execute the analysis - - When running, your analysis will show the status “Running” - - When Complete, the status will switch to “Run Completed” - -The analysis run will include 'analytical' and 'sample' options. -Under 'analytical', 1 version of the scenario analysis will be run. -Under 'sample', 10 samples will be run, to account for the effect of modelling uncertainty on the estimated loss. This value cannot be changed in this version of the tool. -""") - -if os.path.exists("images/STguide_4_runAnalysis.png"): - # Display the image - st.image("images/STguide_4_runAnalysis.png") -else: - # Display a warning message - st.warning(f"Image file '{"STguide_4_runAnalysis.png"}' not found. Please check the file path and try again.") - - -st.markdown(""" -*5. Viewing Results* - - Once the analysis is in the “Run Completed” status, when selecting the analysis, you will be able to click the “Show Output” button -""") - -if os.path.exists("images/STguide_5_runAnalysis_showOutput.png"): - # Display the image - st.image("images/STguide_5_runAnalysis_showOutput.png") -else: - # Display a warning message - st.warning(f"Image file '{"STguide_5_runAnalysis_showOutput.png"}' not found. Please check the file path and try again.") - -st.markdown(""" - - The output data will then be available in the pop up screen, including a summary of the analysis inputs and the modelled results -""") - - -if os.path.exists("images/STguide_6_Output.png"): - # Display the image - st.image("images/STguide_6_Output.png") -else: - # Display a warning message - st.warning(f"Image file '{"STguide_6_Output.png"}' not found. Please check the file path and try again.") - -if os.path.exists("images/STguide_7_ResultsSummary.png"): - # Display the image - st.image("images/STguide_7_ResultsSummary.png") -else: - # Display a warning message - st.warning(f"Image file '{"STguide_7_ResultsSummary.png"}' not found. Please check the file path and try again.") - - -st.markdown(""" - - There is also an option to download the results as a compressed tar file at the bottom of the screen -""") - -if os.path.exists("images/STguide_8_downloadOption.png"): - # Display the image - st.image("images/STguide_8_downloadOption.png") -else: - # Display a warning message - st.warning(f"Image file '{"STguide_8_downloadOption.png"}' not found. Please check the file path and try again.") - - -# Interpreting Results -st.header("5. Interpreting Results") -st.markdown("*[back to top](#table-of-contents)*") - -st.subheader("Available Results") - -st.markdown(""" -The scenarios workflow results present the mean loss of the selected scenario. This can be shown per-location, -per-country (for trans-boundary / cross-border scenarios) and as a scenario total loss. - -The 'analytical' and 'sample' results will be shown, to view the difference between single- and multiple-sample runs. - -The following loss perspectives can be run: - - Ground-Up Loss (GUL): Losses before application of insurance terms - requires no (re)insurance terms in the portfolio. - - Insured Loss (IL): Losses after policy terms but before reinsurance - requires (re)insurance terms in the portfolio. - - Reinsured Loss (RIL): Net losses after reinsurance arrangements - requires (re)insurance terms in the portfolio. -""") - -st.subheader("Viewing Results") - -st.markdown(""" -Geographic Loss Maps: -- Click "Maps" tab to view spatial distribution of scenario loss -- Use zoom controls to focus on specific areas -- Click locations for detailed loss information -""") - -if os.path.exists("images/STguide_9_outputMap.png"): - # Display the image - st.image("images/STguide_9_outputMap.png") -else: - # Display a warning message - st.warning(f"Image file '{"STguide_9_outputMap.png"}' not found. Please check the file path and try again.") - - -st.markdown(""" -Detailed Tabular Results: -- Click "Table" tab -- Switch between different summary levels: portfolio, country, location -- Click column headers to sort data -""") - -if os.path.exists("images/STguide_10_outputTbl.png"): - # Display the image - st.image("images/STguide_10_outputTbl.png") -else: - # Display a warning message - st.warning(f"Image file '{"STguide_10_outputTbl.png"}' not found. Please check the file path and try again.") - -if os.path.exists("images/STguide_11_outputTbloption.png"): - # Display the image - st.image("images/STguide_11_outputTbloption.png") -else: - # Display a warning message - st.warning(f"Image file '{"STguide_11_outputTbloption.png"}' not found. Please check the file path and try again.") - - -# Scenario Comparison -st.header("6. Scenario Comparison") -st.markdown("*[back to top](#table-of-contents)*") - -st.markdown(""" -Compare multiple scenarios side-by-side in the [Comparisons](https://ui.oasislmf-scenarios.com/comparison) tab, by following the instructions in the tab. - -Scenario comparisons could include: -- Loss due to change in hazard such as flood inundation under two different levels of flood protection. -- Loss due to change in exposure distribution or value over time. -- Loss under different asset building code / retrofit conditions, i.e., change in property vulnerability. -- Loss under two representations of the same (e.g., historical) event, from two versions of a model or two different model providers - -Note: this version of the workflow requires that the scenarios being compared are added to the [scenarios list](https://github.com/OasisLMF/scenario) -and run through the Scenarios tab first. Changes directly to the hazard footprint, exposure, or vulnerability are not yet possible in this tool. - -**Analysis Summary** provides a side-by-side review of the input data and analysis settings in the two analyses. - -**Loss Estimates** enables side-by-side visualisation of the loss estimates from both scenarios in chart, table and map form. -""") - - -# Troubleshooting -st.header("7. Troubleshooting") -st.markdown("*[back to top](#table-of-contents)*") - -st.subheader("Common Issues and Solutions") -st.markdown(""" -Analysis Failures: -- Insufficient Data: Verify all required fields are populated -- Model Compatibility: Confirm model supports your data characteristics -- Resource Limits: Check computational resource availability -- Parameter Conflicts: Review analysis configuration settings - -Result Display Issues: -- Browser Compatibility: Update to latest browser version -- JavaScript Errors: Enable JavaScript and clear browser cache -- Memory Issues: Close other applications to free up resources -- Network Timeout: Refresh page and try again -- Blank Charts: Refresh browser or check data filters -- Slow Loading: Large datasets may take time to render -- Export Failures: Check file permissions and browser settings -""") - -st.subheader("Performance Optimization") -st.markdown(""" -Analysis Efficiency: -- Start with smaller sample sizes for testing -- Use appropriate model resolution -- Monitor resource usage during analysis -""") - -st.subheader("Getting Help") -st.markdown(""" -- Open an issue in GitHub: https://github.com/OasisLMF/OasisPythonUI/issues -- Email support: support@oasislmf.org -- Official Oasis LMF documentation: https://oasislmf.github.io/ -- Open Exposure Data (OED) format specifications: https://github.com/OasisLMF/OpenDataStandards/ -- Oasis LMF Information Library: https://oasislmf.org/oasis-information-library -- GitHub repositories with example code and issues: https://github.com/OasisLMF -""") - - -# Limitations -st.header("8. Limitations") -st.markdown("*[back to top](#table-of-contents)*") - -st.markdown(""" -Limitations of this tool include: - -- Users cannot directly upload or adjust their own scenarios, exposure portfolios or vulnerability functions in this version of the tool. -New files can be shared with Oasis and uploaded by the admin team if they are needed for demonstration purposes, for example (see [7. Troubleshooting](#7-troubleshooting)). -Adjustments to scenario already included can be made by obtaining the hazard footprint from the Scenarios GitHub repository and sharing it back to Oasis for upload. -- This version of the tool enables analysis using ground up exposure only - no re/insurance policy terms are handled in the tool. -- The number of simulations that can be run on a scenario are limited to prevent excessive computational burden. -""") - -# Attributions -st.header("9. Attributions") -st.markdown("*[back to top](#table-of-contents)*") - -st.markdown(""" -Many thanks to the following model vendors who have participated in this project and made their scenarios footprint files available: - -- Applied Research Associates (ARA) -- Impact Forecasting -- Insurance Partners Europe (IPE) -- JBA Risk Management -""") - -# Disclaimer -st.header("10. Disclaimer") -st.markdown("*[back to top](#table-of-contents)*") - -st.markdown(""" -All data and information within this repository fall under the BSD 3-Clause License. - -DISCLAIMER: No contributors to this repository, namely the third-party model providers, brokers, insurers or reinsurers take any -responsibility for the outputs produced from these scenarios or deterministic models. Although the providers of the scenarios have -ensured the hazard data captured within the footprint files is as accurate as possible, the event losses produced may vary from those -in the full stochastic model from the same vendor. These scenarios may also be accompanied by different (or simplified) vulnerability -functions which will produce different losses and so do not reflect the company's "true" view of risk for these events. -""") - -if ui_config.skip_login: - quiet_login() - -generate_footer(ui_config) diff --git a/scenarios/a_settings.json b/scenarios/a_settings.json index e30f085..122102c 100644 --- a/scenarios/a_settings.json +++ b/scenarios/a_settings.json @@ -1,8 +1,4 @@ [ - { - "model_name_id": "PiWind", - "settings_path": "./scenarios/defaults/1_piwind_oasislmf-analysis_settings.json" - }, { "model_name_id": "EUWS", "settings_path": "./scenarios/defaults/3_euws_impact-forecasting-analysis_settings.json" diff --git a/scenarios/deploy_scenarios_ui.sh b/scenarios/deploy_scenarios_ui.sh index 0225663..77680ff 100755 --- a/scenarios/deploy_scenarios_ui.sh +++ b/scenarios/deploy_scenarios_ui.sh @@ -1,4 +1,18 @@ #!/bin/bash +# Deploy the public Scenarios demo with install.sh. Run on the host by the +# "Docker Scenarios UI CD" workflow (.github/workflows/scenarios-ui-deploy.yml). +# +# The host's $UI_PATH/.env must be a configured copy of .env.scenarios +# (OASIS_PUBLIC_DEMO=true, real passwords, SCENARIOS_PATH=$MODELS_PATH). +# +# Inputs (environment): +# UI_PATH OasisPythonUI checkout on the host +# MODELS_PATH Scenarios repository checkout (the scenario model data) +# DEPLOY_UI 'true' to rebuild and restart the UI only +# DEPLOY_ALL 'true' to redeploy the whole stack +# WIPE 'true' (with DEPLOY_ALL) to delete all data first +# UPDATE_SCENARIOS 'true' to update the scenario model data first +set -e echo "DEPLOY_UI: $DEPLOY_UI" echo "DEPLOY_ALL: $DEPLOY_ALL" @@ -7,44 +21,42 @@ echo "WIPE: $WIPE" echo "UPDATE_SCENARIOS: $UPDATE_SCENARIOS" echo "MODELS_PATH: $MODELS_PATH" -# clear up space on device -docker system prune --volumes -f - -if [[ "$WIPE" = 'true' ]] && [[ "$DEPLOY_ALL" = 'false' ]]; then +if [[ "$WIPE" = 'true' ]] && [[ "$DEPLOY_ALL" != 'true' ]]; then echo "WIPE without DEPLOY_ALL not allowed." exit 1 fi -if [[ "$UPDATE_SCENARIOS" = 'true' ]]; then - echo "Updating scenarios models directory." - git -C "$MODELS_PATH" pull - ( cd "$MODELS_PATH"; ./get_s3_data_reduced.sh ) # Get from public scenarios s3 - echo "Updated"; +cd "$UI_PATH" +if [[ ! -f .env ]] || ! grep -q '^OASIS_PUBLIC_DEMO=true' .env; then + echo "ERROR: $UI_PATH/.env must be a configured copy of .env.scenarios (OASIS_PUBLIC_DEMO=true)." + exit 1 fi -if [[ "$DEPLOY_UI" = 'true' ]] && [[ "$DEPLOY_ALL" != 'true' ]]; then - git -C "$UI_PATH" pull - docker image pull coreoasis/oasis_scenarios - docker compose -f "$UI_PATH/oasis-scenarios-ui.yml" up -d --no-build +# Free disk space from old images and build cache (named volumes are kept) +docker system prune -f + +git pull --ff-only + +if [[ "$UPDATE_SCENARIOS" = 'true' ]]; then + echo "Updating scenario model data in $MODELS_PATH" + git -C "$MODELS_PATH" pull --ff-only + ( cd "$MODELS_PATH"; ./get_s3_data_reduced.sh ) fi if [[ "$DEPLOY_ALL" = 'true' ]]; then - printf "Deleting docker container:\n" - set +e - docker compose -f "$UI_PATH/oasis-scenarios-platform.yml" -f "$UI_PATH/oasis-scenarios-ui.yml" down --remove-orphans - set -e if [[ "$WIPE" = 'true' ]]; then - printf "Deleting docker data: \n" - docker volume ls | grep OasisData | awk 'BEGIN { FS = "[ \t\n]+" }{ print $2 }' | xargs -r docker volume rm + echo "Removing the stack and all its data" + ./install.sh --uninstall fi - docker compose -f "$UI_PATH/oasis-scenarios-platform.yml" down - docker compose -f "$UI_PATH/oasis-scenarios-ui.yml" down - docker pull coreoasis/model_worker:latest - docker pull coreoasis/api_server:latest - docker pull coreoasis/oasis_scenarios:latest - docker compose -f "$UI_PATH/oasis-scenarios-platform.yml" up -d --no-build - docker compose -f "$UI_PATH/oasis-scenarios-ui.yml" up -d --no-build + ./install.sh --yes --build-ui +elif [[ "$DEPLOY_UI" = 'true' ]]; then + # Rebuild the UI image from this checkout, then recreate only the UI-side services + set -a; source .env; set +a + FILES="-f docker-compose.yml -f docker-compose.models.scenarios.yml -f docker-compose.ui.yml -f docker-compose.public.yml" + [[ -n "${OASIS_ACME_EMAIL:-}" ]] && FILES="$FILES -f docker-compose.acme.yml" + export OASIS_SERVICE_USERNAME_OR_ID="$OASIS_ADMIN_USER" OASIS_SERVICE_PASSWORD_OR_SECRET="$OASIS_ADMIN_PASS" + docker compose $FILES build pythonui + docker compose $FILES up -d --no-deps pythonui scenarios-setup scenarios-prune fi -# run cleanup -docker system prune --volumes -f +docker system prune -f diff --git a/scenarios/portfolios.json b/scenarios/portfolios.json index 44df542..f0ca3f3 100644 --- a/scenarios/portfolios.json +++ b/scenarios/portfolios.json @@ -1,18 +1,4 @@ { - "piwind_small": { - "portfolio_name": "piwind-small", - "location_fp": "./OasisPiWind/tests/inputs/SourceLocOEDPiWind10.csv", - "accounts_fp": "./OasisPiWind/tests/inputs/SourceAccOEDPiWind.csv", - "ri_info_fp": "./OasisPiWind/tests/inputs/SourceReinsInfoOEDPiWind.csv", - "ri_scope_fp": "./OasisPiWind/tests/inputs/SourceReinsScopeOEDPiWind.csv" - }, - "piwind_large": { - "portfolio_name": "piwind-large", - "location_fp": "./OasisPiWind/tests/inputs/SourceLocOEDPiWind.csv", - "accounts_fp": "./OasisPiWind/tests/inputs/SourceAccOEDPiWind.csv", - "ri_info_fp": "./OasisPiWind/tests/inputs/SourceReinsInfoOEDPiWind.csv", - "ri_scope_fp": "./OasisPiWind/tests/inputs/SourceReinsScopeOEDPiWind.csv" - }, "maeq": { "portfolio_name": "maeq-test", "location_fp": "../Scenarios/ImpactForecasting/MAEQ/1.0.0/tests/MAEQ_100_oasis.csv", diff --git a/scenarios/ui-config.json b/scenarios/ui-config.json index 5d4a9bd..d382204 100644 --- a/scenarios/ui-config.json +++ b/scenarios/ui-config.json @@ -1,32 +1,59 @@ { - "pages" : [ - {"path": "pages/scenariosGuide.py", "label": "User Guide"}, - {"path": "pages/scenarios.py", "label": "Scenarios"}, - {"path": "pages/comparison.py", "label": "Comparison"} - ], - "post_login_page": "pages/scenariosGuide.py", - "model_map": { - "PiWind": ["piwind-small", "piwind-large"], - "MAEQ": ["maeq-test"], - "EUWS": ["euws-test"], - "TREQ": ["treq-test"], - "Philippines-Taiwan-Defended": ["philippines-taiwan-typhoon-flat", "phillippines-taiwan-comparison-test"], - "Philippines-Taiwan-Undefended": ["philippines-taiwan-typhoon-flat", "phillippines-taiwan-comparison-test"], - "US-Hurricane": ["us-hurricane-flat"], - "Ghana-E635900": ["ghana-flood-flat"], - "Ghana-E689982": ["ghana-flood-flat"], - "Ghana-E760461": ["ghana-flood-flat"], - "Nepal-E151185": ["nepal-flood-flat"], - "Nepal-E432557": ["nepal-flood-flat"], - "Nepal-E505423": ["nepal-flood-flat"], - "France-Hail": ["france-hail-flat"] + "_comment": "Config for the public Scenarios app (scenarios_app.py). Pages are defined in scenarios_app.py. Scenario names and descriptions come from each model's settings; peril and countries from its exposure.", + "scenarios": { + "max_samples": 50, + "default_samples": 10, + "max_active_runs_per_visitor": 2, + "max_active_runs": 3, + "processes_per_run": 2, + "showcase_tag": "[showcase]", + "retention_days": 7 }, - "footer" : { - "path": "ui_assets/footer.md", - "pages": [ - "scenarios", - "comparison" + "model_map": { + "MAEQ": [ + "maeq-test" + ], + "EUWS": [ + "euws-test" + ], + "TREQ": [ + "treq-test" + ], + "Philippines-Taiwan-Defended": [ + "philippines-taiwan-typhoon-flat", + "phillippines-taiwan-comparison-test" + ], + "Philippines-Taiwan-Undefended": [ + "philippines-taiwan-typhoon-flat", + "phillippines-taiwan-comparison-test" + ], + "US-Hurricane": [ + "us-hurricane-flat" + ], + "Ghana-E635900": [ + "ghana-flood-flat" + ], + "Ghana-E689982": [ + "ghana-flood-flat" + ], + "Ghana-E760461": [ + "ghana-flood-flat" + ], + "Nepal-E151185": [ + "nepal-flood-flat" + ], + "Nepal-E432557": [ + "nepal-flood-flat" + ], + "Nepal-E505423": [ + "nepal-flood-flat" + ], + "France-Hail": [ + "france-hail-flat" ] }, + "footer": { + "path": "scenarios/assets/footer.md" + }, "skip_login": true } diff --git a/scenarios_app.py b/scenarios_app.py new file mode 100644 index 0000000..bb64075 --- /dev/null +++ b/scenarios_app.py @@ -0,0 +1,52 @@ +"""Public, credential-free Scenarios app. + +Run with `streamlit run scenarios_app.py`. Visitors can explore pre-loaded +disaster scenarios against pre-loaded exposure, run them (within limits), +and view results; they cannot upload data. Only the pages registered below +exist in this app: `st.navigation` replaces the `pages/` directory used by +the standard UI, so none of its pages (uploads, deletes, ...) are reachable. +""" +import logging + +import streamlit as st +from requests.exceptions import HTTPError + +from modules.authorisation import quiet_login +from modules.config import retrieve_ui_config +from modules.scenarios import VISITOR_PARAM, visitor_id + +logger = logging.getLogger(__name__) + +st.set_page_config(page_title='Oasis Scenarios', page_icon='images/oasis_logo.png', layout='wide') + +ui_config = retrieve_ui_config() + +# Credential free: the app uses its service account for every visitor +try: + quiet_login() +except HTTPError as e: + logger.error(f'Scenarios login failed: {e}') +if 'client_interface' not in st.session_state: + st.error('The scenarios service is unavailable right now. Please try again later.') + st.stop() + +vid = visitor_id() + +st.logo('images/oasis_logo_bg.png', size='large') +st.html('''''') + +pages = [ + st.Page('scenarios_ui/explore.py', title='Run a scenario', icon=':material/play_circle:', default=True), + st.Page('scenarios_ui/showcase.py', title='Showcase', icon=':material/auto_awesome:'), + st.Page('scenarios_ui/compare.py', title='Compare', icon=':material/compare_arrows:'), + st.Page('scenarios_ui/guide.py', title='Guide', icon=':material/menu_book:'), +] +# Links drawn explicitly: the shared Streamlit config hides the built-in page menu +page = st.navigation(pages, position='hidden') +with st.sidebar: + for p in pages: + # Carry the visitor id so a reload on any page keeps the visitor's runs + st.page_link(p, query_params={VISITOR_PARAM: vid}) +page.run() diff --git a/scenarios_ui/common.py b/scenarios_ui/common.py new file mode 100644 index 0000000..a7c761b --- /dev/null +++ b/scenarios_ui/common.py @@ -0,0 +1,145 @@ +"""Helpers shared by the Scenarios app pages.""" +import json +import logging +from copy import deepcopy +from pathlib import Path + +import streamlit as st +from oasis_data_manager.errors import OasisException +from requests.exceptions import HTTPError + +from modules.config import retrieve_ui_config +from modules.scenarios import GROUP_BY_OPTIONS, ScenarioLimits, display_name, is_showcase, visitor_id +from modules.schemas import PERSPECTIVES +from modules.settings import get_analyses_settings +from pages.components.common import format_status +from pages.components.data import analysis_files, analysis_settings, cached_model_settings +from pages.components.results import render_results +from pages.components.settings_editor import default_settings + +logger = logging.getLogger(__name__) + + +class Context: + """Per-run page context: API client, config, limits and visitor id.""" + + def __init__(self): + self.ci = st.session_state['client_interface'] + self.ui_config = retrieve_ui_config() + self.limits = ScenarioLimits.from_config(self.ui_config) + self.vid = visitor_id() + + def scenario_name(self, model): + return cached_model_settings(self.ci, model).get('name') or model['model_id'] + + def run_title(self, analysis, models_by_id): + """How to name a run: showcase runs by their scenario's name, others by their run name. + + The scenario name comes from the model settings, so a renamed scenario doesn't need its + showcase rebuilt. + """ + model = models_by_id.get(analysis.get('model')) + if model is not None and is_showcase(analysis, self.limits): + return self.scenario_name(model) + return display_name(analysis['name']) + + +def footer(ui_config): + """Disclaimer / licence footer from the UI config, on every Scenarios page.""" + path = (ui_config.footer or {}).get('path') + if not path: + return + try: + text = Path(path).read_text() + except OSError: + logger.error(f'Footer file not found at {path}') + return + st.divider() + st.caption(text) + + +def run_settings(ci, model, number_of_samples, group_fields): + """Analysis settings for a scenario run. + + Starts from the model's latest settings template on the platform (falling + back to a bundled defaults/ file, then model defaults) and applies the + visitor's choices: number of samples and group-by fields. Group-by fields + are written into the outputs (join_summary_info). + """ + settings = None + try: + templates = ci.models.setting_templates.get(model['id']) or [] + if templates: + latest = max(t['id'] for t in templates) + settings = ci.models.setting_templates.get_contents(model['id'], latest) + except (HTTPError, OasisException, AttributeError) as e: + logger.warning(f"No settings template for model {model['id']}: {e}") + if not settings: + paths = get_analyses_settings(model_name_id=model['model_id']) + if paths: + settings = json.loads(Path(paths[0]).read_text()) + if not settings: + settings = default_settings(model, cached_model_settings(ci, model)) + + settings = deepcopy(settings) + settings['model_supplier_id'] = model['supplier_id'] + settings['model_name_id'] = model['model_id'] + settings['number_of_samples'] = number_of_samples + settings.setdefault('join_summary_info', True) + for p in PERSPECTIVES: + if settings.get(f'{p}_output'): + for level in settings.get(f'{p}_summaries') or []: + if group_fields: + level['oed_fields'] = list(group_fields) + else: + level.pop('oed_fields', None) + return settings + + +def run_summary(ctx, analysis, settings, models_by_id, portfolios_by_id): + model = models_by_id.get(analysis['model'], {}) + portfolio = portfolios_by_id.get(analysis['portfolio'], {}) + fields = [] + for p in PERSPECTIVES: + for level in (settings or {}).get(f'{p}_summaries') or []: + fields = level.get('oed_fields') or fields + labels = {field: label for label, field in GROUP_BY_OPTIONS} + facts = [('Scenario', ctx.scenario_name(model) if model else '—'), + ('Exposure', portfolio.get('name', '—')), + ('Samples', (settings or {}).get('number_of_samples', '—')), + ('Losses broken down by', ', '.join(labels.get(f, f) for f in fields) or 'Total only')] + # Plain text rather than st.metric, which truncates long scenario names + for col, (label, value) in zip(st.columns([3, 2, 1, 2]), facts): + col.caption(label) + col.markdown(f'**{value}**') + + +def analysis_results(ctx, analysis, models_by_id, portfolios_by_id, key): + """Summary, results and downloads for a completed analysis.""" + st.subheader(ctx.run_title(analysis, models_by_id)) + if analysis['status'] != 'RUN_COMPLETED': + st.info(f"{format_status(analysis['status'])}. Results appear here when the run completes.") + return + + settings = analysis_settings(ctx.ci, analysis) + run_summary(ctx, analysis, settings, models_by_id, portfolios_by_id) + if not settings: + st.warning('The settings for this run are not available, so its outputs cannot be shown.') + return + + with st.spinner('Loading results...'): + outputs = analysis_files(ctx.ci, analysis, 'output_file') + inputs = analysis_files(ctx.ci, analysis, 'input_file') + locations = inputs.get('location.csv', inputs.get('location.parquet')) + render_results(settings, outputs, locations, key=analysis['id']) + + zip_key = f"zip_{analysis['id']}_{analysis.get('modified')}" + if zip_key not in st.session_state: + if st.button('Prepare results download (.zip)', key=f'{key}_{zip_key}_prep'): + with st.spinner('Fetching outputs...'): + st.session_state[zip_key] = ctx.ci.download_output_zip(analysis['id']) + st.rerun() + else: + st.download_button('Download results (.zip)', st.session_state[zip_key], type='primary', + icon=':material/download:', key=f'{key}_{zip_key}_dl', + file_name=f"{display_name(analysis['name'])}.zip".replace(' ', '_')) diff --git a/pages/comparison.py b/scenarios_ui/compare.py similarity index 73% rename from pages/comparison.py rename to scenarios_ui/compare.py index bfb6164..7a882c5 100644 --- a/pages/comparison.py +++ b/scenarios_ui/compare.py @@ -1,83 +1,61 @@ -from modules.authorisation import validate_page, handle_login -from modules.visualisation import OutputInterface -import streamlit as st +"""Compare: results of two runs side by side (showcase runs and your own runs).""" import pandas as pd -from modules.nav import SidebarNav -from modules.config import retrieve_ui_config -from modules.validation import LenValidation, NotNoneValidation, ValidationGroup -from pages.components.common import PERSPECTIVES_MAP -from pages.components.footer import generate_footer -from pages.components.output import generate_aalcalc_comparison_fragment, generate_leccalc_comparison_fragment -from pages.components.output import generate_eltcalc_comparison_fragment, summarise_inputs -from pages.components.output import generate_pltcalc_comparison_fragment -from pages.components.output import generate_alt_comparison_fragment, EP_CALC_LABELS - -########################################################################################## -# Header -########################################################################################## - -ui_config = retrieve_ui_config() -validate_page("Comparison") - -st.set_page_config( - page_title="Comparison", - layout="centered" -) - -cols = st.columns([0.1, 0.8, 0.1]) -with cols[1]: - st.image("images/oasis_logo.png") +import streamlit as st -########################################################################################## -# Page -########################################################################################## +from modules.scenarios import showcase_analyses, visitor_analyses +from modules.visualisation import OutputInterface +from pages.components.common import PERSPECTIVES_MAP +from pages.components.output import (EP_CALC_LABELS, generate_aalcalc_comparison_fragment, + generate_alt_comparison_fragment, generate_eltcalc_comparison_fragment, + generate_leccalc_comparison_fragment, generate_pltcalc_comparison_fragment, + summarise_inputs) +from scenarios_ui.common import Context, footer + +ctx = Context() +ui_config = ctx.ui_config +client_interface = ctx.ci +client = client_interface.client -# Retrieve client -handle_login(ui_config.skip_login) +st.title('Compare') +st.markdown( + 'Compare the results of two runs side by side: for example a flood with and without defences, two ' + 'different scenarios, or the same scenario with different settings. Choose from the showcase runs and ' + 'your own completed runs.') -SidebarNav() +all_analyses = client_interface.analyses.get() +models_by_id = {m['id']: m for m in client_interface.models.get()} +showcase = {a['id'] for a in showcase_analyses(all_analyses, ctx.limits, list(models_by_id.values()), ui_config)} +mine = {a['id'] for a in visitor_analyses(all_analyses, ctx.vid)} +analyses = sorted([a for a in all_analyses if a['status'] == 'RUN_COMPLETED' and a['id'] in showcase | mine], + key=lambda a: (a['id'] not in mine, ctx.run_title(a, models_by_id).lower())) -client_interface = st.session_state["client_interface"] -client = client_interface.client -'## Compare two scenario loss estimates' -'This tool enables two analyses to be compared to look at the difference in, for example - change in exposure, hazard or vulnerability.' -'A use case for this, would be to compare loss from flood in an area defended by a different level of flood protection, or no flood protection.' -'It can also be used to test the impact of two different hazard scenarios, different vulnerability of the buildings in the portfolio, or of a different value/number of buildings in that portfolio.' +def option_label(analysis): + source = 'your run' if analysis['id'] in mine else 'showcase' + return f"{ctx.run_title(analysis, models_by_id)} ({source})" -"First, select two analyses, from the precomputed set. To add an analysis to the list, run it in the 'Scenario' tool." -'Currently, it is not possible to add your own scenarios directly; please describe any scenario you would like to add, here: https://github.com/OasisLMF/OasisPythonUI/issues' +if len(analyses) < 2: + st.info('You need at least two completed runs to compare. Run a scenario, or check the showcase.') + footer(ui_config) + st.stop() -analyses = sorted(client_interface.analyses.search(metadata={'status': 'RUN_COMPLETED'}), key=lambda x: x['id'], reverse=True) cols = st.columns(2) selected = [] -with cols[0]: - selected_analysis = st.selectbox("Select Analysis 1", options=analyses, - format_func=lambda x: x['name'], index=None) - if selected_analysis: - selected.append(selected_analysis) -with cols[1]: - selected_analysis = st.selectbox("Select Analysis 2", options=analyses, - format_func=lambda x: x['name'], index=None) - if selected_analysis: - selected.append(selected_analysis) - - -validations = ValidationGroup() -none_validation = NotNoneValidation() -none_validation.message = 'Select 2 analyses.' -validations.add_validation(none_validation, selected) -len_validation = LenValidation() -len_validation.message = 'Select 2 analyses.' -validations.add_validation(len_validation, selected, 2) - -if not validations.is_valid(): - st.info(validations.message) - generate_footer(ui_config) +for i, col in enumerate(cols): + choice = col.selectbox(f'Run {i + 1}', options=analyses, format_func=option_label, index=None, + placeholder='Choose a run', key=f'compare_run_{i}') + if choice: + selected.append(choice) + +if len(selected) != 2: + st.info('Select 2 runs.') + footer(ui_config) st.stop() +titles = [ctx.run_title(a, models_by_id) for a in selected] selected = pd.DataFrame(selected) +selected['name'] = titles analysis_ids = [selected['id'][i] for i in range(2)] model_ids = [selected['model'][i] for i in range(2)] @@ -215,11 +193,15 @@ def merge_locations(locations_1, locations_2): if oed_fields is not None: output.set_oed_fields(p, oed_fields) - if all([s.get('aalcalc', False) for s in summaries]): + def produced(output_type, p=p, outputs=outputs): + """Both runs produced this output (requested outputs can be missing).""" + return all(o.has_output(p, output_type) for o in outputs) + + if all([s.get('aalcalc', False) for s in summaries]) and produced('aalcalc'): st.write("### Mean loss comparison chart") generate_aalcalc_comparison_fragment(p, outputs, names) - if all([s.get('eltcalc', False) for s in summaries]): + if all([s.get('eltcalc', False) for s in summaries]) and produced('eltcalc'): st.write("### Per-location loss estimates") locations = [get_locations_file(id) for id in analysis_ids] locations = merge_locations(*locations) @@ -238,7 +220,7 @@ def merge_locations(locations_1, locations_2): generate_leccalc_comparison_fragment(p, outputs, names=names, lec_outputs=lec_outputs) - if all(o.get('elt_moment', False) for o in ord_settings): + if all(o.get('elt_moment', False) for o in ord_settings) and produced('elt_moment'): st.write("### MELT Output") locations = [get_locations_file(id) for id in analysis_ids] locations = merge_locations(*locations) @@ -254,7 +236,7 @@ def merge_locations(locations_1, locations_2): 'MaxImpactedExposure': 'Max Impacted Exposure', }) - if all(o.get('elt_quantile', False) for o in ord_settings): + if all(o.get('elt_quantile', False) for o in ord_settings) and produced('elt_quantile'): st.write("### QELT Output") locations = [get_locations_file(id) for id in analysis_ids] locations = merge_locations(*locations) @@ -267,7 +249,7 @@ def merge_locations(locations_1, locations_2): data_cols=['Loss'], event_id='EventId') - if all(o.get('plt_moment', False) for o in ord_settings): + if all(o.get('plt_moment', False) for o in ord_settings) and produced('plt_moment'): st.write("### MPLT Output") generate_pltcalc_comparison_fragment(p, outputs, names=names, output_type='plt_moment', @@ -276,7 +258,7 @@ def merge_locations(locations_1, locations_2): 'MeanImpactedExposure', 'MaxImpactedExposure']) - if all(o.get('plt_quantile', False) for o in ord_settings): + if all(o.get('plt_quantile', False) for o in ord_settings) and produced('plt_quantile'): st.write("### QPLT Output") generate_pltcalc_comparison_fragment(p, outputs, names=names, output_type='plt_quantile', @@ -285,15 +267,15 @@ def merge_locations(locations_1, locations_2): filter_format_func=lambda x: '{:.2f}'.format(x), value_col='Loss') - if all(o.get('alt_meanonly', False) for o in ord_settings): + if all(o.get('alt_meanonly', False) for o in ord_settings) and produced('alt_meanonly'): st.write("### ALT MeanOnly Output") generate_alt_comparison_fragment(p, outputs, 'alt_meanonly', names=names) - if all(o.get('alt_period', False) for o in ord_settings): + if all(o.get('alt_period', False) for o in ord_settings) and produced('alt_period'): st.write("### PALT Output") generate_alt_comparison_fragment(p, outputs, 'alt_period', names=names) - if all(any(o.get(e, False) for e in ept_settings) for o in ord_settings): + if all(any(o.get(e, False) for e in ept_settings) for o in ord_settings) and produced('ept'): st.write("### EPT Output") ep_type_map = {1: 'OEP', 2: 'OEP TVAR', 3: 'AEP', 4: 'AEP TVAR'} ep_calc_map = EP_CALC_LABELS @@ -306,4 +288,4 @@ def merge_locations(locations_1, locations_2): return_period_col='ReturnPeriod', loss_col='Loss', group_col_default='SummaryId') -generate_footer(ui_config) +footer(ui_config) diff --git a/scenarios_ui/explore.py b/scenarios_ui/explore.py new file mode 100644 index 0000000..d175605 --- /dev/null +++ b/scenarios_ui/explore.py @@ -0,0 +1,238 @@ +"""Run a scenario: choose a scenario and its exposure, run it, and view the results.""" +from datetime import datetime, timezone + +import pandas as pd +import streamlit as st +from oasis_data_manager.errors import OasisException +from requests.exceptions import HTTPError + +from modules.oed import has_coordinates +from modules.scenarios import (GROUP_BY_OPTIONS, display_name, is_active, limit_processes, run_blocked_reason, + scenario_catalogue, + scenario_portfolios, tagged_name, visitor_analyses, + visitor_tag) +from modules.ui import api_error_message, flash, show_flash +from pages.components.common import analysis_progress, current_task, status_label +from pages.components.data import cached_model_settings, portfolio_file_df +from pages.components.exposure import exposure_overview +from scenarios_ui.common import Context, analysis_results, footer, run_settings + +SELECTED_MODEL = 'sc_model_id' +SELECTED_PORTFOLIO = 'sc_portfolio_id' +SELECTED_RUN = 'sc_run_id' + +ctx = Context() +ci = ctx.ci +show_flash() + +models = ci.models.get() +portfolios = ci.portfolios.get() +analyses = ci.analyses.get() +models_by_id = {m['id']: m for m in models} +portfolios_by_id = {p['id']: p for p in portfolios} +my_runs = sorted(visitor_analyses(analyses, ctx.vid), key=lambda a: a['id'], reverse=True) + +st.title('Run a scenario') +st.markdown( + 'Estimate the losses a real or realistic disaster could cause to a pre-loaded portfolio of ' + 'buildings, using the open-source [Oasis](https://oasislmf.org/) loss modelling framework. ' + 'Choose a scenario, check the exposure it will be run against, then run it and explore the results.') + +catalogue = scenario_catalogue(models, portfolios, ctx.ui_config, lambda m: cached_model_settings(ci, m), + lambda p: portfolio_file_df(ci, p, 'location_file')) +if not catalogue: + st.warning('No scenarios are available at the moment. Please check back later.') + footer(ctx.ui_config) + st.stop() + + +########################################################################################## +# 1. Scenario +########################################################################################## + +st.header('1. Choose a scenario', divider='gray') +selected_model_id = st.session_state.get(SELECTED_MODEL) + + +def countries_label(countries): + if len(countries) <= 3: + return ', '.join(countries) + return f"{', '.join(countries[:2])} +{len(countries) - 2} more" + + +f_search, f_peril, f_country, f_provider = st.columns([0.34, 0.22, 0.22, 0.22]) +search = f_search.text_input('Search', placeholder='Search scenarios', label_visibility='collapsed', + key='sc_filter_search') +perils = f_peril.multiselect('Peril', sorted({e['peril'] for e in catalogue}), placeholder='Any peril', + label_visibility='collapsed', key='sc_filter_peril') +countries = f_country.multiselect('Country', sorted({c for e in catalogue for c in e['countries']}), + placeholder='Any country', label_visibility='collapsed', key='sc_filter_country') +providers = f_provider.multiselect('Provider', sorted({e['provider'] for e in catalogue}), placeholder='Any provider', + label_visibility='collapsed', key='sc_filter_provider') + +needle = (search or '').strip().lower() +shown = [e for e in catalogue + if (not needle or needle in f"{e['title']} {e['description']} {' '.join(e['countries'])}".lower()) + and (not perils or e['peril'] in perils) + and (not countries or set(countries) & set(e['countries'])) + and (not providers or e['provider'] in providers)] + +st.caption(f'{len(shown)} of {len(catalogue)} scenarios. Select a row to choose a scenario.') +if shown: + table = pd.DataFrame([{'id': e['id'], 'Scenario': e['title'], 'Peril': e['peril'], + 'Country': countries_label(e['countries']), 'Provider': e['provider']} for e in shown]) + ids = table['id'].tolist() + # A new table whenever the filters change, so a stale row selection can't pick the wrong scenario + table_key = f"sc_table_{hash((needle, tuple(perils), tuple(countries), tuple(providers)))}" + + def on_select(): + rows = st.session_state[table_key].selection.rows + if rows: + st.session_state[SELECTED_MODEL] = ids[rows[0]] + st.session_state[SELECTED_PORTFOLIO] = None + + st.dataframe(table, key=table_key, on_select=on_select, selection_mode='single-row', hide_index=True, + column_order=['Scenario', 'Peril', 'Country', 'Provider'], width='stretch', + height=min(38 + 35 * len(table), 38 + 35 * 20), + column_config={'Scenario': st.column_config.TextColumn(width='large')}) +else: + st.info('No scenarios match these filters.') + +chosen = next((e for e in catalogue if e['id'] == selected_model_id), None) +if chosen: + with st.container(border=True): + st.markdown(f"**{chosen['title']}**") + st.caption(' · '.join(x for x in [chosen['peril'], ', '.join(chosen['countries']), + f"Provided by {chosen['provider']}"] if x)) + if chosen['description']: + st.write(chosen['description']) + +model = models_by_id.get(selected_model_id) + + +########################################################################################## +# 2. Exposure +########################################################################################## + +portfolio = None +locations = None +if model is not None: + st.header('2. Check the exposure', divider='gray') + options = scenario_portfolios(model, portfolios, ctx.ui_config) + if len(options) > 1: + ids = [p['id'] for p in options] + current = st.session_state.get(SELECTED_PORTFOLIO) + portfolio_id = st.radio('Exposure portfolio', ids, horizontal=True, + index=ids.index(current) if current in ids else 0, + format_func=lambda i: portfolios_by_id[i]['name'], + help='The buildings the scenario will be run against.') + else: + portfolio_id = options[0]['id'] + st.session_state[SELECTED_PORTFOLIO] = portfolio_id + portfolio = portfolios_by_id[portfolio_id] + + st.caption(f"The scenario will be run against the **{portfolio['name']}** portfolio. " + 'You cannot upload your own exposure in this tool.') + with st.spinner('Loading exposure...'): + try: + locations = portfolio_file_df(ci, portfolio, 'location_file') + except (HTTPError, OasisException): + locations = None + if locations is not None: + exposure_overview(locations, breakdowns=False) + + +########################################################################################## +# 3. Run +########################################################################################## + +if model is not None and portfolio is not None: + st.header('3. Run', divider='gray') + limits = ctx.limits + + left, right = st.columns(2) + samples = left.slider( + 'Number of samples', min_value=1, max_value=limits.max_samples, value=limits.default_samples, + help='Damage to each building is uncertain. Each sample is one possible outcome of the scenario; ' + 'averaging over more samples gives a more reliable estimate but takes longer. The results also ' + 'show the model\'s analytical mean, which does not depend on the number of samples.') + + available = set(locations.columns) if locations is not None else set() + if (portfolio.get('accounts_file') or {}).get('stored'): + available.add('PortNumber') + group_options = [(label, field) for label, field in GROUP_BY_OPTIONS if field in available] + # Default to a location breakdown where the exposure has coordinates, so results can be mapped + mappable = has_coordinates(locations) + default_labels = ['Location'] if mappable and any(f == 'LocNumber' for _, f in group_options) else [] + labels = right.pills('Break losses down by', [label for label, _ in group_options], selection_mode='multi', + default=default_labels, key=f"sc_group_by_{model['id']}_{portfolio['id']}", + help='Show losses per portfolio, country or location as well as in total. ' + 'A location breakdown is needed for loss maps.') + group_fields = [field for label, field in group_options if label in (labels or [])] + + blocked = run_blocked_reason(analyses, ctx.vid, limits) + if blocked: + st.info(blocked) + if st.button('Run scenario', type='primary', icon=':material/play_arrow:', disabled=bool(blocked)): + name = f"{ctx.scenario_name(model)} – {portfolio['name']} ({datetime.now(timezone.utc):%d %b %H:%M} UTC)" + try: + with st.spinner('Starting run...'): + settings = limit_processes(run_settings(ci, model, samples, group_fields), + limits.processes_per_run) + analysis = ci.create_analysis(portfolio['id'], model['id'], tagged_name(name, visitor_tag(ctx.vid))) + ci.upload_settings(analysis['id'], settings) + ci.generate_and_run(analysis['id']) + except (HTTPError, OasisException) as e: + st.error(f'The run could not be started. {api_error_message(e)}') + else: + st.session_state[SELECTED_RUN] = analysis['id'] + flash('Run started. Results will appear below when it completes.') + st.rerun() + + +########################################################################################## +# Your runs +########################################################################################## + +st.header('Your runs', divider='gray') +if not my_runs: + st.caption('Runs you start appear here. They are kept for a few days.') +else: + snapshot = {a['id']: a['status'] for a in my_runs} + any_running = any(is_active(a) for a in my_runs) + + @st.fragment(run_every='3s' if any_running else None) + def live_progress(): + if not any_running: + return + fresh = visitor_analyses(ci.analyses.get(), ctx.vid) + if {a['id']: a['status'] for a in fresh} != snapshot: + st.rerun() + for a in fresh: + if is_active(a): + fraction, detail = analysis_progress(a) + task = current_task(ci.analyses.sub_tasks(a['id'])) + text = ' · '.join(x for x in [f"**{display_name(a['name'])}**", status_label(a), + task, detail] if x) + st.progress(fraction or 0.0, text=text) + + live_progress() + + table = pd.DataFrame([{'id': a['id'], 'Run': display_name(a['name']), 'Status': status_label(a)} + for a in my_runs]) + ids = table['id'].tolist() + + def on_select(): + rows = st.session_state['sc_runs_table'].selection.rows + st.session_state[SELECTED_RUN] = ids[rows[0]] if rows else None + + st.dataframe(table, key='sc_runs_table', on_select=on_select, selection_mode='single-row', + hide_index=True, column_order=['Run', 'Status'], width='stretch') + + selected_run = next((a for a in my_runs if a['id'] == st.session_state.get(SELECTED_RUN)), None) + if selected_run is None: + st.caption('Select a run to see its results.') + else: + analysis_results(ctx, selected_run, models_by_id, portfolios_by_id, key='explore') + +footer(ctx.ui_config) diff --git a/scenarios_ui/guide.py b/scenarios_ui/guide.py new file mode 100644 index 0000000..99d2831 --- /dev/null +++ b/scenarios_ui/guide.py @@ -0,0 +1,88 @@ +"""Guide: what the Scenarios tool is and how to use it.""" +import streamlit as st + +from scenarios_ui.common import Context, footer + +ctx = Context() +limits = ctx.limits + +st.title('Guide') + +st.markdown(""" +The **Oasis Scenarios** tool lets you see how catastrophe loss modelling works, using the open-source +[Oasis Loss Modelling Framework](https://oasislmf.org/). It runs real historical events and realistic +disaster scenarios - floods, windstorms, earthquakes, hail - against pre-loaded portfolios of buildings, +and shows you the losses they would cause. + +It is free to use and needs no account. You cannot upload your own data: every scenario and portfolio has +been prepared in advance, so you can focus on running models and understanding their results. +""") + +st.header('How a loss model works') +st.markdown(""" +Every Oasis model combines three parts: + +- **Hazard** - how severe the event is at each place, for example flood depth or wind speed. In this tool + each scenario provides a *hazard footprint* for one or a few events. +- **Vulnerability** - how much damage that severity causes to a building, as a share of its value. +- **Exposure** - the buildings at risk: where they are, what they are built from and what they are worth, + in the [Open Exposure Data (OED)](https://oasislmf.org/open-data-standards) format. + +Oasis combines them to estimate the loss to each building, then adds the losses up. +""") + +st.header('Running a scenario') +st.markdown(f""" +1. **Choose a scenario** on the *Run a scenario* page. Each card says who provided it and what it represents. +2. **Check the exposure.** The map and figures show the buildings the scenario will be run against. +3. **Run it.** Choose: + - **Number of samples** (up to {limits.max_samples}) - damage is uncertain, so Oasis draws several + possible outcomes (samples) and averages them. More samples give a steadier average but take longer. + - **Break losses down by** - portfolio, country or location, to see where losses come from. +4. **Watch it run.** A progress bar shows the current step and how many events have been processed. + Most scenarios finish within a few minutes. +5. **Explore the results** under *Your runs*, and download them as a zip file. + +You can have up to {limits.max_active_runs_per_visitor} runs in progress at a time. Your runs are linked to +this browser address (the `?v=` part of the URL): bookmark it to come back to them. Runs are kept for a few +days. +""") + +st.header('Reading the results') +st.markdown(""" +Results follow the [Open Results Data (ORD)](https://oasislmf.org/open-data-standards) standard. Which tables +you see depends on the scenario, but the most common are: + +- **Event loss tables (ELT)** - the loss from each event. *Sample* ELTs (SELT) give the loss in each sample; + *moment* ELTs (MELT) give the mean and standard deviation. +- **Average loss tables (ALT)** - the average loss across the events in the scenario. +- **Exceedance probability tables (EPT)** - for scenarios with many events, how likely losses are to exceed + each level. With one or a few events these are less meaningful. + +**Mean of samples vs analytical mean.** Sample tables can show the *mean of samples* - the average of the +sampled losses - or the model's *analytical mean*, calculated exactly from the damage distribution without +sampling. With few samples the two can differ noticeably; as you add samples, the mean of samples gets closer +to the analytical mean. + +**Loss perspectives.** *Ground up loss* is the cost of the damage before any insurance. Some scenarios also +show *insured loss*, after policy terms such as deductibles and limits. +""") + +st.header('Comparing runs') +st.markdown(""" +The *Compare* page puts two runs side by side - for example the same flood with and without flood defences, +or two different scenarios against the same buildings. Choose from the showcase runs and your own runs. +""") + +st.header('Where the data comes from') +st.markdown(""" +The scenarios are contributed by model providers and are published in the +[Oasis Scenarios repository](https://github.com/OasisLMF/Scenarios). They may use simplified hazard, +vulnerability or exposure compared with the providers' full commercial models, so treat the results as +illustrative. + +To suggest a scenario or report a problem, open an issue on +[GitHub](https://github.com/OasisLMF/OasisPythonUI/issues). +""") + +footer(ctx.ui_config) diff --git a/scenarios_ui/showcase.py b/scenarios_ui/showcase.py new file mode 100644 index 0000000..257879c --- /dev/null +++ b/scenarios_ui/showcase.py @@ -0,0 +1,44 @@ +"""Showcase: curated, pre-computed scenario runs that anyone can explore without waiting.""" +import streamlit as st + +from modules.scenarios import VISITOR_PARAM, showcase_analyses +from pages.components.data import cached_model_settings +from scenarios_ui.common import Context, analysis_results, footer + +ctx = Context() +ci = ctx.ci + +models = ci.models.get() +models_by_id = {m['id']: m for m in models} +portfolios_by_id = {p['id']: p for p in ci.portfolios.get()} +showcase = [a for a in showcase_analyses(ci.analyses.get(), ctx.limits, models, ctx.ui_config) if a['status'] == 'RUN_COMPLETED'] + +st.title('Showcase') +st.markdown('Results from scenarios we have already run for you, so you can explore what Oasis produces ' + 'without waiting for a run. To run a scenario yourself, use **Run a scenario**.') + +if not showcase: + st.info('No showcase results are available yet. They are added when the service is set up.') + footer(ctx.ui_config) + st.stop() + +titles = {a['id']: ctx.run_title(a, models_by_id) for a in showcase} +showcase.sort(key=lambda a: titles[a['id']].lower()) +ids = [a['id'] for a in showcase] +by_id = {a['id']: a for a in showcase} +selected_id = st.selectbox('Scenario', ids, format_func=lambda i: titles[i], + key='showcase_selected') +analysis = by_id[selected_id] + +model = models_by_id.get(analysis['model']) +if model is not None: + description = cached_model_settings(ci, model).get('description') + if description: + st.caption(description) + if st.button('Run this scenario yourself', icon=':material/play_circle:'): + st.session_state['sc_model_id'] = model['id'] + st.session_state['sc_portfolio_id'] = analysis['portfolio'] + st.switch_page('scenarios_ui/explore.py', query_params={VISITOR_PARAM: ctx.vid}) + +analysis_results(ctx, analysis, models_by_id, portfolios_by_id, key='showcase') +footer(ctx.ui_config) diff --git a/scripts/add_settings_template.py b/scripts/add_settings_template.py index 41c5da9..f082be7 100644 --- a/scripts/add_settings_template.py +++ b/scripts/add_settings_template.py @@ -24,11 +24,16 @@ def add_model_analysis_settings(client, model_id, analysis_settings_path): with open(analysis_settings_path, "r") as f: analysis_settings_json = json.load(f) - # send post to make template + # Reuse an existing template of the same name so re-running updates it model_pk = models[0]["id"] - data = {"name": f"{model_id}_default_settings"} - resp = client.models.setting_templates.post(model_pk, data=data).json() - template_id = resp["id"] + name = f"{model_id}_default_settings" + existing = [t for t in client.models.setting_templates.get(model_pk).json() if t.get("name") == name] + if existing: + template_id = existing[0]["id"] + logger.info(f"Updating existing template {name} ({template_id})") + else: + resp = client.models.setting_templates.post(model_pk, data={"name": name}).json() + template_id = resp["id"] # send post with content logger.info(f"[ ] Uploading analysis settings template for {model_id}...") diff --git a/scripts/add_showcase_analyses.py b/scripts/add_showcase_analyses.py new file mode 100644 index 0000000..fa7c4bf --- /dev/null +++ b/scripts/add_showcase_analyses.py @@ -0,0 +1,190 @@ +"""Create and run the showcase analyses for the public Scenarios app. + +For each scenario model in the Scenarios UI config's `model_map` that is +registered on the platform, runs the model against its first portfolio +using the model's settings template, and tags the analysis name with the +showcase tag (e.g. `[showcase]`) so the app lists it on the Showcase page +and the prune job keeps it. + +Runs one scenario at a time (--max-concurrent), waiting for each to finish, +and caps each run's processes (scenarios.processes_per_run): starting every +scenario at once can exhaust the host's memory. + +Where the exposure has coordinates, showcase runs break losses down by +location (summary level 1, shown first, with maps) as well as giving the +template's portfolio totals (level 2). + +Idempotent: scenarios with a completed or in-progress showcase run are +skipped; failed or cancelled showcase runs are replaced. --replace rebuilds +existing showcase runs (e.g. after changing templates or this script). + +Usage: + python scripts/add_showcase_analyses.py -c scenarios/ui-config.json [--retry] +""" +import argparse +import json +import logging +import time +from copy import deepcopy +from pathlib import Path + +from utils import LOG_LEVEL, initialise_client, parse_initialise_args + +from modules.oed import has_coordinates +from modules.scenarios import is_active, limit_processes + +FAILED = ['INPUTS_GENERATION_ERROR', 'INPUTS_GENERATION_CANCELLED', 'RUN_ERROR', 'RUN_CANCELLED'] +# A generate-and-run passes through READY between input generation and the +# loss run, so only these statuses mean a showcase run has finished +FINISHED = ['RUN_COMPLETED'] + FAILED + +logger = logging.getLogger(__name__) +logging.basicConfig(level=LOG_LEVEL) + + +def model_settings(client, model): + try: + return client.models.settings.get(model['id']).json() or {} + except Exception: # noqa: BLE001 - a model without settings still gets a showcase run + return {} + + +def settings_template(client, model): + templates = client.models.setting_templates.get(model['id']).json() or [] + if not templates: + return None + latest = max(t['id'] for t in templates) + return client.models.setting_templates.content.get(model['id'], latest).json() + + +def map_field(client, portfolio): + """The OED field to break showcase losses down by so they can be mapped. + + LocNumber when the locations have coordinates (a point map), else CountryCode + when they span several countries (a country map), else None (totals only). + """ + try: + locations = client.portfolios.location_file.get_dataframe(portfolio['id']) + except Exception as e: # noqa: BLE001 - no map is better than no showcase run + logger.warning(f"Could not read the location file of {portfolio['name']}: {e}") + return None + if 'LocNumber' in locations.columns and has_coordinates(locations): + return 'LocNumber' + if 'CountryCode' in locations.columns and locations['CountryCode'].nunique() > 1: + return 'CountryCode' + return None + + +def showcase_settings(template, model, samples, group_field=None): + """Settings for a showcase run, adding a level grouped by `group_field` first when given.""" + settings = deepcopy(template) + settings['model_supplier_id'] = model['supplier_id'] + settings['model_name_id'] = model['model_id'] + settings['number_of_samples'] = samples + settings.setdefault('join_summary_info', True) + if group_field: + for p in ['gul', 'il', 'ri', 'rl']: + levels = settings.get(f'{p}_summaries') or [] + if not settings.get(f'{p}_output') or not levels: + continue + grouped = deepcopy(levels[0]) + grouped['oed_fields'] = [group_field] + total = deepcopy(levels[0]) + total.pop('oed_fields', None) + rest = [deepcopy(level) for level in levels[1:]] + settings[f'{p}_summaries'] = [dict(level, id=i) for i, level in enumerate([grouped, total] + rest, 1)] + return settings + + +def wait_for_slot(client, running, max_concurrent, timeout): + """Block until fewer than `max_concurrent` of `running` are in progress.""" + start = time.time() + while True: + statuses = {i: client.analyses.get(i).json()['status'] for i in running} + for i, status in statuses.items(): + if status in FINISHED: + logger.info(f'Showcase run {i} finished: {status}') + running.remove(i) + if len(running) < max_concurrent: + return + if time.time() - start > timeout: + raise SystemExit(f'Timed out waiting for showcase runs {running}') + time.sleep(15) + + +def main(): + parser = argparse.ArgumentParser(description='Create and run Scenarios showcase analyses') + parser.add_argument('-c', '--config', default='./scenarios/ui-config.json', type=Path, + help='Scenarios UI config (model_map and scenarios.showcase_tag)') + parser.add_argument('-s', '--samples', default=10, type=int, help='Number of samples per run') + parser.add_argument('--models', nargs='+', default=None, help='Only these model ids (default: all)') + parser.add_argument('--force', action='store_true', help='Add a run even if one exists') + parser.add_argument('--replace', action='store_true', + help='Delete and rebuild existing showcase runs (completed or failed)') + parser.add_argument('--max-concurrent', default=1, type=int, + help='Showcase runs in progress at once (default 1)') + parser.add_argument('--timeout', default=3600, type=int, help='Seconds to wait for a run to finish') + parser.add_argument('-r', '--retry', action='store_true', help='Retry initialising client') + parser.add_argument('-m', '--max-retries', default=10, type=int, help='Max number of retries') + parser.add_argument('-i', '--retry_interval', default=10, type=int, help='Seconds between retries') + args = vars(parser.parse_args()) + + config = json.loads(args['config'].read_text()) + tag = config.get('scenarios', {}).get('showcase_tag', '[showcase]') + processes = config.get('scenarios', {}).get('processes_per_run', 2) + model_map = config.get('model_map', {}) + + client = initialise_client(*parse_initialise_args(**args)) + if client is None: + raise SystemExit('Could not connect to the API') + + models = {m['model_id']: m for m in client.models.get().json()} + portfolios = {p['name']: p for p in client.portfolios.get().json()} + existing = [a for a in client.analyses.get().json() if a['name'].endswith(tag)] + running = [a['id'] for a in existing if is_active(a)] + + for model_id, portfolio_names in model_map.items(): + if args['models'] and model_id not in args['models']: + continue + model = models.get(model_id) + portfolio = next((portfolios[n] for n in portfolio_names if n in portfolios), None) + if model is None or portfolio is None: + logger.info(f'Skipping {model_id}: model or portfolio not on the platform') + continue + mine = [a for a in existing if a['model'] == model['id']] + if args['replace']: + for old in [a for a in mine if a['status'] in FINISHED]: + logger.info(f"Replacing showcase run {old['id']} for {model_id}") + client.analyses.delete(old['id']) + mine = [a for a in mine if a['status'] not in FINISHED] + if not args['force'] and any(a['status'] not in FAILED for a in mine): + logger.info(f'Skipping {model_id}: showcase analysis already exists') + continue + for failed in [a for a in mine if a['status'] in FAILED]: + logger.info(f"Replacing failed showcase run {failed['id']} ({failed['status']}) for {model_id}") + client.analyses.delete(failed['id']) + + template = settings_template(client, model) + if template is None: + logger.warning(f'Skipping {model_id}: no settings template (run add_settings_template.py first)') + continue + + wait_for_slot(client, running, args['max_concurrent'], args['timeout']) + name = model_settings(client, model).get('name') or model_id + analysis = client.create_analysis(portfolio_id=portfolio['id'], model_id=model['id'], + analysis_name=f"{name} – {portfolio['name']} {tag}") + group_field = map_field(client, portfolio) + settings = limit_processes(showcase_settings(template, model, args['samples'], group_field), processes) + client.upload_settings(analysis['id'], settings) + client.analyses.generate_and_run(analysis['id']) + running.append(analysis['id']) + logger.info(f"Started showcase run {analysis['id']} for {model_id} on {portfolio['name']}" + f"{f' (by {group_field})' if group_field else ''}") + + # Wait for the last runs so setup only finishes when the showcase is ready + wait_for_slot(client, running, 1, args['timeout']) + logger.info('Showcase runs complete') + + +if __name__ == '__main__': + main() diff --git a/scripts/add_test_portfolios.py b/scripts/add_test_portfolios.py index d717d1f..782f25a 100644 --- a/scripts/add_test_portfolios.py +++ b/scripts/add_test_portfolios.py @@ -13,8 +13,11 @@ def add_portfolio(client, input_args): existing_names = [r['name'] for r in client.portfolios.get().json()] logger.info('Adding portfolios...') + missing = [v for k, v in input_args.items() if k.endswith('_fp') and v and not Path(v).is_file()] if input_args.get('portfolio_name') in existing_names: logger.info(f'Skipping {input_args["portfolio_name"]}') + elif missing: + logger.warning(f'Skipping {input_args["portfolio_name"]}: files not found: {missing}') else: logger.info(f'Adding {input_args["portfolio_name"]}') client.upload_inputs(**input_args) diff --git a/scripts/prune_analysis.py b/scripts/prune_analysis.py index ed22cb8..e3397c5 100644 --- a/scripts/prune_analysis.py +++ b/scripts/prune_analysis.py @@ -1,12 +1,11 @@ -from oasislmf.platform_api.client import APIClient -from oasis_data_manager.errors import OasisException -import time import os import datetime import argparse import logging from requests import HTTPError +from utils import initialise_client + def main(): parser = argparse.ArgumentParser(prog='analysis-prune', @@ -18,11 +17,15 @@ def main(): parser.add_argument('-d', '--days', help='Number of days of history to preserve (default 7).', default=7, type=int) - parser.add_argument('--user', help='Username for oasislmf client.', - default='admin') + parser.add_argument('--user', help='Username (simple auth). Default: OASIS_SERVICE_USERNAME_OR_ID, ' + 'then .streamlit/secrets.toml.', default=None) + + parser.add_argument('--password', help='Password (simple auth). Prefer OASIS_SERVICE_PASSWORD_OR_SECRET, ' + 'which keeps it out of the process list.', default=None) - parser.add_argument('--password', help='Password for oasislmf client.', - default='password') + parser.add_argument('--keep-tag', action='append', default=[], + help='Never delete analyses whose name ends with this tag, e.g. "[showcase]". ' + 'Can be given more than once.') parser.add_argument('--log', help='Set logging level.', default='WARNING') parser.add_argument('--retry_time', help='Time between retries (s).', default=60, type=int) @@ -36,26 +39,22 @@ def main(): week_ago = datetime.datetime.today() - datetime.timedelta(days=args.days) week_ago = week_ago.strftime('%Y-%m-%d') - print('Pruning analyses created before: ', week_ago) - - api_url = os.environ.get('API_URL', 'http://localhost:8000') - retries = 0 - while True: - if retries > args.n_retries: - logger.error(f'Failed to create client. No. of retries: {retries}') - print('Client intialisation failed.') - return - try: - client = APIClient(username=args.user, - password=args.password, - api_url=api_url) - break - except OasisException: - logger.debug(f'Client initialisation failed. Attempt {retries}/{args.n_retries}') - retries += 1 - time.sleep(args.retry_time) + print('Pruning analyses created before: ', week_ago, flush=True) + + # Same service-account login as the other scripts (env vars, then secrets.toml) + if args.user: + os.environ['OASIS_SERVICE_USERNAME_OR_ID'] = args.user + if args.password: + os.environ['OASIS_SERVICE_PASSWORD_OR_SECRET'] = args.password + os.environ.setdefault('API_URL', 'http://localhost:8000') + client = initialise_client(max_retries=args.n_retries + 1, retry_interval=args.retry_time) + if client is None: + logger.error('Failed to create client.') + print('Client initialisation failed.', flush=True) + return old_analyses = client.analyses.search(metadata={'created__lt': week_ago}).json() + old_analyses = [a for a in old_analyses if not any(a['name'].endswith(t) for t in args.keep_tag)] analysis_ids = [a['id'] for a in old_analyses] confirmed = 'n' diff --git a/scripts/scenarios_setup.sh b/scripts/scenarios_setup.sh new file mode 100755 index 0000000..06a2ea1 --- /dev/null +++ b/scripts/scenarios_setup.sh @@ -0,0 +1,43 @@ +#!/bin/bash +# Load the Scenarios app's data onto the platform: exposure portfolios, +# analysis settings templates and showcase analyses. +# +# Runs as the one-shot `scenarios-setup` service (docker-compose.models.scenarios.yml) +# from the UI image, with /usr/src/app as the working directory. Every step is +# idempotent, so it is safe to run on every deploy. +set -e + +CONFIG=${SCENARIOS_UI_CONFIG:-scenarios/ui-config.json} +MIN_MODELS=${SCENARIOS_MIN_MODELS:-1} + +echo "=== Waiting for $MIN_MODELS scenario models to register ===" +# Workers register their models as they start. Wait for all of them, but carry +# on with whatever has registered if some never do (their scenarios are skipped). +python3 - "$MIN_MODELS" <<'PY' +import sys, time +sys.path.insert(0, 'scripts') +from utils import initialise_client +client = initialise_client(max_retries=30, retry_interval=10) +if client is None: + sys.exit('Could not connect to the API') +expected = int(sys.argv[1]) +for _ in range(60): + models = sorted(m['model_id'] for m in client.models.get().json()) + if len(models) >= expected: + break + time.sleep(10) +print(f'{len(models)} of {expected} models registered: {", ".join(models)}') +if len(models) < expected: + print('WARNING: not all models registered; scenarios without a model are skipped') +PY + +echo "=== Adding exposure portfolios ===" +python3 scripts/add_test_portfolios.py -c scenarios/portfolios.json -r + +echo "=== Adding analysis settings templates ===" +python3 scripts/add_settings_template.py -c scenarios/a_settings.json -r + +echo "=== Starting showcase analyses ===" +python3 scripts/add_showcase_analyses.py -c "$CONFIG" -r + +echo "=== Scenarios setup complete ===" diff --git a/scripts/utils.py b/scripts/utils.py index ad371e0..579c5b0 100644 --- a/scripts/utils.py +++ b/scripts/utils.py @@ -1,4 +1,9 @@ -import streamlit as st +import sys +from pathlib import Path + +# Allow `python scripts/