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 b/.env index dabc5fb..954cf35 100644 --- a/.env +++ b/.env @@ -14,7 +14,7 @@ DOCKER_SOCK=/var/run/docker.sock # Hostname Configuration OASIS_UI_HOSTNAME=ui.oasis.local -OASIS_PROTOCOL=http +OASIS_PROTOCOL=https # Authentication Type API_AUTH_TYPE=keycloak @@ -22,12 +22,12 @@ OASIS_SERVER_ALLOWED_OIDC_AUTH_PROVIDERS=keycloak,authentik # Image Versions SERVER_IMG=coreoasis/api_server -VERS_API=2.5 +VERS_API=2.5.9 WORKER_IMG=coreoasis/model_worker -VERS_WORKER=2.5 +VERS_WORKER=2.5.9 PYTHONUI_IMG=coreoasis/oasispythonui_app VERS_UI=latest -VERS_PIWIND=stable/2.5.x +VERS_PIWIND=2.5.9 # Database Configuration OASIS_SERVER_DB_HOST=server-db diff --git a/.env.authentik b/.env.authentik index 25a7664..3cd4937 100644 --- a/.env.authentik +++ b/.env.authentik @@ -14,7 +14,7 @@ DOCKER_SOCK=/var/run/docker.sock # Hostname Configuration OASIS_UI_HOSTNAME=ui.oasis.local -OASIS_PROTOCOL=http +OASIS_PROTOCOL=https # Authentication Type API_AUTH_TYPE=authentik @@ -22,12 +22,12 @@ OASIS_SERVER_ALLOWED_OIDC_AUTH_PROVIDERS=keycloak,authentik # Image Versions SERVER_IMG=coreoasis/api_server -VERS_API=2.5 +VERS_API=2.5.9 WORKER_IMG=coreoasis/model_worker -VERS_WORKER=2.5 +VERS_WORKER=2.5.9 PYTHONUI_IMG=coreoasis/oasispythonui_app VERS_UI=latest -VERS_PIWIND=stable/2.5.x +VERS_PIWIND=2.5.9 # Database Configuration OASIS_SERVER_DB_HOST=server-db diff --git a/.env.example b/.env.example index 7149797..2cdd575 100644 --- a/.env.example +++ b/.env.example @@ -35,7 +35,7 @@ DOCKER_SOCK=/var/run/docker.sock # - External access URLs OASIS_UI_HOSTNAME=localhost -OASIS_PROTOCOL=http +OASIS_PROTOCOL=https # ============================================================================ # AUTHENTICATION CONFIGURATION @@ -75,16 +75,16 @@ OASIS_SERVICE_CLIENT_SECRET=serviceNotSoSecret # ============================================================================ SERVER_IMG=coreoasis/api_server -VERS_API=2.5 +VERS_API=2.5.9 WORKER_IMG=coreoasis/model_worker -VERS_WORKER=2.5 +VERS_WORKER=2.5.9 PYTHONUI_IMG=coreoasis/oasispythonui_app VERS_UI=latest # PiWind model version -VERS_PIWIND=stable/2.5.x +VERS_PIWIND=2.5.9 # ============================================================================ # DATABASE CONFIGURATION diff --git a/.env.keycloak b/.env.keycloak index dabc5fb..954cf35 100644 --- a/.env.keycloak +++ b/.env.keycloak @@ -14,7 +14,7 @@ DOCKER_SOCK=/var/run/docker.sock # Hostname Configuration OASIS_UI_HOSTNAME=ui.oasis.local -OASIS_PROTOCOL=http +OASIS_PROTOCOL=https # Authentication Type API_AUTH_TYPE=keycloak @@ -22,12 +22,12 @@ OASIS_SERVER_ALLOWED_OIDC_AUTH_PROVIDERS=keycloak,authentik # Image Versions SERVER_IMG=coreoasis/api_server -VERS_API=2.5 +VERS_API=2.5.9 WORKER_IMG=coreoasis/model_worker -VERS_WORKER=2.5 +VERS_WORKER=2.5.9 PYTHONUI_IMG=coreoasis/oasispythonui_app VERS_UI=latest -VERS_PIWIND=stable/2.5.x +VERS_PIWIND=2.5.9 # Database Configuration OASIS_SERVER_DB_HOST=server-db diff --git a/.env.scenarios b/.env.scenarios new file mode 100644 index 0000000..0eec9e8 --- /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 (14 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/.env.simple b/.env.simple index 50d4b45..cc22680 100644 --- a/.env.simple +++ b/.env.simple @@ -14,7 +14,7 @@ DOCKER_SOCK=/var/run/docker.sock # Hostname Configuration OASIS_UI_HOSTNAME=ui.oasis.local -OASIS_PROTOCOL=http +OASIS_PROTOCOL=https # Authentication Type API_AUTH_TYPE=simple @@ -26,12 +26,12 @@ OASIS_ADMIN_PASS=password # Image Versions SERVER_IMG=coreoasis/api_server -VERS_API=2.5 +VERS_API=2.5.9 WORKER_IMG=coreoasis/model_worker -VERS_WORKER=2.5 +VERS_WORKER=2.5.9 PYTHONUI_IMG=coreoasis/oasispythonui_app VERS_UI=latest -VERS_PIWIND=stable/2.5.x +VERS_PIWIND=2.5.9 # Database Configuration OASIS_SERVER_DB_HOST=server-db diff --git a/.github/workflows/code-quality.yml b/.github/workflows/code-quality.yml new file mode 100644 index 0000000..5c5442b --- /dev/null +++ b/.github/workflows/code-quality.yml @@ -0,0 +1,63 @@ +# Code quality and tests, following OasisLMF's code-quality workflow: +# - ruff: pyflakes checks and docstring style (rules in pyproject.toml) +# - PEP8: fails if autopep8 would change any file +# - tests: the pytest suite +# +# To fix formatting locally: +# autopep8 --in-place --recursive --max-line-length 150 --ignore E402 --exclude OasisPiWind . +# ruff check --fix . + +name: Code Quality + +on: + pull_request: + push: + branches: + - main + - stable** + +env: + max_line_length: 150 + python_version: "3.12" + +jobs: + lint: + name: Lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: ${{ env.python_version }} + + - name: Install code quality tools + run: pip install --upgrade autopep8 ruff + + - name: Lint (ruff) + if: ${{ ! cancelled() }} + run: ruff check --output-format full . + + - name: Check PEP8 compliance + if: ${{ ! cancelled() }} + run: | + autopep8 --diff --exit-code --recursive --max-line-length ${{ env.max_line_length }} \ + --ignore E402 --exclude OasisPiWind . + + tests: + name: Tests + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: ${{ env.python_version }} + cache: pip + cache-dependency-path: requirements.txt + + - name: Install dependencies + run: pip install -r requirements.txt pytest + + - name: Run tests + run: python -m pytest -q 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/.gitignore b/.gitignore index 85566a2..4406710 100644 --- a/.gitignore +++ b/.gitignore @@ -183,3 +183,6 @@ cython_debug/ # Generated OIDC configurations oidc/*/generated/ + +# Locally generated TLS certificates +certs/ diff --git a/README.md b/README.md index e2de835..5723136 100644 --- a/README.md +++ b/README.md @@ -5,11 +5,21 @@ A web-based UI utilising [Streamlit](https://github.com/streamlit/streamlit) to manage exposure data and run modeling workflows on the OasisLMF platform. -The current version of the UI contains the following pages: +The standard UI (`ui-config.json`) has three pages: -- `/analyses` - View and create portfolios and analyses. -- `/dashboard` - View the output of completed analyses. -- `/simplified` - Simplified UI which allows for the running of analyses using previously loaded portfolios & models. +- `/analyses` - Browse analyses and their results, and create, configure and run new ones. +- `/portfolios` - Create portfolios, manage their OED files and explore their exposure. +- `/models` - Browse the models registered on the platform and their settings. + +Analysis settings are edited with controls generated from the ODS-tools +analysis and model settings schemas, and validated before they are saved. + +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. ## Prerequisites @@ -84,14 +94,32 @@ To tear everything down (removes containers and volumes): ## Access Points -All services are reachable on port 80 via Traefik after a successful install: +All services are reachable via Traefik after a successful install: | Service | URL | |---------|-----| -| UI | `http://ui.oasis.local/` | -| API | `http://ui.oasis.local/api/` | -| Keycloak Admin | `http://ui.oasis.local/auth/` | -| Authentik Admin | `http://ui.oasis.local/authentik/` | +| UI | `https://ui.oasis.local/` | +| API | `https://ui.oasis.local/api/` | +| Keycloak Admin | `https://ui.oasis.local/auth/` | +| Authentik Admin | `https://ui.oasis.local/authentik/` | + +### HTTPS + +With `OASIS_PROTOCOL=https` (the default) browsers are redirected from `http://` +to `https://` for the UI and login pages. The `/api` route stays available +over plain HTTP for scripts and API clients. + +The installer runs `scripts/generate-certs.sh`, which writes `certs/ui.crt` +and `certs/ui.key` for `OASIS_UI_HOSTNAME`: + +- If [mkcert](https://github.com/FiloSottile/mkcert) is installed, its locally + trusted CA is used and browsers accept the certificate without a warning + (run `mkcert -install` once). +- Otherwise a local CA is created at `certs/oasis-local-ca.crt`. Import it into + your browser or OS trust store to remove the certificate warning; the script + prints the commands. +- To use your own certificate, put it at `certs/ui.crt` / `certs/ui.key` + before running the installer. ## Switching Between Auth Types @@ -141,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: @@ -149,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` @@ -194,9 +222,9 @@ deploy, including redeploys over an existing installation. |----------|-------------|---------| | `API_AUTH_TYPE` | Auth mode: `simple`, `keycloak`, or `authentik` | `authentik` | | `OASIS_UI_HOSTNAME` | Hostname the UI and proxy listen on | `ui.oasis.local` | -| `OASIS_PROTOCOL` | `http` or `https` | `http` | -| `VERS_API` | Oasis server image tag | `2.5` | -| `VERS_WORKER` | Oasis worker image tag | `2.5` | +| `OASIS_PROTOCOL` | `http` or `https` | `https` | +| `VERS_API` | Oasis server image tag | `2.5.9` | +| `VERS_WORKER` | Oasis worker image tag | `2.5.9` | | `VERS_UI` | Python UI image tag | `latest` | See the `.env.*` templates for the full list with inline comments. @@ -237,6 +265,24 @@ through the Keycloak admin console at `/auth/` (`keycloak` / `password`). Edit `oidc/authentik/users.yaml` and re-run `./install.sh`, or add users through the Authentik admin console at `/authentik/` (`akadmin` / `password`). +## Development + +Pull requests run the **Code Quality** workflow (`.github/workflows/code-quality.yml`), +which mirrors OasisLMF's checks: + +- `ruff check .` - pyflakes checks and docstring style (rules in `pyproject.toml`) +- `autopep8 --diff --exit-code` - PEP8 formatting, 150 character lines +- `pytest` - the test suite + +To run them locally: + +```bash +pip install -r requirements.txt pytest ruff autopep8 +python -m pytest -q +ruff check --fix . +autopep8 --in-place --recursive --max-line-length 150 --ignore E402 --exclude OasisPiWind . +``` + ## Troubleshooting Usually first thing to try before anything is clearing browser cache/cookies for the hostname. @@ -270,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://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 public site is at https://ui.oasislmf-scenarios.com/ -Default scenarios in the tool are processed/hosted at https://github.com/OasisLMF/Scenarios +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.authentik.yml b/docker-compose.authentik.yml index fa93b7d..10e8ac0 100644 --- a/docker-compose.authentik.yml +++ b/docker-compose.authentik.yml @@ -35,6 +35,7 @@ services: - "traefik.http.routers.authentik.rule=PathPrefix(`/authentik`)" - "traefik.http.services.authentik.loadbalancer.server.port=9000" - "traefik.http.routers.authentik.entrypoints=web" + - "traefik.http.routers.authentik.middlewares=${OASIS_WEB_ENTRY_MIDDLEWARE:-http-passthrough@file}" - "traefik.http.routers.authentik-secure.rule=PathPrefix(`/authentik`)" - "traefik.http.routers.authentik-secure.entrypoints=websecure" - "traefik.http.routers.authentik-secure.tls=true" diff --git a/docker-compose.keycloak.yml b/docker-compose.keycloak.yml index 9a4f43b..2a39883 100644 --- a/docker-compose.keycloak.yml +++ b/docker-compose.keycloak.yml @@ -31,6 +31,12 @@ services: labels: - "traefik.enable=true" - "traefik.http.routers.keycloak.rule=PathPrefix(`/auth`)" + - "traefik.http.routers.keycloak.entrypoints=web" + - "traefik.http.routers.keycloak.middlewares=${OASIS_WEB_ENTRY_MIDDLEWARE:-http-passthrough@file}" + - "traefik.http.routers.keycloak-secure.rule=PathPrefix(`/auth`)" + - "traefik.http.routers.keycloak-secure.entrypoints=websecure" + - "traefik.http.routers.keycloak-secure.tls=true" + - "traefik.http.routers.keycloak-secure.service=keycloak" - "traefik.http.services.keycloak.loadbalancer.server.port=8080" environment: # Database configuration diff --git a/docker-compose.models.piwind.yml b/docker-compose.models.piwind.yml index 2ee738c..4c6c343 100644 --- a/docker-compose.models.piwind.yml +++ b/docker-compose.models.piwind.yml @@ -86,6 +86,8 @@ services: OASIS_MODEL_ID: PiWind OASIS_MODEL_VERSION_ID: v2 OASIS_RUN_MODE: v2 + # Where the worker reports events completed, shown as run progress in the UI + OASIS_ANALYSIS_STATUS_URL: http://server:8000/analysis-status/ OASIS_OASISLMF_VERSION: ${OASIS_OASISLMF_VERSION} OASIS_ODS_VERSION: ${OASIS_ODS_VERSION} OASIS_ODM_VERSION: ${OASIS_ODM_VERSION} diff --git a/docker-compose.models.scenarios.yml b/docker-compose.models.scenarios.yml index 379fde2..4cf8da2 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 @@ -15,6 +16,13 @@ x-shared-env: &worker-env INGRESS_EXTERNAL_HOST: ${OASIS_UI_HOSTNAME:-localhost} INGRESS_INTERNAL_HOST: traefik + # 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 14 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} @@ -60,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 @@ -70,38 +81,42 @@ x-worker: &worker services: - piwind-worker: + maeq-worker: <<: *worker environment: <<: *worker-env - OASIS_MODEL_SUPPLIER_ID: OasisLMF - OASIS_MODEL_ID: PiWind + OASIS_MODEL_SUPPLIER_ID: Impact Forecasting + OASIS_MODEL_ID: MAEQ OASIS_MODEL_VERSION_ID: 'v2' OASIS_RUN_MODE: v2 volumes: - - ./OasisPiWind/:/home/worker/model + - ${SCENARIOS_PATH}/ImpactForecasting/MAEQ/1.0.0/:/home/worker/model - filestore-data:/shared-fs:rw - maeq-worker: + euws-worker: <<: *worker environment: <<: *worker-env OASIS_MODEL_SUPPLIER_ID: Impact Forecasting - OASIS_MODEL_ID: MAEQ + OASIS_MODEL_ID: EUWS OASIS_MODEL_VERSION_ID: 'v2' OASIS_RUN_MODE: v2 volumes: - - ${SCENARIOS_PATH}/ImpactForecasting/MAEQ/1.0.0/:/home/worker/model + - ${SCENARIOS_PATH}/ImpactForecasting/EUWS/1.0.0/:/home/worker/model - filestore-data:/shared-fs:rw - euws-worker: + # Storm Domingos: the EUWS model data with its other event set, using the + # Domingos config and model settings from the same folder + euws-domingos-worker: <<: *worker environment: <<: *worker-env OASIS_MODEL_SUPPLIER_ID: Impact Forecasting - OASIS_MODEL_ID: EUWS + OASIS_MODEL_ID: EUWS-Domingos OASIS_MODEL_VERSION_ID: 'v2' OASIS_RUN_MODE: v2 + OASIS_OASISLMF_CONFIG: /home/worker/model/oasislmf_domingos.json + OASIS_MODEL_SETTINGS_FILE: /home/worker/model/meta-data/model_settings_domingos.json volumes: - ${SCENARIOS_PATH}/ImpactForecasting/EUWS/1.0.0/:/home/worker/model - filestore-data:/shared-fs:rw @@ -247,3 +262,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=14 + 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 0d58bbc..8e9f489 100644 --- a/docker-compose.ui.yml +++ b/docker-compose.ui.yml @@ -12,6 +12,7 @@ services: - "traefik.http.routers.pythonui.rule=PathPrefix(`/`)" - "traefik.http.routers.pythonui.entrypoints=web" - "traefik.http.routers.pythonui.priority=1" + - "traefik.http.routers.pythonui.middlewares=${OASIS_WEB_ENTRY_MIDDLEWARE:-http-passthrough@file}" # HTTPS router (OIDC callback redirects to /?session_token=... on HTTPS) - "traefik.http.routers.pythonui-secure.rule=PathPrefix(`/`)" - "traefik.http.routers.pythonui-secure.entrypoints=websecure" @@ -24,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/docker-compose.yml b/docker-compose.yml index f411c5d..b7e030f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -73,15 +73,21 @@ services: - "--providers.docker=true" - "--providers.docker.exposedbydefault=false" - "--entrypoints.web.address=:80" - - "--entrypoints.websecure.address=:8443" + # HTTPS on 443 inside the container too: the server reaches the IdP at + # https:/// remapped to traefik:443 (INGRESS_INTERNAL_HOST) + - "--entrypoints.websecure.address=:443" + - "--providers.file.directory=/etc/traefik/dynamic" + - "--providers.file.watch=true" - "--ping=true" - "--api.insecure=true" ports: - "${OASIS_HTTP_PORT-80}:80" - - "${OASIS_HTTPS_PORT-443}:8443" + - "${OASIS_HTTPS_PORT-443}:443" - "${TRAEFIK_DASHBOARD_PORT-8090}:8080" volumes: - ${DOCKER_SOCK:-/var/run/docker.sock}:/var/run/docker.sock:ro + - ./traefik/dynamic:/etc/traefik/dynamic:ro + - ./certs:/certs:ro healthcheck: test: ["CMD", "traefik", "healthcheck", "--ping"] interval: 10s @@ -124,7 +130,7 @@ services: channel-layer: condition: service_started healthcheck: - test: ["CMD", "curl", "--fail", "http://localhost:8000/healthcheck/"] + test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/healthcheck/')"] interval: 30s timeout: 10s retries: 10 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 b1f5384..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 @@ -151,6 +156,21 @@ echo "" # Set service account credentials based on auth type # ============================================================================ +echo "--- Configuring HTTPS ---" +cert_fingerprint() { cat "$SCRIPT_DIR/certs/ui.crt" 2>/dev/null | sha256sum; } +CERT_BEFORE="$(cert_fingerprint)" +bash "$SCRIPT_DIR/scripts/generate-certs.sh" +# Traefik only reloads certificates when its config changes, so restart it after deploy if needed +[ "$(cert_fingerprint)" != "$CERT_BEFORE" ] && CERT_CHANGED=true || CERT_CHANGED=false +if [ "$OASIS_PROTOCOL" = "https" ]; then + export OASIS_WEB_ENTRY_MIDDLEWARE="https-redirect@file" + echo " -> Browsers using http:// are redirected to https://" +else + export OASIS_WEB_ENTRY_MIDDLEWARE="http-passthrough@file" + echo " -> Serving over http:// (https:// is also available)" +fi +echo "" + echo "--- Configuring service credentials ---" if [ "$API_AUTH_TYPE" = "simple" ]; then @@ -214,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 "" @@ -236,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 @@ -286,6 +327,11 @@ echo "--- Deploying services ---" # Start all services docker compose $COMPOSE_FILES up -d +if [ "$CERT_CHANGED" = true ]; then + echo " -> Certificate changed: restarting traefik to load it" + docker compose $COMPOSE_FILES restart traefik +fi + echo "" # ============================================================================ @@ -296,7 +342,16 @@ echo "--- Waiting for services to be healthy ---" # Wait for core services echo " -> Waiting for server..." -docker compose $COMPOSE_FILES exec -T server sh -c 'for i in $(seq 1 60); do curl -sf http://localhost:8000/healthcheck/ > /dev/null 2>&1 && exit 0; sleep 5; done; exit 1' || { +# The api_server image (2.5.9+) has no shell or curl, so poll from the host using its python3. +server_ready() { + for i in $(seq 1 60); do + docker compose $COMPOSE_FILES exec -T server python3 -c \ + "import urllib.request; urllib.request.urlopen('http://localhost:8000/healthcheck/')" > /dev/null 2>&1 && return 0 + sleep 5 + done + return 1 +} +server_ready || { echo " WARNING: Server health check timed out. Check logs with: docker compose $COMPOSE_FILES logs server" } @@ -325,16 +380,20 @@ echo "" echo " Auth type: $API_AUTH_TYPE" echo " Hostname: $OASIS_UI_HOSTNAME" echo "" -echo " Access Points (via Traefik on port 80):" -echo " UI: http://${OASIS_UI_HOSTNAME}/" -echo " API: http://${OASIS_UI_HOSTNAME}/api/" -echo " API Docs: http://${OASIS_UI_HOSTNAME}/api/swagger/" +echo " Access Points (via Traefik):" +echo " UI: ${OASIS_PROTOCOL}://${OASIS_UI_HOSTNAME}/" +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: http://${OASIS_UI_HOSTNAME}/auth/admin/" + echo " Keycloak: ${OASIS_PROTOCOL}://${OASIS_UI_HOSTNAME}/auth/admin/" echo " (${KEYCLOAK_ADMIN_USER} / ${KEYCLOAK_ADMIN_PASSWORD})" elif [ "$API_AUTH_TYPE" = "authentik" ]; then - echo " Authentik: http://${OASIS_UI_HOSTNAME}/authentik/" + echo " Authentik: ${OASIS_PROTOCOL}://${OASIS_UI_HOSTNAME}/authentik/" echo " (akadmin / ${AUTHENTIK_BOOTSTRAP_PASSWORD})" fi diff --git a/modules/authorisation.py b/modules/authorisation.py index 19d43a6..8140f15 100644 --- a/modules/authorisation.py +++ b/modules/authorisation.py @@ -1,12 +1,12 @@ -''' -Module to handle authorisation. -''' +"""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__) @@ -42,8 +42,9 @@ def logout(): def handle_login(skip_login=False): """Handle the redirect behaviour for login or initalise if login skipped. - Parameters: - skip_login (bool): If True, login user + Args: + skip_login (bool): If True, log in with the service credentials instead of + redirecting to the login page. """ if "client_interface" in st.session_state: return @@ -51,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.") @@ -71,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/client.py b/modules/client.py index cbbae89..d8b1d50 100644 --- a/modules/client.py +++ b/modules/client.py @@ -1,3 +1,7 @@ +import io +import tarfile +import zipfile + import pandas as pd from oasislmf.platform_api.client import APIClient import tempfile @@ -9,10 +13,23 @@ logger = get_session_logger() +def tar_to_zip(tar_bytes): + """Repack a (gzipped) tar archive as a zip archive, keeping paths.""" + out = io.BytesIO() + with tarfile.open(fileobj=io.BytesIO(tar_bytes), mode='r:*') as tar, \ + zipfile.ZipFile(out, 'w', compression=zipfile.ZIP_DEFLATED) as zf: + for member in tar.getmembers(): + if not member.isfile(): + continue + name = member.name.lstrip('./') + if not name or '..' in name.split('/'): + continue # never write paths that escape the archive root + zf.writestr(name, tar.extractfile(member).read()) + return out.getvalue() + + class JsonEndpointInterface: - ''' - Abstract class for handling a endpoint of the Oasis APIClient restricted to json output. - ''' + """Abstract class for handling a endpoint of the Oasis APIClient restricted to json output.""" def __init__(self, client, endpoint_name='portfolios'): self.endpoint = getattr(client, endpoint_name) @@ -22,9 +39,7 @@ def get(self, ID=None): class SettingsTemplateInterface: - ''' - Class for handling interactions with the SettingsTemplateEndpoint of the Oasis APIClient - ''' + """Class for handling interactions with the SettingsTemplateEndpoint of the Oasis APIClient""" def __init__(self, client): self.endpoint = getattr(client, 'setting_templates', None) @@ -41,10 +56,9 @@ def get_contents(self, model_pk, ID): class EndpointInterface: - ''' - Abstract class for handling a endpoint of the Oasis APIClient. Includes + """Abstract class for handling a endpoint of the Oasis APIClient. Includes handling both file and json endpoints. - ''' + """ def __init__(self, client, endpoint_name='portfolios'): self.endpoint = getattr(client, endpoint_name) @@ -73,9 +87,7 @@ def get_file(self, ID, filename, df=False): class ModelsEndpointInterface(EndpointInterface): - ''' - Interface for models endpoint of the Oasis APIClient. - ''' + """Interface for models endpoint of the Oasis APIClient.""" def __init__(self, client): super().__init__(client, endpoint_name='models') @@ -84,17 +96,14 @@ def __init__(self, client): class AnalysesEndpointInterface(EndpointInterface): - ''' - Interface for analyses endpoint of the Oasis APIClient. - ''' + """Interface for analyses endpoint of the Oasis APIClient.""" def __init__(self, client): super().__init__(client, endpoint_name='analyses') self.settings = JsonEndpointInterface(self.endpoint, endpoint_name='settings') def get_traceback(self, ID, error_type='input_generation'): - ''' - Get the contents of the traceback file if it exists + """Get the contents of the traceback file if it exists Parameters ---------- @@ -106,7 +115,7 @@ def get_traceback(self, ID, error_type='input_generation'): Returns ------- `str` contents of traceback file or `None` if the file does not exist. - ''' + """ traceback_endpoint = error_type + '_traceback_file' try: @@ -115,11 +124,23 @@ def get_traceback(self, ID, error_type='input_generation'): logger.error(e) return None + def cancel(self, ID): + return self.endpoint.cancel(ID) + + def sub_tasks(self, ID): + """Sub-tasks of an analysis run (name, status, ...); [] if unavailable.""" + try: + return self.endpoint.sub_task_list(ID).json() or [] + except (HTTPError, ValueError) as e: + logger.warning(f'No sub-task list for analysis {ID}: {e}') + return [] + + def delete(self, ID): + return self.endpoint.delete(ID) + class PortfoliosEndpointInterface(EndpointInterface): - ''' - Interface for portfolios endpoint of the Oasis APIClient. - ''' + """Interface for portfolios endpoint of the Oasis APIClient.""" def __init__(self, client): super().__init__(client, "portfolios") @@ -137,48 +158,76 @@ def get_reinsurance_info_file(self, ID, df=False): def get_reinsurance_scope_file(self, ID, df=False): return self.get_file(ID, "reinsurance_scope_file", df) + FILE_TYPES = { + 'location_file': 'Location', + 'accounts_file': 'Accounts', + 'reinsurance_info_file': 'Reinsurance info', + 'reinsurance_scope_file': 'Reinsurance scope', + } + + def upload_file(self, ID, file_type, file_bytes, filename): + """Attach (or replace) one of the portfolio's OED files.""" + assert file_type in self.FILE_TYPES, f'Unknown portfolio file type {file_type}' + content_type = 'application/octet-stream' if filename.endswith('.parquet') else 'text/csv' + return getattr(self.endpoint, file_type).upload_byte(ID, file_bytes, filename, content_type) + + def delete_file(self, ID, file_type): + assert file_type in self.FILE_TYPES, f'Unknown portfolio file type {file_type}' + return getattr(self.endpoint, file_type).delete(ID) + + def rename(self, ID, name): + return self.endpoint.update(ID, name) + + def delete(self, ID): + return self.endpoint.delete(ID) + def create(self, name, location_file=None, accounts_file=None, reinsurance_info_file=None, reinsurance_scope_file=None): - ''' - Create a portfolio using the `UploadedFile` objects created when using the `st.file_uploader`. + """Create a portfolio using the `UploadedFile` objects created when using the `st.file_uploader`. Parameters ---------- name : str Name for the assigned portfolio location_file : UploadedFile + OED location file. accounts_file : UploadedFile + OED accounts file. + reinsurance_info_file : UploadedFile + OED reinsurance info file. reinsurance_scope_file : UploadedFile - reinsurance_scope_file : UploadedFile - ''' + OED reinsurance scope file. + """ - def prepare_upload_f(fname, fbytes): - if fbytes is None: + def prepare_upload_f(fname, upload): + if upload is None: return None - return {'name': fname, 'bytes': fbytes} + # Keep the uploaded file's own name (and so its extension) where available + name = getattr(upload, 'name', None) or fname + data = upload.getvalue() if hasattr(upload, 'getvalue') else upload + return {'name': name, 'bytes': data} location_f = prepare_upload_f('location_file', location_file) accounts_f = prepare_upload_f('accounts_file', accounts_file) ri_info_f = prepare_upload_f('reinsurance_info_file', reinsurance_info_file) ri_scope_f = prepare_upload_f('reinsurance_scope_file', reinsurance_scope_file) - self.client.upload_inputs(portfolio_name=name, - location_fp=location_f, - accounts_fp=accounts_f, - ri_info_fp=ri_info_f, - ri_scope_fp=ri_scope_f) + return self.client.upload_inputs(portfolio_name=name, + location_fp=location_f, + accounts_fp=accounts_f, + ri_info_fp=ri_info_f, + ri_scope_fp=ri_scope_f) class ClientInterface: - ''' - Wrapper interface around the Oasis APIClient. + """Wrapper interface around the Oasis APIClient. Attributes: client: Instance of the `APIClient` from `oasislmf.platform_api.client`. portfolios: Interface for managing portfolios. analyses: Interface for managing analyses. models: Interface for managing models. - ''' + """ def __init__(self, client=None, auth_type=None, username=None, password=None, access_token=None, refresh_token=None, client_id=None, client_secret=None): api_url = os.environ.get('API_URL', 'http://localhost:8000') @@ -205,8 +254,7 @@ def create_analysis(self, portfolio_id, model_id, analysis_name): return resp def create_and_generate_analysis(self, portfolio_id, model_id, analysis_name): - '''Create the analysis and run input generation. - ''' + """Create the analysis and run input generation.""" resp = self.create_analysis(portfolio_id, model_id, analysis_name) resp = self.generate(resp["id"]) @@ -216,23 +264,23 @@ def upload_settings(self, analysis_id, analysis_settings): self.client.upload_settings(analysis_id, analysis_settings) def run(self, analysis_id): - '''Run the analysis specified by `analysis_id`. - ''' + """Run the analysis specified by `analysis_id`.""" return self.client.analyses.run(analysis_id) def generate(self, analysis_id): - '''Run input generation of `analysis_id`. - ''' + """Run input generation of `analysis_id`.""" return self.client.analyses.generate(analysis_id) def generate_and_run(self, analysis_id): - '''Generate input files and run the analysis specified by `analysis_id`. - ''' + """Generate input files and run the analysis specified by `analysis_id`.""" return self.client.analyses.generate_and_run(analysis_id) + def download_output_zip(self, analysis_id): + """Analysis outputs as zip bytes (the API serves a .tar.gz).""" + return tar_to_zip(self.download_output(analysis_id)) + def download_output(self, analysis_id): - '''Retrieve the output files from a given analysis specified by `analysis_id`. - ''' + """Retrieve the output files from a given analysis specified by `analysis_id`.""" with tempfile.TemporaryDirectory() as tmpdir: self.client.download_output(analysis_id, download_path=tmpdir) fname = os.listdir(tmpdir)[0] diff --git a/modules/config.py b/modules/config.py index e8212f0..3066419 100644 --- a/modules/config.py +++ b/modules/config.py @@ -6,6 +6,7 @@ logger = logging.getLogger(__name__) OASIS_UI_CONFIG = "ui-config.json" + class UIConfig(): """Class to hold config information for the UI. Loads the infomation from OASIS_UI_CONFIG environment variabel (defaults to `ui-config.json`). @@ -17,6 +18,7 @@ class UIConfig(): of exposure sets the model should correspond to. skip_login (bool): If True skip the login redirection. """ + def __init__(self): config_path = os.getenv("OASIS_UI_CONFIG", OASIS_UI_CONFIG) @@ -32,13 +34,16 @@ 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(): - '''Retrieve ui config. + """Retrieve ui config. First checks `session_state` and if not present loads from file. - ''' + """ if 'ui-config' in st.session_state: logger.info("Loading ui-config from session_state.") return st.session_state['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/nav.py b/modules/nav.py index 1c5468f..d75f490 100644 --- a/modules/nav.py +++ b/modules/nav.py @@ -10,7 +10,8 @@ def SidebarNav(no_client=False): with st.sidebar: if "client_interface" in st.session_state or no_client: for page_config in ui_config.pages: - st.page_link(page_config['path'], label=page_config['label']) + st.page_link(page_config['path'], label=page_config['label'], + icon=page_config.get('icon')) if "client_interface" in st.session_state: if get_auth_type() != 'simple': id_token = st.session_state.get("id_token", "") @@ -22,6 +23,13 @@ def SidebarNav(no_client=False): logout() else: st.page_link('app.py', label="Login") - # Add logo + # Add logo. Streamlit's largest logo size (2rem) leaves the wide Oasis + # wordmark cramped, so enlarge it in the sidebar and collapsed header. st.logo(image="images/oasis_logo_bg.png", size="large") + st.html('''''') 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 33a1ada..0000000 --- a/modules/rerun.py +++ /dev/null @@ -1,74 +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..e5c45f5 --- /dev/null +++ b/modules/scenarios.py @@ -0,0 +1,193 @@ +"""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 vulnerability_info(model_settings): + """The vulnerability functions a scenario uses, from its model settings. + + Scenarios describe them in `data_settings.vulnerability`: `source`, `description` + and optionally `url`. Returns None when a scenario doesn't. + """ + info = ((model_settings or {}).get('data_settings') or {}).get('vulnerability') + if not isinstance(info, dict) or not info.get('source'): + return None + return {key: info[key] for key in ('source', 'description', 'url') if info.get(key)} + + +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 '', + 'vulnerability': vulnerability_info(settings), + }) + return sorted(catalogue, key=lambda e: e['title'].lower()) diff --git a/modules/schemas.py b/modules/schemas.py new file mode 100644 index 0000000..b43ebfb --- /dev/null +++ b/modules/schemas.py @@ -0,0 +1,125 @@ +"""Access to the ODS-tools analysis / model settings JSON schemas. + +The schemas are the source of truth for labels, descriptions, defaults and +the available output options, so the UI follows ods_tools upgrades rather +than hard-coding them. +""" +import json +from functools import lru_cache +from pathlib import Path + +import ods_tools +from ods_tools.oed.settings import AnalysisSettingHandler + +SCHEMA_DIR = Path(ods_tools.__file__).parent / 'data' + +PERSPECTIVES = ['gul', 'il', 'ri', 'rl'] +PERSPECTIVE_LABELS = { + 'gul': 'Ground up loss (GUL)', + 'il': 'Insured loss (IL)', + 'ri': 'Net of reinsurance (RI)', + 'rl': 'Ceded to reinsurance (RL)', +} + +# Model settings keys that select one option from a list of `{id, desc}` options +CATEGORICAL_MODEL_SETTINGS = [ + 'event_set', + 'event_occurrence_id', + 'footprint_set', + 'vulnerability_set', + 'pla_loss_factors_set', +] + +# Model settings keys holding lists of user-settable parameters, mapped to the +# kind of control used to edit them. +PARAMETER_TYPES = { + 'string_parameters': 'string', + 'list_parameters': 'list', + 'dictionary_parameters': 'dict', + 'boolean_parameters': 'bool', + 'float_parameters': 'float', + 'numeric_parameters': 'number', + 'integer_parameters': 'int', + 'dropdown_parameters': 'dropdown', +} + +# OED fields that can always be used to group outputs, in addition to any the +# model declares in `data_settings`. +DEFAULT_GROUP_FIELDS = ['PortNumber', 'AccNumber', 'LocNumber', 'CountryCode', 'LocPeril'] + + +@lru_cache +def analysis_settings_schema(): + with open(SCHEMA_DIR / 'analysis_settings_schema.json') as f: + return json.load(f) + + +@lru_cache +def model_settings_schema(): + with open(SCHEMA_DIR / 'model_settings_schema.json') as f: + return json.load(f) + + +def analysis_property(key): + """Schema entry for a top-level analysis settings key (`{}` if unknown).""" + return analysis_settings_schema()['properties'].get(key, {}) + + +def model_settings_property(key): + """Schema entry for a key under the model settings `model_settings` section.""" + props = model_settings_schema()['properties']['model_settings'].get('properties', {}) + return props.get(key, {}) + + +def model_property(key): + """Schema entry for a top-level model settings key.""" + return model_settings_schema()['properties'].get(key, {}) + + +def title(schema_entry, fallback): + return schema_entry.get('title') or fallback + + +def ord_output_options(): + """Boolean ORD output flags from the schema as `{key: (title, description)}`. + + Excludes the non-table flags (`parquet_format`, `alct_confidence`, + `return_period_file`), which are handled separately. + """ + props = (analysis_settings_schema()['definitions']['output_summaries'] + ['items']['properties']['ord_output']['properties']) + skip = {'parquet_format', 'alct_confidence', 'return_period_file'} + return {k: (v.get('title', k), v.get('description', '')) + for k, v in props.items() + if v.get('type') == 'boolean' and k not in skip} + + +# Groupings of the ORD output flags for presentation +ORD_OUTPUT_GROUPS = { + 'Event loss tables (ELT)': ['elt_sample', 'elt_quantile', 'elt_moment'], + 'Period loss tables (PLT)': ['plt_sample', 'plt_quantile', 'plt_moment'], + 'Average loss tables (ALT)': ['alt_period', 'alt_meanonly', 'alct_convergence'], + 'Exceedance probability tables (EPT)': [ + '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', + ], + 'Per-sample EPT (PSEPT)': ['psept_aep', 'psept_oep'], +} + +# A sensible starting set of outputs for a new summary level +DEFAULT_ORD_OUTPUTS = ['elt_moment', 'alt_meanonly', 'ept_full_uncertainty_aep', 'ept_full_uncertainty_oep'] + + +def validate_analysis_settings(settings): + """Validate analysis settings against the ODS analysis settings schema. + + The model-derived schema (`AnalysisSettingHandler.make(model_setting_json=...)`) + isn't used: in ods_tools 5.0.x it rejects the event/footprint set selectors + whenever a model defines parameters, and its dropdown `oneOf` never + validates. Model options are instead constrained by the editor's controls. + + Returns: + (bool, dict): validity and `{field: [messages]}`. + """ + return AnalysisSettingHandler.make().validate(settings, raise_error=False) diff --git a/modules/settings.py b/modules/settings.py index cce1e6c..7349012 100644 --- a/modules/settings.py +++ b/modules/settings.py @@ -1,6 +1,7 @@ from pathlib import Path import re + def get_analyses_settings(defaults_path=None, model_id=None, model_name_id=None, supplier_id=None): if defaults_path is None: 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/ui.py b/modules/ui.py new file mode 100644 index 0000000..9c08ed3 --- /dev/null +++ b/modules/ui.py @@ -0,0 +1,64 @@ +"""Shared page scaffolding and feedback helpers for the standard UI pages.""" +import json +import logging + +import streamlit as st +from requests.exceptions import HTTPError + +from modules.authorisation import handle_login, validate_page +from modules.config import retrieve_ui_config +from modules.nav import SidebarNav + +logger = logging.getLogger(__name__) + +_FLASH_KEY = '_flash_messages' + + +def page_setup(label, title=None): + """Configure, authorise and add navigation to a page. + + Args: + label: page label as configured in `ui-config.json`. + title: page heading (defaults to `label`). + + Returns: + ClientInterface for the logged-in session. + """ + ui_config = retrieve_ui_config() + st.set_page_config(page_title=f'{label} · Oasis', layout='wide') + validate_page(label) + handle_login(ui_config.skip_login) + SidebarNav() + show_flash() + st.title(title or label) + return st.session_state['client_interface'] + + +def flash(message, icon='✅'): + """Queue a toast to show after the next rerun (st.toast alone is lost on rerun).""" + st.session_state.setdefault(_FLASH_KEY, []).append((message, icon)) + + +def show_flash(): + for message, icon in st.session_state.pop(_FLASH_KEY, []): + st.toast(message, icon=icon) + + +def api_error_message(error): + """Human readable message for an API error, including the server's reason.""" + if isinstance(error, HTTPError) and error.response is not None: + try: + detail = error.response.json() + if isinstance(detail, dict): + detail = '; '.join(f'{k}: {v}' for k, v in detail.items()) + elif isinstance(detail, list): + detail = '; '.join(str(d) for d in detail) + except (ValueError, json.JSONDecodeError): + detail = error.response.text[:500] + return f'{error.response.status_code} {error.response.reason}: {detail}' + return str(error) + + +def show_api_error(action, error): + logger.error(f'{action} failed: {error}') + st.error(f'{action} failed. {api_error_message(error)}') diff --git a/modules/validation.py b/modules/validation.py index a2e41d7..20f4b33 100644 --- a/modules/validation.py +++ b/modules/validation.py @@ -3,21 +3,25 @@ def validate_not_none(param, paramName='parameter'): return False, f'{paramName} is not set.' return True, "" + def validate_name(name, paramName="Name"): if not name or len(name) == 0: return False, f"{paramName} is required." return True, "" + def validate_key_vals(df, key, vals): if df is not None and df[key] in vals: return True, "" return False, f"{key} has incorrect value." + def validate_key_is_not_null(df, col): if df[col] is None: return False, f"{col} is None." return True, "" + def process_validations(validations): valid = True msg = '' @@ -50,7 +54,7 @@ def set_message(self, message): return self.message def validate(self, *args, **kwargs): - self.valid = self.validation_func(*args, **kwargs) + self.valid = self.validation_func(*args, **kwargs) if not self.valid: raise ValidationError(self.message) @@ -127,6 +131,7 @@ def __init__(self, pname="Parameter"): def validation_func(map, key, value_list): return map[key] in value_list + class LenValidation(Validation): def __init__(self, pname="Parameter"): self.message = f'{pname} is incorrect size.' @@ -179,13 +184,13 @@ def get_message(self): class ValidationError(Exception): - """ - Custom exception class for validation errors. + """Custom exception class for validation errors. Attributes ---------- message: explanation of error """ + def __init__(self, message): self.message = message super().__init__(self.message) diff --git a/modules/visualisation.py b/modules/visualisation.py index af42f61..48d437f 100644 --- a/modules/visualisation.py +++ b/modules/visualisation.py @@ -1,7 +1,5 @@ from oasis_data_manager.errors import OasisException -import plotly.express as px import logging -import streamlit as st logger = logging.getLogger(__name__) @@ -10,28 +8,74 @@ 2: 'Sample' } + class OutputInterface: def __init__(self, output_file_dict): - ''' - Parameters + """Parameters ---------- output_file_dict : dict Dictionary of output files as pd.DataFrames with the key as the output file name. - ''' + """ self.output_file_dict = output_file_dict self.oed_fields = {} + self.summary_levels = {} + self.file_prefixes = {} + + def set_file_prefix(self, perspective, prefix): + """Inuring priority prefix for a perspective's files, e.g. `IP1_` for + `rl_IP1_S1_selt.csv`. `''` (default) is the final/only priority. + """ + self.file_prefixes[perspective] = prefix + + def has_summary_info(self, perspective, summary_level=None): + level = summary_level or self.summary_level(perspective) + 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 + (written by pytools join-summary-info). + """ + if self.has_summary_info(perspective, summary_level): + return True + level = summary_level or self.summary_level(perspective) + stem = f"{perspective}_{self.file_prefixes.get(perspective, '')}S{level}_" + files = [df for name, df in self.output_file_dict.items() + if name.startswith(stem) and not name.endswith('summary-info.csv')] + return bool(files) and all(set(oed_fields) <= set(df.columns) for df in files) def set_oed_fields(self, perspective, oed_fields): self.oed_fields[perspective] = oed_fields + def set_summary_level(self, perspective, summary_level): + """Select which summary level (`S` files) to visualise for a perspective.""" + self.summary_levels[perspective] = summary_level + + def summary_level(self, perspective): + return self.summary_levels.get(perspective, 1) + def get(self, summary_level, perspective, output_type, **kwargs): - ''' - Generate graph from the output file. + """Generate graph from the output file. Parameters ---------- summary_level : int + Summary level (`S` in the output file names). perspective : str One of the following - `gul` : ground up loss @@ -60,7 +104,7 @@ def get(self, summary_level, perspective, output_type, **kwargs): Returns ------- plotly.Figure - ''' + """ supported_outputs = ['eltcalc', 'aalcalc', 'leccalc', 'pltcalc', 'elt_sample', 'elt_moment', 'elt_quantile', 'plt_sample', 'plt_moment', 'plt_quantile', @@ -68,30 +112,34 @@ def get(self, summary_level, perspective, output_type, **kwargs): 'ept', 'psept' ] assert output_type in supported_outputs, 'Output type not supported' - assert perspective in ['gul', 'il', 'ri'], 'Perspective not valid' + assert perspective in ['gul', 'il', 'ri', 'rl'], 'Perspective not valid' if output_type == "leccalc": assert kwargs.get("analysis_type") in ["full_uncertainty", "sample_mean", "wheatsheaf", "wheatsheaf_mean"], "Analysis type not supported." assert kwargs.get("loss_type") in ["aep", "oep"], "Loss type not supported." - fname = self._request_to_fname(summary_level, perspective, output_type, - **kwargs) - results = self.output_file_dict.get(fname) + prefix = self.file_prefixes.get(perspective, '') + fname = self._request_to_fname(summary_level, perspective, output_type, prefix=prefix, + **kwargs) + 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)) + 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: + logger.warning(f'{fname}: no summary info for {missing}') kwargs['oed_fields'] = oed_fields result = getattr(self, f'generate_{output_type}')(results, **kwargs) return result @staticmethod - def _request_to_fname(summary_level, perspective, output_type, **kwargs): + def _request_to_fname(summary_level, perspective, output_type, prefix='', **kwargs): if output_type[:4] in ['elt_', 'plt_']: output_type = output_type[4] + output_type[:3] @@ -106,18 +154,26 @@ def _request_to_fname(summary_level, perspective, output_type, **kwargs): if output_type[:4] == 'alct': output_type = 'alct' - fname = f'{perspective}_S{summary_level}_{output_type}' + fname = f'{perspective}_{prefix}S{summary_level}_{output_type}' if output_type == 'leccalc': fname += f'_{kwargs.get("analysis_type")}_{kwargs.get("loss_type")}' fname += '.csv' return fname @staticmethod - def _request_to_summary_info_fname(summary_level, perspective): - return f'{perspective}_S{summary_level}_summary-info.csv' + def _request_to_summary_info_fname(summary_level, perspective, prefix=''): + return f'{perspective}_{prefix}S{summary_level}_summary-info.csv' @staticmethod def add_oed_fields(results, summary_info, oed_fields): + """Join OED group fields onto `results` from the summary-info file. + + Fields already in `results` (joined by pytools join-summary-info) are + left as they are; without a summary-info file nothing is joined. + """ + oed_fields = [f for f in oed_fields if f not in results.columns] + if not oed_fields or summary_info is None: + return results summary_info = summary_info.set_index('summary_id') summary_info = summary_info[oed_fields] if 'summary_id' in results.columns: diff --git a/oasis-platform.yml b/oasis-platform.yml index e5334d3..f4eeaf1 100755 --- a/oasis-platform.yml +++ b/oasis-platform.yml @@ -51,7 +51,7 @@ services: volumes: - filestore-OasisData:/shared-fs:rw healthcheck: - test: curl --fail http:localhost:8000/healthcheck/ || exit + test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/healthcheck/')"] interval: 30s retries : 10 start_period: 30s diff --git a/oasis-scenarios-platform.yml b/oasis-scenarios-platform.yml deleted file mode 100755 index 02dd84c..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: curl --fail http://localhost:8000/healthcheck/ || exit - 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 bc3756b..7038789 100644 --- a/pages/analyses.py +++ b/pages/analyses.py @@ -1,420 +1,532 @@ -from modules.settings import get_analyses_settings -from modules.authorisation import validate_page, handle_login -from oasis_data_manager.errors import OasisException -import streamlit as st -from requests.exceptions import HTTPError -from modules.nav import SidebarNav -from modules.rerun import RefreshHandler -from modules.validation import KeyInValuesValidation, KeyNotNoneValidation, KeyValueValidation, NotNoneValidation, ValidationGroup -from modules.config import retrieve_ui_config import json -from json import JSONDecodeError -import time -from pages.components.create import consume_analysis_settings, create_analysis_form, create_portfolio_form, produce_analysis_settings -from pages.components.display import DataframeView import logging +from pathlib import Path + +import streamlit as st +from oasis_data_manager.errors import OasisException +from requests.exceptions import HTTPError -from pages.components.footer import generate_footer +from modules.settings import get_analyses_settings +from modules.schemas import PERSPECTIVE_LABELS, PERSPECTIVES +from modules.ui import flash, page_setup, show_api_error +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, 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) from pages.components.logs import display_traceback_file -from pages.components.process import enrich_analyses -from pages.components.output import summarise_inputs +from pages.components.results import render_results +from pages.components.settings_editor import analysis_settings_editor, reset_editor logger = logging.getLogger(__name__) -########################################################################################## -# Header -########################################################################################## - -ui_config = retrieve_ui_config() -validate_page("Analyses") +ci = page_setup('Analyses') -st.set_page_config( - page_title = "Analysis", - layout = "centered" -) +VIEW_KEY = 'analyses_view' # None (list), 'new', or ('edit', analysis_id) +RUNNABLE_WITH_INPUTS = ['READY', 'RUN_COMPLETED', 'RUN_CANCELLED', 'RUN_ERROR'] -cols = st.columns([0.1, 0.8, 0.1]) -with cols[1]: - st.image("images/oasis_logo.png") +if st.session_state.get(NEW_ANALYSIS_DEFAULTS) is not None: + st.session_state[VIEW_KEY] = 'new' -########################################################################################## -# Page -########################################################################################## - -# Retrieve client -handle_login(ui_config.skip_login) -SidebarNav() - -client_interface = st.session_state["client_interface"] -client = client_interface.client - -"## Portfolios" +portfolios = ci.portfolios.get() +models = ci.models.get() +analyses = ci.analyses.get() +portfolios_by_id = {p['id']: p for p in portfolios} +models_by_id = {m['id']: m for m in models} +analyses_by_id = {a['id']: a for a in analyses} +models_table = models_df(ci, models) -def show_portfolio(): - display_cols = [ 'name' ] - portfolios = client_interface.portfolios.get(df=True) - portfolio_view = DataframeView(portfolios, display_cols=display_cols) - portfolio_view.display() +def close_editor(editor_key=None): + if editor_key: + reset_editor(editor_key) + st.session_state[VIEW_KEY] = None + st.session_state[NEW_ANALYSIS_DEFAULTS] = None -@st.dialog(title="Create Portfolio") -def create_portfolio(): - form_data = create_portfolio_form() - if form_data is None: - return +def portfolio_fields(portfolio): + """Columns of the portfolio's location and accounts files (for grouping losses).""" + fields = [] + for file_type in ['location_file', 'accounts_file']: + try: + df = portfolio_file_df(ci, portfolio, file_type) + except (HTTPError, OasisException) as e: + logger.warning(f"Could not read {file_type} of portfolio {portfolio['id']}: {e}") + df = None + if df is not None: + fields += [c for c in df.columns if c not in fields] + return fields - try: - with st.spinner(text="Creating portfolio..."): - client_interface.portfolios.create(name = form_data.get('name'), - location_file = form_data.get('location_file'), - accounts_file = form_data.get('accounts_file'), - reinsurance_info_file = form_data.get('reinsurance_info_file'), - reinsurance_scope_file = form_data.get('reinsurance_scope_file') - ) - st.success("Successfully created portfolio") - time.sleep(0.5) - st.rerun() - except HTTPError as e: - st.error(e) -st.write("Available Portfolios: ") -show_portfolio() -if st.button("Create Portfolio"): - create_portfolio() +def start_run(analysis, regenerate=False): + """Run an analysis, generating inputs first if needed.""" + if regenerate or analysis['status'] not in RUNNABLE_WITH_INPUTS: + ci.generate_and_run(analysis['id']) + else: + ci.run(analysis['id']) ########################################################################################## -"## Analyses" - -analysis_container = st.container() +# Settings templates +########################################################################################## -rerun_interval_analysis = None +def template_picker(model, key, current=None): + """Choose what to base the analysis settings on. -@st.fragment -def new_analysis(): - portfolios = client_interface.portfolios.get() - models = client_interface.models.get() + Returns: + (source_id, settings) — settings is None for "model defaults". + """ + sources = {} + if current: + sources['current'] = ('Current analysis settings', lambda: current) - resp = create_analysis_form(portfolios, models) - if resp: + try: + templates = ci.models.setting_templates.get(model['id']) or [] + except (HTTPError, OasisException, AttributeError) as e: + logger.warning(f'No setting templates for model {model["id"]}: {e}') + templates = [] + for t in sorted(templates, key=lambda t: t['id'], reverse=True): + sources[f"template_{t['id']}"] = ( + f"Template: {t.get('name') or t['id']}", + lambda t=t: ci.models.setting_templates.get_contents(model['id'], t['id'])) + + # Bundled defaults/ files are only a fallback for models without platform templates + if not templates: + for path in get_analyses_settings(model_name_id=model['model_id'], supplier_id=model['supplier_id']): + sources[f'file_{path}'] = (f'Default file: {Path(path).name}', + lambda path=path: json.loads(Path(path).read_text())) + + for a in sorted(analyses, key=lambda a: a['id'], reverse=True): + if a['model'] == model['id'] and a.get('settings') and (not current or a['id'] != current.get('_id')): + # `modified` in the id so an edited analysis isn't served from cache + sources[f"analysis_{a['id']}_{a.get('modified')}"] = (f"Copy of analysis: {a['name']}", + lambda a=a: analysis_settings(ci, a)) + + sources['model'] = ('Model defaults', lambda: None) + sources['upload'] = ('Upload a settings file…', None) + + choice = st.selectbox('Start from', list(sources), format_func=lambda s: sources[s][0], + key=f'{key}_template', + help='Settings to pre-fill the form with. You can change anything afterwards.') + + if choice == 'upload': + upload = st.file_uploader('analysis_settings.json', type=['json'], key=f'{key}_upload') + if upload is None: + return choice, None try: - 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) - -def analysis_summary_expander(selected): - analysis_id = selected['id'] - with st.expander("Analysis Summary"): - - summary_tab, inputs_tab, outputs_tab = st.tabs(["Summary", "Inputs", "Outputs"]) - - @st.cache_data(show_spinner="Fetching input data...") - def get_input_file(analysis_id): - return client_interface.analyses.get_file(analysis_id, 'input_file', df=True) - - inputs = get_input_file(analysis_id) - - locations = inputs.get('location.csv', None) - if client.analyses.get(analysis_id).json().get('settings') is not None: - a_settings = client.analyses.settings.get(analysis_id).json() - else: - a_settings = None - - with summary_tab: - summarise_inputs(locations, a_settings) - - @st.cache_data - def convert_df(df): - return df.to_csv(index=False).encode("utf-8") - - with inputs_tab: - input_file_list = sorted(list(inputs.keys())) - - st.write("Input files:") - for fname in input_file_list: + return f'upload_{upload.file_id}', json.load(upload) + except json.JSONDecodeError as e: + st.error(f'Could not read the settings file: {e}') + return choice, None - left, right, _ = st.columns([1, 1, 1]) - left.write(fname) - right.download_button("Download", convert_df(inputs[fname]), - key=f'download_{fname}', - file_name=fname) - - - @st.cache_data(show_spinner="Fetching output data...") - def get_output_file(analysis_id): - return client_interface.analyses.get_file(analysis_id, 'output_file', df=True) - - if selected['status'] == 'RUN_COMPLETED': - outputs = get_output_file(analysis_id) - with outputs_tab: - output_file_list = sorted(list(outputs.keys())) - - st.write("Output files:") - for fname in output_file_list: + if choice == 'current': + return choice, current + try: + base = session_cached(('template', model['id'], choice), sources[choice][1]) + except (HTTPError, OasisException, OSError, json.JSONDecodeError) as e: + st.error(f'Could not load "{sources[choice][0]}": {e}') + base = None + return choice, base - left, right, _ = st.columns([1, 1, 1]) - left.write(fname) - right.download_button("Download", convert_df(outputs[fname]), - key=f'download_{fname}', - file_name=fname) - fname = f"analysis_{analysis_id}_output.tar.gz" - @st.cache_data(show_spinner="Fetching output tar data...") - def get_output_tar(analysis_id): - return client_interface.download_output(analysis_id) - fdata = get_output_tar(analysis_id) +########################################################################################## +# New analysis +########################################################################################## - st.download_button('Download All Outputs', - data=fdata, - file_name=fname) - else: - outputs = None - with outputs_tab: - st.info("Run not complete.") +def new_analysis_view(): + defaults = st.session_state.get(NEW_ANALYSIS_DEFAULTS) or {} + title_col, back_col = st.columns([0.85, 0.15], vertical_alignment='bottom') + title_col.subheader('New analysis') + if back_col.button('Cancel', icon=':material/close:', width='stretch'): + close_editor() + st.rerun() -def run_analysis(re_handler): - analyses = client_interface.analyses.get(df=True) - if analyses.empty: - st.info("No analyses.") + usable = [p for p in portfolios if (p.get('location_file') or {}).get('stored')] + if not usable or not models: + st.warning('You need a portfolio with a location file and at least one model to create an analysis.') + if not usable and st.button('Go to Portfolios'): + close_editor() + st.switch_page(PORTFOLIOS_PAGE) return - portfolios = client_interface.portfolios.get(df=True) - models = client_interface.models.get(df=True) - - completed_statuses = ['RUN_COMPLETED', 'RUN_CANCELLED', 'RUN_ERROR'] - running_statuses = ['RUN_QUEUED', 'RUN_STARTED'] - - re_handler.update_queue() - - # Check for running analysis - 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) - - left, middle, right = st.columns(3, vertical_alignment='center') - st.write('1) Select an analysis:') - - portfolios = client_interface.portfolios.get(df=True) - models = client_interface.models.get(df=True) - analyses = enrich_analyses(analyses, portfolios, models).sort_values('id', ascending=False) - - display_cols = ['name', 'portfolio_name', 'model_id', 'model_supplier', 'status'] - - analyses_view = DataframeView(analyses, selectable='single', display_cols=display_cols) - selected = analyses_view.display() - - # Analysis run buttons - validations = ValidationGroup() - validations.add_validation(NotNoneValidation('Selected analysis'), selected) - validations.add_validation(KeyInValuesValidation('Status'), selected, - 'status', ['NEW', 'INPUTS_GENERATION_CANCELLED', - 'READY', 'RUN_COMPLETED', - 'RUN_CANCELLED', 'RUN_ERROR' ]) - - - left, middle, right = st.columns(3, vertical_alignment='center') - left.markdown("2) Generate Inputs:") + portfolio_ids = [p['id'] for p in usable] + model_ids = [m['id'] for m in models] + + with st.container(border=True): + c1, c2, c3 = st.columns(3) + portfolio_id = c1.selectbox( + 'Portfolio', portfolio_ids, + index=portfolio_ids.index(defaults['portfolio']) if defaults.get('portfolio') in portfolio_ids + else (0 if len(portfolio_ids) == 1 else None), + format_func=lambda i: portfolios_by_id[i]['name'], placeholder='Choose a portfolio', + key='new_analysis_portfolio') + model_id = c2.selectbox( + 'Model', model_ids, + index=model_ids.index(defaults['model']) if defaults.get('model') in model_ids + else (0 if len(model_ids) == 1 else None), + format_func=lambda i: model_label(models_by_id[i], cached_model_settings(ci, models_by_id[i])), + placeholder='Choose a model', key='new_analysis_model') + + suggested = '' + if portfolio_id and model_id: + suggested = (f"{portfolios_by_id[portfolio_id]['name']} – " + f"{cached_model_settings(ci, models_by_id[model_id]).get('name') or models_by_id[model_id]['model_id']}") + name = c3.text_input('Analysis name', placeholder=suggested or 'Name', + help='Leave blank to use the suggested name.', key='new_analysis_name') + name = name.strip() or suggested + + if portfolio_id is None or model_id is None: + st.caption('Choose a portfolio and a model to set up the analysis.') + return - if middle.button("Generate", width='stretch', disabled=not validations.is_valid()): + model, portfolio = models_by_id[model_id], portfolios_by_id[portfolio_id] + model_settings = cached_model_settings(ci, model) + + st.markdown('#### Settings') + source, base = template_picker(model, f'new_{model_id}') + editor_key = f'new_{portfolio_id}_{model_id}_{source}' + settings, valid, problems = analysis_settings_editor(model, model_settings, portfolio, base, editor_key, + portfolio_fields(portfolio)) + + st.divider() + if problems: + st.caption(f':orange[{len(problems)} problem(s) to fix — see the Review tab.]') + run_col, create_col, _ = st.columns([0.2, 0.2, 0.6]) + run = run_col.button('Create and run', type='primary', icon=':material/play_arrow:', + disabled=not valid or not name, width='stretch') + create = create_col.button('Create only', disabled=not valid or not name, width='stretch', + help='Create the analysis and save its settings without running it.') + + if run or create: try: - client.analyses.generate(selected['id']) - st.success('Input generation started.') - time.sleep(0.5) - re_handler.start(selected['id'], ['READY', 'INPUTS_GENERATION_CANCELLED', 'INPUTS_GENERATION_ERROR']) - except HTTPError as e: - st.error("Input generation failed.") - logger.error(e) - + with st.spinner('Creating analysis...'): + analysis = ci.create_analysis(portfolio_id, model_id, name) + ci.upload_settings(analysis['id'], settings) + if run: + ci.generate_and_run(analysis['id']) + except (HTTPError, OasisException) as e: + show_api_error('Creating analysis', e) + return + st.session_state[SELECTED_ANALYSIS] = analysis['id'] + flash(f'Analysis "{name}" ' + ('created and started' if run else 'created')) + close_editor(editor_key) + st.rerun() - left, middle, right = st.columns(3, vertical_alignment='center') - left.markdown("3) Setup Analysis:") - # Upload settings button - @st.dialog("Upload Settings File") - def upload_settings_file(analysis): - with st.form("upload_settings_form", clear_on_submit=True, enter_to_submit=False): - uploadedFile = st.file_uploader("Analysis Settings JSON file") +########################################################################################## +# Edit settings +########################################################################################## - submitted = st.form_submit_button("Submit") +def edit_settings_view(analysis): + title_col, back_col = st.columns([0.85, 0.15], vertical_alignment='bottom') + title_col.subheader(f"Settings: {analysis['name']}") + if back_col.button('Cancel', icon=':material/close:', width='stretch'): + close_editor() + st.rerun() - if submitted: - try: - analysis_settings = json.load(uploadedFile) - client.upload_settings(analysis['id'], analysis_settings) - st.success('Analysis settings uploaded.') - time.sleep(0.5) - st.rerun() - except (JSONDecodeError, HTTPError) as e: - st.error(f'Invalid Settings File: {e}') - logger.error(e) - - @st.dialog("Set Analysis Settings", width="large") - def set_analysis_settings(analysis): - model = client.models.get(analysis['model']).json() - model_settings = client.models.settings.get(analysis['model']).json() - - valid_oed_fields = client.analyses.summary_levels_file.get(analysis['id']).json() - invalid_fields = ['OEDVersion'] - - keys = list(valid_oed_fields.keys()) - for k in keys: - new_k = k.lower() - valid_oed_fields[new_k] = valid_oed_fields.pop(k)['available'] - for f in invalid_fields: - valid_oed_fields[new_k].pop(f, None) - - # Load current settings - try: - default_settings = client_interface.analyses.settings.get(analysis['id']) - except HTTPError as _: - default_paths = get_analyses_settings(model_name_id=model["model_id"], supplier_id=model["supplier_id"]) - - if default_paths: - with open(default_paths[0], 'r') as f: - default_settings = json.load(f) - else: - default_settings = None - - produce_analysis_settings(model, model_settings, - oed_fields=valid_oed_fields, - initial_settings=default_settings) - - - validations = ValidationGroup() - validations.add_validation(NotNoneValidation('Analysis'), selected) - validations.add_validation(KeyInValuesValidation('Status'), selected, 'status', ['READY', 'NEW', 'RUN_ERROR', 'RUN_CANCELLED', 'RUN_COMPLETED']) - if middle.button("Upload Settings File", disabled=not validations.is_valid(), - width='stretch'): - upload_settings_file(selected) - - # Set settings button - validations = ValidationGroup() - validations.add_validation(NotNoneValidation('Analysis'), selected) - validations.add_validation(KeyValueValidation('Status'), selected, 'status', 'READY') - enable_button = validations.is_valid() - msg = None - if not enable_button: - msg = validations.message - if right.button("Set Analysis Settings", disabled=not enable_button, help=msg, - width='stretch'): - set_analysis_settings(selected) - - created_analysis_settings = consume_analysis_settings() - if 'upload_analysis_state' not in st.session_state: - st.session_state['upload_analysis_state'] = None - - if created_analysis_settings is not None: - try: - client.upload_settings(selected['id'], created_analysis_settings) - st.session_state['upload_analysis_state'] = 'success' - time.sleep(0.5) - st.rerun() - except (JSONDecodeError, HTTPError) as e: - st.session_state['upload_analysis_state'] = 'error' - logger.error(e) - - if st.session_state['upload_analysis_state'] == 'success': - st.toast('Analysis settings uploaded.') - elif st.session_state['upload_analysis_state'] == 'error': - st.toast(f'Error: Setting analysis settings failed.') - st.session_state['upload_analysis_state'] = None - - # Run analysis button - left, middle, right = st.columns(3, vertical_alignment='center') - left.markdown("4) Run Analysis:") - - validations = ValidationGroup() - validations.add_validation(NotNoneValidation('Analysis'), selected) - validations.add_validation(KeyInValuesValidation('Status'), selected, - 'status', ['READY', 'RUN_COMPLETED', - 'RUN_CANCELLED', 'RUN_ERROR']) - validations.add_validation(KeyNotNoneValidation('Settings'), selected, 'settings') - - run_enabled = validations.is_valid() - msg = None - if not run_enabled: - msg = validations.message - - if middle.button("Run", width='stretch', disabled=not run_enabled, help=msg): + model = models_by_id.get(analysis['model']) + portfolio = portfolios_by_id.get(analysis['portfolio']) + if model is None or portfolio is None: + st.error('The model or portfolio for this analysis no longer exists.') + return + model_settings = cached_model_settings(ci, model) + + current = analysis_settings(ci, analysis) + if current: + current = {**current, '_id': analysis['id']} + source, base = template_picker(model, f"edit_{analysis['id']}", current) + if base: + base = {k: v for k, v in base.items() if k != '_id'} + editor_key = f"edit_{analysis['id']}_{source}" + settings, valid, problems = analysis_settings_editor(model, model_settings, portfolio, base, editor_key, + portfolio_fields(portfolio)) + + st.divider() + in_progress = is_active(analysis) + if in_progress: + st.caption(':orange[The analysis is running. Settings can be changed once it finishes.]') + elif problems: + st.caption(f':orange[{len(problems)} problem(s) to fix — see the Review tab.]') + run_col, save_col, _ = st.columns([0.2, 0.2, 0.6]) + run = run_col.button('Save and run', type='primary', icon=':material/play_arrow:', + disabled=not valid or in_progress, width='stretch') + save = save_col.button('Save', disabled=not valid or in_progress, width='stretch') + + if run or save: try: - client_interface.run(selected['id']) + ci.upload_settings(analysis['id'], settings) + if run: + # Regenerate inputs: model options can affect input generation + start_run(analysis, regenerate=True) + except (HTTPError, OasisException) as e: + show_api_error('Saving settings', e) + return + flash('Settings saved' + (' and run started' if run else '')) + close_editor(editor_key) + st.rerun() - st.success("Run started") - time.sleep(0.5) - re_handler.start(selected['id'], completed_statuses) - except HTTPError as e: - st.error('Starting run failed.') - logger.error(e) +########################################################################################## +# Analysis list and detail +########################################################################################## - # Misc buttons - left, middle, right = st.columns(3, vertical_alignment='center') +def settings_summary(settings): + left, right = st.columns(2) + left.metric('Samples', settings.get('number_of_samples', '—')) + perspectives = [PERSPECTIVE_LABELS[p] for p in PERSPECTIVES if settings.get(f'{p}_output')] + right.metric('Perspectives', len(perspectives), help=', '.join(perspectives)) + if settings.get('model_settings'): + st.markdown('**Model options**') + st.dataframe([{'Option': k, 'Value': json.dumps(v) if isinstance(v, (list, dict)) else str(v)} + for k, v in settings['model_settings'].items()], hide_index=True) + rows = [] + for p in PERSPECTIVES: + if not settings.get(f'{p}_output'): + continue + for level in settings.get(f'{p}_summaries', []): + ords = [k for k, v in level.get('ord_output', {}).items() if v is True and k != 'parquet_format'] + legacy = [k for k in ['eltcalc', 'aalcalc', 'pltcalc', 'lec_output'] if level.get(k)] + rows.append({'Perspective': p.upper(), 'Level': level.get('id'), + 'Group by': ', '.join(level.get('oed_fields') or []) or 'Portfolio total', + 'Outputs': ', '.join(ords + legacy)}) + if rows: + st.markdown('**Outputs**') + st.dataframe(rows, hide_index=True) + + +def results_tab(analysis, settings): + if analysis['status'] != 'RUN_COMPLETED': + st.info('Results appear here once the analysis has run successfully.') + return + if not settings: + st.warning('No analysis settings found, so outputs cannot be interpreted.') + return + with st.spinner('Loading outputs...'): + 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, key=analysis['id']) + + st.divider() + st.markdown('**Output files**') + file_col, dl_col = st.columns([0.6, 0.4], vertical_alignment='bottom') + fname = file_col.selectbox('File', sorted(outputs), key=f"out_file_{analysis['id']}") + if fname: + dl_col.download_button('Download', outputs[fname].to_csv(index=False).encode(), + file_name=fname, key=f"dl_out_{analysis['id']}") + zip_key = f"zip_{analysis['id']}_{analysis.get('modified')}" + if zip_key not in st.session_state: + if st.button('Prepare download of all outputs (.zip)', key=f'{zip_key}_prep'): + with st.spinner('Fetching outputs...'): + st.session_state[zip_key] = ci.download_output_zip(analysis['id']) + st.rerun() + else: + st.download_button('Download all outputs (.zip)', st.session_state[zip_key], + file_name=f"analysis_{analysis['id']}_output.zip", key=f'{zip_key}_dl', + type='primary', icon=':material/download:') - validation = NotNoneValidation('Selected analysis') - button_enabled = validation.is_valid(selected) - if left.button("Delete", width='stretch', disabled = not button_enabled, help=validation.message): +def inputs_tab(analysis): + if analysis['status'] in ['NEW', 'INPUTS_GENERATION_QUEUED', 'INPUTS_GENERATION_STARTED', + 'INPUTS_GENERATION_ERROR', 'INPUTS_GENERATION_CANCELLED']: + st.info('Input files appear here once input generation has completed.') + return + load_key = f"show_inputs_{analysis['id']}" + if not st.session_state.get(load_key): + if st.button('Load generated input files', key=f'{load_key}_btn'): + st.session_state[load_key] = True + st.rerun() + return + with st.spinner('Loading inputs...'): + inputs = analysis_files(ci, analysis, 'input_file') + fname = st.selectbox('File', sorted(inputs), key=f"in_file_{analysis['id']}") + if fname: + df = inputs[fname] + st.caption(f'{len(df):,} rows') + st.dataframe(df.head(1000), hide_index=True, height=300) + st.download_button('Download', df.to_csv(index=False).encode(), file_name=fname, + key=f"dl_in_{analysis['id']}") + + +def logs_tab(analysis): + shown = False + for kind in ['input_generation', 'run']: + tb = ci.analyses.get_traceback(analysis['id'], kind) + if tb: + shown = True + display_traceback_file(tb, trace_type=kind) + if not shown: + st.info('No error logs for this analysis.') + + +def analysis_detail(analysis): + status = analysis['status'] + portfolio = portfolios_by_id.get(analysis['portfolio'], {}) + model = models_by_id.get(analysis['model'], {}) + 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']) + + settings = analysis_settings(ci, analysis) + ran_before = status not in ['NEW', 'INPUTS_GENERATION_ERROR', 'INPUTS_GENERATION_CANCELLED', 'READY'] + if btn_cols[0].button('Re-run' if ran_before else 'Run', type='primary', icon=':material/play_arrow:', + disabled=in_progress or not settings, width='stretch', + help=None if settings else 'Set up the analysis settings first.'): try: - client.analyses.delete(selected['id']) + start_run(analysis) + flash('Run started') st.rerun() - except HTTPError as e: - st.error("Deletion failed.") - logger.error(e) - - validations = ValidationGroup() - validations.add_validation(NotNoneValidation('Analysis'), selected) - - run_enabled = validations.is_valid() - msg = None - if not run_enabled: - msg = validations.message + except (HTTPError, OasisException) as e: + show_api_error('Starting run', e) - if middle.button("Logs", width='stretch', disabled=not run_enabled, help=msg): - @st.dialog("Log", width='large') - def error_log_dialog(analysis_id): - input_gen_traceback = client_interface.analyses.get_traceback(analysis_id, 'input_generation') - run_traceback = client_interface.analyses.get_traceback(analysis_id, 'run') - - if input_gen_traceback is not None: - display_traceback_file(input_gen_traceback, trace_type='input_generation') - - if input_gen_traceback and run_traceback: - st.write('---') - - if run_traceback is not None: - display_traceback_file(run_traceback, trace_type='run') - - if input_gen_traceback is None and run_traceback is None: - st.info('No traceback logs to show.') - - error_log_dialog(selected['id']) + if btn_cols[1].button('Settings', icon=':material/tune:', width='stretch', disabled=in_progress): + st.session_state[VIEW_KEY] = ('edit', analysis['id']) + st.rerun() + if in_progress: + if btn_cols[2].button('Cancel', icon=':material/stop:', width='stretch'): + try: + ci.analyses.cancel(analysis['id']) + flash('Cancellation requested', icon='⛔') + st.rerun() + except (HTTPError, OasisException) as e: + show_api_error('Cancelling', e) - if selected is not None and selected['status'] in ['READY', 'RUN_COMPLETED']: - analysis_summary_expander(selected) + with btn_cols[3].popover('Delete', icon=':material/delete:', width='stretch', disabled=in_progress): + st.write(f"Delete **{analysis['name']}**? This cannot be undone.") + if st.button('Delete analysis', type='primary', key=f"delete_{analysis['id']}"): + try: + ci.analyses.delete(analysis['id']) + st.session_state[SELECTED_ANALYSIS] = None + flash(f"Analysis \"{analysis['name']}\" deleted") + st.rerun() + except (HTTPError, OasisException) as e: + show_api_error('Deleting analysis', e) + + link_cols = st.columns([0.5, 0.5]) + if link_cols[0].button(f"Portfolio: {portfolio.get('name', '—')}", type='tertiary', + icon=':material/folder_open:', disabled=not portfolio): + open_record(PORTFOLIOS_PAGE, SELECTED_PORTFOLIO, portfolio['id']) + model_name = models_table.set_index('id')['name'].get(model.get('id'), model.get('model_id', '—')) + if link_cols[1].button(f'Model: {model_name}', type='tertiary', icon=':material/deployed_code:', + disabled=not model): + open_record(MODELS_PAGE, SELECTED_MODEL, model['id']) + + if status in ERROR_STATUSES: + st.error(f'{format_status(status)}. See the Logs tab for details.') + if not settings and not in_progress: + st.info('This analysis has no settings yet. Use **Settings** to set it up, then run it.') + + tabs = st.tabs(['Results', 'Settings', 'Inputs', 'Logs']) + with tabs[0]: + results_tab(analysis, settings) + with tabs[1]: + if settings: + settings_summary(settings) + with st.expander('Settings JSON'): + st.json(settings, expanded=2) + st.download_button('Download analysis_settings.json', json.dumps(settings, indent=2), + file_name=f"analysis_{analysis['id']}_settings.json", + key=f"dl_settings_{analysis['id']}") + else: + st.info('No settings yet.') + with tabs[2]: + inputs_tab(analysis) + with tabs[3]: + logs_tab(analysis) + + +def list_view(): + header_left, header_right = st.columns([0.8, 0.2], vertical_alignment='bottom') + header_left.caption('An analysis runs a model against a portfolio with a set of analysis settings. ' + 'Select one to see its results, or create a new one.') + if header_right.button('New analysis', type='primary', icon=':material/add:', width='stretch'): + st.session_state[VIEW_KEY] = 'new' + st.rerun() + if not analyses: + st.info('No analyses yet. Create one to get started.') + return -# Initialise refreshing -re_handler = RefreshHandler(client_interface) -run_every = re_handler.run_every() + table = analyses_df(analyses, portfolios, models_table) + + f1, f2, f3, f4 = st.columns([0.3, 0.25, 0.225, 0.225]) + search = f1.text_input('Search', placeholder='Analysis name', label_visibility='collapsed') + status_groups = { + 'In progress': IN_PROGRESS_STATUSES, + 'Completed': ['RUN_COMPLETED'], + 'Failed / cancelled': ERROR_STATUSES + ['RUN_CANCELLED', 'INPUTS_GENERATION_CANCELLED'], + 'Not run': ['NEW', 'READY'], + } + groups = f2.multiselect('Status', list(status_groups), placeholder='Any status', + label_visibility='collapsed') + portfolio_filter = f3.selectbox('Portfolio', sorted(table['portfolio_name'].unique()), + index=None, placeholder='Any portfolio', label_visibility='collapsed') + model_filter = f4.selectbox('Model', sorted(table['model_name'].unique()), + index=None, placeholder='Any model', label_visibility='collapsed') + + if search: + table = table[table['name'].str.contains(search, case=False, regex=False)] + if groups: + table = table[table['status'].isin(sum((status_groups[g] for g in groups), []))] + if portfolio_filter: + table = table[table['portfolio_name'] == portfolio_filter] + if model_filter: + table = table[table['model_name'] == model_filter] + + column_config = { + 'id': st.column_config.NumberColumn('ID', width='small'), + 'name': 'Name', + 'status_label': 'Status', + 'portfolio_name': 'Portfolio', + 'model_name': 'Model', + 'modified': st.column_config.DatetimeColumn('Last updated', format='D MMM YYYY, HH:mm'), + } + selected_id = selectable_table(table, ['id', 'name', 'status_label', 'portfolio_name', 'model_name', 'modified'], + SELECTED_ANALYSIS, column_config, + height=min(38 + 35 * max(len(table), 1), 400)) + + snapshot = {a['id']: a['status'] for a in analyses} + any_running = any(is_active(a) for a in analyses) + + @st.fragment(run_every='2s' if any_running else None) + def live_status(): + if not any_running: + return + fresh = ci.analyses.get() + if {a['id']: a['status'] for a in fresh} != snapshot: + st.rerun() # A status changed: refresh the whole page + for a in fresh: + 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']}**", status_label(a), task, detail] if x) + st.progress(fraction or 0.0, text=text) + + live_status() + + if selected_id is None: + st.caption('Select an analysis above to see its details.') + return -@st.fragment(run_every=run_every) -def analysis_fragment(): - run_analysis_tab, create_analysis_tab = st.tabs(["Run Analysis", "Create Analysis"]) - with create_analysis_tab: - new_analysis() + st.divider() + analysis_detail(analyses_by_id[selected_id]) - with run_analysis_tab: - run_analysis(re_handler) -analysis_fragment() -if run_every is not None: - st.info('Analysis running.') +########################################################################################## +# Page +########################################################################################## -generate_footer(ui_config) +view = st.session_state.get(VIEW_KEY) +if view == 'new': + new_analysis_view() +elif isinstance(view, tuple) and view[0] == 'edit' and view[1] in analyses_by_id: + edit_settings_view(analyses_by_id[view[1]]) +else: + list_view() diff --git a/pages/components/common.py b/pages/components/common.py index cafe0ff..6a1d222 100644 --- a/pages/components/common.py +++ b/pages/components/common.py @@ -1,30 +1,141 @@ -""" -File containig some common methods for `pages/`. -""" +"""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 PERSPECTIVES_MAP = { - 'gul': 'Ground Up Loss', - 'il': 'Insured Loss', - 'ri': 'Reinsured Loss' - } + 'gul': 'Ground Up Loss', + 'il': 'Insured Loss', + 'ri': 'Reinsured Loss' +} STATUS_COLORS = { - 'NEW': 'green', - 'READY': 'green', - 'RUN_STARTED': 'goldenrod', - 'RUN_QUEUED': 'goldenrod', - 'RUN_CANCELLED': 'darkred', - 'RUN_ERROR': 'darkred', - 'INPUTS_GENERATION_QUEUED': 'goldenrod', - 'INPUTS_GENERATION_STARTED': 'goldenrod', - 'INPUTS_GENERATION_CANCELLED': 'darkred', - 'INPUTS_GENERATION_ERROR': 'darkred' - } + 'NEW': 'green', + 'READY': 'green', + 'RUN_STARTED': 'goldenrod', + 'RUN_QUEUED': 'goldenrod', + 'RUN_CANCELLED': 'darkred', + 'RUN_ERROR': 'darkred', + 'INPUTS_GENERATION_QUEUED': 'goldenrod', + 'INPUTS_GENERATION_STARTED': 'goldenrod', + 'INPUTS_GENERATION_CANCELLED': 'darkred', + 'INPUTS_GENERATION_ERROR': 'darkred' +} + def get_page_path(): - """Get the current page path from streamlit context. - """ + """Get the current page path from streamlit context.""" return PurePosixPath(urlparse(st.context.url).path).parts[-1] + + +########################################################################################## +# Status helpers +########################################################################################## + +STATUS_ICONS = { + 'NEW': '🆕', + 'INPUTS_GENERATION_QUEUED': '⏳', + 'INPUTS_GENERATION_STARTED': '⏳', + 'INPUTS_GENERATION_CANCELLED': '⛔', + 'INPUTS_GENERATION_ERROR': '❌', + 'READY': '🟢', + 'RUN_QUEUED': '⏳', + 'RUN_STARTED': '⏳', + 'RUN_COMPLETED': '✅', + 'RUN_CANCELLED': '⛔', + 'RUN_ERROR': '❌', +} + +ERROR_STATUSES = ['INPUTS_GENERATION_ERROR', 'RUN_ERROR'] + + +def format_status(status): + """e.g. `RUN_COMPLETED` -> `✅ Run completed`.""" + if not isinstance(status, str): + return '' + label = status.replace('_', ' ').capitalize() + 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)`. + + Uses the events completed during the loss calculation when the worker + reports them (needs `OASIS_ANALYSIS_STATUS_URL` set on the worker), + otherwise the sub-task counts. + """ + events_total = analysis.get('num_events_total') or 0 + events_done = analysis.get('num_events_complete') or 0 + if analysis.get('status') == 'RUN_STARTED' and events_total: + return min(events_done / events_total, 1.0), f'{events_done:,} of {events_total:,} events' + + counts = analysis.get('status_count') or {} + total = counts.get('TOTAL') or 0 + if total: + done = counts.get('COMPLETED', 0) + return done / total, f'{done} of {total} tasks' + return None, '' + + +def current_task(sub_tasks): + """Name of the sub-task(s) being worked on, e.g. "Generate losses chunk 0". + + Falls back to the next queued task when nothing has started yet. + """ + started = [t.get('name') for t in sub_tasks if t.get('status') == 'STARTED' and t.get('name')] + if started: + return ', '.join(dict.fromkeys(started)) + queued = [t.get('name') for t in sub_tasks if t.get('status') in ('QUEUED', 'PENDING') and t.get('name')] + return f'Waiting for: {queued[0]}' if queued else '' + + +########################################################################################## +# Tables and selection +########################################################################################## + +def selectable_table(df, columns, state_key, column_config=None, key=None, height='auto'): + """Show `df` as a single-row selectable table and remember the selected `id`. + + The selection is stored in `st.session_state[state_key]` so that other + pages can preselect a record (set the key, then `st.switch_page`). + + Returns: + The selected record id, or None. + """ + key = key or f'{state_key}_table' + ids = df['id'].tolist() if not df.empty else [] + + def on_select(): + rows = st.session_state[key].selection.rows + st.session_state[state_key] = ids[rows[0]] if rows else None + + st.dataframe(df, key=key, on_select=on_select, selection_mode='single-row', + hide_index=True, column_order=columns, column_config=column_config or {}, + width='stretch', height=height) + + selected = st.session_state.get(state_key) + return selected if selected in ids else None + + +def open_record(page, state_key, record_id): + """Navigate to `page` with `record_id` preselected.""" + st.session_state[state_key] = record_id + st.switch_page(page) + + +SELECTED_PORTFOLIO = 'selected_portfolio_id' +SELECTED_MODEL = 'selected_model_id' +SELECTED_ANALYSIS = 'selected_analysis_id' +NEW_ANALYSIS_DEFAULTS = 'new_analysis_defaults' + +PORTFOLIOS_PAGE = 'pages/portfolios.py' +MODELS_PAGE = 'pages/models.py' +ANALYSES_PAGE = 'pages/analyses.py' diff --git a/pages/components/create.py b/pages/components/create.py deleted file mode 100644 index 3c2c0c5..0000000 --- a/pages/components/create.py +++ /dev/null @@ -1,728 +0,0 @@ -# Module to display ui components for running analyses -from copy import copy -from pages.components.output import ViewSummarySettings, summarise_summary_level -import streamlit as st -from modules.validation import NameValidation, NotNoneValidation, ValidationError, ValidationGroup - - -class FormFragment(): - def __init__(self, params={}): - self.params = params - - def display(self): - return {} - -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 - -class PortfolioFilesFragment(FormFragment): - def display(self): - options = self.params.get('options', []) - - name = st.text_input('Portfolio Name', value=None, key='portfolio_name') - loc_file = st.selectbox('Select Location File', options, index=None) - acc_file = st.selectbox('Select Accounts File', options, index=None) - ri_file = st.selectbox('Select Reinsurance Info File', options, index=None) - rs_file = st.selectbox('Select Reinsurance Scope File', options, index=None) - - return { - 'name': name, - 'location_file': loc_file, - 'accounts_file': acc_file, - 'reinsurance_info_file': ri_file, - 'reinsurance_scope_file': rs_file - } - -def create_portfolio_form(): - files = st.file_uploader("Upload portfolio files", accept_multiple_files=True) - filesDict = { f.name: f for f in files} - - options = [f.name for f in files] - - with st.form("create_portfolio_form", clear_on_submit=True, enter_to_submit=False): - name = st.text_input('Portfolio Name', value=None, key='portfolio_name') - loc_file = st.selectbox('Select Location File', options, index=None) - acc_file = st.selectbox('Select Accounts File', options, index=None) - ri_file = st.selectbox('Select Reinsurance Info File', options, index=None) - rs_file = st.selectbox('Select Reinsurance Scope File', options, index=None) - - submitted = st.form_submit_button("Create Portfolio") - - - if submitted: - validation = NameValidation("Name") - if not validation.is_valid(name): - st.error(validation.message) - return None - - return { - 'name': name, - 'location_file': filesDict.get(loc_file), - 'accounts_file': filesDict.get(acc_file), - 'reinsurance_info_file': filesDict.get(ri_file), - 'reinsurance_scope_file': filesDict.get(rs_file) - } - - - -class ModelSettingsFragment: - '''Form fragment which sets categorical model settings. - - Currently handles the following settings: - - `event_set`, - - `event_occurrence_id`, - - `footprint_set`, - - `vulnerability_set`, - - `pla_loss_factor_set`, - - Args: - model_settings (dict) : model settings for form fragment - ''' - def __init__(self, model_settings): - self.model_settings = model_settings['model_settings'] - - def display(self): - ''' - Display the form fragment. - - Returns: - (dict) selected options in a dict under the `model_settings` key. - ''' - # Handle categorical settings - valid_settings = [ - 'event_set', - 'event_occurrence_id', - 'footprint_set', - 'vulnerability_set', - 'pla_loss_factor_set', - ] - - model_settings = self.model_settings - outputs = {'model_settings': {}} - - for k, v in model_settings.items(): - if k in valid_settings: - default = v.get('default', None) - options = v['options'] - default_index = self._get_default_index(options, default) - selected = st.selectbox(f"Set {v['name']}", options=v['options'], format_func=self._format_option, index=default_index) - outputs['model_settings'][k] = selected["id"] - return outputs - - @staticmethod - def _format_option(opt): - return f'{opt["id"]} : {opt["desc"]}' - - @staticmethod - def _get_default_index(options, default=None): - if default is None: - return None - return [i for i in range(len(options)) if options[i]['id'] == default][0] - - -class PerspectivesFragment: - '''Form fragment to set the active perspectives. - - Args: - model_settings (dict) - default (list) : List of active perspectives. - ''' - def __init__(self, model_settings={}, default=[]): - self.valid_perspectives = ['gul', 'il', 'ri'] - if "valid_output_perspectives" in model_settings.get('model_settings', {}): - self.valid_perspectives = model_settings["model_settings"]["valid_output_perspectives"] - - self.default = default - - def display(self): - valid_outputs = self.valid_perspectives - default = self.default - - outputs = {} - perspectives = {'gul': 'Ground up loss', - 'il': 'Insured loss', - 'ri': 'Reinsurance net loss'} - opt_cols = st.columns(3) - - for col, p in zip(opt_cols, perspectives.keys()): - with col: - opt = st.checkbox(p.upper(), help=perspectives[p], - value = p in default, - disabled = (p not in valid_outputs) - ) - outputs[f'{p}_output'] = opt - - return outputs - - -class JoinSummaryInfoFragment: - '''Form fragment to set the join_summary_info flag. - - Args: - analysis_settings (dict) - ''' - def __init__(self, analysis_settings={}): - self.analysis_settings = analysis_settings - - def display(self): - default_value = self.analysis_settings.get("join_summary_info", False) - outputs = {} - opt = st.checkbox( - "Join Summary Info", - help="Joins summary info to output files", - value = default_value, - disabled = False - ) - - outputs[f'join_summary_info'] = opt - return outputs - - -class NumberSamplesFragment: - '''Form fragment to set the number of samples in the analysis settings. - - Args: - model_settings (dict) - analysis_settings (dict) - - Usage: - Initialise and run `display()` to create form elements. Returns corresponding section of analysis settings. - ''' - def __init__(self, model_settings={}, analysis_settings={}): - self.model_settings = model_settings - self.analysis_settings = analysis_settings - - - def display(self): - model_settings = self.model_settings - analysis_settings = self.analysis_settings - - outputs = {} - - default_samples = model_settings.get("model_default_samples", 10) - default_samples = analysis_settings.get("number_of_samples", default_samples) - outputs["number_of_samples"] = st.number_input("Number of samples", - min_value = 1, - value = default_samples, - key="number_samples_input") - - return outputs - - -def merge_settings(settings1, settings2): - from copy import copy - settings1 = copy(settings1) - - for key, value in settings2.items(): - if key in settings1 and isinstance(settings1[key], dict) and isinstance(value, dict): - settings1[key] = merge_settings(settings1[key], value) - elif key in settings1 and isinstance(settings1[key], list) and isinstance(value, list): - settings1[key] += value - else: - settings1[key] = value - return settings1 - -def merge_summaries(summaries1, summaries2): - summaries1 = list(sorted(summaries1, key= lambda x: x['id'])) - summaries2 = list(sorted(summaries2, key= lambda x: x['id'])) - - i1, i2, output_summaries = 0, 0, [] - - while i1 < len(summaries1) and i2 < len(summaries2): - if summaries1[i1]['id'] == summaries2[i2]['id']: - output_summaries.append(summaries1[i1] | summaries2[i2]) - i1 += 1 - i2 += 1 - elif summaries1[i1]['id'] < summaries2[i2]['id']: - output_summaries.append(summaries1[i1]) - i1 += 1 - else: - output_summaries.append(summaries2[i2]) - i2 += 1 - - output_summaries.extend(summaries1[i1:]) - output_summaries.extend(summaries2[i2:]) - - return output_summaries - -def extract_default_from_level_settings(level_settings): - '''Extract default dict for output fragments from analysis settings. - ''' - default = {'ord_outputs': {}, 'legacy_outputs': {}} - summary = summarise_summary_level(level_settings) - - summary_ord = summary.get('ord_output', []) - - # Handle ord output - default['ord_outputs']['elt'] = [opt[4:] for opt in summary_ord if opt.startswith('elt')] - default['ord_outputs']['plt'] = [opt[4:] for opt in summary_ord if opt.startswith('plt')] - default['ord_outputs']['alt'] = [opt[4:] for opt in summary_ord if opt.startswith('alt')] - default['ord_outputs']['alct_convergence'] = 'alct_convergence' in summary_ord - default['ord_outputs']['alct_confidence'] = level_settings.get('ord_output', {}).get('alct_confidence', 0.95) - default['ord_outputs']['ept'] = [opt[4:] for opt in summary_ord if opt.startswith('ept')] - default['ord_outputs']['psept'] = [opt[6:] for opt in summary_ord if opt.startswith('psept')] - - # Handle legacy output - default['legacy_outputs'] = summary.get('legacy_output', None) - - # oed field - default['oed_fields'] = summary.get('oed_fields', []) - - return default - - -@st.fragment -def summary_settings_fragment(oed_fields, perspective): - if f'{perspective}_summaries' not in st.session_state: - st.session_state[f'{perspective}_summaries'] = [] - original_summaries = st.session_state[f'{perspective}_summaries'] - curr_summaries = copy(original_summaries) - oed_fields = oed_fields.get(perspective, None) - if oed_fields is not None and isinstance(oed_fields, dict): - oed_fields = list(oed_fields.keys()) - - selected = ViewSummarySettings(original_summaries, key=f'{perspective}_summaries_view', - selectable=True) - - col1, col2, col3, *_ = st.columns(5) - - level_container = st.container(border=True) - - if f'adding_level_{perspective}' not in st.session_state: - st.session_state[f'adding_level_{perspective}'] = False - if f'editing_level_{perspective}' not in st.session_state: - st.session_state[f'editing_level_{perspective}'] = False - - if col1.button('Add Level', key=f'{perspective}_summary_add_button', - width='stretch'): - st.session_state[f'adding_level_{perspective}'] = not st.session_state[f'adding_level_{perspective}'] - st.session_state[f'{perspective}_summaries'] = original_summaries - - if st.session_state[f'adding_level_{perspective}']: - with level_container: - curr_summary_settings = SummarySettingsFragment(oed_fields, perspective) - curr_summary_settings['id'] = max([s['id'] for s in curr_summaries] + [0]) + 1 - submitted = st.button('Create Level') - - if submitted: - st.session_state[f'adding_level_{perspective}'] = False - curr_summaries.append(curr_summary_settings) - st.session_state[f'{perspective}_summaries'] = curr_summaries - st.rerun(scope='fragment') - - if col2.button('Delete Level', key=f'{perspective}_summary_delete_button', - width='stretch', disabled=selected is None): - pos = [i for i, el in enumerate(curr_summaries) if el['id'] == selected][0] - curr_summaries.pop(pos) - st.session_state[f'{perspective}_summaries'] = curr_summaries - st.rerun(scope='fragment') - - if col3.button('Edit Level', key=f'{perspective}_summary_edit_button', - width='stretch', disabled=selected is None): - st.session_state[f'editing_level_{perspective}'] = not st.session_state[f'editing_level_{perspective}'] - st.session_state[f'{perspective}_summaries'] = original_summaries - - if st.session_state[f'editing_level_{perspective}']: - if selected is None: - st.session_state[f'editing_level_{perspective}'] = False - st.rerun(scope='fragment') - - st.info('Editing level') - pos = [i for i, el in enumerate(curr_summaries) if el['id'] == selected][0] - selected_summary = curr_summaries[pos] - defaults = extract_default_from_level_settings(selected_summary) - - with level_container: - updated_summary_settings = SummarySettingsFragment(oed_fields, perspective, defaults) - submit_edit = st.button('Save Edit') - - if submit_edit: - curr_summaries.pop(pos) - updated_summary_settings['id'] = selected_summary['id'] - st.session_state[f'editing_level_{perspective}'] = False - curr_summaries.append(updated_summary_settings) - st.session_state[f'{perspective}_summaries'] = curr_summaries - st.rerun(scope='fragment') - -def SummarySettingsFragment(oed_fields, perspective, default_outputs={}): - ''' - Fragment to generate UI which creates summary settings. - - Args: - oed_fields: List of OED group by field options. - perspective: perspective name (`gul`, `il`, `ri`) - default_outputs : dict with default options to preload form. - - Returns: - dict: single summary setting instance. - ''' - ord_output = ORDOutputFragment(perspective, default_outputs.get('ord_outputs', {})).display() - summaries_settings = {'ord_output' : ord_output} - - legacy_outputs = False - if len(default_outputs.get('legacy_outputs', [])) > 0: - legacy_outputs = True - if st.checkbox("Enable legacy outputs", key=f'{perspective}_enable_legacy_check', value=legacy_outputs): - p_summaries = OutputFragment(perspective=perspective, default=default_outputs.get('legacy_outputs', [])).display() - summaries_settings |= p_summaries - - if oed_fields: - p_summaries = OEDGroupFragment(perspective=perspective, - oed_options=oed_fields, - default=default_outputs.get('oed_fields', [])).display() - summaries_settings |= p_summaries - return summaries_settings - - -class ORDOutputFragment: - ''' - Generate selectboxes to select ORD output settings. - - Args: - perspective: perspective name (`gul`, `il`, `ri`) - default : dictionary containing the default options. - ''' - def __init__(self, perspective, default={}): - self.perspective = perspective - self.default = default - - def display(self): - ord_options = {} - perspective = self.perspective - defaults = self.default - - def output_type_multiselect(label, options, prefix, key=None, default=None): - selected_options = st.multiselect(label, options=options, key=key, default=default) - - output_dict = {} - for opt in options: - output_dict[f'{prefix}_{opt}'] = opt in selected_options - return output_dict - - elt_plt_options = ['sample', 'quantile', 'moment'] - - ord_options |= output_type_multiselect(label='Event Loss Table (ELT) Output', prefix='elt', - options=elt_plt_options, - default=defaults.get('elt', None), - key=f'{perspective}_elt_multiselect') - - ord_options |= output_type_multiselect(label='Period Loss Table (ELT) Output', prefix='plt', - options=elt_plt_options, - default=defaults.get('plt', None), - key=f'{perspective}_plt_multiselect') - - ord_options |= output_type_multiselect(label='Average Loss Table (ALT) Output', prefix='alt', - options=['period', 'meanonly'], - default=defaults.get('alt', None), - key=f'{perspective}_alt_multiselect') - - alct_enabled = ord_options.get('alt_period', False) - if alct_enabled: - alct_container = st.container(border=True) - alct_container.write('Average Loss Convergence Table (ALCT) Options') - ord_options['alct_convergence'] = alct_container.checkbox('Generate Convergence Table', - key=f'{perspective}_alct_conv_check', - value=defaults.get('alct_convergence', False)) - ord_options['alct_confidence'] = alct_container.number_input('Confidence Level', - min_value=0.0, max_value=1.0, - key=f'{perspective}_alct_conf_numeric', - value=defaults.get('alct_confidence', 0.95)) - - ept_output_options = [ - 'full_uncertainty_aep', - 'full_uncertainty_oep', - 'mean_sample_aep', - 'mean_sample_oep', - 'per_sample_mean_aep', - 'per_sample_mean_oep' - ] - ord_options |= output_type_multiselect(label='Exceedance Probability Table (EPT) Output: ', prefix='ept', - options=ept_output_options, - default=defaults.get('ept', None), - key=f'{perspective}_ept_multiselect') - - ord_options |= output_type_multiselect(label='Per Sample Exceedance Probability Table (PS EPT) Output:', prefix='psept', - options=['aep', 'oep'], - default=defaults.get('psep', None), - key=f'{perspective}_psep_multiselect') - - return ord_options - - -class OutputFragment: - ''' - Fragment to select legacy outputs. - - Args: - perspective: perspective name (`gul`, `il`, `ri`) - default (list[str]): List of default outputs - ''' - def __init__(self, perspective, default=[]): - self.perspective = perspective - self.default = default - - def display(self): - perspective = self.perspective - default = self.default - - options = [ - 'eltcalc', - 'aalcalc', - 'aalcalcmeanonly', - 'pltcalc', - 'summarycalc', - 'leccalc-full_uncertainty_aep', - 'leccalc-full_uncertainty_oep', - 'leccalc-persample_aep', - 'leccalc-persample_oep', - 'leccalc-persample_mean_aep', - 'leccalc-persample_mean_oep', - 'leccalc-sample_mean_aep', - 'leccalc-sample_mean_oep' - ] - - selected = st.multiselect(f"{perspective.upper()} Outputs", - options, key=f'{perspective}_legacy_output_select', - default=default) - - output_dict = { - 'eltcalc': False, - 'aalcalc': False, - 'aalcalcmeanonly': False, - 'pltcalc': False, - 'summarycalc': False, - 'lec_output': False, - 'leccalc': { - 'full_uncertainty_aep': False, - 'full_uncertainty_oep': False, - 'wheatsheaf_aep': False, - 'wheatsheaf_oep': False, - 'wheatsheaf_mean_aep': False, - 'wheatsheaf_mean_oep': False, - 'sample_mean_aep': False, - 'sample_mean_oep': False - } - - } - - for output_option in selected: - if output_option[:7] == 'leccalc': - output_dict['lec_output'] = True - lec_option = output_option[8:] - lec_option = lec_option.replace('persample', 'wheatsheaf') - output_dict['leccalc'][lec_option] = True - else: - output_dict[output_option] = True - - return output_dict - - -class OEDGroupFragment(FormFragment): - ''' - Fragment to select OED group fields in the analysis settings form. - - Note that the following fields are excluded: - `[ "BuildingTIV", "ContentsTIV", "OtherTIV", "BITIV", "OEDVersion" ]` - - Args: - perspective: perspective name (`gul`, `il`, `ri`) - oed_options (list[str]): List of potential `oed_fields` to select from. - If `None` the following default groups are possible `['PortNumber', - 'CountryCode', 'LocNumber']`. - defaults (list[str]): Default `oed_fields` to pre-fill. - - ''' - EXCLUDED_FIELDS = [ "BuildingTIV", "ContentsTIV", "OtherTIV", "BITIV", "OEDVersion" ] - - def __init__(self, perspective, oed_options=None, default=[]): - if oed_options is None: - oed_options = ['PortNumber', 'CountryCode', 'LocNumber'] - - self.oed_options = oed_options - self.perspective = perspective - self.default = default - - def display(self): - perspective = self.perspective - oed_options = self.oed_options - defaults = self.default - - oed_options = sorted(filter(self.valid_field_filter, oed_options)) - - oed_fields = st.multiselect(f"{perspective.upper()} OED grouping:", - oed_options, - default=defaults, - key=f'{perspective}_oed_select') - - output = {'oed_fields': oed_fields} - - return output - - @staticmethod - def valid_field_filter(field): - if field in OEDGroupFragment.EXCLUDED_FIELDS: - return False - return True - - -def clear_summaries_settings(): - """Remove summaries settings from session state. - """ - perspectives = ['gul', 'il', 'ri'] - # Reset form if previously rendered - for p in perspectives: - setting_name = f'{p}_summaries' - if setting_name in st.session_state: - del st.session_state[setting_name] - - -def save_settings(initial_settings, selected_settings): - perspectives = ['gul', 'il', 'ri'] - for p in perspectives: - settings_name = f'{p}_summaries' - - # Remove default summaries - if settings_name in initial_settings.keys(): - initial_settings.pop(settings_name) - - if settings_name in st.session_state: - selected_settings[settings_name] = st.session_state[settings_name] - - settings = merge_settings(initial_settings, selected_settings) - clear_summaries_settings() # Remove settings from session state - st.write('Saving settings') - st.session_state['created_analysis_settings'] = settings - -def produce_analysis_settings(model, model_settings, oed_fields=None, initial_settings=None): - ''' - Create a form to get user input for setting analysis settings. When the - user saves the settings the key `created_analysis_settings` in the - session_state is updated with the analysis settings. - - The produced analysis settings can be retrieved by calling `consume_analysis_settings`. - - Parameters - ---------- - model : dict - Information about the model, particularly `model_id` and `supplier_id`. - model_settings : dict - Model settings dictionary for given model. - oed_fields : list[str] - List of OED Fields to allow user to group by. If `None`, - attempt to infer the `oed_fields` from the `data_settings` in - `model_settings`. - initial_settings : dict - Analysis settings to initialise the form with. - - ''' - clear_summaries_settings() # Run this once prior to loading fragment - create_analysis_settings_fragment(model, model_settings, oed_fields, initial_settings) - - -def consume_analysis_settings(): - ''' - Retrieve the analysis settings produced from `produce_analysis_settings` from the session state. - Returns - ------- - dict : Dictionary of the new analysis settings. - ''' - if 'created_analysis_settings' in st.session_state: - output = copy(st.session_state['created_analysis_settings']) - del st.session_state['created_analysis_settings'] - else: - output = None - return output - -@st.fragment -def create_analysis_settings_fragment(model, model_settings, oed_fields=None, initial_settings=None): - '''Form fragment for creating analysis settings. - ''' - perspectives = ['gul', 'il', 'ri'] - - if oed_fields is None: - oed_fields = model_settings.get('data_settings', {}).get('damage_group_fields', []) - oed_fields.extend(model_settings.get('data_settings', {}).get('hazard_group_fields', [])) - oed_fields = {p : list(set(oed_fields)) for p in perspectives} - - if initial_settings is not None: - analysis_settings = copy(initial_settings) - else: - analysis_settings = { - 'model_settings': {}, - 'model_supplier_id': model["supplier_id"], - 'model_name_id': model["model_id"], - 'gul_output': True, - 'gul_summaries': [], - } - - - form_container = st.container(border=True) - with form_container: - selected_settings = {} - - selected_settings |= ModelSettingsFragment(model_settings=model_settings).display() - selected_settings |= NumberSamplesFragment(model_settings=model_settings, - analysis_settings=analysis_settings).display() - default_perspectives = [p for p in perspectives if analysis_settings.get(f'{p}_output', False)] - selected_settings |= PerspectivesFragment(model_settings=model_settings, - default=default_perspectives).display() - selected_settings |= JoinSummaryInfoFragment(analysis_settings=analysis_settings).display() - - p_tabs = st.tabs([p.upper() for p in perspectives]) - for p, tab in zip(perspectives, p_tabs): - with tab: - st.write(f'### {p.upper()} Output Settings') - - if f'{p}_summaries' not in st.session_state: - st.session_state[f'{p}_summaries'] = analysis_settings.get(f'{p}_summaries', []) - summary_settings_fragment(oed_fields, p) - - if st.button('Save Settings', on_click=save_settings, - args=[analysis_settings, selected_settings], - key="save_button_create_analysis"): - st.rerun() diff --git a/pages/components/data.py b/pages/components/data.py new file mode 100644 index 0000000..5661f6b --- /dev/null +++ b/pages/components/data.py @@ -0,0 +1,177 @@ +"""Loading and shaping platform records for the standard UI pages. + +List endpoints are always fetched fresh. Larger payloads (exposure files, +analysis inputs/outputs) are cached per session, keyed on the record's +`modified` timestamp, so they refresh after any change but are not shared +between users. +""" +import logging +import re + +import pandas as pd +import streamlit as st +from requests.exceptions import HTTPError + +from modules.client import PortfoliosEndpointInterface +from pages.components.common import status_label + +logger = logging.getLogger(__name__) + +_CACHE_KEY = '_session_data_cache' +_CACHE_MAX = 20 + + +def session_cached(key, loader): + """Return `loader()` cached in this session under `key`.""" + cache = st.session_state.setdefault(_CACHE_KEY, {}) + if key not in cache: + if len(cache) >= _CACHE_MAX: + cache.pop(next(iter(cache))) + cache[key] = loader() + return cache[key] + + +def _to_datetime(df, cols=('created', 'modified')): + for c in cols: + if c in df.columns: + df[c] = pd.to_datetime(df[c], errors='coerce') + return df + + +########################################################################################## +# Portfolios +########################################################################################## + +FILE_TYPES = PortfoliosEndpointInterface.FILE_TYPES + + +# Filename patterns used to guess which OED file an upload is, checked in order +_FILE_PATTERNS = [ + ('reinsurance_info_file', r'(ri|reins).*info|info'), + ('reinsurance_scope_file', r'(ri|reins).*scope|scope'), + ('location_file', r'loc'), + ('accounts_file', r'acc'), +] + + +def guess_file_type(filename): + """Guess the portfolio file type from an uploaded file's name (or None).""" + name = filename.lower() + for file_type, pattern in _FILE_PATTERNS: + if re.search(pattern, name): + return file_type + return None + + +def portfolios_df(portfolios, analyses=None): + """Portfolio records as a DataFrame with file-presence and analysis-count columns.""" + rows = [] + for p in portfolios: + row = {'id': p['id'], 'name': p['name'], + 'created': p.get('created'), 'modified': p.get('modified')} + for f in FILE_TYPES: + row[f] = bool((p.get(f) or {}).get('stored')) + rows.append(row) + df = pd.DataFrame(rows, columns=['id', 'name', 'created', 'modified', *FILE_TYPES]) + if analyses is not None: + counts = pd.Series([a['portfolio'] for a in analyses], dtype='Int64').value_counts() + df['n_analyses'] = df['id'].map(counts).fillna(0).astype(int) + return _to_datetime(df) + + +def portfolio_file_df(ci, portfolio, file_type): + """Dataframe of one of a portfolio's OED files (cached until it changes).""" + if not (portfolio.get(file_type) or {}).get('stored'): + return None + key = ('portfolio_file', portfolio['id'], file_type, portfolio.get('modified'), + portfolio[file_type]['stored']) + return session_cached(key, lambda: ci.portfolios.get_file(portfolio['id'], file_type, df=True)) + + +########################################################################################## +# Models +########################################################################################## + +def model_settings(ci, model_id): + """Model settings dict ({} if the model has none registered).""" + try: + return ci.models.settings.get(model_id) or {} + except HTTPError as e: + logger.warning(f'No settings for model {model_id}: {e}') + return {} + + +def model_label(model, settings=None): + name = (settings or {}).get('name') or model.get('model_id') + return f"{name} ({model.get('supplier_id')}, {model.get('version_id')})" + + +def models_df(ci, models, analyses=None): + rows = [] + for m in models: + settings = session_cached(('model_settings', m['id'], m.get('modified')), + lambda: model_settings(ci, m['id'])) + rows.append({ + 'id': m['id'], + 'name': settings.get('name') or m['model_id'], + 'supplier_id': m.get('supplier_id'), + 'model_id': m.get('model_id'), + 'version_id': m.get('version_id'), + 'run_mode': m.get('run_mode'), + 'created': m.get('created'), + 'modified': m.get('modified'), + }) + df = pd.DataFrame(rows, columns=['id', 'name', 'supplier_id', 'model_id', 'version_id', + 'run_mode', 'created', 'modified']) + if analyses is not None: + counts = pd.Series([a['model'] for a in analyses], dtype='Int64').value_counts() + df['n_analyses'] = df['id'].map(counts).fillna(0).astype(int) + return _to_datetime(df) + + +def cached_model_settings(ci, model): + return session_cached(('model_settings', model['id'], model.get('modified')), + lambda: model_settings(ci, model['id'])) + + +########################################################################################## +# Analyses +########################################################################################## + +def analyses_df(analyses, portfolios, models_frame): + """Analysis records enriched with portfolio and model names.""" + portfolio_names = {p['id']: p['name'] for p in portfolios} + model_names = dict(zip(models_frame['id'], models_frame['name'])) if not models_frame.empty else {} + rows = [] + for a in analyses: + rows.append({ + 'id': a['id'], + 'name': a['name'], + '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'), + 'model_name': model_names.get(a.get('model'), f"#{a.get('model')}"), + 'created': a.get('created'), + 'modified': a.get('modified'), + }) + df = pd.DataFrame(rows, columns=['id', 'name', 'status', 'status_label', 'portfolio', + 'portfolio_name', 'model', 'model_name', 'created', 'modified']) + return _to_datetime(df).sort_values('id', ascending=False) + + +def analysis_settings(ci, analysis): + if not analysis.get('settings'): + return None + try: + return ci.analyses.settings.get(analysis['id']) + except HTTPError as e: + logger.warning(f"No settings for analysis {analysis['id']}: {e}") + return None + + +def analysis_files(ci, analysis, file_type): + """Input or output files for an analysis as `{filename: DataFrame}`.""" + key = (file_type, analysis['id'], analysis.get('modified')) + return session_cached(key, lambda: ci.analyses.get_file(analysis['id'], file_type, df=True) or {}) diff --git a/pages/components/display.py b/pages/components/display.py index 74ece29..0ba4f64 100644 --- a/pages/components/display.py +++ b/pages/components/display.py @@ -5,22 +5,22 @@ import pydeck as pdk import plotly.express as px import geopandas -from streamlit import column_config from modules.logging import get_session_logger from pages.components.common import STATUS_COLORS logger = get_session_logger() + class View: - ''' - Base class to create a view component. + """Base class to create a view component. Parameters ---------- data : pd.DataFrame Pandas DataFrame containing the data to visualise. - ''' + """ + def __init__(self, data): self.data = data @@ -30,8 +30,7 @@ def display(self): class DataframeView(View): - ''' - Visualise dataframe. + """Visualise dataframe. Basic Usage: @@ -51,7 +50,8 @@ class DataframeView(View): If `single` then single row is selectable. If `multi` then multiple rows selctable. display_cols : list[str] The names of the columns to display. By default displays all the columns. - ''' + """ + def __init__(self, data=None, selectable=False, display_cols=None, hide_index=True, column_config=None): if data is None: @@ -79,11 +79,8 @@ def __init__(self, data=None, selectable=False, display_cols=None, hide_index=Tr else: self.column_config[c] = st.column_config.TextColumn(self.format_column_heading(c)) - def display(self, max_rows=1000, key=None): - ''' - Show the dataframe. - ''' + """Show the dataframe.""" if self.data.empty: st.dataframe(pd.DataFrame(columns=self.display_cols), hide_index=self.hide_index, column_config=self.column_config, @@ -100,8 +97,8 @@ def display(self, max_rows=1000, key=None): } if self.selectable: - args['selection_mode']="single-row" - args['on_select']="rerun" + args['selection_mode'] = "single-row" + args['on_select'] = "rerun" if self.selectable == 'multi': args['selection_mode'] = "multi-row" @@ -113,7 +110,6 @@ def display(self, max_rows=1000, key=None): if n_rows > max_rows: data_styled = data_styled.iloc[:max_rows, :] - def format_status(status): return status.replace('_', ' ').title() @@ -163,9 +159,8 @@ def selected_to_row(self, selected): class MapView(View): def __init__(self, data, longitude="Longitude", latitude="Latitude", - weight=None, map_type = "scatter", country="CountryCode"): - ''' - Class to visualise data on a map. + weight=None, map_type="scatter", country="CountryCode"): + """Class to visualise data on a map. Parameters ---------- @@ -187,7 +182,7 @@ def __init__(self, data, longitude="Longitude", latitude="Latitude", - `scatter` - `heatmap` - `choropleth` - currently only supports countries. - ''' + """ self.data = data self.longitude = longitude self.latitude = latitude @@ -208,7 +203,6 @@ def display(self): else: raise OasisException("Map type not recognised") - def generate_location_map(self): locations = self.data @@ -216,11 +210,11 @@ def generate_location_map(self): 'ScatterplotLayer', locations, get_position=[self.longitude, self.latitude], - get_line_color = [0, 0, 0], - get_fill_color = [255, 140, 0], - radius_min_pixels = 1, - radius_max_pixels = 50, - radius_scale = 2, + get_line_color=[0, 0, 0], + get_fill_color=[255, 140, 0], + radius_min_pixels=1, + radius_max_pixels=50, + radius_scale=2, pickable=True, stroked=True, get_line_width=0.5, @@ -232,7 +226,6 @@ def generate_location_map(self): if viewstate.zoom > 18: viewstate.zoom = 18 - tooltip = {'text': ''} if 'LocPerilsCovered' in locations.columns: tooltip['text'] += "Peril: {LocPerilsCovered}" @@ -254,24 +247,34 @@ 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() + # 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} - zoom = find_zoom_level(lon_range) + # 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: format_weight = format_weight[0].upper() + format_weight[1:] - fig = px.density_map(locations, - lat = self.latitude, - lon = self.longitude, - z = self.weight, + lat=self.latitude, + lon=self.longitude, + z=self.weight, color_continuous_scale="YlOrRd", opacity=0.75, - zoom = zoom, + zoom=zoom, + center=center, labels={self.weight: format_weight}) - fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) + fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) fig.update_layout(coloraxis_colorbar=dict( orientation='h', yanchor='top', @@ -315,8 +318,8 @@ def generate_choropleth(self): if len(locations) == 1: range_color = [0, max(locations[self.weight])] else: - offset = 0.1*(locations[self.weight].max() - locations[self.weight].min()) - range_color = [locations[self.weight].min() - offset, locations[self.weight].max() + 2*offset] + offset = 0.1 * (locations[self.weight].max() - locations[self.weight].min()) + range_color = [locations[self.weight].min() - offset, locations[self.weight].max() + 2 * offset] format_weight = self.weight if len(format_weight) > 1: @@ -333,7 +336,7 @@ def generate_choropleth(self): range_color=range_color, labels={self.weight: format_weight}) - fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) + fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) fig.update_layout(coloraxis_colorbar=dict( orientation='h', yanchor='top', 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 00a202a..0000000 --- a/pages/components/footer.py +++ /dev/null @@ -1,29 +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/logs.py b/pages/components/logs.py index 295e234..9916f0d 100644 --- a/pages/components/logs.py +++ b/pages/components/logs.py @@ -1,5 +1,6 @@ import streamlit as st + def display_traceback_file(tb_text, trace_type): fname = f'{trace_type}_traceback_file' n_lines = 20 @@ -11,5 +12,5 @@ def display_traceback_file(tb_text, trace_type): st.write(f'End of `{fname}`:') st.code(display_lines) fname += '.txt' - st.download_button(label=f'Download', data=tb_text, file_name=fname, + st.download_button(label='Download', data=tb_text, file_name=fname, key=f'{fname}_download_button') diff --git a/pages/components/model_details.py b/pages/components/model_details.py new file mode 100644 index 0000000..f8de134 --- /dev/null +++ b/pages/components/model_details.py @@ -0,0 +1,151 @@ +"""Schema-driven display of a model's settings (`model_settings.json`).""" +import json + +import pandas as pd +import streamlit as st + +from modules import schemas +from modules.schemas import CATEGORICAL_MODEL_SETTINGS, PARAMETER_TYPES, PERSPECTIVE_LABELS + + +def _fmt(value): + if isinstance(value, (list, tuple)): + return ', '.join(f'`{v}`' for v in value) if value else '—' + if isinstance(value, dict): + return f'`{json.dumps(value)}`' + if value is None or value == '': + return '—' + return f'`{value}`' if not isinstance(value, str) or ' ' not in value else value + + +def _field(label, value, help=None): + left, right = st.columns([0.3, 0.7]) + left.markdown(f'**{label}**', help=help) + right.markdown(_fmt(value)) + + +def model_overview(model, settings): + st.markdown(settings.get('description') or ':grey[No description provided.]') + + _field('Supplier', model.get('supplier_id')) + _field('Model', model.get('model_id')) + _field('Version', model.get('version_id')) + _field('Run mode', model.get('run_mode')) + _field('Settings version', settings.get('version')) + + default_samples = schemas.model_property('model_default_samples') + _field(schemas.title(default_samples, 'Default samples'), settings.get('model_default_samples'), + default_samples.get('description')) + + ms = settings.get('model_settings', {}) + perspectives = ms.get('valid_output_perspectives') + entry = schemas.model_settings_property('valid_output_perspectives') + _field(schemas.title(entry, 'Output perspectives'), + [PERSPECTIVE_LABELS.get(p, p) for p in perspectives] if perspectives else 'All', + entry.get('description')) + + data_settings = settings.get('data_settings', {}) + ds_schema = schemas.model_property('data_settings').get('properties', {}) + for key, value in data_settings.items(): + entry = ds_schema.get(key, {}) + _field(schemas.title(entry, key), value, entry.get('description')) + + +def model_perils(settings): + perils = settings.get('lookup_settings', {}).get('supported_perils') + if not perils: + st.caption('The model does not list its supported perils.') + return + df = pd.DataFrame(perils).rename(columns={'id': 'Peril code', 'desc': 'Description', + 'peril_correlation_group': 'Correlation group'}) + st.dataframe(df, hide_index=True) + + +def model_options(settings): + """Categorical selectors (event set, footprint set, ...) and their options.""" + ms = settings.get('model_settings', {}) + found = False + for key in CATEGORICAL_MODEL_SETTINGS: + if key not in ms: + continue + found = True + option = ms[key] + entry = schemas.model_settings_property(key) + with st.container(border=True): + st.markdown(f"**{option.get('name') or schemas.title(entry, key)}**", + help=option.get('tooltip') or entry.get('description')) + if option.get('desc'): + st.caption(option['desc']) + options = pd.DataFrame(option.get('options', [])) + if not options.empty: + options.insert(0, 'Default', options['id'] == option.get('default')) + options = options.rename(columns={'id': 'ID', 'desc': 'Description'}) + st.dataframe(options, hide_index=True) + if not found: + st.caption('The model has no selectable event, footprint or vulnerability sets.') + + +def model_parameters(settings): + """User-settable model parameters, grouped as the model defines.""" + ms = settings.get('model_settings', {}) + rows = [] + for key, kind in PARAMETER_TYPES.items(): + for p in ms.get(key, []): + if p.get('visible') is False: + continue + row = { + 'Parameter': p.get('name'), + 'Description': p.get('desc'), + 'Type': kind, + 'Default': json.dumps(p.get('default')) if isinstance(p.get('default'), (list, dict)) else p.get('default'), + 'Range': f"{p['min']} – {p['max']}" if 'min' in p and 'max' in p else None, + 'Options': ', '.join(str(o.get('id', o)) for o in p.get('options', [])) or None, + 'Used for': p.get('used_for'), + 'Editable': p.get('editable', True), + } + rows.append(row) + + if not rows: + st.caption('The model has no additional parameters.') + return + + df = pd.DataFrame(rows).astype({'Default': 'string'}) + df = df.dropna(axis='columns', how='all') + + groups = sorted(ms.get('parameter_groups', []), key=lambda g: g.get('priority_id', 0)) + grouped = set() + for group in groups: + members = [n for n in group.get('presentation_order', []) if n in set(df['Parameter'])] + if not members: + continue + grouped.update(members) + st.markdown(f"**{group.get('desc') or group.get('name')}**", help=group.get('tooltip')) + st.dataframe(df.set_index('Parameter').loc[members].reset_index(), hide_index=True) + + rest = df[~df['Parameter'].isin(grouped)] + if not rest.empty: + if grouped: + st.markdown('**Other parameters**') + st.dataframe(rest, hide_index=True) + + +def model_details(model, settings): + if not settings: + st.warning('No model settings have been registered for this model.') + return + + overview, options, parameters, perils, raw = st.tabs( + ['Overview', 'Run options', 'Parameters', 'Perils', 'Settings JSON']) + with overview: + model_overview(model, settings) + with options: + model_options(settings) + with parameters: + model_parameters(settings) + with perils: + model_perils(settings) + with raw: + st.json(settings, expanded=2) + st.download_button('Download model_settings.json', json.dumps(settings, indent=2), + file_name=f"{model.get('model_id', 'model')}_model_settings.json", + key=f"download_model_settings_{model['id']}") diff --git a/pages/components/output.py b/pages/components/output.py index fca888b..6c547a8 100644 --- a/pages/components/output.py +++ b/pages/components/output.py @@ -4,13 +4,122 @@ import logging import plotly.express as px import plotly.graph_objects as go -from math import log10 from pages.components.display import DataframeView, MapView from pages.components.common import PERSPECTIVES_MAP +from modules.oed import has_coordinates logger = logging.getLogger(__name__) +# ORD EPCalc codes, in the order they are offered (first is the default) +EP_CALC_LABELS = { + 2: 'Full uncertainty', + 1: 'Mean damage ratio (MeanDR)', + 4: 'Mean sample', + 3: 'Per-sample mean', +} + + +# ORD special sample indices (sidx) - see oasislmf.pytools.common.event_stream +MEAN_SIDX = -1 # analytical (numerically integrated) mean loss +AFFECTED_RISKS_SIDX = -4 # number of affected risks - not a loss +MAX_LOSS_SIDX = -5 # maximum sampled loss (only with the "all sidx" option) + +SAMPLE_MEAN = 'Mean of samples' +ANALYTICAL_MEAN = 'Analytical mean (sidx -1)' +MAX_SAMPLED_LOSS = 'Maximum sampled loss (sidx -5)' + + +def sample_mean(df, n_samples): + """Mean loss over the samples for each row key in a sample table (SELT/SPLT). + + Samples with zero loss have no row, so the mean is the sum of the sampled + losses divided by the number of samples (not the number of rows). + """ + samples = df[df['SampleId'] > 0] + keys = [c for c in samples.columns if c not in ('SampleId', 'Loss', 'ImpactedExposure')] + agg = {'Loss': 'sum'} + if 'ImpactedExposure' in samples.columns: + agg['ImpactedExposure'] = 'max' + result = samples.groupby(keys, as_index=False, observed=True).agg(agg) + result['Loss'] = result['Loss'] / n_samples + result.insert(keys.index('SummaryId') + 1 if 'SummaryId' in keys else 0, 'SampleId', 0) + return result[[c for c in df.columns if c in result.columns]] + + +def sample_selector(df, vis, key): + """Choose which samples of a SELT/SPLT to show; returns the filtered rows.""" + sample_ids = set(df['SampleId'].unique().tolist()) + positive = sorted(sid for sid in sample_ids if sid > 0) + n_samples = getattr(vis, 'number_of_samples', None) or (max(positive) if positive else 1) + + options = [SAMPLE_MEAN] if positive else [] + if MEAN_SIDX in sample_ids: + options.append(ANALYTICAL_MEAN) + if MAX_LOSS_SIDX in sample_ids: + options.append(MAX_SAMPLED_LOSS) + options += positive + + choice = st.selectbox( + 'Samples:', options=options, key=key, + format_func=lambda o: f'Sample {o}' if isinstance(o, int) else o, + help=f'Mean of samples averages the {n_samples} sampled losses. The analytical mean is the ' + 'model\'s numerically integrated mean (ORD sample index -1).') + + if choice == SAMPLE_MEAN: + return sample_mean(df, n_samples) + if choice == ANALYTICAL_MEAN: + return df[df['SampleId'] == MEAN_SIDX] + if choice == MAX_SAMPLED_LOSS: + return df[df['SampleId'] == MAX_LOSS_SIDX] + 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) + return sorted(values, key=lambda v: order.index(v) if v in order else len(order)) + def summarise_locations(locations): summary = pd.Series() @@ -32,6 +141,7 @@ def summarise_locations(locations): def summarise_model_settings(model_settings): return pd.DataFrame([pd.Series(model_settings)]) + def summarise_analysis_settings(analysis_settings, model_settings=None): summary = {} @@ -58,6 +168,7 @@ def summarise_analysis_settings(analysis_settings, model_settings=None): return pd.DataFrame([summary]) + def summarise_output_settings(analysis_settings): perspectives = ['gul', 'il', 'ri'] active_perspectives = [p for p in perspectives if analysis_settings.get(f'{p}_output', False)] @@ -115,9 +226,9 @@ def summarise_output_settings(analysis_settings): return pd.DataFrame(summary, index=active_perspectives) + def summarise_summary_levels(summary_settings): - ''' - Take a list of summary sets from the analysis settings and produce a list of summaries of each level. + """Take a list of summary sets from the analysis settings and produce a list of summaries of each level. Returns List[dict] where each dict corresponds to a single summary level with @@ -126,12 +237,12 @@ def summarise_summary_levels(summary_settings): - `ord_output` - list of ord outputs - `legacy_outputs` - list of legacy outputs - `oed_fields` - list of oed group fields - ''' + """ return [summarise_summary_level(level) for level in summary_settings] + def summarise_summary_level(summary_level_settings): - '''Summarise a single summary set from the analysis settings. - ''' + """Summarise a single summary set from the analysis settings.""" curr_summary = {} # Handle ord outputs @@ -151,10 +262,10 @@ def summarise_summary_level(summary_level_settings): for opt in valid_options: if ord_output.get(opt, False): - ord_outputs_list.append(opt) + ord_outputs_list.append(opt) curr_summary['ord_output'] = ord_outputs_list - ## Handle legacy outputs + # Handle legacy outputs output_options = [ 'eltcalc', @@ -186,6 +297,7 @@ def summarise_summary_level(summary_level_settings): curr_summary['level_id'] = summary_level_settings['id'] return curr_summary + def summarise_inputs(locations=None, analysis_settings=None, model_settings=None, title_prefix='##'): if locations is None and analysis_settings is None: st.info('No locations or analysis settings.') @@ -224,16 +336,17 @@ def summarise_inputs(locations=None, analysis_settings=None, model_settings=None def ViewSummarySettings(summary_settings, key=None, selectable=False): - ''' - Display the summary settings for a single perspective as a selectable dataframe. + """Display the summary settings for a single perspective as a selectable dataframe. Args: summary_settings (list[dict]): List of summary settings to display. + key (str): Widget key for the table. + selectable (bool): Whether a summary level can be selected. Returns: (int) `id` for selected summary settings. - ''' + """ summaries = summarise_summary_levels(summary_settings) summaries = pd.DataFrame(summaries) cols = ['level_id', 'ord_output', 'legacy_output', 'oed_fields'] @@ -247,8 +360,7 @@ def ViewSummarySettings(summary_settings, key=None, selectable=False): def show_settings(settings_list): - """ - Displays abstract settings list. Settings are dict like objects with a + """Displays abstract settings list. Settings are dict like objects with a `parameter` specifying the setting parameter name and `value` which is a display of the value of the setting parameter. """ @@ -265,8 +377,7 @@ def show_settings(settings_list): def model_summary(model, model_settings, detail_level="full"): - """ - Create a summary view of the model settings for the selected model. + """Create a summary view of the model settings for the selected model. Currently supports the following fields: @@ -301,10 +412,10 @@ def model_summary(model, model_settings, detail_level="full"): "minimal" only displays the model `Name`, `Supplier` and `Description`. """ settings_list = [ - {'parameter': 'Name', 'value': model.get('model_name', model.get('model_id', ''))}, - {'parameter': 'Supplier', 'value': model.get('supplier_id', '')}, - {'parameter': 'Description', 'value': model_settings.get('description', '')}, - ] + {'parameter': 'Name', 'value': model.get('model_name', model.get('model_id', ''))}, + {'parameter': 'Supplier', 'value': model.get('supplier_id', '')}, + {'parameter': 'Description', 'value': model_settings.get('description', '')}, + ] if detail_level == "minimal": show_settings(settings_list) @@ -322,7 +433,7 @@ def model_summary(model, model_settings, detail_level="full"): settings_list.append({'parameter': 'Event Set Options', 'value': es_options_view}) if _model_settings["event_set"].get("default", None): settings_list.append({'parameter': 'Event Set Default', - 'value': f'`{_model_settings["event_set"]["default"]}`'}) + 'value': f'`{_model_settings["event_set"]["default"]}`'}) if "event_occurrence_id" in _model_settings: eo_options = _model_settings["event_occurrence_id"].get('options', []) @@ -333,7 +444,7 @@ def model_summary(model, model_settings, detail_level="full"): settings_list.append({'parameter': 'Event Occurrence ID Options', 'value': eo_options_view}) if _model_settings["event_occurrence_id"].get("default", None): settings_list.append({'parameter': 'Event Occurrence ID Default', - 'value': f'`{_model_settings["event_occurrence_id"]["default"]}`'}) + 'value': f'`{_model_settings["event_occurrence_id"]["default"]}`'}) if "lookup_settings" in model_settings: lookup_settings = model_settings.get("lookup_settings") @@ -366,6 +477,7 @@ def model_summary(model, model_settings, detail_level="full"): show_settings(settings_list) + def elt_group_fields(df, group_fields, agg_dict=None, categorical_cols=[]): if agg_dict is None: agg_dict = {} @@ -404,8 +516,9 @@ def oed_fields_group(oed_fields, key_prefix=None, selection_mode='multi'): return group_fields -def elt_ord_table(result, perspective, oed_fields = None, key_prefix=None, - order_cols=None, data_cols=None, name_map = {}, + +def elt_ord_table(result, perspective, oed_fields=None, key_prefix=None, + order_cols=None, data_cols=None, name_map={}, event_id='EventId', additional_cols=None, selectable=False): table_df = result if key_prefix is None: @@ -424,7 +537,7 @@ def elt_ord_table(result, perspective, oed_fields = None, key_prefix=None, if order_cols: if len(order_cols) > 1: order_col = st.radio('Sort By: ', options=order_cols, index=0, horizontal=True, - format_func = lambda x: name_map.get(x, x), + format_func=lambda x: name_map.get(x, x), key=f'{key_prefix}_elt_ord_order_col') else: order_col = order_cols[0] @@ -435,8 +548,8 @@ def elt_ord_table(result, perspective, oed_fields = None, key_prefix=None, with st.popover("OED Filters", width='stretch'): for oed_field in oed_fields: options = table_df[oed_field].unique() - oed_filter = st.multiselect(f"{oed_field} Filter:", options, - key=f'{key_prefix}_{oed_field}_elt_filter') + oed_filter = st.multiselect(f"{oed_field} Filter:", options, + key=f'{key_prefix}_{oed_field}_elt_filter') if oed_filter: table_df = table_df[table_df[oed_field].isin(oed_filter)] @@ -446,7 +559,7 @@ def elt_ord_table(result, perspective, oed_fields = None, key_prefix=None, for c in data_cols: table_view.column_config[c] = st.column_config.NumberColumn(name_map.get(c, c), - format='%.2f') + format='%.2f') for c in oed_fields: table_view.column_config[c] = st.column_config.ListColumn(name_map.get(c, c)) for c in additional_cols: @@ -459,6 +572,7 @@ def elt_ord_table(result, perspective, oed_fields = None, key_prefix=None, return table_df, selected return table_df + def eltcalc_table(eltcalc_result, perspective, oed_fields=None, show_cols=None, key_prefix=None): if key_prefix is None: @@ -482,7 +596,6 @@ def eltcalc_table(eltcalc_result, perspective, oed_fields=None, show_cols=None, group_fields = type_col + group_fields table_df = elt_group_fields(eltcalc_result, group_fields, categorical_cols=oed_fields) - cols = type_col + oed_fields + show_cols table_df = table_df[cols] @@ -495,7 +608,7 @@ def eltcalc_table(eltcalc_result, perspective, oed_fields=None, show_cols=None, st.error('Output too large, try grouping') logger.error(f'eltcalc view df size: {df_memory}') else: - table_view = DataframeView(table_df, display_cols = cols) + table_view = DataframeView(table_df, display_cols=cols) for col in show_cols: table_view.column_config[col] = st.column_config.NumberColumn(col, format='%.2f') for c in oed_fields: @@ -506,11 +619,10 @@ def eltcalc_table(eltcalc_result, perspective, oed_fields=None, show_cols=None, table_view.display() + def eltcalc_map(map_df, locations, oed_fields=[], map_type=None, intensity_col='mean', group_fields=None): - ''' - Generate MapView of output of eltcalc. Either `heatmap` or `choropleth` depending on portfolio. - ''' + """Generate MapView of output of eltcalc. Either `heatmap` or `choropleth` depending on portfolio.""" if group_fields is None: group_fields = [] @@ -555,28 +667,28 @@ 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. - ''' - if loc_df is None: - return False - if not set(['Latitude', 'Longitude']).issubset(loc_df.columns): - return False - lat_long = loc_df[['Latitude', 'Longitude']] - if (lat_long == lat_long.iloc[0]).all(axis=None): - return False +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 'LocNumber' in oed_fields and valid_locations(locations): + return 'heatmap' + if 'CountryCode' in oed_fields: + return 'choropleth' + return None + - 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 def generate_eltcalc_fragment(perspective, output, - table = True, map = False, locations = None): - ''' - Generate an `eltcalc` visualisation. Currently supports the `table` + table=True, map=False, locations=None): + """Generate an `eltcalc` visualisation. Currently supports the `table` and `map` visualisation. For `map` visualisation, a `locations` dataframe is required. @@ -584,7 +696,8 @@ def generate_eltcalc_fragment(perspective, output, ---------- perspective : str Chosen perspective `gul`, `il` or `ri`. - vis_interface : OutputInterface + output : OutputInterface + Interface to the analysis output files. table : bool If `True` displays table view. map : bool @@ -592,14 +705,15 @@ def generate_eltcalc_fragment(perspective, output, locations : DataFrame DataFrame representing `locations.csv` file. Required for `map` view. - ''' + """ oed_fields = output.oed_fields.get(perspective) or [] - eltcalc_result = output.get(1, perspective, 'eltcalc') + 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: @@ -609,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) @@ -624,9 +730,10 @@ def generate_eltcalc_fragment(perspective, output, with tab: eltcalc_table(eltcalc_result, perspective, oed_fields) + @st.fragment def generate_melt_fragment(p, vis, locations=None): - data_df = vis.get(1, p, 'elt_moment') + data_df = vis.get(vis.summary_level(p), p, 'elt_moment') oed_fields = vis.oed_fields.get(p) or [] # Type filter @@ -638,53 +745,40 @@ 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') - map_event_container = st.container() - - 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]) with tabs[0]: data_df, selected = elt_ord_table(data_df, perspective=p, oed_fields=oed_fields, - order_cols=['MeanLoss','MeanImpactedExposure', - 'MaxImpactedExposure'], - data_cols=['MeanLoss','MeanImpactedExposure', - 'MaxImpactedExposure'], - key_prefix=f'melt_{p}', - selectable='multi') + order_cols=['MeanLoss', 'MeanImpactedExposure', + 'MaxImpactedExposure'], + data_cols=['MeanLoss', 'MeanImpactedExposure', + 'MaxImpactedExposure'], + key_prefix=f'melt_{p}', + selectable='multi') selected_events = [] 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)] with tabs[1]: if len(selected_events) > 0: data = pd.DataFrame( - {'EventId':[selected_events] } + {'EventId': [selected_events]} ) st.dataframe(data, - column_config= {'EventId' : st.column_config.ListColumn('Mapped EventIds')}, + column_config={'EventId': st.column_config.ListColumn('Mapped EventIds')}, hide_index=True) loss_col = st.radio('Intensity Column:', ['MeanLoss', 'MeanImpactedExposure', 'MaxImpactedExposure'], index=0, horizontal=True, key=f'melt_{p}_intensity_col') @@ -694,7 +788,7 @@ def generate_melt_fragment(p, vis, locations=None): @st.fragment def generate_qelt_fragment(p, vis, locations=None): - data_df = vis.get(1, p, 'elt_quantile') + data_df = vis.get(vis.summary_level(p), p, 'elt_quantile') oed_fields = vis.oed_fields.get(p) or [] options = data_df['Quantile'].unique() @@ -703,37 +797,26 @@ 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') - map_event_container = st.container() - - 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]) with tabs[0]: table_df, selected = elt_ord_table(data_df, perspective=p, - oed_fields=oed_fields, key_prefix=f'qelt_{p}', - order_cols=['Loss'], data_cols=['Loss'], - selectable="multi") + oed_fields=oed_fields, key_prefix=f'qelt_{p}', + order_cols=['Loss'], data_cols=['Loss'], + selectable="multi") selected_events = [] 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)] @@ -741,10 +824,10 @@ def generate_qelt_fragment(p, vis, locations=None): with tabs[1]: if len(selected_events) > 0: data = pd.DataFrame( - {'EventId':[selected_events] } + {'EventId': [selected_events]} ) st.dataframe(data, - column_config= {'EventId' : st.column_config.ListColumn('Mapped EventIds')}, + column_config={'EventId': st.column_config.ListColumn('Mapped EventIds')}, hide_index=True) eltcalc_map(map_df, locations, oed_fields, map_type, intensity_col='Loss') @@ -753,8 +836,7 @@ def generate_qelt_fragment(p, vis, locations=None): @st.fragment def generate_selt_fragment(p, vis, locations=None): - ''' - Generate a `elt_sample` (SELT) visualisation. This is the ORD + """Generate a `elt_sample` (SELT) visualisation. This is the ORD counterpart of the legacy `eltcalc` output, but reports the raw per-sample loss for each event/summary combination instead of Analytical/Sample summary statistics. Supports `table` and `map` @@ -770,47 +852,30 @@ def generate_selt_fragment(p, vis, locations=None): present if the analysis was run with ktools' "all sidx" option) is the maximum sampled loss. Real per-sample draws use positive `SampleId` values (1..N). - ''' - MEAN_SIDX = -1 - - data_df = vis.get(1, p, 'elt_sample') + """ + data_df = vis.get(vis.summary_level(p), p, 'elt_sample') oed_fields = vis.oed_fields.get(p) or [] - aggregate_label = 'Mean (All Samples)' - sample_options = sorted(sid for sid in data_df['SampleId'].unique().tolist() if sid > 0) - sample_filter = st.selectbox('Sample Filter:', options=[aggregate_label] + sample_options, - key=f'selt_{p}_sample_filter') - - if sample_filter == aggregate_label: - data_df = data_df[data_df['SampleId'] == MEAN_SIDX] - else: - data_df = data_df[data_df['SampleId'] == sample_filter] + 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]) with tabs[0]: data_df, selected = elt_ord_table(data_df, perspective=p, oed_fields=oed_fields, - order_cols=['Loss'], data_cols=['Loss'], - key_prefix=f'selt_{p}', selectable='multi') + order_cols=['Loss'], data_cols=['Loss'], + key_prefix=f'selt_{p}', selectable='multi') selected_events = [] 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)] @@ -829,7 +894,8 @@ def generate_selt_fragment(p, vis, locations=None): @st.fragment def generate_aalcalc_fragment(p, vis): - result = vis.get(1, p, 'aalcalc') + 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 @@ -845,26 +911,32 @@ def generate_aalcalc_fragment(p, vis): group_field = ['type'] if breakdown_field: - result[breakdown_field] = result[breakdown_field].astype(str) group_field += [breakdown_field] result = result.loc[:, group_field + ['mean']] - result = result.groupby(group_field, as_index=False).agg({'mean': 'sum'}) + result = result.groupby(group_field, as_index=False, dropna=False).agg({'mean': 'sum'}) + if breakdown_field: + # Group on the raw values so numeric fields sort numerically, then + # label each bar with its own value + result[breakdown_field] = result[breakdown_field].astype(str) - graph = px.bar(result, x='type', y='mean', color=breakdown_field, - labels = {'type': 'Type', 'mean': 'Mean'}, - color_discrete_sequence= px.colors.sequential.RdBu) + graph = px.bar(result, x=breakdown_field or 'type', y='mean', + labels={'type': 'Type', 'mean': 'Mean'}, + color_discrete_sequence=px.colors.sequential.RdBu) + graph.update_xaxes(type='category') if breakdown_field_invalid: st.error("Too many values in group field.") st.plotly_chart(graph, width='stretch') + @st.fragment def generate_alt_fragment(p, vis, output_type='alt_meanonly'): - result = vis.get(1, p, output_type) + 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 @@ -880,45 +952,73 @@ def generate_alt_fragment(p, vis, output_type='alt_meanonly'): group_field = [type_field] if breakdown_field: - result[breakdown_field] = result[breakdown_field].astype(str) group_field += [breakdown_field] result = result.loc[:, group_field + [mean_field]] - result = result.groupby(group_field, as_index=False).agg({mean_field: 'sum'}) + result = result.groupby(group_field, as_index=False, dropna=False).agg({mean_field: 'sum'}) + if breakdown_field: + # Group on the raw values so numeric fields sort numerically, then + # label each bar with its own value + result[breakdown_field] = result[breakdown_field].astype(str) 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, - labels = {type_field: type_formatted, mean_field: mean_formatted}, - color_discrete_sequence= px.colors.sequential.RdBu) + 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) + graph.update_xaxes(type='category') if breakdown_field_invalid: st.error("Too many values in group field.") st.plotly_chart(graph, width='stretch', key=f'{output_type}_{p}_graph') + @st.fragment def generate_alct_fragment(p, vis): - ''' - Generate an `alct_convergence` (ALCT) visualisation. ALCT is a - diagnostic table reporting sample-convergence statistics for the ALT - output and has no direct legacy analogue, so it is rendered as a - plain filterable/sortable table rather than a chart. - ''' - result = vis.get(1, p, 'alct_convergence') + """Generate an `alct_convergence` (ALCT) visualisation: how the period + average loss and its confidence interval converge as the number of + samples grows, followed by the key convergence statistics. + """ + result = vis.get(vis.summary_level(p), p, 'alct_convergence') oed_fields = vis.oed_fields.get(p) or [] - selected_group = None - if oed_fields and len(oed_fields) > 0: + group_col = 'SummaryId' + if oed_fields: selected_group = st.pills('Breakdown OED Field: ', options=oed_fields, key=f'alct_{p}_group_field_pills') + if selected_group: + group_col = selected_group + result[group_col] = result[group_col].astype(str) - if selected_group: - result[selected_group] = result[selected_group].astype(str) + groups = result[group_col].unique().tolist() + if len(groups) > 5: + groups = st.multiselect(f'{group_col} values:', options=groups, default=groups[:5], + key=f'alct_{p}_group_filter') + plot_df = result[result[group_col].isin(groups)].sort_values('SampleSize') - table_view = DataframeView(result) - numeric_cols = result.select_dtypes(include='number').columns - for c in numeric_cols: - table_view.column_config[c] = st.column_config.NumberColumn(c, format='%.4f') + fig = go.Figure() + for group in groups: + g = plot_df[plot_df[group_col] == group] + # A single sample has no confidence interval (reported as 0) + name = f'{group_col} {group}' if group_col == 'SummaryId' else str(group) + if {'LowerCI', 'UpperCI'} <= set(g.columns): + ci = g[g['SampleSize'] > 1] + fig.add_trace(go.Scatter(x=list(ci['SampleSize']) + list(ci['SampleSize'][::-1]), + y=list(ci['UpperCI']) + list(ci['LowerCI'][::-1]), + fill='toself', opacity=0.2, line={'width': 0}, hoverinfo='skip', + showlegend=False, legendgroup=name)) + fig.add_trace(go.Scatter(x=g['SampleSize'], y=g['MeanLoss'], mode='lines+markers', name=name, + legendgroup=name)) + fig.update_layout(xaxis_title='Number of samples', yaxis_title='Mean loss', + margin={'t': 20}, legend_title_text=group_col) + st.plotly_chart(fig) + st.caption('Shaded bands show the confidence interval of the mean loss.') + + table_cols = [group_col, 'SampleSize', 'MeanLoss', 'LowerCI', 'UpperCI', 'StandardError', 'RelativeError'] + table_view = DataframeView(result[[c for c in table_cols if c in result]].copy()) + for c in ['MeanLoss', 'LowerCI', 'UpperCI', 'StandardError']: + table_view.column_config[c] = st.column_config.NumberColumn(c, format='%.2f') + table_view.column_config['RelativeError'] = st.column_config.NumberColumn('RelativeError', format='%.4f') table_view.display() @@ -931,7 +1031,7 @@ def generate_leccalc_fragment(p, vis, lec_outputs): else: analysis_type = '_'.join(option.split('_')[:-1]) loss_type = option.split('_')[-1] - result = vis.get(1, p, 'leccalc', analysis_type = analysis_type, loss_type = loss_type) + result = vis.get(vis.summary_level(p), p, 'leccalc', analysis_type=analysis_type, loss_type=loss_type) oed_fields = vis.oed_fields.get(p) or [] selected_group = None @@ -942,14 +1042,14 @@ def generate_leccalc_fragment(p, vis, lec_outputs): selected_group = 'summary_id' if analysis_type == "wheatsheaf": - result_plot = result.groupby(["summary_id", "return_period"] + oed_fields, as_index=False).agg(min_loss = ("loss", "min"), - max_loss = ("loss", "max"), - mean_loss = ("loss", "mean")) + result_plot = result.groupby(["summary_id", "return_period"] + oed_fields, as_index=False).agg(min_loss=("loss", "min"), + max_loss=("loss", "max"), + mean_loss=("loss", "mean")) result_plot = result_plot[[selected_group, "return_period", "mean_loss", "max_loss", "min_loss"]] result_plot = result_plot.groupby([selected_group, 'return_period'], as_index=False).agg({'mean_loss': 'sum', - 'max_loss': 'sum', - 'min_loss': 'sum', + 'max_loss': 'sum', + 'min_loss': 'sum', }) result_plot = result_plot.sort_values(by=["return_period", "mean_loss"], ascending=[True, False]) @@ -959,30 +1059,29 @@ def generate_leccalc_fragment(p, vis, lec_outputs): as_index=False).agg({'loss': 'sum'}) result_plot = result_plot.sort_values(by=['return_period', 'loss'], ascending=[True, False]) - log_x = log10(result_plot['return_period'].max()) - log10(result_plot['return_period'].min()) > 2 + log_x = False # EP curves are read on a linear return period axis unique_group = result_plot[selected_group].unique().tolist() if len(unique_group) > 5: filter_group = st.multiselect(f'Filtered {selected_group} Values:', - options = unique_group, - default = unique_group[:5], + options=unique_group, + default=unique_group[:5], key=f'leccalc_{p}_group_filter') result_plot = result_plot[result_plot[selected_group].isin(filter_group)] - if analysis_type == "wheatsheaf": fig = go.Figure() for item in result_plot[selected_group].unique().tolist(): result_item = result_plot[result_plot[selected_group] == item] fig.add_trace(go.Scatter( - x = result_item["return_period"], - y = result_item["mean_loss"], - error_y = {'array': result_item["max_loss"], - 'arrayminus': result_item["min_loss"]}, - name = item)) + x=result_item["return_period"], + y=result_item["mean_loss"], + error_y={'array': result_item["max_loss"], + 'arrayminus': result_item["min_loss"]}, + name=item)) fig.update_layout( - xaxis = dict(title = dict(text = 'Return Period')), - yaxis = dict(title = dict(text = 'Loss')), + xaxis=dict(title=dict(text='Return Period')), + yaxis=dict(title=dict(text='Loss')), legend_title_text=selected_group, showlegend=True ) @@ -992,20 +1091,20 @@ def generate_leccalc_fragment(p, vis, lec_outputs): else: fig = px.line(result_plot, x='return_period', y='loss', color=selected_group, line_dash='type', markers=False, - labels = {'return_period': 'Return Period', 'loss': - 'Loss', 'type': 'Type', - selected_group: selected_group}, + labels={'return_period': 'Return Period', 'loss': + 'Loss', 'type': 'Type', + selected_group: selected_group}, line_group='type', log_x=log_x) st.plotly_chart(fig) + def generate_leccalc_comparison_fragment(perspective, outputs, names=None, output_type='leccalc', lec_outputs=None, filter_specs=None, return_period_col='return_period', loss_col='loss', group_col_default='summary_id'): - ''' - Compare an EP-curve output across two analyses: fetch (for the + """Compare an EP-curve output across two analyses: fetch (for the legacy `leccalc` output, only after the user picks which analysis_type/loss_type file via a "Select Output" pills widget - a single ORD `ept` file already holds every EPType/EPCalc @@ -1021,6 +1120,12 @@ def generate_leccalc_comparison_fragment(perspective, outputs, names=None, Parameters ---------- + perspective : str + Perspective to compare (`gul`, `il`, `ri`). + outputs : List[OutputInterface] + Output interfaces for the analyses being compared. + names : List[str] + Display names for the analyses. output_type : str `OutputInterface` output type to fetch: `leccalc` (default) or `ept`. @@ -1044,7 +1149,7 @@ def generate_leccalc_comparison_fragment(perspective, outputs, names=None, group_col_default : str Column to group by when no OED field is chosen (`summary_id` for legacy, `SummaryId` for ORD). - ''' + """ if len(outputs) > 2: st.error('Maximum 2 outputs for comparison') logger.error(f'Too many outputs for {output_type} comparison plot.\nOutputs: {outputs}') @@ -1085,9 +1190,9 @@ def format_lec_options(opt): analysis_type = '_'.join(option.split('_')[:-1]) loss_type = option.split('_')[-1] - results = [o.get(1, perspective, 'leccalc', analysis_type = analysis_type, loss_type = loss_type) for o in outputs] + results = [o.get(o.summary_level(perspective), perspective, 'leccalc', analysis_type=analysis_type, loss_type=loss_type) for o in outputs] else: - results = [o.get(1, perspective, output_type) for o in outputs] + results = [o.get(o.summary_level(perspective), perspective, output_type) for o in outputs] for spec in filter_specs: col = spec['col'] @@ -1095,6 +1200,12 @@ def format_lec_options(opt): for r in results: values.update(r[col].unique().tolist()) + 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, @@ -1115,7 +1226,7 @@ def format_lec_options(opt): name_map = {i: names[i] for i in range(len(names))} selected_analysis = st.segmented_control('Analysis Filter:', options=name_map.keys(), - format_func = lambda x: name_map.get(x, x), + format_func=lambda x: name_map.get(x, x), key=f'{perspective}_{output_type}_name_filter') linestyles = ['dash', None] @@ -1132,9 +1243,7 @@ def format_lec_options(opt): result_plot = result_plot.sort_values(by=[return_period_col, loss_col], ascending=[True, False]) results_plot.append(result_plot) - log_x = [log10(result_plot[return_period_col].max()) - log10(result_plot[return_period_col].min()) > 2 - for result_plot in results_plot] - log_x = any(log_x) + log_x = False # EP curves are read on a linear return period axis unique_group = [] for result_plot in results_plot: @@ -1144,14 +1253,13 @@ def format_lec_options(opt): graphed_group_fields = unique_group if len(unique_group) > 5: filter_group = st.multiselect(f'Filtered {selected_group} Values:', - options = unique_group, - default = unique_group[:5], + options=unique_group, + default=unique_group[:5], key=f'{output_type}_comparison_{perspective}_group_filter') for i in range(len(results_plot)): results_plot[i] = results_plot[i][results_plot[i][selected_group].isin(filter_group)] graphed_group_fields = filter_group - fig = go.Figure() colors = px.colors.qualitative.Plotly j = 0 @@ -1162,8 +1270,8 @@ def format_lec_options(opt): fig.add_trace(go.Scatter(x=curr_result[return_period_col], y=curr_result[loss_col], name=field, legendgroup=name, legendgrouptitle_text=name, line=dict(color=colors[i % len(colors)], dash=linestyles[j % 2]), - hovertemplate= hover_title + '
Return Period: %{x}'+ - '
Loss: %{y}', + hovertemplate=hover_title + '
Return Period: %{x}' + + '
Loss: %{y}', customdata=[f'{name}'])) j += 1 @@ -1176,11 +1284,11 @@ def format_lec_options(opt): st.plotly_chart(fig, key=f'{output_type}_comparison_{perspective}_graph') + @st.cache_data(show_spinner='Creating pltcalc bar') -def pltcalc_bar(result, selected_group=None, number_shown=10, date_id = False, +def pltcalc_bar(result, selected_group=None, number_shown=10, date_id=False, year='Year', month='Month', day='Day', loss='MeanLoss'): - ''' - Bar plot of pltcalc output ranked by loss in descending order by year. + """Bar plot of pltcalc output ranked by loss in descending order by year. Parameters ---------- @@ -1194,7 +1302,11 @@ def pltcalc_bar(result, selected_group=None, number_shown=10, date_id = False, If `True` then pltcalc produced data with a `date_id` column. Otherwise `occ_year`, `occ_month` and `occ_day` columns expected in `result`. - ''' + year, month, day : str + Names of the date columns used when `date_id` is `False`. + loss : str + Loss column to plot. + """ if not date_id: result[[year, month, day]] = result[[year, month, day]].astype(str) result[year] = result[year].str.zfill(result[year].str.len().max()) @@ -1235,13 +1347,14 @@ def pltcalc_bar(result, selected_group=None, number_shown=10, date_id = False, return fig + @st.fragment def generate_pltcalc_fragment(p, vis): - result = vis.get(1, p, 'pltcalc') + result = vis.get(vis.summary_level(p), p, 'pltcalc') oed_fields = vis.oed_fields.get(p) or [] selected_group = None - if oed_fields and len(oed_fields) > 0 : + if oed_fields and len(oed_fields) > 0: selected_group = st.pills('Grouped OED Field: ', options=oed_fields, key=f'pltcalc_{p}_group_field_pills') selected_group_invalid = False @@ -1251,10 +1364,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', @@ -1264,20 +1374,21 @@ def generate_pltcalc_fragment(p, vis): with st.spinner('Generating pltcalc...'): if set(date_cols.values()).issubset(result.columns): - fig = pltcalc_bar(result, selected_group, date_id=False, loss='mean', **date_cols) + fig = pltcalc_bar(result, selected_group, date_id=False, loss='mean', **date_cols) else: fig = pltcalc_bar(result, selected_group, date_id=True, loss='mean') st.plotly_chart(fig) if selected_group_invalid: st.error("Too many values in group field.") + @st.fragment def generate_mplt_fragment(p, vis): - result = vis.get(1, p, 'plt_moment') + result = vis.get(vis.summary_level(p), p, 'plt_moment') oed_fields = vis.oed_fields.get(p) or [] selected_group = None - if oed_fields and len(oed_fields) > 0 : + if oed_fields and len(oed_fields) > 0: selected_group = st.pills('Grouped OED Field: ', options=oed_fields, key=f'mplt_{p}_group_field_pills') selected_group_invalid = False @@ -1287,8 +1398,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] @@ -1311,13 +1422,14 @@ def generate_mplt_fragment(p, vis): st.error("Too many values in group field.") st.plotly_chart(fig) + @st.fragment def generate_qplt_fragment(p, vis): - result = vis.get(1, p, 'plt_quantile') + result = vis.get(vis.summary_level(p), p, 'plt_quantile') oed_fields = vis.oed_fields.get(p) or [] selected_group = None - if oed_fields and len(oed_fields) > 0 : + if oed_fields and len(oed_fields) > 0: selected_group = st.pills('Grouped OED Field: ', options=oed_fields, key=f'qplt_{p}_group_field_pills') selected_group_invalid = False @@ -1346,10 +1458,10 @@ def generate_qplt_fragment(p, vis): st.error("Too many values in group field.") st.plotly_chart(fig) + @st.fragment def generate_splt_fragment(p, vis): - ''' - Generate a `plt_sample` (SPLT) visualisation. This is the ORD + """Generate a `plt_sample` (SPLT) visualisation. This is the ORD counterpart of the legacy `pltcalc` output, reporting the raw per-sample period loss instead of Analytical/Sample statistics. Follows the same bar-chart pattern as `generate_mplt_fragment` and @@ -1362,10 +1474,8 @@ def generate_splt_fragment(p, vis): -1 is the model's analytically-integrated mean loss, not a recomputed average of this file's own sample rows. Real per-sample draws use positive `SampleId` values (1..N). - ''' - MEAN_SIDX = -1 - - result = vis.get(1, p, 'plt_sample') + """ + result = vis.get(vis.summary_level(p), p, 'plt_sample') oed_fields = vis.oed_fields.get(p) or [] selected_group = None @@ -1379,15 +1489,7 @@ def generate_splt_fragment(p, vis): elif selected_group: result[selected_group] = result[selected_group].astype(str) - aggregate_label = 'Mean (All Samples)' - sample_options = sorted(sid for sid in result['SampleId'].unique().tolist() if sid > 0) - sample_filter = st.selectbox('Sample Filter:', options=[aggregate_label] + sample_options, - key=f'splt_{p}_sample_filter') - - if sample_filter == aggregate_label: - result = result[result['SampleId'] == MEAN_SIDX] - else: - result = result[result['SampleId'] == sample_filter] + result = sample_selector(result, vis, key=f'splt_{p}_sample_filter') date_cols = { 'year': 'Year', @@ -1405,32 +1507,27 @@ def generate_splt_fragment(p, vis): @st.fragment def generate_ept_fragment(p, vis): - result = vis.get(1, p, 'ept') + result = vis.get(vis.summary_level(p), p, 'ept') ep_type_map = { - 1 : 'OEP', - 2 : 'OEP TVAR', - 3 : 'AEP', - 4 : 'AEP TVAR' + 1: 'OEP', + 2: 'OEP TVAR', + 3: 'AEP', + 4: 'AEP TVAR' } - ep_calc_map = { - 1 : 'MeanDR', - 2 : 'Full', - 3 : 'PerSampleMean', - 4 : 'MeanSample' - } + ep_calc_map = EP_CALC_LABELS type_options = result['EPType'].unique() if len(type_options) > 1: selected_type = st.radio('EP Curve Type: ', options=type_options, horizontal=True, - format_func= lambda x: ep_type_map.get(x, x), + format_func=lambda x: ep_type_map.get(x, x), key=f'ept_{p}_type_filter') result = result[result['EPType'] == selected_type] - calc_options = result['EPCalc'].unique() + calc_options = order_ep_calcs(result['EPCalc'].unique()) selected_calc = None if len(calc_options) > 1: @@ -1442,7 +1539,7 @@ def generate_ept_fragment(p, vis): oed_fields = vis.oed_fields.get(p) or [] selected_group = None - if oed_fields and len(oed_fields) > 0 : + if oed_fields and len(oed_fields) > 0: selected_group = st.pills('Grouped OED Field: ', options=oed_fields, key=f'ept_{p}_group_field_pills') if selected_group is None: @@ -1457,28 +1554,28 @@ def generate_ept_fragment(p, vis): unique_group = unique_group[selected_group].tolist() result = result.sort_values(by=['ReturnPeriod', 'Loss'], ascending=[True, False]) - log_x = log10(result['ReturnPeriod'].max()) - log10(result['ReturnPeriod'].min()) > 2 + log_x = False # EP curves are read on a linear return period axis all_selected = result[selected_group].unique().tolist() unique_group += [e for e in all_selected if e not in unique_group] if len(unique_group) > 5: filter_group = st.multiselect(f'Filtered {selected_group} Values:', - options = unique_group, - default = unique_group[:5], + options=unique_group, + default=unique_group[:5], key=f'ept_{p}_group_filter') result = result[result[selected_group].isin(filter_group)] fig = px.line(result, x='ReturnPeriod', y='Loss', color=selected_group, markers=False, - labels = {'ReturnPeriod': 'Return Period'}, + labels={'ReturnPeriod': 'Return Period'}, log_x=log_x) st.plotly_chart(fig) + @st.fragment def generate_psept_fragment(p, vis): - ''' - Generate a `psept` (Per Sample EPT) visualisation. This is the ORD + """Generate a `psept` (Per Sample EPT) visualisation. This is the ORD counterpart of the legacy `leccalc` `wheatsheaf`/per-sample EP curve output, plotting a return-period/loss curve per sample. Follows the same structure as `generate_ept_fragment`, with an added sample @@ -1494,22 +1591,22 @@ def generate_psept_fragment(p, vis): bars), so those special rows must be excluded rather than read - left in, -1's precomputed mean would be silently averaged in alongside the real samples as if it were one of them. - ''' - result = vis.get(1, p, 'psept') + """ + result = vis.get(vis.summary_level(p), p, 'psept') result = result[result['SampleId'] > 0] ep_type_map = { - 1 : 'OEP', - 2 : 'OEP TVAR', - 3 : 'AEP', - 4 : 'AEP TVAR' + 1: 'OEP', + 2: 'OEP TVAR', + 3: 'AEP', + 4: 'AEP TVAR' } type_options = result['EPType'].unique() if len(type_options) > 1: selected_type = st.radio('EP Curve Type: ', options=type_options, horizontal=True, - format_func= lambda x: ep_type_map.get(x, x), + format_func=lambda x: ep_type_map.get(x, x), key=f'psept_{p}_type_filter') result = result[result['EPType'] == selected_type] @@ -1517,7 +1614,7 @@ def generate_psept_fragment(p, vis): oed_fields = vis.oed_fields.get(p) or [] selected_group = None - if oed_fields and len(oed_fields) > 0 : + if oed_fields and len(oed_fields) > 0: selected_group = st.pills('Grouped OED Field: ', options=oed_fields, key=f'psept_{p}_group_field_pills') if selected_group is None: @@ -1537,15 +1634,15 @@ def generate_psept_fragment(p, vis): unique_group = unique_group[selected_group].tolist() result_plot = result_plot.sort_values(by=['ReturnPeriod', 'mean_loss'], ascending=[True, False]) - log_x = log10(result_plot['ReturnPeriod'].max()) - log10(result_plot['ReturnPeriod'].min()) > 2 + log_x = False # EP curves are read on a linear return period axis all_selected = result_plot[selected_group].unique().tolist() unique_group += [e for e in all_selected if e not in unique_group] if len(unique_group) > 5: filter_group = st.multiselect(f'Filtered {selected_group} Values:', - options = unique_group, - default = unique_group[:5], + options=unique_group, + default=unique_group[:5], key=f'psept_{p}_group_filter') result_plot = result_plot[result_plot[selected_group].isin(filter_group)] @@ -1553,19 +1650,20 @@ def generate_psept_fragment(p, vis): for item in result_plot[selected_group].unique().tolist(): result_item = result_plot[result_plot[selected_group] == item] fig.add_trace(go.Scatter( - x = result_item['ReturnPeriod'], - y = result_item['mean_loss'], - error_y = {'array': result_item['max_loss'] - result_item['mean_loss'], - 'arrayminus': result_item['mean_loss'] - result_item['min_loss']}, - name = item)) + x=result_item['ReturnPeriod'], + y=result_item['mean_loss'], + error_y={'array': result_item['max_loss'] - result_item['mean_loss'], + 'arrayminus': result_item['mean_loss'] - result_item['min_loss']}, + name=item)) fig.update_layout( - xaxis = dict(title = dict(text = 'Return Period'), type='log' if log_x else None), - yaxis = dict(title = dict(text = 'Loss')), + xaxis=dict(title=dict(text='Return Period'), type='log' if log_x else None), + yaxis=dict(title=dict(text='Loss')), legend_title_text=selected_group, showlegend=True ) st.plotly_chart(fig) + def shared_oed_fields(p, outputs): oed_fields = [outputs[i].oed_fields.get(p) for i in (0, 1)] @@ -1576,8 +1674,9 @@ def shared_oed_fields(p, outputs): return list(set(oed_fields[0]).intersection(oed_fields[1])) -def generate_aalcalc_comparison_fragment(p, outputs, names = None): - results = [o.get(1, p, 'aalcalc') for o in outputs] + +def generate_aalcalc_comparison_fragment(p, outputs, names=None): + results = [o.get(o.summary_level(p), p, 'aalcalc') for o in outputs] oed_fields = shared_oed_fields(p, outputs) breakdown_field = None @@ -1590,8 +1689,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): @@ -1619,21 +1718,21 @@ def generate_aalcalc_comparison_fragment(p, outputs, names = None): results = results.groupby('name', as_index=False).agg({'mean': 'sum'}) graph = px.bar(results, x='name', y='mean', color=breakdown_field, - labels = {'mean': 'Mean', 'name': 'Analysis Name'}, - color_discrete_sequence= px.colors.sequential.RdBu, + labels={'mean': 'Mean', 'name': 'Analysis Name'}, + color_discrete_sequence=px.colors.sequential.RdBu, category_orders={'name': names}) st.plotly_chart(graph, width='stretch') if breakdown_field_invalid: st.error("Too many values in group field.") + def generate_eltcalc_comparison_fragment(perspective, outputs, names=None, locations=None, output_type='eltcalc', filter_col='type', filter_label='Type Filter:', filter_index=0, data_cols=None, event_id='event_id', name_map=None, intensity_col=None): - ''' - Compare an event-level-table output across two analyses: filter to + """Compare an event-level-table output across two analyses: filter to a single value of `filter_col`, then show a `table`/`map` view. Covers the legacy `eltcalc` output and every ORD `elt_*` output that shares the same "single equality filter, per-event value @@ -1651,6 +1750,14 @@ def generate_eltcalc_comparison_fragment(perspective, outputs, names=None, Parameters ---------- + perspective : str + Perspective to compare (`gul`, `il`, `ri`). + outputs : List[OutputInterface] + Output interfaces for the analyses being compared. + names : List[str] + Display names for the analyses. + locations : DataFrame + Locations used for the map view. output_type : str `OutputInterface` output type to fetch, e.g. `eltcalc`, `elt_moment`, `elt_quantile`. @@ -1671,7 +1778,7 @@ def generate_eltcalc_comparison_fragment(perspective, outputs, names=None, Column name -> display name overrides for the table. intensity_col : str Map intensity column. Defaults to `data_cols[0]`. - ''' + """ if data_cols is None: data_cols = ['mean', 'exposure_value'] if name_map is None: @@ -1679,10 +1786,12 @@ def generate_eltcalc_comparison_fragment(perspective, outputs, names=None, if intensity_col is None: intensity_col = data_cols[0] - results = [o.get(1, perspective, output_type) for o in outputs] + 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) @@ -1691,13 +1800,13 @@ def generate_eltcalc_comparison_fragment(perspective, outputs, names=None, for i in range(len(results)): results[i] = results[i][results[i][filter_col] == selected_filter] - results[i]['name'] = names[i] if names[i] else f'Analysis {i+1}' + results[i]['name'] = names[i] if names[i] else f'Analysis {i + 1}' results[i]['loc_analysis_id'] = i + 1 analysis_map = {i: names[i] for i in range(2)} selected_analysis = st.segmented_control('Analysis Filter:', options=analysis_map.keys(), - format_func = lambda x: analysis_map.get(x, x), + format_func=lambda x: analysis_map.get(x, x), key=f'{perspective}_{output_type}_name_filter') if selected_analysis is not None: @@ -1709,33 +1818,27 @@ def generate_eltcalc_comparison_fragment(perspective, outputs, names=None, with table_tab: result, selected = elt_ord_table(result, perspective=perspective, oed_fields=oed_fields, - order_cols=data_cols, data_cols=data_cols, - key_prefix=f'{perspective}_{output_type}', event_id=event_id, - additional_cols=['name'], - name_map = {**name_map, 'name': 'Analysis Name'}, - selectable='multi') + order_cols=data_cols, data_cols=data_cols, + key_prefix=f'{perspective}_{output_type}', event_id=event_id, + additional_cols=['name'], + name_map={**name_map, 'name': 'Analysis Name'}, + selectable='multi') with map_tab: if locations is 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']) + def generate_pltcalc_comparison_fragment(p, outputs, names=None, output_type='plt_moment', filter_col='SampleType', filter_label='Type Filter:', filter_index=0, filter_format_func=None, value_col='Loss', value_col_options=None): - ''' - Compare total period-loss across two analyses: filter to a single + """Compare total period-loss across two analyses: filter to a single value of `filter_col`, aggregate a loss column by analysis name (and, optionally, a breakdown OED field), then show a bar chart. Mirrors generate_aalcalc_comparison_fragment's bar-chart-by- @@ -1750,6 +1853,12 @@ def generate_pltcalc_comparison_fragment(p, outputs, names=None, output_type='pl Parameters ---------- + p : str + Perspective to compare (`gul`, `il`, `ri`). + outputs : List[OutputInterface] + Output interfaces for the analyses being compared. + names : List[str] + Display names for the analyses. output_type : str `OutputInterface` output type to fetch. filter_col : str @@ -1768,8 +1877,8 @@ def generate_pltcalc_comparison_fragment(p, outputs, names=None, output_type='pl If given, renders a "Loss Filter" radio letting the user choose the loss column from these options, instead of using the fixed `value_col`. - ''' - results = [o.get(1, p, output_type) for o in outputs] + """ + results = [o.get(o.summary_level(p), p, output_type) for o in outputs] oed_fields = shared_oed_fields(p, outputs) breakdown_field = None @@ -1782,7 +1891,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) @@ -1819,21 +1930,21 @@ def generate_pltcalc_comparison_fragment(p, outputs, names=None, output_type='pl results = results.groupby('name', as_index=False).agg({value_col: 'sum'}) graph = px.bar(results, x='name', y=value_col, color=breakdown_field, - labels = {value_col: value_col, 'name': 'Analysis Name'}, - color_discrete_sequence= px.colors.sequential.RdBu, + labels={value_col: value_col, 'name': 'Analysis Name'}, + color_discrete_sequence=px.colors.sequential.RdBu, category_orders={'name': names}) st.plotly_chart(graph, width='stretch', key=f'{output_type}_{p}_comparison_graph') if breakdown_field_invalid: st.error("Too many values in group field.") + def generate_alt_comparison_fragment(p, outputs, output_type='alt_meanonly', names=None): - ''' - Compare `alt_meanonly`/`alt_period` (ALT) outputs across two + """Compare `alt_meanonly`/`alt_period` (ALT) outputs across two analyses. Generalises generate_aalcalc_comparison_fragment for the ORD `SampleType`/`MeanLoss` columns used by generate_alt_fragment. - ''' - results = [o.get(1, p, output_type) for o in outputs] + """ + results = [o.get(o.summary_level(p), p, output_type) for o in outputs] type_field = 'SampleType' mean_field = 'MeanLoss' @@ -1877,8 +1988,8 @@ def generate_alt_comparison_fragment(p, outputs, output_type='alt_meanonly', nam results = results.groupby('name', as_index=False).agg({mean_field: 'sum'}) graph = px.bar(results, x='name', y=mean_field, color=breakdown_field, - labels = {mean_field: mean_field, 'name': 'Analysis Name'}, - color_discrete_sequence= px.colors.sequential.RdBu, + labels={mean_field: mean_field, 'name': 'Analysis Name'}, + color_discrete_sequence=px.colors.sequential.RdBu, category_orders={'name': names}) st.plotly_chart(graph, width='stretch', key=f'{output_type}_{p}_comparison_graph') diff --git a/pages/components/process.py b/pages/components/process.py deleted file mode 100644 index 52158df..0000000 --- a/pages/components/process.py +++ /dev/null @@ -1,123 +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) - - 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() - st.write(portfolios) - 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 new file mode 100644 index 0000000..b9ee8ca --- /dev/null +++ b/pages/components/results.py @@ -0,0 +1,145 @@ +"""Render the outputs of a completed analysis, driven by its analysis settings.""" +import re + +import streamlit as st + +from modules.schemas import PERSPECTIVE_LABELS, PERSPECTIVES +from modules.visualisation import OutputInterface +from pages.components.output import (generate_aalcalc_fragment, generate_alct_fragment, + generate_alt_fragment, generate_eltcalc_fragment, + generate_ept_fragment, generate_leccalc_fragment, + generate_melt_fragment, generate_mplt_fragment, + generate_pltcalc_fragment, generate_psept_fragment, + generate_qelt_fragment, generate_qplt_fragment, + generate_selt_fragment, generate_splt_fragment) + +EPT_FLAGS = ['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'] +PSEPT_FLAGS = ['psept_aep', 'psept_oep'] + + +def _sections(summary, locations): + """(title, render-callable) for each output enabled in a summary level.""" + ord_settings = summary.get('ord_output', {}) + sections = [] + + def add(enabled, title, render, output_type=None): + if enabled: + 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), 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), 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), 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'), 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'), 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), 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')), output_type=None) + add(summary.get('pltcalc'), 'PLT (legacy)', generate_pltcalc_fragment, output_type='pltcalc') + return sections + + +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.') + return + + vis = OutputInterface(outputs) + vis.number_of_samples = settings.get('number_of_samples') + perspectives = [p for p in PERSPECTIVES if settings.get(f'{p}_output')] + if not perspectives: + st.info('No loss perspectives were enabled in the analysis settings.') + return + + tabs = st.tabs([PERSPECTIVE_LABELS[p] for p in perspectives]) + for p, tab in zip(perspectives, tabs): + with tab: + levels = {lv['id']: lv for lv in settings.get(f'{p}_summaries') or [] if 'id' in lv} + if not levels: + st.info('No summary levels were configured for this perspective.') + continue + + level_id = next(iter(levels)) + 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}' + (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])) + + summary = levels[level_id] + vis.set_summary_level(p, level_id) + + # Reinsurance outputs can be split by inuring priority (rl_IP1_S1_..., ri_S1_...) + priorities = inuring_priorities(outputs, p, level_id) + prefix = priorities[0] if priorities else '' + if len(priorities) > 1: + prefix = st.selectbox('Inuring priority', priorities, format_func=priority_label, + key=f'results_priority_{p}_{level_id}') + vis.set_file_prefix(p, prefix) + + oed_fields = summary.get('oed_fields') or None + if oed_fields and not vis.fields_available(p, oed_fields, level_id): + st.caption(f"Breakdown by {', '.join(oed_fields)} isn't available here: the run produced " + "no summary-info file for this perspective, so results are shown by SummaryId.") + oed_fields = None + vis.set_oed_fields(p, oed_fields) + + sections = _sections(summary, locations) + if not sections: + st.info('No outputs were selected for this summary level.') + for i, (title, render, output_type) in enumerate(sections): + with st.expander(title, expanded=i == 0): + # 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): + fields = level.get('oed_fields') or [] + if isinstance(fields, str): + fields = [fields] + grouping = f"grouped by {', '.join(fields)}" if fields else 'portfolio total' + return f"Level {level['id']}: {grouping}" + + +def inuring_priorities(outputs, perspective, level_id): + """File prefixes for the inuring priorities present, final ('') first. + + e.g. `['', 'IP1_']` for ri_S1_* and ri_IP1_S1_*, or `['IP1_']` for rl_IP1_S1_*. + """ + pattern = re.compile(rf'^{perspective}_(IP\d+_)?S{level_id}_') + found = {m.group(1) or '' for name in outputs if (m := pattern.match(name))} + return sorted(found, key=lambda pre: (pre != '', int(pre[2:-1]) if pre else 0)) + + +def priority_label(prefix): + return 'Final' if not prefix else f'Inuring priority {prefix[2:-1]}' diff --git a/pages/components/settings_editor.py b/pages/components/settings_editor.py new file mode 100644 index 0000000..348aef2 --- /dev/null +++ b/pages/components/settings_editor.py @@ -0,0 +1,558 @@ +"""Schema-driven analysis settings editor. + +Controls are generated from the ODS-tools analysis settings schema (general +options and output flags) and from the selected model's settings (run options +and model parameters). `analysis_settings_editor` returns the assembled +settings dict on every rerun; the caller decides when to save it. +""" +import json +from copy import deepcopy + +import streamlit as st + +from modules import schemas +from modules.schemas import (CATEGORICAL_MODEL_SETTINGS, DEFAULT_GROUP_FIELDS, DEFAULT_ORD_OUTPUTS, + ORD_OUTPUT_GROUPS, PARAMETER_TYPES, PERSPECTIVE_LABELS, PERSPECTIVES) + + +########################################################################################## +# Helpers +########################################################################################## + +def _label(entry, fallback): + return schemas.title(entry, fallback).rstrip('.') + + +def _parse_number_list(text, cast): + """Parse "10, 50, 100" into a list of numbers. Returns (values, error).""" + if not text or not text.strip(): + return None, None + try: + return [cast(v) for v in text.replace(';', ',').split(',') if v.strip()], None + except ValueError: + return None, f'Could not read "{text}" as a comma separated list of numbers.' + + +def _list_text(values): + return ', '.join(str(v) for v in values) if values else '' + + +def _events_text(event_ids, event_ranges): + parts = [str(e) for e in event_ids or []] + if event_ranges: + parts += [r.strip() for r in str(event_ranges).split(',') if r.strip()] + return ', '.join(parts) + + +def _parse_events(text): + """Parse "1, 5, 100-120" into (event_ids, event_ranges, error). + + Single ids go to `event_ids` and hyphenated ranges to `event_ranges`; + oasislmf combines the two. + """ + if not text or not text.strip(): + return None, None, None + ids, ranges = [], [] + for part in text.replace(';', ',').split(','): + part = part.strip() + if not part: + continue + try: + if '-' in part: + lo, hi = (int(v) for v in part.split('-', 1)) + if lo < 1 or hi < lo: + raise ValueError + ranges.append(f'{lo}-{hi}') + else: + value = int(part) + if value < 1: + raise ValueError + ids.append(value) + except ValueError: + return None, None, f'Could not read "{part}" as an event id (a whole number from 1) or range like 100-120.' + return ids or None, ','.join(ranges) or None, None + + +def selected_option(model_settings, setting, option_id): + """The option dict chosen for a categorical model setting (e.g. the event set), or {}.""" + options = model_settings.get('model_settings', {}).get(setting, {}).get('options', []) + return next((o for o in options if o.get('id') == option_id), {}) + + +def valid_metrics(model_settings, event_set=None): + """Output metrics the model supports (None = no restriction). + + An event set's `valid_metrics` overrides the model's `valid_output_metrics`. + """ + return (event_set or {}).get('valid_metrics') or \ + model_settings.get('model_settings', {}).get('valid_output_metrics') or None + + +def metric_allowed(flag, metrics): + """Whether an ORD output flag is allowed by a `valid_metrics` list. + + Entries may name a flag exactly (`elt_sample`), a table family (`elt`, + `plt`, `alt`, `ept`, `psept`), or a loss type (`aep`, `oep`). + """ + if not metrics: + return True + family = flag.split('_')[0] + if flag.startswith('alct'): + family = 'alt' + loss_type = flag.rsplit('_', 1)[-1] + return flag in metrics or family in metrics or (loss_type in ('aep', 'oep') and loss_type in metrics) + + +def default_ord_outputs(metrics=None): + return {o: True for o in DEFAULT_ORD_OUTPUTS if metric_allowed(o, metrics)} + + +def perspective_availability(model_settings, portfolio, event_set=None): + """Which perspectives can be run, with a reason for those that can't. + + An event set's `valid_perspectives` overrides the model's `valid_output_perspectives`. + """ + valid = list((event_set or {}).get('valid_perspectives') + or model_settings.get('model_settings', {}).get('valid_output_perspectives') or PERSPECTIVES) + # The model settings schema has no 'rl': ceded reinsurance follows 'ri' + if 'ri' in valid and 'rl' not in valid: + valid.append('rl') + has = {f: bool((portfolio.get(f) or {}).get('stored')) for f in + ['accounts_file', 'reinsurance_info_file', 'reinsurance_scope_file']} + + reasons = {} + for p in PERSPECTIVES: + if p not in valid: + reasons[p] = ('Not supported by the selected event set.' if (event_set or {}).get('valid_perspectives') + else 'Not supported by this model.') + elif p in ('il', 'ri', 'rl') and not has['accounts_file']: + reasons[p] = 'The portfolio has no accounts file.' + elif p in ('ri', 'rl') and not (has['reinsurance_info_file'] and has['reinsurance_scope_file']): + reasons[p] = 'The portfolio has no reinsurance info and scope files.' + return reasons + + +def default_settings(model, model_settings): + """Minimal starting settings for a model when no template is used.""" + return { + 'model_supplier_id': model['supplier_id'], + 'model_name_id': model['model_id'], + 'number_of_samples': model_settings.get('model_default_samples', + schemas.analysis_property('number_of_samples').get('default', 10)), + 'gul_output': True, + 'gul_summaries': [{'id': 1, 'ord_output': default_ord_outputs(valid_metrics(model_settings))}], + } + + +def group_field_options(model_settings, extra=(), portfolio_fields=()): + """OED fields offered for grouping losses. + + Common grouping fields and those the model suggests come first, followed + by every other column in the portfolio's OED files (alphabetically). + """ + data_settings = model_settings.get('data_settings', {}) + fields = list(DEFAULT_GROUP_FIELDS) + for f in [*data_settings.get('damage_group_fields', []), *data_settings.get('hazard_group_fields', []), + *model_settings.get('model_settings', {}).get('summary_report_fields', []), *extra, + *sorted(portfolio_fields, key=str.lower)]: + # OED field names are case-insensitive: keep the first spelling seen + if f.lower() not in {x.lower() for x in fields}: + fields.append(f) + return fields + + +########################################################################################## +# Sections +########################################################################################## + +def general_section(base, model_settings, key): + out = {} + errors = [] + + entry = schemas.analysis_property('number_of_samples') + default_samples = base.get('number_of_samples', + model_settings.get('model_default_samples', entry.get('default', 10))) + left, _ = st.columns(2) + out['number_of_samples'] = left.number_input( + _label(entry, 'Number of samples'), min_value=entry.get('minimum', 0), step=1, + value=int(default_samples), help=entry.get('description'), key=f'{key}_samples') + + with st.expander('Advanced'): + entry = schemas.analysis_property('gul_threshold') + out['gul_threshold'] = st.number_input( + _label(entry, 'Ground-up loss threshold'), min_value=float(entry.get('minimum', 0)), + value=float(base.get('gul_threshold', entry.get('default', 0))), + help=entry.get('description'), key=f'{key}_gul_threshold') + + text = st.text_input( + 'Events', value=_events_text(base.get('event_ids'), base.get('event_ranges')), + placeholder='e.g. 1, 5, 100-120', + help='Run only these event ids. Use commas between ids and hyphens for ranges. ' + 'Leave blank to run every event in the event set.', + key=f'{key}_events') + event_ids, event_ranges, error = _parse_events(text) + if error: + errors.append(error) + if event_ids: + out['event_ids'] = event_ids + if event_ranges: + out['event_ranges'] = event_ranges + + entry = schemas.analysis_property('return_periods') + text = st.text_input(_label(entry, 'Return periods'), value=_list_text(base.get('return_periods')), + placeholder='e.g. 10, 50, 100, 250, 500, 1000', + help=f"{entry.get('description', '')} Leave blank to use the model's defaults.", + key=f'{key}_return_periods') + values, error = _parse_number_list(text, int) + if error: + errors.append(error) + elif values: + out['return_periods'] = values + + entry = schemas.analysis_property('quantiles') + text = st.text_input(_label(entry, 'Quantiles'), value=_list_text(base.get('quantiles')), + placeholder='e.g. 0.05, 0.5, 0.95', + help=f"{entry.get('description', '')} Used by quantile (Q) outputs.", + key=f'{key}_quantiles') + values, error = _parse_number_list(text, float) + if error: + errors.append(error) + elif values: + out['quantiles'] = values + + perils = model_settings.get('lookup_settings', {}).get('supported_perils', []) + if perils: + entry = schemas.analysis_property('peril_filter') + peril_desc = {p['id']: p.get('desc', '') for p in perils} + out['peril_filter'] = st.multiselect( + _label(entry, 'Peril filter'), options=list(peril_desc), + default=[p for p in base.get('peril_filter', []) if p in peril_desc], + format_func=lambda p: f'{p} – {peril_desc[p]}' if peril_desc[p] else p, + help=f"{entry.get('description', '')} Leave empty to include all perils.", + key=f'{key}_peril_filter') or None + + entry = schemas.analysis_property('join_summary_info') + out['join_summary_info'] = st.toggle( + _label(entry, 'Join summary info'), value=bool(base.get('join_summary_info', True)), + help=f"{entry.get('description', '')} Writes the group-by fields into each output file, " + "so results can be broken down without a separate summary-info lookup. On by default.", + key=f'{key}_join_summary_info') + + return {k: v for k, v in out.items() if v is not None}, errors + + +def _parameter_control(param, kind, current, key): + name = param['name'] + label = param.get('desc') or name + help_text = param.get('tooltip') or (f'`{name}`' if param.get('desc') else None) + disabled = param.get('editable') is False + value = current.get(name, param.get('default')) + wkey = f'{key}_param_{name}' + + if kind == 'bool': + return st.toggle(label, value=bool(value), help=help_text, disabled=disabled, key=wkey), None + if kind == 'float': + lo, hi = float(param['min']), float(param['max']) + step = float(param.get('stepsize') or (hi - lo) / 100 or 0.01) + return st.slider(label, min_value=lo, max_value=hi, value=float(value), step=step, + help=help_text, disabled=disabled, key=wkey), None + if kind == 'int': + return st.number_input(label, value=int(value), step=1, help=help_text, + disabled=disabled, key=wkey), None + if kind == 'number': + return st.number_input(label, value=float(value), help=help_text, + disabled=disabled, key=wkey), None + if kind == 'dropdown': + options = param.get('options', []) + ids = [o['id'] for o in options] + descs = {o['id']: o.get('desc', '') for o in options} + return st.selectbox(label, ids, index=ids.index(value) if value in ids else 0, + format_func=lambda i: f'{i} – {descs[i]}' if descs[i] else str(i), + help=help_text, disabled=disabled, key=wkey), None + if kind in ('list', 'dict'): + text = st.text_area(label, value=json.dumps(value), help=f"{help_text or ''} (JSON)".strip(), + disabled=disabled, key=wkey, height=68) + try: + parsed = json.loads(text) + except json.JSONDecodeError as e: + return value, f'{label}: invalid JSON ({e.msg}).' + expected = list if kind == 'list' else dict + if not isinstance(parsed, expected): + return value, f'{label}: expected a JSON {expected.__name__}.' + return parsed, None + return st.text_input(label, value='' if value is None else str(value), help=help_text, + disabled=disabled, key=wkey), None + + +def model_options_section(base, model_settings, key): + ms = model_settings.get('model_settings', {}) + current = base.get('model_settings', {}) + out, errors = {}, [] + + selectors = [k for k in CATEGORICAL_MODEL_SETTINGS if ms.get(k, {}).get('options')] + if selectors: + cols = st.columns(min(len(selectors), 2)) + for i, k in enumerate(selectors): + option = ms[k] + ids = [o['id'] for o in option['options']] + descs = {o['id']: o.get('desc', '') for o in option['options']} + default = current.get(k, option.get('default')) + entry = schemas.model_settings_property(k) + out[k] = cols[i % len(cols)].selectbox( + option.get('name') or _label(entry, k), ids, + index=ids.index(default) if default in ids else 0, + format_func=lambda i, d=descs: f'{i} – {d[i]}' if d[i] else str(i), + help=option.get('tooltip') or option.get('desc') or entry.get('description'), + key=f'{key}_ms_{k}') + + params = {} + for type_key, kind in PARAMETER_TYPES.items(): + for p in ms.get(type_key, []): + if p.get('visible') is False: + if p['name'] in current: + out[p['name']] = current[p['name']] + continue + params[p['name']] = (p, kind) + + groups = sorted(ms.get('parameter_groups', []), key=lambda g: g.get('priority_id', 0)) + rendered = set() + + def render(names): + for n in names: + p, kind = params[n] + value, error = _parameter_control(p, kind, current, key) + out[n] = value + if error: + errors.append(error) + rendered.add(n) + + for g in groups: + names = [n for n in g.get('presentation_order', []) if n in params and n not in rendered] + if not names: + continue + title = g.get('desc') or g.get('name') + if g.get('collapsible'): + with st.expander(title, expanded=not g.get('default_collapsed', False)): + render(names) + else: + st.markdown(f'**{title}**', help=g.get('tooltip')) + render(names) + + rest = [n for n in params if n not in rendered] + if rest: + if rendered: + st.markdown('**Other parameters**') + render(rest) + + if not selectors and not params: + st.caption('This model has no run options to set.') + + # Keep any model settings from the template that the model doesn't describe + for k, v in current.items(): + out.setdefault(k, v) + return out, errors + + +def _levels_state_key(key, scope): + return f'{key}_levels_{scope}' + + +def _init_levels(key, scope, summaries, metrics=None): + """Track summary levels for `scope` ('all' or a perspective) in session state.""" + state_key = _levels_state_key(key, scope) + if state_key not in st.session_state: + levels = [deepcopy(s) for s in (summaries or [])] + if not levels: + levels = [{'id': 1, 'ord_output': default_ord_outputs(metrics)}] + st.session_state[state_key] = levels + return st.session_state[state_key] + + +def summary_levels_editor(key, scope, summaries, field_options, metrics=None): + """Edit a list of summary levels (group-by fields + ORD outputs). + + `metrics` (from `valid_metrics`) disables outputs the model doesn't support. + """ + levels = _init_levels(key, scope, summaries, metrics) + flags = schemas.ord_output_options() + result = [] + + for level in list(levels): + lid = level['id'] + wkey = f'{key}_{scope}_{lid}' + ord_output = level.get('ord_output', {}) + with st.container(border=True): + head, remove = st.columns([0.85, 0.15], vertical_alignment='center') + head.markdown(f'**Summary level {lid}**') + if remove.button('Remove', key=f'{wkey}_remove', disabled=len(levels) == 1, width='stretch'): + levels.remove(level) + st.rerun() + + existing = level.get('oed_fields') or [] + if isinstance(existing, str): + existing = [existing] + fields = st.multiselect( + 'Group losses by', options=list(dict.fromkeys([*field_options, *existing])), + default=existing, placeholder='Portfolio total (no grouping)', + help='OED fields to break losses down by. Leave empty for a single portfolio-level total.', + key=f'{wkey}_fields') + + selected = [] + cols = st.columns(len(ORD_OUTPUT_GROUPS)) + for col, (group, keys) in zip(cols, ORD_OUTPUT_GROUPS.items()): + with col: + st.markdown(f'**{group}**', unsafe_allow_html=True) + for k in keys: + unsupported = not metric_allowed(k, metrics) + # oasislmf only writes the ALCT alongside the period ALT (PALT) + needs_palt = k == 'alct_convergence' and 'alt_period' not in selected + blocked = unsupported or needs_palt + help_text = flags[k][1] + (' Not supported by this model.' if unsupported else + ' Requires PALT.' if needs_palt else '') + if col.checkbox(flags[k][0], value=bool(ord_output.get(k)) and not blocked, + help=help_text, disabled=blocked, key=f'{wkey}_{k}') \ + and not blocked: + selected.append(k) + + new_level = {k: v for k, v in level.items() if k not in ('ord_output', 'oed_fields')} + new_ord = {k: v for k, v in ord_output.items() if k not in flags} + new_ord.update({k: True for k in selected}) + if 'alct_convergence' in selected: + new_ord['alct_confidence'] = st.number_input( + 'ALCT confidence level', min_value=0.0, max_value=1.0, + value=float(ord_output.get('alct_confidence', 0.95)), key=f'{wkey}_alct_conf') + new_level['ord_output'] = new_ord + if fields: + new_level['oed_fields'] = fields + + legacy = [k for k in ['eltcalc', 'aalcalc', 'aalcalcmeanonly', 'pltcalc', 'summarycalc', 'lec_output'] + if level.get(k)] + if legacy: + st.caption(f"Also keeps legacy ktools outputs from the template: {', '.join(legacy)}") + if not selected and not legacy: + st.caption(':orange[No outputs selected for this level.]') + result.append(new_level) + + if st.button('Add summary level', icon=':material/add:', key=f'{key}_{scope}_add'): + next_id = max([lv['id'] for lv in levels] + [0]) + 1 + levels.append({'id': next_id, 'ord_output': default_ord_outputs(metrics)}) + st.rerun() + + return result + + +def outputs_section(base, model_settings, portfolio, key, portfolio_fields=(), event_set=None): + out, errors = {}, [] + unavailable = perspective_availability(model_settings, portfolio, event_set) + metrics = valid_metrics(model_settings, event_set) + if metrics: + st.caption(f"This model {'event set ' if (event_set or {}).get('valid_metrics') else ''}" + f"supports these outputs only: {', '.join(metrics)}.") + + st.markdown('**Loss perspectives**') + cols = st.columns(len(PERSPECTIVES)) + enabled = [] + for col, p in zip(cols, PERSPECTIVES): + reason = unavailable.get(p) + default = bool(base.get(f'{p}_output', p == 'gul')) and not reason + if col.checkbox(PERSPECTIVE_LABELS[p], value=default, disabled=bool(reason), + help=reason or schemas.analysis_property(f'{p}_output').get('description'), + key=f'{key}_{p}_output'): + enabled.append(p) + out[f'{p}_output'] = p in enabled + + if not enabled: + errors.append('Select at least one loss perspective.') + return out, errors + + existing = {p: base.get(f'{p}_summaries') for p in PERSPECTIVES} + first = next((existing[p] for p in PERSPECTIVES if existing[p]), None) + same_default = all(existing[p] in (None, first) for p in PERSPECTIVES) + extra_fields = [f for s in (first or []) for f in (s.get('oed_fields') or [])] + field_options = group_field_options(model_settings, extra_fields, portfolio_fields) + + same = st.toggle('Use the same outputs for every perspective', value=same_default, + key=f'{key}_same_outputs') + if same: + levels = summary_levels_editor(key, 'all', first, field_options, metrics) + for p in enabled: + out[f'{p}_summaries'] = deepcopy(levels) + else: + tabs = st.tabs([PERSPECTIVE_LABELS[p] for p in enabled]) + for p, tab in zip(enabled, tabs): + with tab: + out[f'{p}_summaries'] = summary_levels_editor(key, p, existing[p] or first, field_options, metrics) + + with st.expander('Advanced output options'): + flag = (schemas.analysis_settings_schema()['definitions']['output_summaries']['items'] + ['properties']['ord_output']['properties']['parquet_format']) + parquet = st.toggle(_label(flag, 'Parquet output'), help=flag.get('description'), + value=any(s.get('ord_output', {}).get('parquet_format') + for s in (first or [])), key=f'{key}_parquet') + for p in enabled: + for level in out[f'{p}_summaries']: + level['ord_output']['parquet_format'] = parquet + return out, errors + + +########################################################################################## +# Editor +########################################################################################## + +def analysis_settings_editor(model, model_settings, portfolio, base_settings, key, portfolio_fields=()): + """Render the editor and return `(settings, valid, problems)`. + + Args: + model: model record from the API. + model_settings: the model's settings (may be `{}`). + portfolio: portfolio record, used to decide which perspectives are possible. + base_settings: settings to start from (template / existing settings). + key: unique widget key prefix. Change it to reset the editor. + portfolio_fields: columns in the portfolio's OED files, offered for grouping. + """ + base = deepcopy(base_settings) if base_settings else default_settings(model, model_settings) + + general_tab, model_tab, outputs_tab, review_tab = st.tabs( + ['General', 'Model options', 'Outputs', 'Review']) + + with general_tab: + general, general_errors = general_section(base, model_settings, key) + with model_tab: + ms, ms_errors = model_options_section(base, model_settings, key) + with outputs_tab: + event_set = selected_option(model_settings, 'event_set', ms.get('event_set')) + outputs, output_errors = outputs_section(base, model_settings, portfolio, key, portfolio_fields, event_set) + + # Start from the template so keys the editor doesn't manage are kept + settings = {k: v for k, v in base.items() + if k not in ('return_periods', 'quantiles', 'peril_filter', 'model_settings', + 'event_ids', 'event_ranges') + and not any(k.startswith(f'{p}_') for p in PERSPECTIVES)} + settings.update(general) + settings['model_supplier_id'] = model['supplier_id'] + settings['model_name_id'] = model['model_id'] + settings['model_settings'] = ms + settings.update(outputs) + + problems = general_errors + ms_errors + output_errors + if not problems: + valid, messages = schemas.validate_analysis_settings(settings) + problems += [f'{field}: {"; ".join(msgs)}' for field, msgs in messages.items()] + + with review_tab: + if problems: + st.error('These settings need attention before they can be used:\n\n' + + '\n'.join(f'- {p}' for p in problems)) + else: + st.success('Settings are valid.') + st.json(settings, expanded=3) + st.download_button('Download analysis_settings.json', json.dumps(settings, indent=2), + file_name='analysis_settings.json', key=f'{key}_download') + + return settings, not problems, problems + + +def reset_editor(key): + """Clear editor state stored under `key` (e.g. after saving).""" + for k in [k for k in st.session_state if str(k).startswith(f'{key}_')]: + del st.session_state[k] diff --git a/pages/dashboard.py b/pages/dashboard.py deleted file mode 100644 index 67c7a13..0000000 --- a/pages/dashboard.py +++ /dev/null @@ -1,184 +0,0 @@ -from modules.config import retrieve_ui_config -import streamlit as st -from modules.client import ClientInterface -from modules.nav import SidebarNav -from modules.authorisation import validate_page -import pandas as pd - -from pages.components.footer import generate_footer -from pages.components.output import generate_alt_fragment, generate_eltcalc_fragment, generate_qplt_fragment -from pages.components.output import generate_leccalc_fragment, generate_melt_fragment, generate_mplt_fragment -from pages.components.output import generate_pltcalc_fragment, generate_qelt_fragment, summarise_inputs -from pages.components.output import generate_aalcalc_fragment, generate_ept_fragment -from pages.components.output import generate_selt_fragment, generate_splt_fragment -from pages.components.output import generate_alct_fragment, generate_psept_fragment -from modules.visualisation import OutputInterface - -st.set_page_config( - page_title = "Dashboard", - layout = "centered" -) - -validate_page("Dashboard") - -ui_config = retrieve_ui_config() -handle_login(ui_config.skip_login) - -client_interface = st.session_state["client_interface"] -client = client_interface.client - -SidebarNav() - -# Embed Logo -cols = st.columns([0.1, 0.8, 0.1]) -with cols[1]: - st.image("images/oasis_logo.png") - -analyses = sorted(client_interface.analyses.search(metadata={'status': 'RUN_COMPLETED'}), key=lambda x: x['id'], reverse=True) -selected_analysis = st.selectbox("Select Analysis", options=analyses, - format_func= lambda x : x['name'], index=None) - -if selected_analysis is None: - generate_footer(ui_config) - st.stop() - -analysis_id = selected_analysis['id'] - -@st.cache_data -def get_analysis_inputs(ID): - return client_interface.analyses.get_file(ID, 'input_file', df=True) - -with st.spinner("Loading data..."): - inputs = get_analysis_inputs(analysis_id) - settings = client.analyses.settings.get(analysis_id).json() - -st.write("# Analysis Summary") -with st.spinner('Loading analysis summary...'): - summarise_inputs(inputs.get('location.csv', None), settings) - -@st.cache_data -def get_analysis_outputs(ID): - return client_interface.analyses.get_file(ID, 'output_file', df=True) - -with st.spinner("Loading data..."): - outputs = get_analysis_outputs(analysis_id) - -# Set up visualisation interface -vis = OutputInterface(outputs) -perspectives = ['gul', 'il', 'ri'] -for p in perspectives: - p_oed_fields = settings.get(f'{p}_summaries', [{}])[0].get('oed_fields', None) - if p_oed_fields: - vis.set_oed_fields(p, p_oed_fields) - -st.write("# Output") -with st.spinner("Loading visualisations..."): - for p in perspectives: - if not settings.get(f'{p}_output', False): - continue - - st.write(f'## {p.upper()}') - - summaries_settings = settings.get(f'{p}_summaries', [{}])[0] - - if summaries_settings.get('eltcalc', False): - elt_expander = st.expander("ELT Output") - with elt_expander: - locations = None - if inputs: - locations = inputs.get('location.csv') - generate_eltcalc_fragment(p, vis, locations=locations, map=True) - - if summaries_settings.get('aalcalc', False): - aal_expander = st.expander("AAL Output") - with aal_expander: - generate_aalcalc_fragment(p, vis) - - if summaries_settings.get('lec_output', False): - lec_expander = st.expander("LEC Output") - with lec_expander: - lec_options = summaries_settings.get('leccalc') - generate_leccalc_fragment(p, vis, lec_options) - - if summaries_settings.get("pltcalc", False): - plt_expander = st.expander("PLT Output") - with plt_expander: - generate_pltcalc_fragment(p, vis) - - # Handle ORD outputs - - ord_settings = summaries_settings.get("ord_output", {}) - - if ord_settings.get("elt_moment", False): - expander = st.expander("MELT Output") - with expander: - locations = None - if inputs: - locations = inputs.get('location.csv') - generate_melt_fragment(p, vis, locations=locations) - - if ord_settings.get('elt_quantile', False): - expander = st.expander("QELT Output") - with expander: - generate_qelt_fragment(p, vis, locations=locations) - - if ord_settings.get("elt_sample", False): - expander = st.expander("SELT Output") - with expander: - locations = None - if inputs: - locations = inputs.get('location.csv') - generate_selt_fragment(p, vis, locations=locations) - - if ord_settings.get("plt_moment", False): - expander = st.expander("MPLT Output") - with expander: - generate_mplt_fragment(p, vis) - - if ord_settings.get("plt_quantile", False): - expander = st.expander("QPLT Output") - with expander: - generate_qplt_fragment(p, vis) - - if ord_settings.get("plt_sample", False): - expander = st.expander("SPLT Output") - with expander: - generate_splt_fragment(p, vis) - - if ord_settings.get("alt_meanonly", False): - expander = st.expander("ALT MeanOnly") - with expander: - generate_alt_fragment(p, vis, 'alt_meanonly') - - if ord_settings.get("alt_period", False): - expander = st.expander("PALT") - with expander: - generate_alt_fragment(p, vis, 'alt_period') - - if ord_settings.get("alct_convergence", False): - expander = st.expander("ALCT Output") - with expander: - generate_alct_fragment(p, vis) - - 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]): - expander = st.expander("EPT Output") - with expander: - generate_ept_fragment(p, vis) - - psept_settings = ['psept_aep', 'psept_oep'] - - if any([ord_settings.get(e, False) for e in psept_settings]): - expander = st.expander("PSEPT Output") - with expander: - generate_psept_fragment(p, vis) - -generate_footer(ui_config) diff --git a/pages/models.py b/pages/models.py new file mode 100644 index 0000000..e4b9c36 --- /dev/null +++ b/pages/models.py @@ -0,0 +1,68 @@ +import streamlit as st + +from modules.ui import page_setup +from pages.components.common import (ANALYSES_PAGE, NEW_ANALYSIS_DEFAULTS, SELECTED_ANALYSIS, + SELECTED_MODEL, open_record, selectable_table) +from pages.components.data import analyses_df, cached_model_settings, models_df +from pages.components.model_details import model_details + +ci = page_setup('Models') + +models = ci.models.get() +analyses = ci.analyses.get() +models_by_id = {m['id']: m for m in models} + +st.caption('Models registered on this platform. Select one to see its settings, ' + 'run options and the analyses that have used it.') + +if not models: + st.info('No models are registered on this platform.') + st.stop() + +table = models_df(ci, models, analyses) +column_config = { + 'name': 'Name', + 'id': st.column_config.NumberColumn('ID', width='small'), + 'supplier_id': 'Supplier', + 'model_id': 'Model ID', + 'version_id': 'Version', + 'run_mode': st.column_config.TextColumn('Run mode', width='small'), + 'n_analyses': st.column_config.NumberColumn('Analyses', width='small'), +} +selected_id = selectable_table(table, ['id', 'name', 'supplier_id', 'model_id', 'version_id', + 'run_mode', 'n_analyses'], + SELECTED_MODEL, column_config) + +if selected_id is None: + st.caption('Select a model above to see its details.') + st.stop() + +model = models_by_id[selected_id] +settings = cached_model_settings(ci, model) +model_analyses = [a for a in analyses if a['model'] == selected_id] + +st.divider() +title_col, action_col = st.columns([0.8, 0.2], vertical_alignment='bottom') +title_col.subheader(settings.get('name') or model['model_id']) +if action_col.button('New analysis', icon=':material/play_arrow:', width='stretch', + help='Create an analysis using this model'): + st.session_state[NEW_ANALYSIS_DEFAULTS] = {'model': selected_id} + st.switch_page(ANALYSES_PAGE) + +details_col, analyses_col = st.columns([0.62, 0.38], gap='large') + +with details_col: + model_details(model, settings) + +with analyses_col: + st.markdown(f'**Analyses using this model ({len(model_analyses)})**') + if not model_analyses: + st.caption('None yet.') + else: + a_table = analyses_df(model_analyses, ci.portfolios.get(), table) + open_id = selectable_table( + a_table, ['name', 'portfolio_name', 'status_label'], 'model_open_analysis', + {'name': 'Analysis', 'portfolio_name': 'Portfolio', 'status_label': 'Status'}, + key=f'model_analyses_{selected_id}') + if st.button('Open analysis', disabled=open_id is None, icon=':material/open_in_new:'): + open_record(ANALYSES_PAGE, SELECTED_ANALYSIS, open_id) diff --git a/pages/portfolios.py b/pages/portfolios.py new file mode 100644 index 0000000..c9b5b91 --- /dev/null +++ b/pages/portfolios.py @@ -0,0 +1,217 @@ +import streamlit as st +from requests.exceptions import HTTPError + +from modules.ui import flash, page_setup, show_api_error +from pages.components.common import (ANALYSES_PAGE, NEW_ANALYSIS_DEFAULTS, SELECTED_ANALYSIS, + 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.exposure import exposure_overview + +ci = page_setup('Portfolios') + +portfolios = ci.portfolios.get() +analyses = ci.analyses.get() +portfolios_by_id = {p['id']: p for p in portfolios} + + +########################################################################################## +# Create portfolio +########################################################################################## + +@st.dialog('New portfolio', width='large') +def create_portfolio_dialog(): + name = st.text_input('Portfolio name', key='new_portfolio_name') + uploads = st.file_uploader('OED files (CSV or parquet)', accept_multiple_files=True, + type=['csv', 'parquet'], key='new_portfolio_files') + by_name = {f.name: f for f in uploads} + + assignment = {} + if uploads: + st.caption('Check which file is which. Guessed from the file names.') + guesses = {guess_file_type(f.name): f.name for f in reversed(uploads)} + options = list(by_name) + for file_type, label in FILE_TYPES.items(): + guess = guesses.get(file_type) + choice = st.selectbox(f'{label} file', options, + index=options.index(guess) if guess else None, + placeholder='None', key=f'new_portfolio_{file_type}') + if choice: + assignment[file_type] = by_name[choice] + + problems = [] + if not name: + problems.append('Enter a portfolio name.') + if name and name in [p['name'] for p in portfolios]: + problems.append(f'A portfolio called "{name}" already exists.') + if 'location_file' not in assignment: + problems.append('A location file is required.') + chosen = [f.name for f in assignment.values()] + if len(chosen) != len(set(chosen)): + problems.append('Each uploaded file can only be used once.') + + for p in problems: + st.caption(f':orange[{p}]') + + if st.button('Create portfolio', type='primary', disabled=bool(problems)): + try: + with st.spinner('Uploading...'): + created = ci.portfolios.create( + name=name, **assignment) + st.session_state[SELECTED_PORTFOLIO] = (created or {}).get('id') + flash(f'Portfolio "{name}" created') + st.rerun() + except HTTPError as e: + show_api_error('Creating portfolio', e) + + +########################################################################################## +# Portfolio list +########################################################################################## + +header_left, header_right = st.columns([0.8, 0.2], vertical_alignment='bottom') +header_left.caption('Portfolios are sets of OED exposure files. Select one to view or change its files, ' + 'explore its exposure, or see the analyses run against it.') +if header_right.button('New portfolio', type='primary', icon=':material/add:', width='stretch'): + create_portfolio_dialog() + +if not portfolios: + st.info('No portfolios yet. Create one to get started.') + st.stop() + +table = portfolios_df(portfolios, analyses) +column_config = { + 'name': 'Name', + 'id': st.column_config.NumberColumn('ID', width='small'), + 'location_file': st.column_config.CheckboxColumn('Location', width='small'), + 'accounts_file': st.column_config.CheckboxColumn('Accounts', width='small'), + 'reinsurance_info_file': st.column_config.CheckboxColumn('RI info', width='small'), + 'reinsurance_scope_file': st.column_config.CheckboxColumn('RI scope', width='small'), + 'n_analyses': st.column_config.NumberColumn('Analyses', width='small'), + 'modified': st.column_config.DatetimeColumn('Modified', format='D MMM YYYY, HH:mm'), +} +selected_id = selectable_table(table.sort_values('id', ascending=False), + ['id', 'name', *FILE_TYPES, 'n_analyses', 'modified'], + SELECTED_PORTFOLIO, column_config) + +if selected_id is None: + st.caption('Select a portfolio above to see its details.') + st.stop() + +portfolio = portfolios_by_id[selected_id] +portfolio_analyses = [a for a in analyses if a['portfolio'] == selected_id] + + +########################################################################################## +# Portfolio detail +########################################################################################## + +st.divider() +title_col, *action_cols = st.columns([0.55, 0.15, 0.15, 0.15], vertical_alignment='bottom') +title_col.subheader(portfolio['name']) + +with action_cols[0]: + if st.button('New analysis', icon=':material/play_arrow:', width='stretch', + disabled=not (portfolio.get('location_file') or {}).get('stored'), + help='Create an analysis using this portfolio'): + st.session_state[NEW_ANALYSIS_DEFAULTS] = {'portfolio': selected_id} + st.switch_page(ANALYSES_PAGE) + +with action_cols[1].popover('Rename', icon=':material/edit:', width='stretch'): + new_name = st.text_input('New name', value=portfolio['name'], key=f'rename_{selected_id}') + if st.button('Save', key=f'rename_save_{selected_id}', disabled=not new_name or new_name == portfolio['name']): + try: + ci.portfolios.rename(selected_id, new_name) + flash('Portfolio renamed') + st.rerun() + except HTTPError as e: + show_api_error('Renaming portfolio', e) + +with action_cols[2].popover('Delete', icon=':material/delete:', width='stretch'): + if portfolio_analyses: + st.warning(f'{len(portfolio_analyses)} analyses use this portfolio. They will lose access to its files.') + st.write(f"Delete **{portfolio['name']}**? This cannot be undone.") + if st.button('Delete portfolio', type='primary', key=f'delete_{selected_id}'): + try: + ci.portfolios.delete(selected_id) + st.session_state[SELECTED_PORTFOLIO] = None + flash(f"Portfolio \"{portfolio['name']}\" deleted") + st.rerun() + except HTTPError as e: + show_api_error('Deleting portfolio', e) + +files_tab, exposure_tab, analyses_tab = st.tabs( + ['Files', 'Exposure', f'Analyses ({len(portfolio_analyses)})']) + + +with files_tab: + for file_type, label in FILE_TYPES.items(): + info = portfolio.get(file_type) or {} + attached = bool(info.get('stored')) + + with st.container(border=True): + name_col, status_col, *btn_cols = st.columns([0.2, 0.35, 0.15, 0.15, 0.15], + vertical_alignment='center') + name_col.markdown(f'**{label}**') + status_col.markdown(f"`{info.get('name')}`" if attached else ':grey[Not attached]') + + preview_key = f'preview_{selected_id}_{file_type}' + if attached and btn_cols[0].button('Hide' if st.session_state.get(preview_key) else 'Preview', + key=f'{preview_key}_btn', width='stretch'): + st.session_state[preview_key] = not st.session_state.get(preview_key, False) + st.rerun() + + with btn_cols[1].popover('Replace' if attached else 'Attach', width='stretch'): + upload = st.file_uploader(f'{label} file', type=['csv', 'parquet'], + key=f'upload_{selected_id}_{file_type}') + if st.button('Upload', key=f'upload_btn_{selected_id}_{file_type}', disabled=upload is None): + try: + ci.portfolios.upload_file(selected_id, file_type, upload.getvalue(), upload.name) + flash(f'{label} file uploaded') + st.rerun() + except HTTPError as e: + show_api_error(f'Uploading {label.lower()} file', e) + + if attached: + with btn_cols[2].popover('Remove', width='stretch'): + st.write(f'Remove the {label.lower()} file from this portfolio?') + if st.button('Remove', type='primary', key=f'remove_{selected_id}_{file_type}'): + try: + ci.portfolios.delete_file(selected_id, file_type) + flash(f'{label} file removed') + st.rerun() + except HTTPError as e: + show_api_error(f'Removing {label.lower()} file', e) + + if attached and st.session_state.get(preview_key): + with st.spinner('Loading file...'): + df = portfolio_file_df(ci, portfolio, file_type) + if df is not None: + st.caption(f'{len(df):,} rows × {df.shape[1]} columns') + st.dataframe(df.head(1000), hide_index=True, height=300) + st.download_button('Download CSV', df.to_csv(index=False).encode(), + file_name=info.get('name') or f'{file_type}.csv', + key=f'download_{selected_id}_{file_type}') + + +with exposure_tab: + if not (portfolio.get('location_file') or {}).get('stored'): + st.info('Attach a location file to see an exposure summary.') + else: + with st.spinner('Loading locations...'): + locations = portfolio_file_df(ci, portfolio, 'location_file') + exposure_overview(locations) + + +with analyses_tab: + if not portfolio_analyses: + st.info('No analyses have been run against this portfolio.') + else: + a_table = analyses_df(portfolio_analyses, portfolios, models_df(ci, ci.models.get())) + open_id = selectable_table( + a_table, ['name', 'model_name', 'status_label', 'modified'], 'portfolio_open_analysis', + {'name': 'Analysis', 'model_name': 'Model', 'status_label': 'Status', + 'modified': st.column_config.DatetimeColumn('Modified', format='D MMM YYYY, HH:mm')}, + key=f'portfolio_analyses_{selected_id}') + if st.button('Open analysis', disabled=open_id is None, icon=':material/open_in_new:'): + open_record(ANALYSES_PAGE, SELECTED_ANALYSIS, open_id) diff --git a/pages/scenarios.py b/pages/scenarios.py deleted file mode 100644 index 377cba0..0000000 --- a/pages/scenarios.py +++ /dev/null @@ -1,514 +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, 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: - 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 a9a3097..0000000 --- a/pages/scenariosGuide.py +++ /dev/null @@ -1,430 +0,0 @@ -from modules.authorisation import quiet_login, 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.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 modules.client import ClientInterface -import logging -import os - -from pages.components.output import generate_eltcalc_fragment, generate_leccalc_fragment, generate_pltcalc_fragment, model_summary, summarise_inputs, generate_aalcalc_fragment -from pages.components.process import enrich_analyses, enrich_portfolios - -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/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..9ecdbaf --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,22 @@ +# Code quality configuration, mirroring OasisLMF (.github/workflows/code-quality.yml). + +[tool.ruff] +# ruff replaces flake8; autopep8 covers PEP8 formatting. +line-length = 150 +exclude = [".git", ".venv", "venv", "OasisPiWind", "scenarios", "oidc", "certs"] +# required for the DOC* (pydoclint) rules below, which are preview-only. +preview = true + +[tool.ruff.lint] +select = [ + # All pyflakes checks (flake8's F rules): unused imports/variables, undefined names, ... + "F", + # Docstring style rules used by OasisLMF + "D200", "D201", "D202", "D206", "D207", "D208", "D209", "D210", "D212", + "D214", "D300", "D301", "D403", "D405", "D410", "D411", "D412", "D414", + "D416", "D417", "D419", + "DOC202", "DOC402", +] + +[tool.ruff.lint.per-file-ignores] +"tests/**" = ["D"] diff --git a/requirements.txt b/requirements.txt index 297dad1..4901af3 100644 --- a/requirements.txt +++ b/requirements.txt @@ -96,7 +96,7 @@ oasis-data-manager==0.2.0 # via # oasislmf # ods-tools -oasislmf==2.5.0 +oasislmf==2.5.9 # via -r requirements.in ods-tools==5.0.1 # via oasislmf diff --git a/scenarios/a_settings.json b/scenarios/a_settings.json index e30f085..db44ef0 100644 --- a/scenarios/a_settings.json +++ b/scenarios/a_settings.json @@ -1,12 +1,12 @@ [ - { - "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" }, + { + "model_name_id": "EUWS-Domingos", + "settings_path": "./scenarios/defaults/15_euws-domingos_impact-forecasting-analysis_settings.json" + }, { "model_name_id": "MAEQ", "settings_path": "./scenarios/defaults/2_maeq_impact-forecasting-analysis_settings.json" diff --git a/scenarios/defaults/15_euws-domingos_impact-forecasting-analysis_settings.json b/scenarios/defaults/15_euws-domingos_impact-forecasting-analysis_settings.json new file mode 100644 index 0000000..5e3a64a --- /dev/null +++ b/scenarios/defaults/15_euws-domingos_impact-forecasting-analysis_settings.json @@ -0,0 +1,18 @@ +{ + "model_supplier_id": "ImpactForecasting", + "model_name_id": "EUWS-Domingos", + "number_of_samples": 10, + "model_settings": { + "event_set": "domingos" + }, + "gul_output": true, + "gul_summaries": [ + { + "id": 1, + "ord_output": { + "elt_moment": true + } + } + ], + "gul_threshold": 0 +} 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..cbe4d11 100644 --- a/scenarios/ui-config.json +++ b/scenarios/ui-config.json @@ -1,32 +1,62 @@ { - "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" + ], + "EUWS-Domingos": [ + "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..2d8b878 --- /dev/null +++ b/scenarios_ui/common.py @@ -0,0 +1,159 @@ +"""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, vulnerability_info +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 vulnerability_note(model_settings): + """Which vulnerability functions a scenario uses (from its model settings).""" + info = vulnerability_info(model_settings) + if info is None: + st.caption('**Vulnerability:** not documented for this scenario.') + return + source = f"[{info['source']}]({info['url']})" if info.get('url') else info['source'] + st.markdown(f'**Vulnerability:** {source}', + help='How much damage the hazard causes to a building, as a share of its value. ' + 'See the Guide for more on vulnerability functions.') + if info.get('description'): + st.caption(info['description']) + + +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 66% rename from pages/comparison.py rename to scenarios_ui/compare.py index f5c39a0..73a03ba 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 - -########################################################################################## -# 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, vulnerability_note + +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)] @@ -85,26 +63,31 @@ st.subheader("Analysis Summary") st.markdown(""" This section summarises the analyses selected for comparison: the number and value of buildings in the portfolio; -the hazard footprint selected, and the outputs available. -Under 'output settings', 'gul' referes to ground up loss, before insurance contract terms apply; 'aalcal' denotes that the +the hazard footprint selected, the vulnerability functions used, and the outputs available. Losses depend on the +vulnerability functions as well as the hazard, so runs of different scenarios may not be directly comparable. +Under 'output settings', 'gul' refers to ground up loss, before insurance contract terms apply; 'aalcal' denotes that the Annual Average Loss has been estimated; 'eltcalc' denotes that the per-event loss has been estimated. """) expander = st.expander('Analysis Summary') with expander: cols = st.columns(2) + + @st.cache_data -def get_analysis_inputs(ID): +def get_analysis_inputs(ID, modified=None): # `modified` busts the cache after a re-run return client_interface.analyses.get_file(ID, 'input_file', df=True) + @st.cache_data -def get_analysis_outputs(ID): +def get_analysis_outputs(ID, modified=None): # `modified` busts the cache after a re-run return client_interface.analyses.get_file(ID, 'output_file', df=True) + def get_location_df(inputs): - '''Return the locations DataFrame from an `input_file` dict, whichever + """Return the locations DataFrame from an `input_file` dict, whichever of `location.csv` or `location.parquet` is present. - ''' + """ if not inputs: return None if 'location.csv' in inputs: @@ -113,37 +96,41 @@ def get_location_df(inputs): return inputs['location.parquet'] return None + analysis_settings = [] model_settings = [] with cols[0]: st.write(f"## {selected['name'][0]}") with st.spinner("Loading data..."): - inputs = get_analysis_inputs(analysis_ids[0]) + inputs = get_analysis_inputs(analysis_ids[0], selected['modified'][0]) analysis_settings.append(client.analyses.settings.get(analysis_ids[0]).json()) model_settings.append(client_interface.models.settings.get(model_ids[0])) with st.spinner('Loading analysis summary...'): summarise_inputs(get_location_df(inputs), analysis_settings[0], model_settings[0], title_prefix='###') + vulnerability_note(model_settings[0]) with cols[1]: st.write(f"## {selected['name'][1]}") with st.spinner("Loading data..."): - inputs = get_analysis_inputs(analysis_ids[1]) + inputs = get_analysis_inputs(analysis_ids[1], selected['modified'][1]) analysis_settings.append(client.analyses.settings.get(analysis_ids[1]).json()) model_settings.append(client_interface.models.settings.get(model_ids[1])) with st.spinner('Loading analysis summary...'): summarise_inputs(get_location_df(inputs), analysis_settings[1], model_settings[1], title_prefix='###') + vulnerability_note(model_settings[1]) + @st.cache_data def get_locations_file(ID): inputs = client_interface.analyses.get_file(ID, 'input_file', df=True) return get_location_df(inputs) + @st.cache_data def merge_locations(locations_1, locations_2): - '''Concatenate locations for comparison and add `loc_analysis_id` identifier. - ''' + """Concatenate locations for comparison and add `loc_analysis_id` identifier.""" if locations_1 is None or locations_2 is None: return None @@ -163,6 +150,7 @@ def merge_locations(locations_1, locations_2): return locations + perspectives = ['gul', 'il', 'ri'] st.write("# Loss estimates") @@ -173,7 +161,7 @@ def merge_locations(locations_1, locations_2): continue summaries = [s.get(f'{p}_summaries', [{}])[0] for s in analysis_settings] - names = selected['name'].tolist() # 'GUL OUTPUT' SHOULD BE MORE UNDERSTANDABLE FOR NON-EXPERT USERS BY USING TITLE 'GROUND UP LOSS' + names = selected['name'].tolist() # 'GUL OUTPUT' SHOULD BE MORE UNDERSTANDABLE FOR NON-EXPERT USERS BY USING TITLE 'GROUND UP LOSS' ord_settings = [s.get('ord_output', {}) or {} for s in summaries] @@ -188,7 +176,7 @@ def merge_locations(locations_1, locations_2): supported_outputs = ['aalcalc', 'eltcalc', 'lec_output'] supported_ord_outputs = ['elt_moment', 'elt_quantile', 'plt_moment', - 'plt_quantile', 'alt_meanonly', 'alt_period'] + 'plt_quantile', 'alt_meanonly', 'alt_period'] has_legacy = any(all(s.get(output, False) for s in summaries) for output in supported_outputs) has_ord = any(all(o.get(output, False) for o in ord_settings) for output in supported_ord_outputs) @@ -200,18 +188,23 @@ def merge_locations(locations_1, locations_2): st.error('No comparison available.') with st.spinner("Loading data..."): - outputs = [OutputInterface(get_analysis_outputs(id)) for id in analysis_ids] + outputs = [OutputInterface(get_analysis_outputs(id, modified)) + for id, modified in zip(analysis_ids, selected['modified'])] for output, s in zip(outputs, summaries): oed_fields = s.get('oed_fields', None) 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) @@ -230,7 +223,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) @@ -246,7 +239,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) @@ -259,7 +252,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', @@ -268,7 +261,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', @@ -277,18 +270,18 @@ 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 = {1: 'MeanDR', 2: 'Full', 3: 'PerSampleMean', 4: 'MeanSample'} + ep_calc_map = EP_CALC_LABELS generate_leccalc_comparison_fragment(p, outputs, names=names, output_type='ept', filter_specs=[ @@ -298,4 +291,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..92e55c1 --- /dev/null +++ b/scenarios_ui/explore.py @@ -0,0 +1,239 @@ +"""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, vulnerability_note + +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']) + vulnerability_note(cached_model_settings(ci, models_by_id[chosen['id']])) + +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..84d690a --- /dev/null +++ b/scenarios_ui/guide.py @@ -0,0 +1,120 @@ +"""Guide: what the Scenarios tool is and how to use it.""" +import streamlit as st + +from modules.scenarios import scenario_models, vulnerability_info +from pages.components.data import cached_model_settings +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('Vulnerability functions') +st.markdown(""" +A vulnerability function gives the damage to a building, as a share of its value, for each level of hazard - +for example how much a house is damaged by one metre of flood water. Functions usually depend on what the +building is used for (its *occupancy*) and sometimes on how it is built, and they can include uncertainty: a +spread of possible damage at each hazard level, which is what the samples draw from. + +The same hazard footprint can give very different losses with different vulnerability functions, so they are +as important to the result as the event itself. The scenarios here use these functions: +""") +ci = ctx.ci +by_source = {} +for model in scenario_models(ci.models.get(), ci.portfolios.get(), ctx.ui_config): + info = vulnerability_info(cached_model_settings(ci, model)) or {'source': 'Not documented'} + entry = by_source.setdefault(info['source'], {'url': info.get('url'), 'scenarios': []}) + entry['scenarios'].append(ctx.scenario_name(model)) +lines = [] +for source, entry in sorted(by_source.items()): + label = f"[{source}]({entry['url']})" if entry['url'] else source + lines.append(f"- **{label}**: {', '.join(sorted(entry['scenarios']))}") +st.markdown('\n'.join(lines)) +st.markdown(""" +Each scenario's functions are described in full when you choose it. They are part of the scenario's model +data and cannot be changed in this tool. To run a scenario with different functions, download it from the +[Oasis Scenarios repository](https://github.com/OasisLMF/Scenarios) and replace its vulnerability files - for +example with functions from the [Oasis Vulnerability Library](https://github.com/OasisLMF/VulnerabilityLibrary) - +then run it with the [Oasis MDK](https://github.com/OasisLMF/OasisLMF). +""") + +st.header('Running a scenario') +st.markdown(f""" +1. **Choose a scenario** on the *Run a scenario* page. Filter the list by peril, country or provider; the + chosen scenario shows what it represents, who provided it and which vulnerability functions it uses. +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..aef6427 --- /dev/null +++ b/scenarios_ui/showcase.py @@ -0,0 +1,45 @@ +"""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, vulnerability_note + +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) + vulnerability_note(cached_model_settings(ci, model)) + 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 5ebcffa..f082be7 100644 --- a/scripts/add_settings_template.py +++ b/scripts/add_settings_template.py @@ -9,6 +9,7 @@ logger = logging.getLogger(__name__) logging.basicConfig(level=LOG_LEVEL) + def add_model_analysis_settings(client, model_id, analysis_settings_path): models = client.models.search({'model_id': str(model_id)}).json() if not models: @@ -23,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}...") @@ -61,5 +67,5 @@ def main(): model_analysis_config["settings_path"]) -if __name__=="__main__": +if __name__ == "__main__": main() 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/generate-certs.sh b/scripts/generate-certs.sh new file mode 100755 index 0000000..c54b4cf --- /dev/null +++ b/scripts/generate-certs.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +# Create the TLS certificate Traefik serves for HTTPS. +# +# Writes certs/ui.crt and certs/ui.key for $OASIS_UI_HOSTNAME (plus localhost). +# - If `mkcert` is installed, its locally trusted CA is used, so browsers +# accept the certificate without a warning (run `mkcert -install` once). +# - Otherwise a local CA is created with openssl (certs/oasis-local-ca.crt); +# import that CA into your browser / OS trust store to remove the warning. +# +# Existing certificates covering the hostname are kept, so you can drop your +# own certs/ui.crt and certs/ui.key in place (e.g. from your organisation's CA). +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CERT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)/certs" +HOSTNAME="${OASIS_UI_HOSTNAME:-ui.oasis.local}" +CRT="$CERT_DIR/ui.crt" +KEY="$CERT_DIR/ui.key" +CA_CRT="$CERT_DIR/oasis-local-ca.crt" +CA_KEY="$CERT_DIR/oasis-local-ca.key" + +mkdir -p "$CERT_DIR" + +if [ -f "$CRT" ] && [ -f "$KEY" ] \ + && openssl x509 -in "$CRT" -noout -checkend 604800 >/dev/null 2>&1 \ + && openssl x509 -in "$CRT" -noout -ext subjectAltName 2>/dev/null | grep -q "DNS:${HOSTNAME}\b"; then + echo " -> Using existing certificate for ${HOSTNAME} ($CRT)" + exit 0 +fi + +if command -v mkcert >/dev/null 2>&1; then + echo " -> Creating certificate for ${HOSTNAME} with mkcert" + mkcert -cert-file "$CRT" -key-file "$KEY" "$HOSTNAME" localhost 127.0.0.1 >/dev/null 2>&1 + echo " If your browser still warns, run 'mkcert -install' once to trust mkcert's CA." + exit 0 +fi + +if [ ! -f "$CA_CRT" ] || [ ! -f "$CA_KEY" ]; then + echo " -> Creating local certificate authority ($CA_CRT)" + openssl req -x509 -new -nodes -newkey rsa:2048 -sha256 -days 3650 \ + -keyout "$CA_KEY" -out "$CA_CRT" -subj "/CN=Oasis local development CA" >/dev/null 2>&1 + chmod 600 "$CA_KEY" +fi + +echo " -> Creating certificate for ${HOSTNAME} signed by the local CA" +TMP="$(mktemp -d)" +trap 'rm -rf "$TMP"' EXIT +cat > "$TMP/ext.cnf" </dev/null 2>&1 +openssl x509 -req -in "$TMP/ui.csr" -CA "$CA_CRT" -CAkey "$CA_KEY" -CAcreateserial \ + -out "$CRT" -days 825 -sha256 -extfile "$TMP/ext.cnf" >/dev/null 2>&1 +chmod 600 "$KEY" + +cat < Privacy & Security > Certificates > Import $CA_CRT + - System (Ubuntu): sudo cp $CA_CRT /usr/local/share/ca-certificates/oasis-local-ca.crt && sudo update-ca-certificates + Or install mkcert, run 'mkcert -install', delete certs/ui.* and re-run the installer. +EOF diff --git a/scripts/prune_analysis.py b/scripts/prune_analysis.py index 3f379c8..e3397c5 100644 --- a/scripts/prune_analysis.py +++ b/scripts/prune_analysis.py @@ -1,12 +1,10 @@ -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(): @@ -19,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 for oasislmf client.', - default='password') + 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('--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) @@ -37,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' @@ -82,5 +80,6 @@ def main(): except HTTPError: logger.error(f'Failed to delete: {id}.') -if __name__=="__main__": + +if __name__ == "__main__": main() 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 7936146..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/