From ac97d7933f4e56f3cc9eafa0eeee07e9bb5ad6c8 Mon Sep 17 00:00:00 2001 From: Ben Hayes Date: Thu, 5 Nov 2026 11:57:09 +0000 Subject: [PATCH 01/33] Fix workflow bugs in Analyses, Dashboard and settings form - Dashboard: import handle_login, add page to ui-config, fix README page list - Analyses: allow regenerating inputs after INPUTS_GENERATION_ERROR - Analyses: auto-refresh also tracks analyses generating inputs on page load - Analyses: confirm before deleting an analysis - Key cached input/output fetches on modified time so re-runs aren't stale - Settings form: keep PSEPT selection when editing a level; fix PLT label - Portfolio enrichment: don't crash on missing files; remove debug output Co-Authored-By: Claude Opus 5.5 --- README.md | 6 ++++- pages/analyses.py | 53 ++++++++++++++++++++++++------------- pages/components/create.py | 4 +-- pages/components/process.py | 2 +- pages/dashboard.py | 10 +++---- ui-config.json | 3 ++- 6 files changed, 50 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index e2de835..78631bf 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,11 @@ The current version of the UI contains the following 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. +- `/scenarios` - Simplified UI which allows for the running of analyses using previously loaded portfolios & models. +- `/comparison` - Compare the outputs of two completed analyses. +- `/scenariosGuide` - User guide for the scenarios and comparison pages. + +Which pages appear in the sidebar is controlled by `ui-config.json`. ## Prerequisites diff --git a/pages/analyses.py b/pages/analyses.py index bc3756b..a5a6e25 100644 --- a/pages/analyses.py +++ b/pages/analyses.py @@ -113,10 +113,10 @@ def analysis_summary_expander(selected): 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): + def get_input_file(analysis_id, modified=None): # `modified` busts the cache after a re-run return client_interface.analyses.get_file(analysis_id, 'input_file', df=True) - inputs = get_input_file(analysis_id) + inputs = get_input_file(analysis_id, selected.get('modified')) locations = inputs.get('location.csv', None) if client.analyses.get(analysis_id).json().get('settings') is not None: @@ -145,11 +145,11 @@ def convert_df(df): @st.cache_data(show_spinner="Fetching output data...") - def get_output_file(analysis_id): + def get_output_file(analysis_id, modified=None): # `modified` busts the cache after a re-run return client_interface.analyses.get_file(analysis_id, 'output_file', df=True) if selected['status'] == 'RUN_COMPLETED': - outputs = get_output_file(analysis_id) + outputs = get_output_file(analysis_id, selected.get('modified')) with outputs_tab: output_file_list = sorted(list(outputs.keys())) @@ -164,9 +164,9 @@ def get_output_file(analysis_id): fname = f"analysis_{analysis_id}_output.tar.gz" @st.cache_data(show_spinner="Fetching output tar data...") - def get_output_tar(analysis_id): + def get_output_tar(analysis_id, modified=None): # `modified` busts the cache after a re-run return client_interface.download_output(analysis_id) - fdata = get_output_tar(analysis_id) + fdata = get_output_tar(analysis_id, selected.get('modified')) st.download_button('Download All Outputs', data=fdata, @@ -188,14 +188,22 @@ def run_analysis(re_handler): completed_statuses = ['RUN_COMPLETED', 'RUN_CANCELLED', 'RUN_ERROR'] running_statuses = ['RUN_QUEUED', 'RUN_STARTED'] + generation_done_statuses = ['READY', 'INPUTS_GENERATION_ERROR', 'INPUTS_GENERATION_CANCELLED'] + completed_statuses + generating_statuses = ['INPUTS_GENERATION_QUEUED', 'INPUTS_GENERATION_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) + # Check for running / generating analyses (e.g. after a page reload) + if not re_handler.is_refreshing(): + in_progress = analyses[analyses['status'].isin(running_statuses + generating_statuses)] + if not in_progress.empty: + for _, row in in_progress.iterrows(): + if row['status'] in generating_statuses: + re_handler.add_to_queue(row['id'], generation_done_statuses) + else: + re_handler.add_to_queue(row['id'], completed_statuses) + re_handler.set_refresh_bool(True) + st.rerun() left, middle, right = st.columns(3, vertical_alignment='center') st.write('1) Select an analysis:') @@ -213,7 +221,7 @@ def run_analysis(re_handler): validations = ValidationGroup() validations.add_validation(NotNoneValidation('Selected analysis'), selected) validations.add_validation(KeyInValuesValidation('Status'), selected, - 'status', ['NEW', 'INPUTS_GENERATION_CANCELLED', + 'status', ['NEW', 'INPUTS_GENERATION_CANCELLED', 'INPUTS_GENERATION_ERROR', 'READY', 'RUN_COMPLETED', 'RUN_CANCELLED', 'RUN_ERROR' ]) @@ -359,13 +367,22 @@ def set_analysis_settings(analysis): validation = NotNoneValidation('Selected analysis') button_enabled = validation.is_valid(selected) - if left.button("Delete", width='stretch', disabled = not button_enabled, help=validation.message): - try: - client.analyses.delete(selected['id']) + @st.dialog("Delete Analysis") + def confirm_delete_dialog(analysis): + st.write(f"Delete analysis **{analysis['name']}** (ID {analysis['id']})? This cannot be undone.") + cancel_col, delete_col = st.columns(2) + if cancel_col.button("Cancel", width='stretch'): st.rerun() - except HTTPError as e: - st.error("Deletion failed.") - logger.error(e) + if delete_col.button("Delete", type='primary', width='stretch'): + try: + client.analyses.delete(analysis['id']) + st.rerun() + except HTTPError as e: + st.error("Deletion failed.") + logger.error(e) + + if left.button("Delete", width='stretch', disabled = not button_enabled, help=validation.message): + confirm_delete_dialog(selected) validations = ValidationGroup() validations.add_validation(NotNoneValidation('Analysis'), selected) diff --git a/pages/components/create.py b/pages/components/create.py index 3c2c0c5..de15249 100644 --- a/pages/components/create.py +++ b/pages/components/create.py @@ -451,7 +451,7 @@ def output_type_multiselect(label, options, prefix, key=None, default=None): default=defaults.get('elt', None), key=f'{perspective}_elt_multiselect') - ord_options |= output_type_multiselect(label='Period Loss Table (ELT) Output', prefix='plt', + ord_options |= output_type_multiselect(label='Period Loss Table (PLT) Output', prefix='plt', options=elt_plt_options, default=defaults.get('plt', None), key=f'{perspective}_plt_multiselect') @@ -488,7 +488,7 @@ def output_type_multiselect(label, options, prefix, key=None, default=None): ord_options |= output_type_multiselect(label='Per Sample Exceedance Probability Table (PS EPT) Output:', prefix='psept', options=['aep', 'oep'], - default=defaults.get('psep', None), + default=defaults.get('psept', None), key=f'{perspective}_psep_multiselect') return ord_options diff --git a/pages/components/process.py b/pages/components/process.py index 52158df..c2a7c5f 100644 --- a/pages/components/process.py +++ b/pages/components/process.py @@ -19,6 +19,7 @@ def number_rows(portfolio_ids, client_interface, filename='location_file', col_n if file_df is None: data['id'].append(id) data[col_name].append(None) + continue data['id'].append(id) data[col_name].append(file_df.shape[0]) @@ -33,7 +34,6 @@ def number_accounts(portfolio_ids, client_interface): 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() diff --git a/pages/dashboard.py b/pages/dashboard.py index 67c7a13..ce7251b 100644 --- a/pages/dashboard.py +++ b/pages/dashboard.py @@ -2,7 +2,7 @@ import streamlit as st from modules.client import ClientInterface from modules.nav import SidebarNav -from modules.authorisation import validate_page +from modules.authorisation import validate_page, handle_login import pandas as pd from pages.components.footer import generate_footer @@ -45,11 +45,11 @@ analysis_id = selected_analysis['id'] @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) with st.spinner("Loading data..."): - inputs = get_analysis_inputs(analysis_id) + inputs = get_analysis_inputs(analysis_id, selected_analysis.get('modified')) settings = client.analyses.settings.get(analysis_id).json() st.write("# Analysis Summary") @@ -57,11 +57,11 @@ def get_analysis_inputs(ID): summarise_inputs(inputs.get('location.csv', None), settings) @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) with st.spinner("Loading data..."): - outputs = get_analysis_outputs(analysis_id) + outputs = get_analysis_outputs(analysis_id, selected_analysis.get('modified')) # Set up visualisation interface vis = OutputInterface(outputs) diff --git a/ui-config.json b/ui-config.json index 0555c45..57efeb5 100644 --- a/ui-config.json +++ b/ui-config.json @@ -3,7 +3,8 @@ {"path": "pages/scenariosGuide.py", "label": "User Guide"}, {"path": "pages/scenarios.py", "label": "Scenarios"}, {"path": "pages/comparison.py", "label": "Comparison"}, - {"path": "pages/analyses.py", "label": "Analyses"} + {"path": "pages/analyses.py", "label": "Analyses"}, + {"path": "pages/dashboard.py", "label": "Dashboard"} ], "post_login_page": "pages/scenariosGuide.py", "model_map": { From 095e1f1b6b5032385657abd3a522acf17f89c594 Mon Sep 17 00:00:00 2001 From: Ben Hayes Date: Thu, 5 Nov 2026 11:57:09 +0000 Subject: [PATCH 02/33] Upgrade platform, worker, PiWind and oasislmf to 2.5.9 Co-Authored-By: Claude Opus 5.5 --- .env | 6 +++--- .env.authentik | 6 +++--- .env.example | 6 +++--- .env.keycloak | 6 +++--- .env.simple | 6 +++--- README.md | 4 ++-- requirements.txt | 2 +- 7 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.env b/.env index dabc5fb..4852c8c 100644 --- a/.env +++ b/.env @@ -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..bf23921 100644 --- a/.env.authentik +++ b/.env.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..c841bc6 100644 --- a/.env.example +++ b/.env.example @@ -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..4852c8c 100644 --- a/.env.keycloak +++ b/.env.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.simple b/.env.simple index 50d4b45..7980d4d 100644 --- a/.env.simple +++ b/.env.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/README.md b/README.md index 78631bf..ce591cb 100644 --- a/README.md +++ b/README.md @@ -199,8 +199,8 @@ 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` | +| `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. 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 From 6b4612a0ed7003f34e27976684bb4a44b3b41c9e Mon Sep 17 00:00:00 2001 From: Ben Hayes Date: Thu, 5 Nov 2026 12:12:05 +0000 Subject: [PATCH 03/33] Use python3 for api_server healthchecks The 2.5.9 api_server image no longer ships curl or a shell, so the curl-based healthchecks (and install.sh's wait loop) always failed and the UI/worker never started. Check /healthcheck/ via python3 instead. Co-Authored-By: Claude Opus 5.5 --- docker-compose.yml | 2 +- install.sh | 11 ++++++++++- oasis-platform.yml | 2 +- oasis-scenarios-platform.yml | 2 +- 4 files changed, 13 insertions(+), 4 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index f411c5d..24343b1 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -124,7 +124,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/install.sh b/install.sh index b1f5384..9bd9a6b 100755 --- a/install.sh +++ b/install.sh @@ -296,7 +296,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" } 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 index 02dd84c..96fecba 100755 --- a/oasis-scenarios-platform.yml +++ b/oasis-scenarios-platform.yml @@ -44,7 +44,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 From ead8c2c92946c6f11cb5b6c1a241999ea71c1b08 Mon Sep 17 00:00:00 2001 From: Ben Hayes Date: Thu, 5 Nov 2026 14:05:53 +0000 Subject: [PATCH 04/33] Fix broken Analyses and login tests - mocks: add the settings / setting_templates sub-endpoints ClientInterface wraps, look records up by id, support search/delete, and deep-copy fixture data so tests can't leak state into each other - test_app: use monkeypatch instead of pytest-mock's mocker (not a dependency) and give the mock client the endpoints ClientInterface needs - test_analyses: update for the current page layout (portfolio dialog, Run/Create Analysis tabs, enriched analyses table) and test the create-portfolio form via a standalone fixture app, since AppTest closes dialogs on rerun Co-Authored-By: Claude Opus 5.5 --- tests/fixtures/create_portfolio_form_app.py | 14 +++ tests/mocks.py | 82 +++++++++---- tests/test_analyses.py | 129 ++++++++++---------- tests/test_app.py | 13 +- 4 files changed, 145 insertions(+), 93 deletions(-) create mode 100644 tests/fixtures/create_portfolio_form_app.py diff --git a/tests/fixtures/create_portfolio_form_app.py b/tests/fixtures/create_portfolio_form_app.py new file mode 100644 index 0000000..b827120 --- /dev/null +++ b/tests/fixtures/create_portfolio_form_app.py @@ -0,0 +1,14 @@ +''' +Standalone script for AppTest coverage of `create_portfolio_form`. + +On the Analyses page the form lives inside an `st.dialog`, which AppTest +closes on every full rerun, so the form is exercised on its own here. The +returned form data is stored in `session_state['form_data']`. +''' +import streamlit as st + +from pages.components.create import create_portfolio_form + +form_data = create_portfolio_form() +if form_data is not None: + st.session_state['form_data'] = form_data diff --git a/tests/mocks.py b/tests/mocks.py index ee966b8..7e2b3a0 100644 --- a/tests/mocks.py +++ b/tests/mocks.py @@ -1,44 +1,80 @@ +from copy import deepcopy + from oasis_data_manager.errors import OasisException + class MockJsonObject: - def __init__(self, data = {}): - self.data = data + def __init__(self, data=None): + self.data = {} if data is None else data def json(self): return self.data + class MockEndpoint: - def __init__(self, json_data=[{}]): - self.json_data = json_data + '''Minimal stand-in for an `oasislmf` APIClient endpoint backed by a list of dicts. + + `get(ID)` looks records up by their `id` field (falling back to list + position for records without one), matching the real API. + ''' + def __init__(self, json_data=None): + self.json_data = [] if json_data is None else json_data + # Sub-endpoints wrapped by `modules.client` interfaces + self.settings = MockSubEndpoint() + + def _find(self, ID): + for record in self.json_data: + if isinstance(record, dict) and record.get('id') == ID: + return record + return self.json_data[ID] def get(self, ID=None): if ID is None: - data = self.json_data - else: - data = self.json_data[ID] - return MockJsonObject(data) + return MockJsonObject(self.json_data) + return MockJsonObject(self._find(ID)) + + def search(self, metadata=None): + metadata = metadata or {} + matches = [r for r in self.json_data + if all(r.get(k) == v for k, v in metadata.items())] + return MockJsonObject(matches) + + def delete(self, ID): + self.json_data[:] = [r for r in self.json_data if r.get('id') != ID] + + +class MockSubEndpoint: + '''Sub-endpoint (e.g. `analyses.settings`) keyed by parent ID.''' + def __init__(self, data=None): + self.data = {} if data is None else data + + def get(self, ID=None): + return MockJsonObject(self.data.get(ID, {})) + + +class MockModelsEndpoint(MockEndpoint): + def __init__(self, json_data=None): + super().__init__(json_data) + self.setting_templates = MockSubEndpoint() + self.setting_templates.content = MockSubEndpoint() + class MockApiClient: def __init__(self, username="", password="", - portfolios=[], models=[], analyses=[]): - self.portfolios = MockEndpoint(portfolios) - self.models = MockEndpoint(models) - self.analyses = MockEndpoint(analyses) + portfolios=None, models=None, analyses=None, **kwargs): + # Copy so tests mutating endpoint data can't leak into shared fixtures + self.portfolios = MockEndpoint(deepcopy(portfolios)) + self.models = MockModelsEndpoint(deepcopy(models)) + self.analyses = MockEndpoint(deepcopy(analyses)) @staticmethod def server_info(): - return MockJsonObject + return MockJsonObject() - def upload_inputs(self, portfolio_name=None,**kwargs): + def upload_inputs(self, portfolio_name=None, **kwargs): if portfolio_name is None: raise OasisException('Portfolio name required') - if len(self.portfolios.json_data) == 1: - self.portfolios.json_data[0]['name'] = portfolio_name - - else: - self.portfolios = [ - { - 'name': portfolio_name - } - ] + portfolios = self.portfolios.json_data + next_id = max([p.get('id', 0) for p in portfolios] + [0]) + 1 + portfolios.append({'id': next_id, 'name': portfolio_name}) diff --git a/tests/test_analyses.py b/tests/test_analyses.py index ddb86a0..d72f8b2 100644 --- a/tests/test_analyses.py +++ b/tests/test_analyses.py @@ -1,102 +1,99 @@ from streamlit.testing.v1 import AppTest -import pandas as pd -from pandas.testing import assert_frame_equal import tests.mocks as m from modules.client import ClientInterface -def test_empty_analyses_page(): - at = AppTest.from_file("app.py") - at.session_state["client"] = m.MockApiClient() - at.session_state["client_interface"] = ClientInterface(m.MockApiClient()) + +def analyses_app(client): + at = AppTest.from_file("app.py", default_timeout=30) + at.session_state["client"] = client + at.session_state["client_interface"] = ClientInterface(client=client) at.switch_page("pages/analyses.py") - at = at.run() + return at.run() - # Empty portfolios - portfolios_df = at.dataframe[0].value - columns=['id', 'name', 'created', 'modified'] - expected_df = pd.DataFrame(columns=columns) - assert_frame_equal(expected_df, portfolios_df) +def test_empty_analyses_page(): + at = analyses_app(m.MockApiClient()) + + assert not at.exception - assert at.tabs[0].label == 'Show Portfolios' - assert at.tabs[1].label == 'Create Portfolio' + # Empty portfolios table shows only the name column + portfolios_df = at.dataframe[0].value + assert portfolios_df.empty + assert list(portfolios_df.columns) == ['name'] + assert at.button[0].label == 'Create Portfolio' + + assert [t.label for t in at.tabs] == ['Run Analysis', 'Create Analysis'] - # Empty analyses - analysis_df = at.dataframe[1].value - columns = ["id", "name", "portfolio", "model", "created", "modified", "status"] - expected_df = pd.DataFrame(columns=columns) - assert_frame_equal(expected_df, analysis_df) + info = [i.value for i in at.info] + assert 'No analyses.' in info + assert 'Ensure portfolios and models are loaded.' in info - assert at.tabs[2].label == 'Run Analysis' - assert at.tabs[3].label == 'Create Analysis' def test_display_portfolio(mock_app_test, request): - config = request.config at = mock_app_test - _portfolio_data = config.portfolios_data[0] - df_data = { - 'id' : [config.portfolio_ID], - 'name': [_portfolio_data['name']], - "created": [_portfolio_data['created']], - "modified": [_portfolio_data['modified']], - "storage_links": [_portfolio_data['storage_links']] - } - - expected_df = pd.DataFrame.from_dict(df_data) - expected_df['created'] = pd.to_datetime(expected_df['created']) - expected_df['modified'] = pd.to_datetime(expected_df['modified']) - app_df = at.dataframe[0].value + portfolios_df = at.dataframe[0].value + expected_names = [p['name'] for p in request.config.portfolios_data] + assert list(portfolios_df['name']) == expected_names - assert_frame_equal(expected_df, app_df) def test_display_analyses(mock_app_test, request): + config = request.config at = mock_app_test - _analyses_data = request.config.analyses_data[0] - - expected_data = { - "created": [_analyses_data['created']], - "modified": [_analyses_data['modified']], - "name": [_analyses_data['name']], - "id": [request.config.analyses_ID], - "portfolio": [request.config.portfolio_ID], - "model": [request.config.model_ID], - "status": [_analyses_data['status']], - } - - expected_df = pd.DataFrame.from_dict(expected_data) - expected_df['created'] = pd.to_datetime(expected_df['created']) - expected_df['modified'] = pd.to_datetime(expected_df['modified']) - - app_df = at.dataframe[1].value - assert_frame_equal(expected_df, app_df) - -def test_create_portfolio_form(mock_app_test): + analysis = config.analyses_data[0] + + analyses_df = at.dataframe[1].value + assert len(analyses_df) == 1 + row = analyses_df.iloc[0] + + assert row['id'] == config.analyses_ID + assert row['name'] == analysis['name'] + assert row['status'] == analysis['status'] + # Enriched from the portfolios / models endpoints + assert row['portfolio_name'] == config.portfolios_data[0]['name'] + assert row['model_id'] == config.models_data[0]['model_id'] + assert row['model_supplier'] == config.models_data[0]['supplier_id'] + + +def test_create_portfolio_button_opens_dialog(mock_app_test): at = mock_app_test - _portfolio_data = { - 'name': 'new-string', - } + at = at.button[0].click().run() - at = at.tabs[1].button[0].click().run() + assert not at.exception + assert at.text_input(key='portfolio_name').label == 'Portfolio Name' + + +def test_create_portfolio_form_requires_name(): + at = AppTest.from_file("tests/fixtures/create_portfolio_form_app.py").run() + + at = at.button[0].click().run() assert 'Name' in at.error[0].value + assert 'form_data' not in at.session_state + + +def test_create_portfolio_form_returns_data(): + at = AppTest.from_file("tests/fixtures/create_portfolio_form_app.py").run() - at = at.text_input(key='portfolio_name').input(_portfolio_data['name']).run() - at = at.tabs[1].button[0].click().run() + at = at.text_input(key='portfolio_name').input('new-portfolio').run() + at = at.button[0].click().run() - assert at.dataframe[0].value['name'][0] == _portfolio_data['name'] - assert at.success[0].value == 'Successfully created portfolio' + assert not at.error + form_data = at.session_state['form_data'] + assert form_data['name'] == 'new-portfolio' + assert form_data['location_file'] is None def test_create_analyses_form(mock_app_test, request): at = mock_app_test + create_tab = at.tabs[1] - portfolio_select = at.tabs[3].selectbox[0].options + portfolio_select = create_tab.selectbox[0].options assert len(portfolio_select) == len(request.config.portfolios_data) assert request.config.portfolios_data[0]['name'] in portfolio_select[0] - model_select = at.tabs[3].selectbox[1].options + model_select = create_tab.selectbox[1].options assert len(model_select) == len(request.config.models_data) assert request.config.models_data[0]['supplier_id'] in model_select[0] diff --git a/tests/test_app.py b/tests/test_app.py index 961104e..828a6d6 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -1,6 +1,7 @@ from streamlit.testing.v1 import AppTest import pytest from oasis_data_manager.errors import OasisException +import tests.mocks as m @pytest.fixture(autouse=True) def no_requests(monkeypatch): @@ -29,7 +30,7 @@ def test_login_validation(at_before_login, user, password, err_fragment): assert err_fragment in at.error[0].value @pytest.fixture -def mock_api_client(mocker): +def mock_api_client(monkeypatch): class MockJsonObject: @staticmethod def json(): @@ -39,15 +40,19 @@ class MockApiClient: valid_user = "mock_user" valid_password = "mock_password" - def __init__(self, username="", password="", api_url=""): + def __init__(self, username="", password="", api_url="", **kwargs): if username != self.valid_user or password != self.valid_password: raise OasisException("") - return None + # Endpoints wrapped by ClientInterface + self.portfolios = m.MockEndpoint() + self.analyses = m.MockEndpoint() + self.models = m.MockModelsEndpoint() @staticmethod def server_info(): return MockJsonObject - return mocker.patch("modules.client.APIClient", MockApiClient) + monkeypatch.setattr("modules.client.APIClient", MockApiClient) + return MockApiClient @pytest.mark.parametrize("user, password, errors", [("mock_user", "mock_password", ()), From 407008d89812eb5461ea634f85c7fa6001ca9db8 Mon Sep 17 00:00:00 2001 From: Ben Hayes Date: Thu, 5 Nov 2026 14:30:16 +0000 Subject: [PATCH 05/33] Restructure standard UI into Portfolios, Models and Analyses pages - Standard UI navigation is now Analyses / Portfolios / Models; the Dashboard page is removed (results open within Analyses). Scenarios keeps its own ui-config. - Portfolios: create with auto-detected OED file types, view/attach/ replace/remove files, exposure summary and map, linked analyses. - Models: schema-labelled overview, run options, parameters, perils and raw settings, plus the analyses that used the model. - Analyses: filterable list with live progress, detail with results, settings, inputs and logs; create/edit settings from platform templates, defaults files, previous analyses, uploads or model defaults. - New schema-driven analysis settings editor: controls generated from the ODS-tools analysis settings schema and the model's settings, validated with ods_tools before saving. - Shared page setup, API error messages and persistent toasts. - Remove the old settings form from create.py (Scenarios only needs create_analysis_form). Co-Authored-By: Claude Opus 5.5 --- README.md | 18 +- modules/client.py | 41 +- modules/nav.py | 3 +- modules/schemas.py | 125 +++ modules/ui.py | 66 ++ pages/analyses.py | 832 +++++++++++--------- pages/components/common.py | 84 ++ pages/components/create.py | 679 +--------------- pages/components/data.py | 178 +++++ pages/components/model_details.py | 153 ++++ pages/components/results.py | 92 +++ pages/components/settings_editor.py | 441 +++++++++++ pages/dashboard.py | 184 ----- pages/models.py | 68 ++ pages/portfolios.py | 244 ++++++ tests/conftest.py | 36 +- tests/fixtures/create_portfolio_form_app.py | 14 - tests/fixtures/settings_editor_app.py | 49 ++ tests/mocks.py | 87 +- tests/test_analyses.py | 128 ++- tests/test_portfolios_models.py | 82 ++ tests/test_settings_editor.py | 176 +++++ ui-config.json | 10 +- 23 files changed, 2430 insertions(+), 1360 deletions(-) create mode 100644 modules/schemas.py create mode 100644 modules/ui.py create mode 100644 pages/components/data.py create mode 100644 pages/components/model_details.py create mode 100644 pages/components/results.py create mode 100644 pages/components/settings_editor.py delete mode 100644 pages/dashboard.py create mode 100644 pages/models.py create mode 100644 pages/portfolios.py delete mode 100644 tests/fixtures/create_portfolio_form_app.py create mode 100644 tests/fixtures/settings_editor_app.py create mode 100644 tests/test_portfolios_models.py create mode 100644 tests/test_settings_editor.py diff --git a/README.md b/README.md index ce591cb..7cc440f 100644 --- a/README.md +++ b/README.md @@ -5,15 +5,19 @@ 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. -- `/scenarios` - Simplified UI which allows for the running of analyses using previously loaded portfolios & models. -- `/comparison` - Compare the outputs of two completed analyses. -- `/scenariosGuide` - User guide for the scenarios and comparison pages. +- `/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. -Which pages appear in the sidebar is controlled by `ui-config.json`. +Analysis settings are edited with controls generated from the ODS-tools +analysis and model settings schemas, and validated before they are saved. + +The Scenarios UI (`scenarios/ui-config.json`) is configured separately and adds +the `/scenarios`, `/comparison` and `/scenariosGuide` pages. + +Which pages appear in the sidebar is controlled by the UI config file. ## Prerequisites diff --git a/modules/client.py b/modules/client.py index cbbae89..cb0a8df 100644 --- a/modules/client.py +++ b/modules/client.py @@ -116,6 +116,13 @@ def get_traceback(self, ID, error_type='input_generation'): return None + def cancel(self, ID): + return self.endpoint.cancel(ID) + + def delete(self, ID): + return self.endpoint.delete(ID) + + class PortfoliosEndpointInterface(EndpointInterface): ''' Interface for portfolios endpoint of the Oasis APIClient. @@ -137,6 +144,29 @@ 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): ''' @@ -152,17 +182,20 @@ def create(self, name, location_file=None, accounts_file=None, reinsurance_scope_file : UploadedFile ''' - 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, + return self.client.upload_inputs(portfolio_name=name, location_fp=location_f, accounts_fp=accounts_f, ri_info_fp=ri_info_f, diff --git a/modules/nav.py b/modules/nav.py index 1c5468f..f1cff75 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", "") diff --git a/modules/schemas.py b/modules/schemas.py new file mode 100644 index 0000000..13dcf4b --- /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'] +PERSPECTIVE_LABELS = { + 'gul': 'Ground up loss (GUL)', + 'il': 'Insured loss (IL)', + 'ri': 'Net of reinsurance (RI)', +} + +# 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/ui.py b/modules/ui.py new file mode 100644 index 0000000..39a9e6a --- /dev/null +++ b/modules/ui.py @@ -0,0 +1,66 @@ +''' +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/pages/analyses.py b/pages/analyses.py index a5a6e25..7b52850 100644 --- a/pages/analyses.py +++ b/pages/analyses.py @@ -1,437 +1,509 @@ -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, + format_status, open_record, selectable_table) +from pages.components.data import (analyses_df, analysis_files, analysis_settings, + cached_model_settings, model_label, models_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 -########################################################################################## +ci = page_setup('Analyses') -ui_config = retrieve_ui_config() -validate_page("Analyses") +VIEW_KEY = 'analyses_view' # None (list), 'new', or ('edit', analysis_id) +RUNNABLE_WITH_INPUTS = ['READY', 'RUN_COMPLETED', 'RUN_CANCELLED', 'RUN_ERROR'] -st.set_page_config( - page_title = "Analysis", - layout = "centered" -) +if st.session_state.get(NEW_ANALYSIS_DEFAULTS) is not None: + st.session_state[VIEW_KEY] = 'new' -cols = st.columns([0.1, 0.8, 0.1]) -with cols[1]: - st.image("images/oasis_logo.png") +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) -########################################################################################## -# Page -########################################################################################## - -# Retrieve client -handle_login(ui_config.skip_login) -SidebarNav() - -client_interface = st.session_state["client_interface"] -client = client_interface.client - -"## Portfolios" - -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 - - 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'])) + + 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"): + 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 - summary_tab, inputs_tab, outputs_tab = st.tabs(["Summary", "Inputs", "Outputs"]) + 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 - @st.cache_data(show_spinner="Fetching input data...") - def get_input_file(analysis_id, modified=None): # `modified` busts the cache after a re-run - return client_interface.analyses.get_file(analysis_id, 'input_file', df=True) - inputs = get_input_file(analysis_id, selected.get('modified')) +########################################################################################## +# New analysis +########################################################################################## - 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 +def new_analysis_view(): + defaults = st.session_state.get(NEW_ANALYSIS_DEFAULTS) or {} - with summary_tab: - summarise_inputs(locations, a_settings) + 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() - @st.cache_data - def convert_df(df): - return df.to_csv(index=False).encode("utf-8") + 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 - with inputs_tab: - input_file_list = sorted(list(inputs.keys())) + 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 - st.write("Input files:") - for fname in input_file_list: + model, portfolio = models_by_id[model_id], portfolios_by_id[portfolio_id] + model_settings = cached_model_settings(ci, model) - 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.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) + 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.') - @st.cache_data(show_spinner="Fetching output data...") - def get_output_file(analysis_id, modified=None): # `modified` busts the cache after a re-run - return client_interface.analyses.get_file(analysis_id, 'output_file', df=True) + if run or create: + try: + 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() - if selected['status'] == 'RUN_COMPLETED': - outputs = get_output_file(analysis_id, selected.get('modified')) - with outputs_tab: - output_file_list = sorted(list(outputs.keys())) - st.write("Output files:") - for fname in output_file_list: +########################################################################################## +# Edit settings +########################################################################################## - 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) +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() - fname = f"analysis_{analysis_id}_output.tar.gz" - @st.cache_data(show_spinner="Fetching output tar data...") - def get_output_tar(analysis_id, modified=None): # `modified` busts the cache after a re-run - return client_interface.download_output(analysis_id) - fdata = get_output_tar(analysis_id, selected.get('modified')) + 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) + + st.divider() + in_progress = analysis['status'] in IN_PROGRESS_STATUSES + 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: + 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.download_button('Download All Outputs', - data=fdata, - file_name=fname) - else: - outputs = None - with outputs_tab: - st.info("Run not complete.") +########################################################################################## +# Analysis list and detail +########################################################################################## -def run_analysis(re_handler): - analyses = client_interface.analyses.get(df=True) - if analyses.empty: - st.info("No analyses.") +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 - - 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'] - generation_done_statuses = ['READY', 'INPUTS_GENERATION_ERROR', 'INPUTS_GENERATION_CANCELLED'] + completed_statuses - generating_statuses = ['INPUTS_GENERATION_QUEUED', 'INPUTS_GENERATION_STARTED'] - - re_handler.update_queue() - - # Check for running / generating analyses (e.g. after a page reload) - if not re_handler.is_refreshing(): - in_progress = analyses[analyses['status'].isin(running_statuses + generating_statuses)] - if not in_progress.empty: - for _, row in in_progress.iterrows(): - if row['status'] in generating_statuses: - re_handler.add_to_queue(row['id'], generation_done_statuses) - else: - re_handler.add_to_queue(row['id'], completed_statuses) - re_handler.set_refresh_bool(True) + 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) + + 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']}") + tar_key = f"tar_{analysis['id']}_{analysis.get('modified')}" + if tar_key not in st.session_state: + if st.button('Prepare download of all outputs (.tar.gz)', key=f'{tar_key}_prep'): + with st.spinner('Fetching outputs...'): + st.session_state[tar_key] = ci.download_output(analysis['id']) st.rerun() + else: + st.download_button('Download all outputs (.tar.gz)', st.session_state[tar_key], + file_name=f"analysis_{analysis['id']}_output.tar.gz", key=f'{tar_key}_dl') - 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', 'INPUTS_GENERATION_ERROR', - 'READY', 'RUN_COMPLETED', - 'RUN_CANCELLED', 'RUN_ERROR' ]) - - - left, middle, right = st.columns(3, vertical_alignment='center') - left.markdown("2) Generate Inputs:") - - if middle.button("Generate", width='stretch', disabled=not validations.is_valid()): +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 = status in IN_PROGRESS_STATUSES + + 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.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) - - - 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") + start_run(analysis) + flash('Run started') + st.rerun() + except (HTTPError, OasisException) as e: + show_api_error('Starting run', e) - submitted = st.form_submit_button("Submit") + 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 submitted: + if in_progress: + if btn_cols[2].button('Cancel', icon=':material/stop:', width='stretch'): try: - analysis_settings = json.load(uploadedFile) - client.upload_settings(analysis['id'], analysis_settings) - st.success('Analysis settings uploaded.') - time.sleep(0.5) + ci.analyses.cancel(analysis['id']) + flash('Cancellation requested', icon='⛔') 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): - try: - client_interface.run(selected['id']) - - st.success("Run started") - time.sleep(0.5) + except (HTTPError, OasisException) as e: + show_api_error('Cancelling', e) - re_handler.start(selected['id'], completed_statuses) - except HTTPError as e: - st.error('Starting run failed.') - logger.error(e) - - # Misc buttons - left, middle, right = st.columns(3, vertical_alignment='center') - - validation = NotNoneValidation('Selected analysis') - button_enabled = validation.is_valid(selected) - - @st.dialog("Delete Analysis") - def confirm_delete_dialog(analysis): - st.write(f"Delete analysis **{analysis['name']}** (ID {analysis['id']})? This cannot be undone.") - cancel_col, delete_col = st.columns(2) - if cancel_col.button("Cancel", width='stretch'): - st.rerun() - if delete_col.button("Delete", type='primary', width='stretch'): + 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: - client.analyses.delete(analysis['id']) + ci.analyses.delete(analysis['id']) + st.session_state[SELECTED_ANALYSIS] = None + flash(f"Analysis \"{analysis['name']}\" deleted") st.rerun() - except HTTPError as e: - st.error("Deletion failed.") - logger.error(e) - - if left.button("Delete", width='stretch', disabled = not button_enabled, help=validation.message): - confirm_delete_dialog(selected) - - validations = ValidationGroup() - validations.add_validation(NotNoneValidation('Analysis'), selected) - - run_enabled = validations.is_valid() - msg = None - if not run_enabled: - msg = validations.message - - 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 selected is not None and selected['status'] in ['READY', 'RUN_COMPLETED']: - analysis_summary_expander(selected) + 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(s in IN_PROGRESS_STATUSES for s in snapshot.values()) + + @st.fragment(run_every='4s' 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 + running = [a for a in fresh if a['status'] in IN_PROGRESS_STATUSES] + for a in running: + progress = analysis_progress(a) + text = f"{a['name']}: {format_status(a['status'])}" + st.progress(progress or 0.0, text=text + (f' ({progress:.0%})' if progress is not None else '')) + + 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..22630c7 100644 --- a/pages/components/common.py +++ b/pages/components/common.py @@ -28,3 +28,87 @@ def get_page_path(): """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': '❌', +} + +IN_PROGRESS_STATUSES = ['INPUTS_GENERATION_QUEUED', 'INPUTS_GENERATION_STARTED', + 'RUN_QUEUED', 'RUN_STARTED'] +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 analysis_progress(analysis): + '''Fraction of sub-tasks completed for a running analysis, or None.''' + counts = analysis.get('status_count') or {} + total = counts.get('TOTAL') or 0 + if total == 0: + return None + return counts.get('COMPLETED', 0) / total + + +########################################################################################## +# 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 index de15249..477559a 100644 --- a/pages/components/create.py +++ b/pages/components/create.py @@ -1,16 +1,8 @@ -# Module to display ui components for running analyses -from copy import copy -from pages.components.output import ViewSummarySettings, summarise_summary_level +"""Analysis creation form used by the Scenarios page.""" import streamlit as st -from modules.validation import NameValidation, NotNoneValidation, ValidationError, ValidationGroup - -class FormFragment(): - def __init__(self, params={}): - self.params = params +from modules.validation import NameValidation, NotNoneValidation, ValidationError, ValidationGroup - def display(self): - return {} def create_analysis_form(portfolios, models): """Analysis creation form ui component.""" @@ -59,670 +51,3 @@ def format_model(model): 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 (PLT) 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('psept', 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..d1c373e --- /dev/null +++ b/pages/components/data.py @@ -0,0 +1,178 @@ +''' +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 format_status + +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': format_status(a.get('status')), + '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/model_details.py b/pages/components/model_details.py new file mode 100644 index 0000000..931c46c --- /dev/null +++ b/pages/components/model_details.py @@ -0,0 +1,153 @@ +''' +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/results.py b/pages/components/results.py new file mode 100644 index 0000000..2d763d7 --- /dev/null +++ b/pages/components/results.py @@ -0,0 +1,92 @@ +''' +Render the outputs of a completed analysis, driven by its analysis settings. +''' +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): + if enabled: + sections.append((title, render)) + + # ORD outputs + add(ord_settings.get('elt_sample'), 'Sample event loss table (SELT)', + lambda p, vis: generate_selt_fragment(p, vis, locations=locations)) + add(ord_settings.get('elt_moment'), 'Moment event loss table (MELT)', + lambda p, vis: generate_melt_fragment(p, vis, locations=locations)) + add(ord_settings.get('elt_quantile'), 'Quantile event loss table (QELT)', + lambda p, vis: generate_qelt_fragment(p, vis, locations=locations)) + add(ord_settings.get('plt_sample'), 'Sample period loss table (SPLT)', generate_splt_fragment) + add(ord_settings.get('plt_moment'), 'Moment period loss table (MPLT)', generate_mplt_fragment) + add(ord_settings.get('plt_quantile'), 'Quantile period loss table (QPLT)', generate_qplt_fragment) + add(ord_settings.get('alt_meanonly'), 'Average loss table, mean only (ALT)', + lambda p, vis: generate_alt_fragment(p, vis, 'alt_meanonly')) + add(ord_settings.get('alt_period'), 'Period average loss table (PALT)', + lambda p, vis: generate_alt_fragment(p, vis, 'alt_period')) + add(ord_settings.get('alct_convergence'), 'Average loss convergence table (ALCT)', generate_alct_fragment) + add(any(ord_settings.get(e) for e in EPT_FLAGS), 'Exceedance probability table (EPT)', generate_ept_fragment) + add(any(ord_settings.get(e) for e in PSEPT_FLAGS), 'Per-sample EPT (PSEPT)', generate_psept_fragment) + + # Legacy ktools outputs + add(summary.get('eltcalc'), 'ELT (legacy)', + lambda p, vis: generate_eltcalc_fragment(p, vis, locations=locations, map=True)) + add(summary.get('aalcalc'), 'AAL (legacy)', generate_aalcalc_fragment) + add(summary.get('lec_output'), 'Loss exceedance curve (legacy)', + lambda p, vis: generate_leccalc_fragment(p, vis, summary.get('leccalc'))) + add(summary.get('pltcalc'), 'PLT (legacy)', generate_pltcalc_fragment) + return sections + + +def render_results(settings, outputs, locations=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. + ''' + if not outputs: + st.info('No output files were found for this analysis.') + return + + vis = OutputInterface(outputs) + perspectives = [p for p in PERSPECTIVES if settings.get(f'{p}_output')] + for p in perspectives: + fields = (settings.get(f'{p}_summaries') or [{}])[0].get('oed_fields') + if fields: + vis.set_oed_fields(p, fields) + + 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: + # Visualisations currently use the first summary level + summary = (settings.get(f'{p}_summaries') or [{}])[0] + sections = _sections(summary, locations) + if not sections: + st.info('No outputs were selected for this perspective.') + for i, (title, render) in enumerate(sections): + with st.expander(title, expanded=i == 0): + render(p, vis) diff --git a/pages/components/settings_editor.py b/pages/components/settings_editor.py new file mode 100644 index 0000000..c511daf --- /dev/null +++ b/pages/components/settings_editor.py @@ -0,0 +1,441 @@ +''' +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 perspective_availability(model_settings, portfolio): + '''Which perspectives can be run, with a reason for those that can't.''' + valid = model_settings.get('model_settings', {}).get('valid_output_perspectives') or PERSPECTIVES + 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 this model.' + elif p in ('il', 'ri') and not has['accounts_file']: + reasons[p] = 'The portfolio has no accounts file.' + elif p == 'ri' 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': {o: True for o in DEFAULT_ORD_OUTPUTS}}], + } + + +def group_field_options(model_settings, extra=()): + 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]: + if f not 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, right = 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') + + entry = schemas.analysis_property('gul_threshold') + out['gul_threshold'] = right.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') + + with st.expander('Advanced'): + 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', False)), + help=entry.get('description'), 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): + '''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': {o: True for o in DEFAULT_ORD_OUTPUTS}}] + st.session_state[state_key] = levels + return st.session_state[state_key] + + +def summary_levels_editor(key, scope, summaries, field_options): + '''Edit a list of summary levels (group-by fields + ORD outputs).''' + levels = _init_levels(key, scope, summaries) + 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: + if col.checkbox(flags[k][0], value=bool(ord_output.get(k)), help=flags[k][1], + key=f'{wkey}_{k}'): + 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': {o: True for o in DEFAULT_ORD_OUTPUTS}}) + st.rerun() + + return result + + +def outputs_section(base, model_settings, portfolio, key): + out, errors = {}, [] + unavailable = perspective_availability(model_settings, portfolio) + + st.markdown('**Loss perspectives**') + cols = st.columns(3) + 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) + + 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) + 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) + + 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): + '''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. + ''' + 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: + outputs, output_errors = outputs_section(base, model_settings, portfolio, key) + + # 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') + 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 ce7251b..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, handle_login -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, modified=None): # `modified` busts the cache after a re-run - return client_interface.analyses.get_file(ID, 'input_file', df=True) - -with st.spinner("Loading data..."): - inputs = get_analysis_inputs(analysis_id, selected_analysis.get('modified')) - 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, modified=None): # `modified` busts the cache after a re-run - return client_interface.analyses.get_file(ID, 'output_file', df=True) - -with st.spinner("Loading data..."): - outputs = get_analysis_outputs(analysis_id, selected_analysis.get('modified')) - -# 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..f026d61 --- /dev/null +++ b/pages/portfolios.py @@ -0,0 +1,244 @@ +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.display import MapView +from pages.components.output import summarise_locations, valid_locations + +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') + summary = summarise_locations(locations).iloc[0] + + metric_cols = st.columns(4) + metric_cols[0].metric('Locations', f"{int(summary['number_locations']):,}") + metric_cols[1].metric('Total TIV', f"{summary['TotalTIV']:,.0f}") + if 'CountryCode' in locations: + metric_cols[2].metric('Countries', locations['CountryCode'].nunique()) + if 'LocPerilsCovered' in locations: + metric_cols[3].metric('Peril codes', locations['LocPerilsCovered'].nunique()) + + tiv_cols = [c for c in ['BuildingTIV', 'OtherTIV', 'ContentsTIV', 'BITIV'] if c in locations] + map_col, breakdown_col = st.columns([0.6, 0.4]) + with map_col: + if {'Latitude', 'Longitude', 'BuildingTIV'} <= set(locations.columns) and valid_locations(locations): + MapView(locations, weight='BuildingTIV', map_type='heatmap').display() + elif {'CountryCode', 'BuildingTIV'} <= set(locations.columns): + MapView(locations, weight='BuildingTIV', map_type='choropleth').display() + else: + st.caption('No coordinates or country codes to map.') + with breakdown_col: + for field in ['CountryCode', 'OccupancyCode', 'ConstructionCode', 'LocPerilsCovered']: + if field in locations and tiv_cols: + st.markdown(f'**TIV by {field}**') + breakdown = (locations.groupby(field)[tiv_cols].sum() + .assign(Locations=locations.groupby(field).size()) + .sort_values(tiv_cols[0], ascending=False).reset_index()) + st.dataframe(breakdown, hide_index=True, height=200) + + +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/tests/conftest.py b/tests/conftest.py index a8db8c2..0557f88 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,3 +1,4 @@ +import pandas as pd import pytest from modules.client import ClientInterface from tests.mocks import MockApiClient @@ -16,7 +17,8 @@ def pytest_configure(config): 'name': 'string', "created": "2023-05-26T06:48:52.524821Z", "modified": "2023-05-26T06:48:52.524821Z", - "storage_links": f"http://localhost:8000/v1/portfolios/{config.portfolio_ID}/storage_links/" + "storage_links": f"http://localhost:8000/v1/portfolios/{config.portfolio_ID}/storage_links/", + "location_file": {"name": "location.csv", "stored": "abc.csv"}, }] config.model_ID = 1 @@ -48,21 +50,33 @@ def pytest_configure(config): @pytest.fixture() def mock_api_client(request): config = request.config - return MockApiClient(portfolios=config.portfolios_data, - analyses=config.analyses_data, - models=config.models_data) + client = MockApiClient(portfolios=config.portfolios_data, + analyses=config.analyses_data, + models=config.models_data) + client.portfolios.location_file.files[config.portfolio_ID] = pd.DataFrame({ + 'LocNumber': ['1', '2'], 'CountryCode': ['GB', 'GB'], + 'Latitude': [52.1, 52.2], 'Longitude': [-1.1, -1.2], + 'BuildingTIV': [1000.0, 2000.0], 'LocPerilsCovered': ['WTC', 'WTC'], + }) + return client @pytest.fixture() def mock_client_interface(mock_api_client): return ClientInterface(client = mock_api_client) +def page_app(path, client, state=None): + """AppTest of a page logged in with `client`, with optional session state.""" + at = AppTest.from_file("app.py", default_timeout=30) + at.session_state["client"] = client + at.session_state["client_interface"] = ClientInterface(client=client) + for k, v in (state or {}).items(): + at.session_state[k] = v + at.switch_page(path) + return at.run() + + @pytest.fixture() -def mock_app_test(mock_api_client, mock_client_interface): - at = AppTest.from_file("app.py") - at.session_state["client"] = mock_api_client - at.session_state["client_interface"] = mock_client_interface - at.switch_page("pages/analyses.py") - at.run() - return at +def mock_app_test(mock_api_client): + return page_app("pages/analyses.py", mock_api_client) diff --git a/tests/fixtures/create_portfolio_form_app.py b/tests/fixtures/create_portfolio_form_app.py deleted file mode 100644 index b827120..0000000 --- a/tests/fixtures/create_portfolio_form_app.py +++ /dev/null @@ -1,14 +0,0 @@ -''' -Standalone script for AppTest coverage of `create_portfolio_form`. - -On the Analyses page the form lives inside an `st.dialog`, which AppTest -closes on every full rerun, so the form is exercised on its own here. The -returned form data is stored in `session_state['form_data']`. -''' -import streamlit as st - -from pages.components.create import create_portfolio_form - -form_data = create_portfolio_form() -if form_data is not None: - st.session_state['form_data'] = form_data diff --git a/tests/fixtures/settings_editor_app.py b/tests/fixtures/settings_editor_app.py new file mode 100644 index 0000000..ec49c1a --- /dev/null +++ b/tests/fixtures/settings_editor_app.py @@ -0,0 +1,49 @@ +''' +Standalone script for AppTest coverage of `analysis_settings_editor`. + +Uses a model whose settings exercise every parameter type, parameter groups +and restricted output perspectives. Results are stored in session state as +`editor_settings`, `editor_valid` and `editor_problems`. Set +`session_state['base_settings']` before running to start from a template. +''' +import streamlit as st + +from pages.components.settings_editor import analysis_settings_editor + +MODEL = {'id': 1, 'supplier_id': 'Supplier', 'model_id': 'TestModel', 'version_id': '1'} + +MODEL_SETTINGS = { + 'name': 'Test model', + 'model_default_samples': 7, + 'model_settings': { + 'event_set': { + 'name': 'Event Set', 'desc': 'Event set selection', 'default': 'p', + 'options': [{'id': 'p', 'desc': 'Probabilistic'}, {'id': 'h', 'desc': 'Historic'}], + }, + 'valid_output_perspectives': ['gul', 'il'], + 'boolean_parameters': [{'name': 'use_surge', 'desc': 'Include storm surge', 'default': True}], + 'float_parameters': [{'name': 'demand_surge', 'desc': 'Demand surge factor', 'default': 1.1, + 'min': 1.0, 'max': 2.0, 'stepsize': 0.05}], + 'integer_parameters': [{'name': 'max_events', 'desc': 'Maximum events', 'default': 100}], + 'numeric_parameters': [{'name': 'scale', 'desc': 'Hazard scale', 'default': 0.5}], + 'string_parameters': [{'name': 'tag', 'desc': 'Run tag', 'default': 'base'}], + 'list_parameters': [{'name': 'regions', 'desc': 'Regions', 'default': ['north', 'south']}], + 'dictionary_parameters': [{'name': 'weights', 'desc': 'Weights', 'default': {'a': 1}}], + 'dropdown_parameters': [{'name': 'vuln_curve', 'desc': 'Vulnerability curve', 'default': 'mid', + 'options': [{'id': 'low', 'desc': 'Low'}, {'id': 'mid', 'desc': 'Mid'}]}], + 'parameter_groups': [{'name': 'hazard', 'desc': 'Hazard options', 'priority_id': 1, + 'presentation_order': ['use_surge', 'demand_surge', 'scale']}], + }, + 'lookup_settings': {'supported_perils': [{'id': 'WTC', 'desc': 'Tropical cyclone'}, + {'id': 'WSS', 'desc': 'Storm surge'}]}, + 'data_settings': {'damage_group_fields': ['PortNumber', 'AccNumber', 'LocNumber']}, +} + +# Accounts file but no reinsurance files: IL possible, RI not +PORTFOLIO = {'id': 1, 'name': 'p', 'location_file': {'stored': 'l.csv'}, 'accounts_file': {'stored': 'a.csv'}} + +settings, valid, problems = analysis_settings_editor( + MODEL, MODEL_SETTINGS, PORTFOLIO, st.session_state.get('base_settings'), key='test_editor') +st.session_state['editor_settings'] = settings +st.session_state['editor_valid'] = valid +st.session_state['editor_problems'] = problems diff --git a/tests/mocks.py b/tests/mocks.py index 7e2b3a0..93f6093 100644 --- a/tests/mocks.py +++ b/tests/mocks.py @@ -1,5 +1,8 @@ from copy import deepcopy +from requests import Response +from requests.exceptions import HTTPError + from oasis_data_manager.errors import OasisException @@ -22,6 +25,14 @@ def __init__(self, json_data=None): # Sub-endpoints wrapped by `modules.client` interfaces self.settings = MockSubEndpoint() + def __getattr__(self, name): + # Any `_file` sub-endpoint is created on first use + if name.endswith('_file'): + endpoint = MockFileEndpoint() + setattr(self, name, endpoint) + return endpoint + raise AttributeError(name) + def _find(self, ID): for record in self.json_data: if isinstance(record, dict) and record.get('id') == ID: @@ -42,20 +53,73 @@ def search(self, metadata=None): def delete(self, ID): self.json_data[:] = [r for r in self.json_data if r.get('id') != ID] + def update(self, ID, name): + self._find(ID)['name'] = name + return MockJsonObject(self._find(ID)) + + # Analysis actions record the requested transition + def _set_status(self, ID, status): + self._find(ID)['status'] = status + return MockJsonObject(self._find(ID)) + + def generate_and_run(self, ID): + return self._set_status(ID, 'INPUTS_GENERATION_QUEUED') + + def run(self, ID): + return self._set_status(ID, 'RUN_QUEUED') + + def cancel(self, ID): + return self._set_status(ID, 'RUN_CANCELLED') + + +class MockFileEndpoint: + '''File sub-endpoint (e.g. `portfolios.location_file`) holding DataFrames by ID. + + Missing files raise a 404 `HTTPError`, as the API does. + ''' + def __init__(self): + self.files = {} + + def _missing(self, ID): + response = Response() + response.status_code = 404 + return HTTPError(f'404: no file for {ID}', response=response) + + def get(self, ID): + if ID not in self.files: + raise self._missing(ID) + return MockText(self.files[ID].to_csv(index=False)) + + def get_dataframe(self, ID): + if ID not in self.files: + raise self._missing(ID) + return self.files[ID] + + +class MockText: + def __init__(self, text): + self.text = text + class MockSubEndpoint: '''Sub-endpoint (e.g. `analyses.settings`) keyed by parent ID.''' - def __init__(self, data=None): + def __init__(self, data=None, missing=None): self.data = {} if data is None else data + self.missing = {} if missing is None else missing - def get(self, ID=None): - return MockJsonObject(self.data.get(ID, {})) + def get(self, ID=None, *args): + return MockJsonObject(self.data.get(ID, self.missing)) + + def post(self, ID, data): + self.data[ID] = data + return MockJsonObject(data) class MockModelsEndpoint(MockEndpoint): def __init__(self, json_data=None): super().__init__(json_data) - self.setting_templates = MockSubEndpoint() + # No settings templates by default: `get` returns an empty list + self.setting_templates = MockSubEndpoint(missing=[]) self.setting_templates.content = MockSubEndpoint() @@ -71,10 +135,23 @@ def __init__(self, username="", password="", def server_info(): return MockJsonObject() + def create_analysis(self, portfolio_id, model_id, analysis_name=None, **kwargs): + analyses = self.analyses.json_data + analysis = {'id': max([a['id'] for a in analyses] + [0]) + 1, 'name': analysis_name, + 'portfolio': portfolio_id, 'model': model_id, 'status': 'NEW', 'settings': None} + analyses.append(analysis) + return analysis + + def upload_settings(self, analysis_id, settings): + self.analyses.settings.post(analysis_id, settings) + self.analyses._find(analysis_id)['settings'] = f'/analyses/{analysis_id}/settings/' + def upload_inputs(self, portfolio_name=None, **kwargs): if portfolio_name is None: raise OasisException('Portfolio name required') portfolios = self.portfolios.json_data next_id = max([p.get('id', 0) for p in portfolios] + [0]) + 1 - portfolios.append({'id': next_id, 'name': portfolio_name}) + portfolio = {'id': next_id, 'name': portfolio_name} + portfolios.append(portfolio) + return portfolio diff --git a/tests/test_analyses.py b/tests/test_analyses.py index d72f8b2..1b6f5b3 100644 --- a/tests/test_analyses.py +++ b/tests/test_analyses.py @@ -1,99 +1,85 @@ -from streamlit.testing.v1 import AppTest import tests.mocks as m +from tests.conftest import page_app -from modules.client import ClientInterface +from pages.components.common import NEW_ANALYSIS_DEFAULTS, SELECTED_ANALYSIS - -def analyses_app(client): - at = AppTest.from_file("app.py", default_timeout=30) - at.session_state["client"] = client - at.session_state["client_interface"] = ClientInterface(client=client) - at.switch_page("pages/analyses.py") - return at.run() +PAGE = 'pages/analyses.py' def test_empty_analyses_page(): - at = analyses_app(m.MockApiClient()) + at = page_app(PAGE, m.MockApiClient()) assert not at.exception + assert at.title[0].value == 'Analyses' + assert at.button[0].label == 'New analysis' + assert 'No analyses yet. Create one to get started.' in [i.value for i in at.info] - # Empty portfolios table shows only the name column - portfolios_df = at.dataframe[0].value - assert portfolios_df.empty - assert list(portfolios_df.columns) == ['name'] - assert at.button[0].label == 'Create Portfolio' - - assert [t.label for t in at.tabs] == ['Run Analysis', 'Create Analysis'] - - info = [i.value for i in at.info] - assert 'No analyses.' in info - assert 'Ensure portfolios and models are loaded.' in info - - -def test_display_portfolio(mock_app_test, request): - at = mock_app_test - portfolios_df = at.dataframe[0].value - expected_names = [p['name'] for p in request.config.portfolios_data] - assert list(portfolios_df['name']) == expected_names - - -def test_display_analyses(mock_app_test, request): +def test_analyses_table(mock_app_test, request): config = request.config at = mock_app_test - analysis = config.analyses_data[0] - - analyses_df = at.dataframe[1].value - assert len(analyses_df) == 1 - row = analyses_df.iloc[0] + assert not at.exception + table = at.dataframe[0].value + assert len(table) == 1 + row = table.iloc[0] assert row['id'] == config.analyses_ID - assert row['name'] == analysis['name'] - assert row['status'] == analysis['status'] - # Enriched from the portfolios / models endpoints + assert row['name'] == config.analyses_data[0]['name'] + assert row['status_label'] == '🆕 New' assert row['portfolio_name'] == config.portfolios_data[0]['name'] - assert row['model_id'] == config.models_data[0]['model_id'] - assert row['model_supplier'] == config.models_data[0]['supplier_id'] - + assert row['model_name'] == config.models_data[0]['model_id'] -def test_create_portfolio_button_opens_dialog(mock_app_test): - at = mock_app_test - at = at.button[0].click().run() +def test_selected_analysis_shows_detail(mock_api_client, request): + at = page_app(PAGE, mock_api_client, {SELECTED_ANALYSIS: request.config.analyses_ID}) assert not at.exception - assert at.text_input(key='portfolio_name').label == 'Portfolio Name' - - -def test_create_portfolio_form_requires_name(): - at = AppTest.from_file("tests/fixtures/create_portfolio_form_app.py").run() + assert at.subheader[0].value == request.config.analyses_data[0]['name'] + assert [t.label for t in at.tabs] == ['Results', 'Settings', 'Inputs', 'Logs'] + # No settings yet, so it can't be run + run = [b for b in at.button if b.label == 'Run'][0] + assert run.disabled - at = at.button[0].click().run() - - assert 'Name' in at.error[0].value - assert 'form_data' not in at.session_state +def test_new_analysis_view_from_portfolio(mock_api_client, request): + config = request.config + at = page_app(PAGE, mock_api_client, {NEW_ANALYSIS_DEFAULTS: {'portfolio': config.portfolio_ID}}) -def test_create_portfolio_form_returns_data(): - at = AppTest.from_file("tests/fixtures/create_portfolio_form_app.py").run() + assert not at.exception + assert at.subheader[0].value == 'New analysis' + assert at.selectbox(key='new_analysis_portfolio').value == config.portfolio_ID + # Only one model, so it is preselected + assert at.selectbox(key='new_analysis_model').value == config.model_ID + assert [t.label for t in at.tabs] == ['General', 'Model options', 'Outputs', 'Review'] - at = at.text_input(key='portfolio_name').input('new-portfolio').run() - at = at.button[0].click().run() - assert not at.error - form_data = at.session_state['form_data'] - assert form_data['name'] == 'new-portfolio' - assert form_data['location_file'] is None +def test_create_analysis(mock_api_client, request): + config = request.config + at = page_app(PAGE, mock_api_client, {NEW_ANALYSIS_DEFAULTS: {'portfolio': config.portfolio_ID}}) + at.text_input(key='new_analysis_name').input('my analysis').run() + [b for b in at.button if b.label == 'Create only'][0].click().run() -def test_create_analyses_form(mock_app_test, request): - at = mock_app_test - create_tab = at.tabs[1] + assert not at.exception + created = [a for a in mock_api_client.analyses.json_data if a['name'] == 'my analysis'] + assert len(created) == 1 + assert created[0]['status'] == 'NEW' + settings = mock_api_client.analyses.settings.data[created[0]['id']] + assert settings['model_name_id'] == config.models_data[0]['model_id'] + assert settings['gul_output'] is True + # Back on the list with the new analysis selected + assert at.session_state[SELECTED_ANALYSIS] == created[0]['id'] + assert at.session_state['analyses_view'] is None + + +def test_create_and_run_analysis(mock_api_client, request): + config = request.config + at = page_app(PAGE, mock_api_client, {NEW_ANALYSIS_DEFAULTS: {'portfolio': config.portfolio_ID}}) - portfolio_select = create_tab.selectbox[0].options - assert len(portfolio_select) == len(request.config.portfolios_data) - assert request.config.portfolios_data[0]['name'] in portfolio_select[0] + [b for b in at.button if b.label == 'Create and run'][0].click().run() - model_select = create_tab.selectbox[1].options - assert len(model_select) == len(request.config.models_data) - assert request.config.models_data[0]['supplier_id'] in model_select[0] + assert not at.exception + created = mock_api_client.analyses.json_data[-1] + assert created['status'] == 'INPUTS_GENERATION_QUEUED' + # Name defaults to " – " + assert created['name'] == f"{config.portfolios_data[0]['name']} – {config.models_data[0]['model_id']}" diff --git a/tests/test_portfolios_models.py b/tests/test_portfolios_models.py new file mode 100644 index 0000000..3dfa500 --- /dev/null +++ b/tests/test_portfolios_models.py @@ -0,0 +1,82 @@ +import tests.mocks as m +from tests.conftest import page_app + +from pages.components.common import SELECTED_MODEL, SELECTED_PORTFOLIO +from pages.components.data import guess_file_type + + +def test_empty_portfolios_page(): + at = page_app('pages/portfolios.py', m.MockApiClient()) + assert not at.exception + assert at.title[0].value == 'Portfolios' + assert 'No portfolios yet. Create one to get started.' in [i.value for i in at.info] + + +def test_portfolios_table(mock_api_client, request): + at = page_app('pages/portfolios.py', mock_api_client) + assert not at.exception + + table = at.dataframe[0].value + assert list(table['name']) == [request.config.portfolios_data[0]['name']] + assert bool(table['location_file'].iloc[0]) is True + assert bool(table['accounts_file'].iloc[0]) is False + assert table['n_analyses'].iloc[0] == 1 + + +def test_portfolio_detail(mock_api_client, request): + at = page_app('pages/portfolios.py', mock_api_client, + {SELECTED_PORTFOLIO: request.config.portfolio_ID}) + assert not at.exception + assert at.subheader[0].value == request.config.portfolios_data[0]['name'] + assert [t.label for t in at.tabs] == ['Files', 'Exposure', 'Analyses (1)'] + + +def test_new_portfolio_dialog(mock_api_client): + at = page_app('pages/portfolios.py', mock_api_client) + at = at.button[0].click().run() + + assert not at.exception + assert at.text_input(key='new_portfolio_name').label == 'Portfolio name' + create = [b for b in at.button if b.label == 'Create portfolio'][0] + assert create.disabled # no name or location file yet + + +def test_rename_portfolio(mock_api_client, request): + config = request.config + at = page_app('pages/portfolios.py', mock_api_client, {SELECTED_PORTFOLIO: config.portfolio_ID}) + + at.text_input(key=f'rename_{config.portfolio_ID}').input('renamed').run() + at.button(key=f'rename_save_{config.portfolio_ID}').click().run() + + assert not at.exception + assert mock_api_client.portfolios.json_data[0]['name'] == 'renamed' + + +def test_guess_file_type(): + assert guess_file_type('SourceLocOEDPiWind.csv') == 'location_file' + assert guess_file_type('SourceAccOEDPiWind.csv') == 'accounts_file' + assert guess_file_type('SourceReinsInfoOEDPiWind.csv') == 'reinsurance_info_file' + assert guess_file_type('ri_scope.parquet') == 'reinsurance_scope_file' + assert guess_file_type('exposure.csv') is None + + +def test_models_page(mock_api_client, request): + config = request.config + mock_api_client.models.settings.data[config.model_ID] = { + 'name': 'Friendly model name', + 'description': 'A test model', + 'model_settings': {'event_set': {'name': 'Event Set', 'desc': 'd', 'default': 'p', + 'options': [{'id': 'p', 'desc': 'Probabilistic'}]}}, + } + at = page_app('pages/models.py', mock_api_client, {SELECTED_MODEL: config.model_ID}) + + assert not at.exception + assert list(at.dataframe[0].value['name']) == ['Friendly model name'] + assert at.subheader[0].value == 'Friendly model name' + assert [t.label for t in at.tabs] == ['Overview', 'Run options', 'Parameters', 'Perils', 'Settings JSON'] + + +def test_model_without_settings(mock_api_client, request): + at = page_app('pages/models.py', mock_api_client, {SELECTED_MODEL: request.config.model_ID}) + assert not at.exception + assert 'No model settings have been registered for this model.' in [w.value for w in at.warning] diff --git a/tests/test_settings_editor.py b/tests/test_settings_editor.py new file mode 100644 index 0000000..846500a --- /dev/null +++ b/tests/test_settings_editor.py @@ -0,0 +1,176 @@ +''' +Tests for the schema-driven analysis settings editor. +''' +import pytest +from streamlit.testing.v1 import AppTest + +from modules import schemas +from pages.components.settings_editor import perspective_availability + +APP = 'tests/fixtures/settings_editor_app.py' + + +@pytest.fixture +def editor(): + return AppTest.from_file(APP, default_timeout=30).run() + + +def test_defaults_are_valid(editor): + at = editor + assert not at.exception + assert at.session_state['editor_valid'], at.session_state['editor_problems'] + + settings = at.session_state['editor_settings'] + assert settings['model_supplier_id'] == 'Supplier' + assert settings['model_name_id'] == 'TestModel' + assert settings['number_of_samples'] == 7 # model_default_samples + assert settings['gul_output'] is True + assert settings['gul_summaries'][0]['ord_output']['elt_moment'] is True + + +def test_model_parameters_use_their_defaults(editor): + ms = editor.session_state['editor_settings']['model_settings'] + assert ms == { + 'event_set': 'p', + 'use_surge': True, + 'demand_surge': 1.1, + 'max_events': 100, + 'scale': 0.5, + 'tag': 'base', + 'regions': ['north', 'south'], + 'weights': {'a': 1}, + 'vuln_curve': 'mid', + } + + +def test_controls_match_parameter_types(editor): + at = editor + assert at.selectbox(key='test_editor_ms_event_set').options == ['p – Probabilistic', 'h – Historic'] + assert at.toggle(key='test_editor_param_use_surge').value is True + slider = at.slider(key='test_editor_param_demand_surge') + assert (slider.min, slider.max, slider.step) == (1.0, 2.0, 0.05) + assert at.number_input(key='test_editor_param_max_events').value == 100 + assert at.text_input(key='test_editor_param_tag').value == 'base' + assert at.selectbox(key='test_editor_param_vuln_curve').value == 'mid' + + +def test_changing_controls_updates_settings(editor): + at = editor + at.selectbox(key='test_editor_ms_event_set').set_value('h') + at.toggle(key='test_editor_param_use_surge').set_value(False) + at.number_input(key='test_editor_samples').set_value(50) + at.text_area(key='test_editor_param_regions').input('["east"]') + at.run() + + settings = at.session_state['editor_settings'] + assert settings['number_of_samples'] == 50 + assert settings['model_settings']['event_set'] == 'h' + assert settings['model_settings']['use_surge'] is False + assert settings['model_settings']['regions'] == ['east'] + assert at.session_state['editor_valid'] + + +def test_invalid_json_parameter_is_reported(editor): + at = editor + at.text_area(key='test_editor_param_weights').input('{not json').run() + assert not at.session_state['editor_valid'] + assert any('Weights' in p for p in at.session_state['editor_problems']) + + +def test_return_periods_are_parsed(editor): + at = editor + at.text_input(key='test_editor_return_periods').input('10, 100, 1000').run() + assert at.session_state['editor_settings']['return_periods'] == [10, 100, 1000] + + at.text_input(key='test_editor_return_periods').input('ten').run() + assert not at.session_state['editor_valid'] + + +def test_perspectives_respect_model_and_portfolio(editor): + at = editor + il = at.checkbox(key='test_editor_il_output') + ri = at.checkbox(key='test_editor_ri_output') + assert not il.disabled + assert ri.disabled # not in the model's valid perspectives + + il.check().run() + settings = at.session_state['editor_settings'] + assert settings['il_output'] is True + assert settings['il_summaries'] == settings['gul_summaries'] + assert settings['ri_output'] is False + + +def test_no_perspectives_is_invalid(editor): + at = editor + at.checkbox(key='test_editor_gul_output').uncheck().run() + assert not at.session_state['editor_valid'] + assert 'Select at least one loss perspective.' in at.session_state['editor_problems'] + + +def test_summary_level_group_by_and_outputs(editor): + at = editor + at.multiselect(key='test_editor_all_1_fields').set_value(['LocNumber']) + at.checkbox(key='test_editor_all_1_plt_sample').check() + at.checkbox(key='test_editor_all_1_elt_moment').uncheck() + at.run() + + level = at.session_state['editor_settings']['gul_summaries'][0] + assert level['oed_fields'] == ['LocNumber'] + assert level['ord_output']['plt_sample'] is True + assert 'elt_moment' not in level['ord_output'] + + +def test_add_and_remove_summary_levels(editor): + at = editor + at.button(key='test_editor_all_add').click().run() + assert [lv['id'] for lv in at.session_state['editor_settings']['gul_summaries']] == [1, 2] + + at.button(key='test_editor_all_1_remove').click().run() + assert [lv['id'] for lv in at.session_state['editor_settings']['gul_summaries']] == [2] + + +def test_template_values_are_loaded_and_unmanaged_keys_kept(): + at = AppTest.from_file(APP, default_timeout=30) + at.session_state['base_settings'] = { + 'model_supplier_id': 'Other', 'model_name_id': 'Other', + 'number_of_samples': 3, + 'gul_threshold': 5.0, + 'source_tag': 'keep-me', + 'model_settings': {'event_set': 'h', 'tag': 'from-template'}, + 'gul_output': True, + 'gul_summaries': [{'id': 4, 'oed_fields': ['AccNumber'], 'eltcalc': True, + 'ord_output': {'elt_sample': True}}], + } + at.run() + + assert at.session_state['editor_valid'], at.session_state['editor_problems'] + settings = at.session_state['editor_settings'] + assert settings['model_name_id'] == 'TestModel' # always the selected model + assert settings['number_of_samples'] == 3 + assert settings['gul_threshold'] == 5.0 + assert settings['source_tag'] == 'keep-me' + assert settings['model_settings']['event_set'] == 'h' + assert settings['model_settings']['tag'] == 'from-template' + + level = settings['gul_summaries'][0] + assert level['id'] == 4 + assert level['oed_fields'] == ['AccNumber'] + assert level['eltcalc'] is True # legacy output preserved + assert level['ord_output']['elt_sample'] is True + + +def test_perspective_availability(): + model_settings = {'model_settings': {}} + loc_only = {'location_file': {'stored': 'l.csv'}} + full = {f: {'stored': 'x.csv'} for f in + ['location_file', 'accounts_file', 'reinsurance_info_file', 'reinsurance_scope_file']} + + assert set(perspective_availability(model_settings, loc_only)) == {'il', 'ri'} + assert perspective_availability(model_settings, full) == {} + gul_only = {'model_settings': {'valid_output_perspectives': ['gul']}} + assert set(perspective_availability(gul_only, full)) == {'il', 'ri'} + + +def test_ord_output_groups_cover_schema(): + grouped = {k for keys in schemas.ORD_OUTPUT_GROUPS.values() for k in keys} + assert grouped == set(schemas.ord_output_options()) diff --git a/ui-config.json b/ui-config.json index 57efeb5..353de0b 100644 --- a/ui-config.json +++ b/ui-config.json @@ -1,12 +1,10 @@ { "pages" : [ - {"path": "pages/scenariosGuide.py", "label": "User Guide"}, - {"path": "pages/scenarios.py", "label": "Scenarios"}, - {"path": "pages/comparison.py", "label": "Comparison"}, - {"path": "pages/analyses.py", "label": "Analyses"}, - {"path": "pages/dashboard.py", "label": "Dashboard"} + {"path": "pages/analyses.py", "label": "Analyses", "icon": ":material/analytics:"}, + {"path": "pages/portfolios.py", "label": "Portfolios", "icon": ":material/folder_open:"}, + {"path": "pages/models.py", "label": "Models", "icon": ":material/deployed_code:"} ], - "post_login_page": "pages/scenariosGuide.py", + "post_login_page": "pages/analyses.py", "model_map": { }, "skip_login": false From 16a9b834c8fc50f620255a92eba269479293330e Mon Sep 17 00:00:00 2001 From: Ben Hayes Date: Thu, 5 Nov 2026 15:00:48 +0000 Subject: [PATCH 06/33] Results level selection, zip downloads, EP defaults, event progress, HTTPS - Results: choose which summary level to view per perspective; output fragments read the selected level instead of always S1 - Download all outputs as .zip (repacked from the API's .tar.gz) - EP charts: full uncertainty first/default, then MeanDR; linear return period axis for all EP curves - Live run progress polls every 2s and shows 'x of y events' from num_events_complete/num_events_total (task counts otherwise); model workers now report progress via OASIS_ANALYSIS_STATUS_URL - HTTPS through Traefik: certificate from scripts/generate-certs.sh (mkcert if available, else a local CA), websecure on :443 so the server's internal IdP calls resolve, Keycloak secure route, and browser-facing http routes redirect to https when OASIS_PROTOCOL=https (now the default). /api stays available over http for API clients. Co-Authored-By: Claude Opus 5.5 --- .env | 2 +- .env.authentik | 2 +- .env.example | 2 +- .env.keycloak | 2 +- .env.simple | 2 +- .gitignore | 3 + README.md | 30 +++++++-- docker-compose.authentik.yml | 1 + docker-compose.keycloak.yml | 6 ++ docker-compose.models.piwind.yml | 2 + docker-compose.models.scenarios.yml | 3 + docker-compose.ui.yml | 1 + docker-compose.yml | 10 ++- install.sh | 23 +++++-- modules/client.py | 23 +++++++ modules/visualisation.py | 8 +++ pages/analyses.py | 26 ++++---- pages/comparison.py | 4 +- pages/components/common.py | 19 ++++-- pages/components/output.py | 75 +++++++++++---------- pages/components/results.py | 35 +++++++--- scripts/generate-certs.sh | 66 +++++++++++++++++++ tests/fixtures/results_levels_app.py | 33 ++++++++++ tests/test_results.py | 98 ++++++++++++++++++++++++++++ traefik/dynamic/middlewares.yml | 14 ++++ traefik/dynamic/tls.yml | 9 +++ 26 files changed, 420 insertions(+), 79 deletions(-) create mode 100755 scripts/generate-certs.sh create mode 100644 tests/fixtures/results_levels_app.py create mode 100644 tests/test_results.py create mode 100644 traefik/dynamic/middlewares.yml create mode 100644 traefik/dynamic/tls.yml diff --git a/.env b/.env index 4852c8c..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 diff --git a/.env.authentik b/.env.authentik index bf23921..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 diff --git a/.env.example b/.env.example index c841bc6..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 diff --git a/.env.keycloak b/.env.keycloak index 4852c8c..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 diff --git a/.env.simple b/.env.simple index 7980d4d..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 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 7cc440f..839403d 100644 --- a/README.md +++ b/README.md @@ -92,14 +92,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 @@ -202,7 +220,7 @@ 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` | +| `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` | 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..4764777 100644 --- a/docker-compose.models.scenarios.yml +++ b/docker-compose.models.scenarios.yml @@ -15,6 +15,9 @@ 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/ + # Authentication configuration OASIS_SERVER_API_AUTH_TYPE: ${API_AUTH_TYPE:-simple} OASIS_SERVER_ALLOWED_OIDC_AUTH_PROVIDERS: ${OASIS_SERVER_ALLOWED_OIDC_AUTH_PROVIDERS} diff --git a/docker-compose.ui.yml b/docker-compose.ui.yml index 0d58bbc..23a5fbf 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" diff --git a/docker-compose.yml b/docker-compose.yml index 24343b1..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 diff --git a/install.sh b/install.sh index 9bd9a6b..534abab 100755 --- a/install.sh +++ b/install.sh @@ -151,6 +151,17 @@ echo "" # Set service account credentials based on auth type # ============================================================================ +echo "--- Configuring HTTPS ---" +bash "$SCRIPT_DIR/scripts/generate-certs.sh" +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 @@ -334,16 +345,16 @@ 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}/" +echo " API: ${OASIS_PROTOCOL}://${OASIS_UI_HOSTNAME}/api/" +echo " API Docs: ${OASIS_PROTOCOL}://${OASIS_UI_HOSTNAME}/api/swagger/" 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/client.py b/modules/client.py index cb0a8df..0b9d7c8 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,6 +13,21 @@ 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. @@ -263,6 +282,10 @@ def generate_and_run(self, 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`. ''' diff --git a/modules/visualisation.py b/modules/visualisation.py index af42f61..5de2c2d 100644 --- a/modules/visualisation.py +++ b/modules/visualisation.py @@ -21,10 +21,18 @@ def __init__(self, output_file_dict): ''' self.output_file_dict = output_file_dict self.oed_fields = {} + self.summary_levels = {} 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. diff --git a/pages/analyses.py b/pages/analyses.py index 7b52850..ecb705d 100644 --- a/pages/analyses.py +++ b/pages/analyses.py @@ -298,15 +298,16 @@ def results_tab(analysis, settings): if fname: dl_col.download_button('Download', outputs[fname].to_csv(index=False).encode(), file_name=fname, key=f"dl_out_{analysis['id']}") - tar_key = f"tar_{analysis['id']}_{analysis.get('modified')}" - if tar_key not in st.session_state: - if st.button('Prepare download of all outputs (.tar.gz)', key=f'{tar_key}_prep'): + 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[tar_key] = ci.download_output(analysis['id']) + st.session_state[zip_key] = ci.download_output_zip(analysis['id']) st.rerun() else: - st.download_button('Download all outputs (.tar.gz)', st.session_state[tar_key], - file_name=f"analysis_{analysis['id']}_output.tar.gz", key=f'{tar_key}_dl') + 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:') def inputs_tab(analysis): @@ -473,18 +474,19 @@ def list_view(): snapshot = {a['id']: a['status'] for a in analyses} any_running = any(s in IN_PROGRESS_STATUSES for s in snapshot.values()) - @st.fragment(run_every='4s' if any_running else None) + @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 - running = [a for a in fresh if a['status'] in IN_PROGRESS_STATUSES] - for a in running: - progress = analysis_progress(a) - text = f"{a['name']}: {format_status(a['status'])}" - st.progress(progress or 0.0, text=text + (f' ({progress:.0%})' if progress is not None else '')) + for a in fresh: + if a['status'] not in IN_PROGRESS_STATUSES: + continue + fraction, detail = analysis_progress(a) + text = f"**{a['name']}** · {format_status(a['status'])}" + (f' · {detail}' if detail else '') + st.progress(fraction or 0.0, text=text) live_status() diff --git a/pages/comparison.py b/pages/comparison.py index f5c39a0..099bb71 100644 --- a/pages/comparison.py +++ b/pages/comparison.py @@ -10,7 +10,7 @@ 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 +from pages.components.output import generate_alt_comparison_fragment, EP_CALC_LABELS ########################################################################################## # Header @@ -288,7 +288,7 @@ def merge_locations(locations_1, locations_2): if all(any(o.get(e, False) for e in ept_settings) for o in ord_settings): 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=[ diff --git a/pages/components/common.py b/pages/components/common.py index 22630c7..f1a23cc 100644 --- a/pages/components/common.py +++ b/pages/components/common.py @@ -62,12 +62,23 @@ def format_status(status): def analysis_progress(analysis): - '''Fraction of sub-tasks completed for a running analysis, or None.''' + '''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 == 0: - return None - return counts.get('COMPLETED', 0) / total + if total: + done = counts.get('COMPLETED', 0) + return done / total, f'{done} of {total} tasks' + return None, '' ########################################################################################## diff --git a/pages/components/output.py b/pages/components/output.py index fca888b..6590430 100644 --- a/pages/components/output.py +++ b/pages/components/output.py @@ -4,13 +4,26 @@ 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 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', +} + + +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() @@ -594,7 +607,7 @@ def generate_eltcalc_fragment(perspective, output, ''' 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') tab_names = [] if table: @@ -626,7 +639,7 @@ def generate_eltcalc_fragment(perspective, output, @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 @@ -694,7 +707,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() @@ -773,7 +786,7 @@ def generate_selt_fragment(p, vis, locations=None): ''' 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)' @@ -829,7 +842,7 @@ 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') oed_fields = vis.oed_fields.get(p) or [] breakdown_field = None @@ -862,7 +875,7 @@ def generate_aalcalc_fragment(p, vis): @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' @@ -905,7 +918,7 @@ def generate_alct_fragment(p, vis): 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') + result = vis.get(vis.summary_level(p), p, 'alct_convergence') oed_fields = vis.oed_fields.get(p) or [] selected_group = None @@ -931,7 +944,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 @@ -959,7 +972,7 @@ 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: @@ -1085,9 +1098,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 +1108,7 @@ def format_lec_options(opt): for r in results: values.update(r[col].unique().tolist()) + values = order_ep_calcs(values) if col == 'EPCalc' else sorted(values) if len(values) > 1: format_map = spec.get('format_map') selected_value = st.radio(spec['label'], options=values, horizontal=True, @@ -1132,9 +1146,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: @@ -1237,7 +1249,7 @@ def pltcalc_bar(result, selected_group=None, number_shown=10, date_id = False, @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 @@ -1273,7 +1285,7 @@ def generate_pltcalc_fragment(p, vis): @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 @@ -1313,7 +1325,7 @@ def generate_mplt_fragment(p, vis): @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 @@ -1365,7 +1377,7 @@ def generate_splt_fragment(p, vis): ''' 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 @@ -1405,7 +1417,7 @@ 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', @@ -1414,12 +1426,7 @@ def generate_ept_fragment(p, vis): 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() @@ -1430,7 +1437,7 @@ def generate_ept_fragment(p, vis): 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: @@ -1457,7 +1464,7 @@ 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] @@ -1495,7 +1502,7 @@ def generate_psept_fragment(p, vis): 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 = { @@ -1537,7 +1544,7 @@ 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] @@ -1577,7 +1584,7 @@ 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] + results = [o.get(o.summary_level(p), p, 'aalcalc') for o in outputs] oed_fields = shared_oed_fields(p, outputs) breakdown_field = None @@ -1679,7 +1686,7 @@ 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() @@ -1769,7 +1776,7 @@ def generate_pltcalc_comparison_fragment(p, outputs, names=None, output_type='pl 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 @@ -1833,7 +1840,7 @@ def generate_alt_comparison_fragment(p, outputs, output_type='alt_meanonly', nam 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' diff --git a/pages/components/results.py b/pages/components/results.py index 2d763d7..21c6584 100644 --- a/pages/components/results.py +++ b/pages/components/results.py @@ -70,11 +70,6 @@ def render_results(settings, outputs, locations=None): vis = OutputInterface(outputs) perspectives = [p for p in PERSPECTIVES if settings.get(f'{p}_output')] - for p in perspectives: - fields = (settings.get(f'{p}_summaries') or [{}])[0].get('oed_fields') - if fields: - vis.set_oed_fields(p, fields) - if not perspectives: st.info('No loss perspectives were enabled in the analysis settings.') return @@ -82,11 +77,35 @@ def render_results(settings, outputs, locations=None): tabs = st.tabs([PERSPECTIVE_LABELS[p] for p in perspectives]) for p, tab in zip(perspectives, tabs): with tab: - # Visualisations currently use the first summary level - summary = (settings.get(f'{p}_summaries') or [{}])[0] + 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}', + 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) + vis.set_oed_fields(p, summary.get('oed_fields') or None) + sections = _sections(summary, locations) if not sections: - st.info('No outputs were selected for this perspective.') + st.info('No outputs were selected for this summary level.') for i, (title, render) in enumerate(sections): with st.expander(title, expanded=i == 0): 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}" diff --git a/scripts/generate-certs.sh b/scripts/generate-certs.sh new file mode 100755 index 0000000..62f7518 --- /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="$SCRIPT_DIR/../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 + 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/tests/fixtures/results_levels_app.py b/tests/fixtures/results_levels_app.py new file mode 100644 index 0000000..a69b7b8 --- /dev/null +++ b/tests/fixtures/results_levels_app.py @@ -0,0 +1,33 @@ +''' +Standalone script for AppTest coverage of summary level selection in +`render_results`: two GUL summary levels, each with an EPT whose losses +identify the level (level 1 losses are 100s, level 2 losses are 200s). +''' +import pandas as pd + +from pages.components.results import render_results + + +def ept(base): + return pd.DataFrame({ + 'SummaryId': [1] * 4, + 'EPCalc': [2, 2, 1, 1], + 'EPType': [1, 1, 1, 1], + 'ReturnPeriod': [10.0, 100.0, 10.0, 100.0], + 'Loss': [base + 1, base + 2, base + 3, base + 4], + }) + + +settings = { + 'gul_output': True, + 'gul_summaries': [ + {'id': 1, 'ord_output': {'ept_full_uncertainty_aep': True}}, + {'id': 2, 'oed_fields': ['LocNumber'], 'ord_output': {'ept_full_uncertainty_aep': True}}, + ], +} +outputs = { + 'gul_S1_ept.csv': ept(100), + 'gul_S2_ept.csv': ept(200), + 'gul_S2_summary-info.csv': pd.DataFrame({'summary_id': [1], 'LocNumber': ['loc-1']}), +} +render_results(settings, outputs) diff --git a/tests/test_results.py b/tests/test_results.py new file mode 100644 index 0000000..f3bdb15 --- /dev/null +++ b/tests/test_results.py @@ -0,0 +1,98 @@ +import base64 +import io +import json +import tarfile +import zipfile + +import numpy as np + +from streamlit.testing.v1 import AppTest + +from modules.client import tar_to_zip +from pages.components.common import analysis_progress +from pages.components.output import order_ep_calcs +from pages.components.results import level_label + +APP = 'tests/fixtures/results_levels_app.py' + + +def _values(arr): + '''Plotly figure arrays may be plain lists or base64 typed arrays.''' + if isinstance(arr, dict) and 'bdata' in arr: + return np.frombuffer(base64.b64decode(arr['bdata']), dtype=arr['dtype']).tolist() + return list(arr) + + +def chart_losses(at): + '''Loss values plotted in the first plotly chart.''' + spec = json.loads(at.get('plotly_chart')[0].proto.spec) + return sorted(y for trace in spec['data'] for y in _values(trace['y'])) + + +def test_summary_level_selector(): + at = AppTest.from_file(APP, default_timeout=30).run() + assert not at.exception + + select = at.selectbox(key='results_level_gul') + assert select.options == ['Level 1: portfolio total', 'Level 2: grouped by LocNumber'] + # Level 1, full uncertainty (EPCalc 2) shown by default + assert chart_losses(at) == [101, 102] + + select.set_value(2).run() + assert not at.exception + assert chart_losses(at) == [201, 202] + + +def test_ep_defaults_to_full_uncertainty_then_meandr(): + at = AppTest.from_file(APP, default_timeout=30).run() + calc = at.radio(key='ept_gul_calc_filter') + assert calc.options == ['Full uncertainty', 'Mean damage ratio (MeanDR)'] + assert calc.value == 2 + + calc.set_value(1).run() + assert chart_losses(at) == [103, 104] + + +def test_ep_axis_is_linear(): + at = AppTest.from_file(APP, default_timeout=30).run() + layout = json.loads(at.get('plotly_chart')[0].proto.spec)['layout'] + assert layout.get('xaxis', {}).get('type') != 'log' + + +def test_order_ep_calcs(): + assert order_ep_calcs([1, 3, 2, 4]) == [2, 1, 4, 3] + assert order_ep_calcs([1]) == [1] + + +def test_level_label(): + assert level_label({'id': 3}) == 'Level 3: portfolio total' + assert level_label({'id': 1, 'oed_fields': ['CountryCode', 'LocNumber']}) == \ + 'Level 1: grouped by CountryCode, LocNumber' + + +def test_tar_to_zip_keeps_files_and_paths(): + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode='w:gz') as tar: + for name, data in [('output/gul_S1_ept.csv', b'a\n1\n'), ('./output/il_S1_ept.csv', b'b\n')]: + info = tarfile.TarInfo(name) + info.size = len(data) + tar.addfile(info, io.BytesIO(data)) + + with zipfile.ZipFile(io.BytesIO(tar_to_zip(buf.getvalue()))) as zf: + assert sorted(zf.namelist()) == ['output/gul_S1_ept.csv', 'output/il_S1_ept.csv'] + assert zf.read('output/gul_S1_ept.csv') == b'a\n1\n' + + +def test_progress_uses_events_while_running(): + running = {'status': 'RUN_STARTED', 'num_events_complete': 963, 'num_events_total': 1447, + 'status_count': {'COMPLETED': 2, 'TOTAL': 6}} + fraction, text = analysis_progress(running) + assert text == '963 of 1,447 events' + assert round(fraction, 3) == round(963 / 1447, 3) + + +def test_progress_falls_back_to_tasks(): + queued = {'status': 'RUN_STARTED', 'num_events_complete': 0, 'num_events_total': 0, + 'status_count': {'COMPLETED': 1, 'TOTAL': 4}} + assert analysis_progress(queued) == (0.25, '1 of 4 tasks') + assert analysis_progress({'status': 'RUN_QUEUED'}) == (None, '') diff --git a/traefik/dynamic/middlewares.yml b/traefik/dynamic/middlewares.yml new file mode 100644 index 0000000..95e73af --- /dev/null +++ b/traefik/dynamic/middlewares.yml @@ -0,0 +1,14 @@ +# Middlewares for the plain HTTP (web) entrypoint of browser-facing routers. +# install.sh selects one via OASIS_WEB_ENTRY_MIDDLEWARE: +# https-redirect@file when OASIS_PROTOCOL=https (send browsers to HTTPS) +# http-passthrough@file when OASIS_PROTOCOL=http (serve over HTTP as-is) +http: + middlewares: + https-redirect: + redirectScheme: + scheme: https + permanent: true + http-passthrough: + headers: + customResponseHeaders: + X-Oasis-Entrypoint: http diff --git a/traefik/dynamic/tls.yml b/traefik/dynamic/tls.yml new file mode 100644 index 0000000..c204d9f --- /dev/null +++ b/traefik/dynamic/tls.yml @@ -0,0 +1,9 @@ +# TLS certificate for the websecure (HTTPS) entrypoint. +# Created by scripts/generate-certs.sh (run by install.sh); replace +# certs/ui.crt and certs/ui.key to use your own certificate. +tls: + stores: + default: + defaultCertificate: + certFile: /certs/ui.crt + keyFile: /certs/ui.key From 25f8a7d75f951efa701cd8d037b2d435e99e497f Mon Sep 17 00:00:00 2001 From: Ben Hayes Date: Thu, 5 Nov 2026 15:05:24 +0000 Subject: [PATCH 07/33] Print resolved certificate paths in generate-certs.sh Co-Authored-By: Claude Opus 5.5 --- scripts/generate-certs.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/generate-certs.sh b/scripts/generate-certs.sh index 62f7518..bd0c472 100755 --- a/scripts/generate-certs.sh +++ b/scripts/generate-certs.sh @@ -12,7 +12,7 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -CERT_DIR="$SCRIPT_DIR/../certs" +CERT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)/certs" HOSTNAME="${OASIS_UI_HOSTNAME:-ui.oasis.local}" CRT="$CERT_DIR/ui.crt" KEY="$CERT_DIR/ui.key" From 4fa7f59904b5a70241cc932f646a13220ad4368a Mon Sep 17 00:00:00 2001 From: Ben Hayes Date: Thu, 5 Nov 2026 15:08:53 +0000 Subject: [PATCH 08/33] Restart Traefik when the TLS certificate changes Traefik's file provider only reloads on config changes, so a regenerated certs/ui.crt wasn't served until a manual restart. Co-Authored-By: Claude Opus 5.5 --- install.sh | 9 +++++++++ scripts/generate-certs.sh | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/install.sh b/install.sh index 534abab..d2e2a4b 100755 --- a/install.sh +++ b/install.sh @@ -152,7 +152,11 @@ echo "" # ============================================================================ 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://" @@ -297,6 +301,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 "" # ============================================================================ diff --git a/scripts/generate-certs.sh b/scripts/generate-certs.sh index bd0c472..c54b4cf 100755 --- a/scripts/generate-certs.sh +++ b/scripts/generate-certs.sh @@ -30,7 +30,7 @@ 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 + 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 From 68f0c18785f1bd0be6a42235927ef7dbf4478418 Mon Sep 17 00:00:00 2001 From: Ben Hayes Date: Thu, 5 Nov 2026 15:12:18 +0000 Subject: [PATCH 09/33] Enlarge the sidebar logo Streamlit's largest logo size (2rem) leaves the Oasis wordmark cramped; use 3rem, which fills Streamlit's 200px logo width without distortion. Co-Authored-By: Claude Opus 5.5 --- modules/nav.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/modules/nav.py b/modules/nav.py index f1cff75..d75f490 100644 --- a/modules/nav.py +++ b/modules/nav.py @@ -23,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('''''') From dc2f7458c5403457e52393acafb4384ac3d26307 Mon Sep 17 00:00:00 2001 From: Ben Hayes Date: Thu, 5 Nov 2026 15:43:43 +0000 Subject: [PATCH 10/33] Analysis settings and results improvements Settings editor: - Ground-up loss threshold moved under Advanced - Events field (ids and ranges, e.g. '1, 5, 100-120') mapped to event_ids / event_ranges - Group losses by any column of the portfolio's location/accounts files (common fields first, case-insensitive de-duplication) - 'Ceded to reinsurance (RL)' perspective alongside net of RI; RL follows the model's RI support (the model schema has no 'rl') - ALCT can only be selected with PALT: oasislmf only writes the ALCT as part of the period ALT step, so ALCT alone produced nothing Results: - SELT/SPLT default to the true mean of samples (sum / number of samples); the ORD -1 analytical mean is a separate, labelled option. Previously 'Mean (All Samples)' showed the -1 analytical mean. - RL/RI outputs with inuring priority prefixes (rl_IP1_S1_...), with an inuring priority selector; missing summary-info falls back to SummaryId instead of failing - Outputs requested but not produced show a message instead of an error - ALCT shown as a convergence chart (mean loss and CI vs samples) plus the key statistics Run progress shows the sub-task currently being worked on. Co-Authored-By: Claude Opus 5.5 --- modules/client.py | 8 ++ modules/schemas.py | 3 +- modules/visualisation.py | 29 ++++-- pages/analyses.py | 28 +++++- pages/components/common.py | 12 +++ pages/components/output.py | 128 +++++++++++++++++++------- pages/components/results.py | 39 +++++++- pages/components/settings_editor.py | 108 +++++++++++++++++----- tests/fixtures/alct_fragment_app.py | 14 ++- tests/fixtures/settings_editor_app.py | 3 +- tests/mocks.py | 3 + tests/test_output_fragments.py | 102 +++++++++++--------- tests/test_results.py | 34 +++++++ tests/test_settings_editor.py | 72 ++++++++++++++- 14 files changed, 463 insertions(+), 120 deletions(-) diff --git a/modules/client.py b/modules/client.py index 0b9d7c8..aee31f0 100644 --- a/modules/client.py +++ b/modules/client.py @@ -138,6 +138,14 @@ def get_traceback(self, ID, error_type='input_generation'): 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) diff --git a/modules/schemas.py b/modules/schemas.py index 13dcf4b..9bf0376 100644 --- a/modules/schemas.py +++ b/modules/schemas.py @@ -14,11 +14,12 @@ SCHEMA_DIR = Path(ods_tools.__file__).parent / 'data' -PERSPECTIVES = ['gul', 'il', 'ri'] +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 diff --git a/modules/visualisation.py b/modules/visualisation.py index 5de2c2d..ce9de84 100644 --- a/modules/visualisation.py +++ b/modules/visualisation.py @@ -22,6 +22,17 @@ def __init__(self, output_file_dict): 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 set_oed_fields(self, perspective, oed_fields): self.oed_fields[perspective] = oed_fields @@ -76,14 +87,15 @@ 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) + prefix = self.file_prefixes.get(perspective, '') + fname = self._request_to_fname(summary_level, perspective, output_type, prefix=prefix, + **kwargs) results = self.output_file_dict.get(fname) if results is None: logger.error(f'Failed to find output file: {fname}') @@ -91,7 +103,8 @@ def get(self, summary_level, perspective, output_type, **kwargs): 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.output_file_dict.get( + self._request_to_summary_info_fname(summary_level, perspective, prefix)) results = self.add_oed_fields(results, summary_info, oed_fields) kwargs['oed_fields'] = oed_fields @@ -99,7 +112,7 @@ def get(self, summary_level, perspective, output_type, **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] @@ -114,15 +127,15 @@ 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): diff --git a/pages/analyses.py b/pages/analyses.py index ecb705d..694ebd8 100644 --- a/pages/analyses.py +++ b/pages/analyses.py @@ -11,10 +11,11 @@ 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, + SELECTED_MODEL, SELECTED_PORTFOLIO, analysis_progress, current_task, format_status, open_record, selectable_table) from pages.components.data import (analyses_df, analysis_files, analysis_settings, - cached_model_settings, model_label, models_df, session_cached) + cached_model_settings, model_label, models_df, portfolio_file_df, + session_cached) from pages.components.logs import display_traceback_file from pages.components.results import render_results from pages.components.settings_editor import analysis_settings_editor, reset_editor @@ -45,6 +46,20 @@ def close_editor(editor_key=None): st.session_state[NEW_ANALYSIS_DEFAULTS] = None +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 + + def start_run(analysis, regenerate=False): '''Run an analysis, generating inputs first if needed.''' if regenerate or analysis['status'] not in RUNNABLE_WITH_INPUTS: @@ -171,7 +186,8 @@ def new_analysis_view(): 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) + settings, valid, problems = analysis_settings_editor(model, model_settings, portfolio, base, editor_key, + portfolio_fields(portfolio)) st.divider() if problems: @@ -223,7 +239,8 @@ def edit_settings_view(analysis): 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) + settings, valid, problems = analysis_settings_editor(model, model_settings, portfolio, base, editor_key, + portfolio_fields(portfolio)) st.divider() in_progress = analysis['status'] in IN_PROGRESS_STATUSES @@ -485,7 +502,8 @@ def live_status(): if a['status'] not in IN_PROGRESS_STATUSES: continue fraction, detail = analysis_progress(a) - text = f"**{a['name']}** · {format_status(a['status'])}" + (f' · {detail}' if detail else '') + task = current_task(ci.analyses.sub_tasks(a['id'])) + text = ' · '.join(x for x in [f"**{a['name']}**", format_status(a['status']), task, detail] if x) st.progress(fraction or 0.0, text=text) live_status() diff --git a/pages/components/common.py b/pages/components/common.py index f1a23cc..0d4db7f 100644 --- a/pages/components/common.py +++ b/pages/components/common.py @@ -81,6 +81,18 @@ def analysis_progress(analysis): 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 ########################################################################################## diff --git a/pages/components/output.py b/pages/components/output.py index 6590430..57ce614 100644 --- a/pages/components/output.py +++ b/pages/components/output.py @@ -19,6 +19,62 @@ } + +# 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] + + def order_ep_calcs(values): """Order EPCalc codes so full uncertainty comes first, then MeanDR.""" order = list(EP_CALC_LABELS) @@ -784,20 +840,10 @@ def generate_selt_fragment(p, vis, locations=None): the maximum sampled loss. Real per-sample draws use positive `SampleId` values (1..N). ''' - MEAN_SIDX = -1 - 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') tab_names = ['table', 'map'] with st.container(border=True): @@ -913,25 +959,49 @@ def generate_alt_fragment(p, vis, output_type='alt_meanonly'): @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. + 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() @@ -1375,8 +1445,6 @@ def generate_splt_fragment(p, vis): 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(vis.summary_level(p), p, 'plt_sample') oed_fields = vis.oed_fields.get(p) or [] @@ -1391,15 +1459,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', diff --git a/pages/components/results.py b/pages/components/results.py index 21c6584..8e66a07 100644 --- a/pages/components/results.py +++ b/pages/components/results.py @@ -1,7 +1,10 @@ ''' Render the outputs of a completed analysis, driven by its analysis settings. ''' +import re + import streamlit as st +from oasis_data_manager.errors import OasisException from modules.schemas import PERSPECTIVE_LABELS, PERSPECTIVES from modules.visualisation import OutputInterface @@ -69,6 +72,7 @@ def render_results(settings, outputs, locations=None): 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.') @@ -93,14 +97,31 @@ def render_results(settings, outputs, locations=None): summary = levels[level_id] vis.set_summary_level(p, level_id) - vis.set_oed_fields(p, summary.get('oed_fields') or None) + + # 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.has_summary_info(p, 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) in enumerate(sections): with st.expander(title, expanded=i == 0): - render(p, vis) + try: + render(p, vis) + except OasisException: + st.info('This output was requested in the settings but the run did not produce it.') def level_label(level): @@ -109,3 +130,17 @@ def level_label(level): 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 index c511daf..92a5a8a 100644 --- a/pages/components/settings_editor.py +++ b/pages/components/settings_editor.py @@ -38,9 +38,48 @@ 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 perspective_availability(model_settings, portfolio): '''Which perspectives can be run, with a reason for those that can't.''' - valid = model_settings.get('model_settings', {}).get('valid_output_perspectives') or PERSPECTIVES + valid = list(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']} @@ -48,9 +87,9 @@ def perspective_availability(model_settings, portfolio): for p in PERSPECTIVES: if p not in valid: reasons[p] = 'Not supported by this model.' - elif p in ('il', 'ri') and not has['accounts_file']: + elif p in ('il', 'ri', 'rl') and not has['accounts_file']: reasons[p] = 'The portfolio has no accounts file.' - elif p == 'ri' and not (has['reinsurance_info_file'] and has['reinsurance_scope_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 @@ -67,12 +106,19 @@ def default_settings(model, model_settings): } -def group_field_options(model_settings, extra=()): +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]: - if f not in 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 @@ -88,18 +134,32 @@ def general_section(base, model_settings, key): 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, right = st.columns(2) + 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') - entry = schemas.analysis_property('gul_threshold') - out['gul_threshold'] = right.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') - 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', @@ -300,8 +360,12 @@ def summary_levels_editor(key, scope, summaries, field_options): with col: st.markdown(f'**{group}**', unsafe_allow_html=True) for k in keys: - if col.checkbox(flags[k][0], value=bool(ord_output.get(k)), help=flags[k][1], - key=f'{wkey}_{k}'): + # oasislmf only writes the ALCT alongside the period ALT (PALT) + needs_palt = k == 'alct_convergence' and 'alt_period' not in selected + help_text = flags[k][1] + (' Requires PALT.' if needs_palt else '') + if col.checkbox(flags[k][0], value=bool(ord_output.get(k)) and not needs_palt, + help=help_text, disabled=needs_palt, key=f'{wkey}_{k}') \ + and not needs_palt: selected.append(k) new_level = {k: v for k, v in level.items() if k not in ('ord_output', 'oed_fields')} @@ -331,12 +395,12 @@ def summary_levels_editor(key, scope, summaries, field_options): return result -def outputs_section(base, model_settings, portfolio, key): +def outputs_section(base, model_settings, portfolio, key, portfolio_fields=()): out, errors = {}, [] unavailable = perspective_availability(model_settings, portfolio) st.markdown('**Loss perspectives**') - cols = st.columns(3) + cols = st.columns(len(PERSPECTIVES)) enabled = [] for col, p in zip(cols, PERSPECTIVES): reason = unavailable.get(p) @@ -355,7 +419,7 @@ def outputs_section(base, model_settings, portfolio, key): 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) + 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') @@ -385,7 +449,7 @@ def outputs_section(base, model_settings, portfolio, key): # Editor ########################################################################################## -def analysis_settings_editor(model, model_settings, portfolio, base_settings, key): +def analysis_settings_editor(model, model_settings, portfolio, base_settings, key, portfolio_fields=()): '''Render the editor and return `(settings, valid, problems)`. Args: @@ -394,6 +458,7 @@ def analysis_settings_editor(model, model_settings, portfolio, base_settings, ke 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) @@ -405,11 +470,12 @@ def analysis_settings_editor(model, model_settings, portfolio, base_settings, ke with model_tab: ms, ms_errors = model_options_section(base, model_settings, key) with outputs_tab: - outputs, output_errors = outputs_section(base, model_settings, portfolio, key) + outputs, output_errors = outputs_section(base, model_settings, portfolio, key, portfolio_fields) # 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') + 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'] diff --git a/tests/fixtures/alct_fragment_app.py b/tests/fixtures/alct_fragment_app.py index d05de72..f68b13f 100644 --- a/tests/fixtures/alct_fragment_app.py +++ b/tests/fixtures/alct_fragment_app.py @@ -6,12 +6,16 @@ from modules.visualisation import OutputInterface from pages.components.output import generate_alct_fragment +# Columns as written by oasislmf 2.5's aalpy (-c): one row per sample size alct_df = pd.DataFrame({ - 'SummaryId': [1, 2], - 'SampleSize': [1000, 1000], - 'MeanLoss': [123.45, 67.89], - 'SEMean': [1.23, 0.98], - 'VarianceLoss': [45.6, 12.3], + 'SummaryId': [1, 1, 1, 2, 2, 2], + 'MeanLoss': [100.0, 110.0, 105.0, 50.0, 55.0, 52.0], + 'SDLoss': [10.0, 9.0, 8.0, 5.0, 4.5, 4.0], + 'SampleSize': [1, 2, 4, 1, 2, 4], + 'LowerCI': [0.0, 100.0, 101.0, 0.0, 50.0, 50.5], + 'UpperCI': [0.0, 120.0, 109.0, 0.0, 60.0, 53.5], + 'StandardError': [0.0, 5.0, 2.0, 0.0, 2.5, 0.75], + 'RelativeError': [0.0, 0.045, 0.019, 0.0, 0.045, 0.014], }) summary_info_df = pd.DataFrame({ diff --git a/tests/fixtures/settings_editor_app.py b/tests/fixtures/settings_editor_app.py index ec49c1a..8cdfdc5 100644 --- a/tests/fixtures/settings_editor_app.py +++ b/tests/fixtures/settings_editor_app.py @@ -43,7 +43,8 @@ PORTFOLIO = {'id': 1, 'name': 'p', 'location_file': {'stored': 'l.csv'}, 'accounts_file': {'stored': 'a.csv'}} settings, valid, problems = analysis_settings_editor( - MODEL, MODEL_SETTINGS, PORTFOLIO, st.session_state.get('base_settings'), key='test_editor') + MODEL, MODEL_SETTINGS, PORTFOLIO, st.session_state.get('base_settings'), key='test_editor', + portfolio_fields=['LocNumber', 'OccupancyCode', 'BuildingTIV', 'accnumber']) st.session_state['editor_settings'] = settings st.session_state['editor_valid'] = valid st.session_state['editor_problems'] = problems diff --git a/tests/mocks.py b/tests/mocks.py index 93f6093..83fa199 100644 --- a/tests/mocks.py +++ b/tests/mocks.py @@ -71,6 +71,9 @@ def run(self, ID): def cancel(self, ID): return self._set_status(ID, 'RUN_CANCELLED') + def sub_task_list(self, ID): + return MockJsonObject(self._find(ID).get('sub_tasks', [])) + class MockFileEndpoint: '''File sub-endpoint (e.g. `portfolios.location_file`) holding DataFrames by ID. diff --git a/tests/test_output_fragments.py b/tests/test_output_fragments.py index ab794c8..040cc77 100644 --- a/tests/test_output_fragments.py +++ b/tests/test_output_fragments.py @@ -47,29 +47,44 @@ def test_selt_fragment_renders_table_and_map(): assert len(at.get("plotly_chart")) == 1 -def test_selt_fragment_mean_view_uses_special_sidx_row_not_a_recomputed_average(): - ''' - Regression test: `generate_selt_fragment`'s default "Mean (All - Samples)" view used to recompute the mean itself via a pandas - groupby over the file's positive-SampleId rows. SELT's SampleId - column is ORD's reserved "sidx": -1 is ktools' own - analytically-integrated mean (not a recomputed average of the - positive-sidx rows in the same file), so the fragment should read - that row directly instead. The fixture's -1 rows are deliberately - not the arithmetic average of their samples, so this fails if the - fragment goes back to recomputing. +SAMPLE_OPTIONS = ["Mean of samples", "Analytical mean (sidx -1)", "Sample 1", "Sample 2"] + + +def test_selt_fragment_mean_of_samples_and_analytical_mean(): + ''' + SELT's SampleId column uses ORD's reserved "sidx" values: -1 is the + model's analytically integrated mean, which is not the mean of the + sampled losses. The default view is the true mean of the samples; the + analytical mean is offered separately and labelled as such. The + fixture's -1 rows are deliberately not the average of their samples. ''' at = AppTest.from_file("tests/fixtures/selt_fragment_app.py").run() assert len(at.exception) == 0 - assert at.selectbox(key="selt_gul_sample_filter").value == "Mean (All Samples)" - # Sample filter options must not expose the special sidx rows as if - # they were selectable individual samples. - assert at.selectbox(key="selt_gul_sample_filter").options == ["Mean (All Samples)", "1", "2"] - # sorted descending by Loss: the fixture's -1 rows are [150, 90, 25, 15], - # not the samples' naive averages [200, 100, 30, 20]. + select = at.selectbox(key="selt_gul_sample_filter") + assert select.options == SAMPLE_OPTIONS + assert select.value == "Mean of samples" + # sorted descending by Loss: averages of the two samples + assert list(at.dataframe[0].value["Loss"]) == [200.0, 100.0, 30.0, 20.0] + + select.set_value("Analytical mean (sidx -1)").run() assert list(at.dataframe[0].value["Loss"]) == [150.0, 90.0, 25.0, 15.0] + select.set_value(2).run() + assert list(at.dataframe[0].value["Loss"]) == [300.0, 150.0, 40.0, 30.0] + + +def test_sample_mean_counts_samples_without_rows(): + '''Samples with zero loss have no row, so divide by the number of samples.''' + import pandas as pd + from pages.components.output import sample_mean + + df = pd.DataFrame({'EventId': [1, 1, 1], 'SummaryId': [1, 1, 1], + 'SampleId': [-1, 1, 3], 'Loss': [5.0, 10.0, 20.0]}) + result = sample_mean(df, n_samples=4) + assert list(result['Loss']) == [7.5] # (10 + 20 + 0 + 0) / 4 + assert list(result.columns) == ['EventId', 'SummaryId', 'SampleId', 'Loss'] + def test_splt_fragment_renders_bar_chart(): at = AppTest.from_file("tests/fixtures/splt_fragment_app.py").run() @@ -78,41 +93,46 @@ def test_splt_fragment_renders_bar_chart(): assert len(at.get("plotly_chart")) == 1 -def test_splt_fragment_mean_view_uses_special_sidx_row_not_a_recomputed_average(): +def test_splt_fragment_mean_of_samples_and_analytical_mean(): ''' - Regression test: `generate_splt_fragment`'s default "Mean (All - Samples)" view used to recompute the mean itself via a pandas - groupby over the file's positive-SampleId rows, same bug as SELT's. - SPLT's SampleId column is ORD's reserved "sidx": -1 is ktools' own - analytically-integrated mean, so the fragment should read that row - directly instead. The fixture's -1 rows per (SummaryId, date) are - deliberately not the arithmetic average of their samples (12 not - 15, 17 not 20, 6 not 6.5, 7 not 7.5); `pltcalc_bar` then sums - across SummaryId per date, giving 12+17=29 for 2020-01-01 and - 6+7=13 for 2021-06-15 - not the naive-average equivalents (35, 14), - so this fails if the fragment goes back to recomputing. + As for SELT: the default view averages the samples, and ORD's -1 + analytical mean is a separate option. `pltcalc_bar` sums across + SummaryId per date: sample means give 15+20=35 and 6.5+7.5=14; the + fixture's -1 rows give 12+17=29 and 6+7=13. ''' at = AppTest.from_file("tests/fixtures/splt_fragment_app.py").run() assert len(at.exception) == 0 - assert at.selectbox(key="splt_gul_sample_filter").value == "Mean (All Samples)" - # Sample filter options must not expose the special sidx row as if - # it were a selectable individual sample. - assert at.selectbox(key="splt_gul_sample_filter").options == ["Mean (All Samples)", "1", "2"] + select = at.selectbox(key="splt_gul_sample_filter") + assert select.options == SAMPLE_OPTIONS + assert select.value == "Mean of samples" - spec = _plotly_spec(at.get("plotly_chart")[0]) - losses = [] - for trace in spec['data']: - losses.extend(_decode_plotly_array(trace.get('y'))) - assert sorted(losses) == [13.0, 29.0] + def losses(): + spec = _plotly_spec(at.get("plotly_chart")[0]) + return sorted(v for trace in spec['data'] for v in _decode_plotly_array(trace.get('y'))) + + assert losses() == [14.0, 35.0] + # Fresh run with the choice preset: AppTest can't rerun this fragment + # interactively while its (unselected) single-select pills are present. + at = AppTest.from_file("tests/fixtures/splt_fragment_app.py") + at.session_state["splt_gul_sample_filter"] = "Analytical mean (sidx -1)" + at.run() + assert losses() == [13.0, 29.0] -def test_alct_fragment_renders_table(): + +def test_alct_fragment_renders_convergence_chart_and_table(): at = AppTest.from_file("tests/fixtures/alct_fragment_app.py").run() assert len(at.exception) == 0 - assert len(at.dataframe) == 1 - assert set(at.dataframe[0].value["SummaryId"]) == {1, 2} + # One confidence band and one mean line per summary id + spec = _plotly_spec(at.get("plotly_chart")[0]) + assert len(spec['data']) == 4 + assert spec['layout']['xaxis']['title']['text'] == 'Number of samples' + table = at.dataframe[0].value + assert set(table["SummaryId"]) == {"1", "2"} + assert list(table.columns) == ['SummaryId', 'SampleSize', 'MeanLoss', 'LowerCI', 'UpperCI', + 'StandardError', 'RelativeError'] def test_psept_fragment_renders_ep_curve(): diff --git a/tests/test_results.py b/tests/test_results.py index f3bdb15..c5c16e3 100644 --- a/tests/test_results.py +++ b/tests/test_results.py @@ -96,3 +96,37 @@ def test_progress_falls_back_to_tasks(): 'status_count': {'COMPLETED': 1, 'TOTAL': 4}} assert analysis_progress(queued) == (0.25, '1 of 4 tasks') assert analysis_progress({'status': 'RUN_QUEUED'}) == (None, '') + + +def test_current_task_shows_started_tasks(): + from pages.components.common import current_task + tasks = [ + {'name': 'Prepare losses generation directory', 'status': 'COMPLETED'}, + {'name': 'Generate losses chunk 0', 'status': 'STARTED'}, + {'name': 'Generate losses chunk 1', 'status': 'STARTED'}, + {'name': 'Generate losses output', 'status': 'PENDING'}, + ] + assert current_task(tasks) == 'Generate losses chunk 0, Generate losses chunk 1' + assert current_task(tasks[:1] + tasks[3:]) == 'Waiting for: Generate losses output' + assert current_task([]) == '' + + +def test_inuring_priorities_from_filenames(): + from pages.components.results import inuring_priorities, priority_label + outputs = {'rl_IP1_S1_selt.csv': 1, 'rl_IP2_S1_selt.csv': 1, 'rl_IP1_S2_selt.csv': 1, + 'ri_S1_selt.csv': 1, 'ri_IP1_S1_selt.csv': 1, 'gul_S1_selt.csv': 1} + assert inuring_priorities(outputs, 'rl', 1) == ['IP1_', 'IP2_'] + assert inuring_priorities(outputs, 'ri', 1) == ['', 'IP1_'] + assert inuring_priorities(outputs, 'gul', 1) == [''] + assert priority_label('') == 'Final' + assert priority_label('IP2_') == 'Inuring priority 2' + + +def test_output_interface_reads_prefixed_rl_files(): + import pandas as pd + from modules.visualisation import OutputInterface + ept = pd.DataFrame({'SummaryId': [1], 'EPCalc': [2], 'EPType': [1], 'ReturnPeriod': [10.0], 'Loss': [5.0]}) + vis = OutputInterface({'rl_IP1_S1_ept.csv': ept}) + vis.set_file_prefix('rl', 'IP1_') + assert vis.get(1, 'rl', 'ept').equals(ept) + assert not vis.has_summary_info('rl', 1) diff --git a/tests/test_settings_editor.py b/tests/test_settings_editor.py index 846500a..d8a1d44 100644 --- a/tests/test_settings_editor.py +++ b/tests/test_settings_editor.py @@ -165,12 +165,80 @@ def test_perspective_availability(): full = {f: {'stored': 'x.csv'} for f in ['location_file', 'accounts_file', 'reinsurance_info_file', 'reinsurance_scope_file']} - assert set(perspective_availability(model_settings, loc_only)) == {'il', 'ri'} + assert set(perspective_availability(model_settings, loc_only)) == {'il', 'ri', 'rl'} assert perspective_availability(model_settings, full) == {} gul_only = {'model_settings': {'valid_output_perspectives': ['gul']}} - assert set(perspective_availability(gul_only, full)) == {'il', 'ri'} + assert set(perspective_availability(gul_only, full)) == {'il', 'ri', 'rl'} + # The model schema has no 'rl': ceded reinsurance follows 'ri' + with_ri = {'model_settings': {'valid_output_perspectives': ['gul', 'il', 'ri']}} + assert perspective_availability(with_ri, full) == {} def test_ord_output_groups_cover_schema(): grouped = {k for keys in schemas.ORD_OUTPUT_GROUPS.values() for k in keys} assert grouped == set(schemas.ord_output_options()) + + +def test_events_are_parsed_into_ids_and_ranges(editor): + at = editor + at.text_input(key='test_editor_events').input('1, 5, 100-120, 7').run() + settings = at.session_state['editor_settings'] + assert settings['event_ids'] == [1, 5, 7] + assert settings['event_ranges'] == '100-120' + assert at.session_state['editor_valid'], at.session_state['editor_problems'] + + at.text_input(key='test_editor_events').input('').run() + settings = at.session_state['editor_settings'] + assert 'event_ids' not in settings and 'event_ranges' not in settings + + +def test_invalid_events_are_reported(editor): + at = editor + for bad in ['0', '20-10', 'abc']: + at.text_input(key='test_editor_events').input(bad).run() + assert not at.session_state['editor_valid'], bad + + +def test_template_events_are_shown(): + at = AppTest.from_file(APP, default_timeout=30) + at.session_state['base_settings'] = {'event_ids': [3, 4], 'event_ranges': '10-12,20-21', + 'gul_output': True, 'gul_summaries': [{'id': 1}]} + at.run() + assert at.text_input(key='test_editor_events').value == '3, 4, 10-12, 20-21' + assert at.session_state['editor_settings']['event_ranges'] == '10-12,20-21' + + +def test_gul_threshold_is_advanced(editor): + # Lives in the Advanced expander, not alongside the number of samples + advanced = [e for e in editor.expander if e.label == 'Advanced'][0] + assert advanced.number_input(key='test_editor_gul_threshold').value == 0.0 + + +def test_group_by_offers_portfolio_columns(editor): + options = editor.multiselect(key='test_editor_all_1_fields').options + # Common fields first, then the portfolio's own columns alphabetically + assert options[:5] == ['PortNumber', 'AccNumber', 'LocNumber', 'CountryCode', 'LocPeril'] + assert {'OccupancyCode', 'BuildingTIV'} <= set(options) + # Case-insensitive duplicates of standard fields are dropped + assert 'accnumber' not in options + assert options.count('LocNumber') == 1 + + +def test_alct_requires_palt(editor): + at = editor + alct = at.checkbox(key='test_editor_all_1_alct_convergence') + assert alct.disabled # default outputs don't include PALT + + at.checkbox(key='test_editor_all_1_alt_period').check().run() + alct = at.checkbox(key='test_editor_all_1_alct_convergence') + assert not alct.disabled + alct.check().run() + ord_output = at.session_state['editor_settings']['gul_summaries'][0]['ord_output'] + assert ord_output['alt_period'] and ord_output['alct_convergence'] + assert ord_output['alct_confidence'] == 0.95 + + +def test_rl_perspective_needs_reinsurance_files(editor): + rl = editor.checkbox(key='test_editor_rl_output') + assert rl.label == 'Ceded to reinsurance (RL)' + assert rl.disabled # fixture portfolio has no RI files From 96ae222aa169a6e356ca1db93a489324011dbff8 Mon Sep 17 00:00:00 2001 From: Ben Hayes Date: Thu, 5 Nov 2026 16:03:14 +0000 Subject: [PATCH 11/33] Add Scenarios, Comparison and User Guide page tests Closes the remaining pages in #6. Also keys the Comparison page's cached inputs/outputs on the analysis modified time, so re-runs aren't stale. Co-Authored-By: Claude Opus 5.5 --- pages/comparison.py | 11 ++--- tests/mocks.py | 3 ++ tests/test_scenarios.py | 91 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 100 insertions(+), 5 deletions(-) create mode 100644 tests/test_scenarios.py diff --git a/pages/comparison.py b/pages/comparison.py index 099bb71..70a93e0 100644 --- a/pages/comparison.py +++ b/pages/comparison.py @@ -94,11 +94,11 @@ 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): @@ -118,7 +118,7 @@ def get_location_df(inputs): 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])) @@ -128,7 +128,7 @@ def get_location_df(inputs): 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])) @@ -200,7 +200,8 @@ 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) diff --git a/tests/mocks.py b/tests/mocks.py index 83fa199..835f919 100644 --- a/tests/mocks.py +++ b/tests/mocks.py @@ -1,4 +1,5 @@ from copy import deepcopy +from types import SimpleNamespace from requests import Response from requests.exceptions import HTTPError @@ -129,6 +130,8 @@ def __init__(self, json_data=None): class MockApiClient: def __init__(self, username="", password="", portfolios=None, models=None, analyses=None, **kwargs): + # Token used by pages that cache per user (st.cache_data hash_funcs) + self.api = SimpleNamespace(tkn_access='mock-access-token') # Copy so tests mutating endpoint data can't leak into shared fixtures self.portfolios = MockEndpoint(deepcopy(portfolios)) self.models = MockModelsEndpoint(deepcopy(models)) diff --git a/tests/test_scenarios.py b/tests/test_scenarios.py new file mode 100644 index 0000000..94eaf3c --- /dev/null +++ b/tests/test_scenarios.py @@ -0,0 +1,91 @@ +''' +Smoke tests for the Scenarios UI pages (Scenarios, Comparison, User Guide), +run with the Scenarios UI config. +''' +import pandas as pd +import pytest + +import tests.mocks as m +from tests.conftest import page_app + +SETTINGS = { + 'model_supplier_id': 'OasisLMF', 'model_name_id': 'PiWind', 'number_of_samples': 10, + 'gul_output': True, + 'gul_summaries': [{'id': 1, 'ord_output': {'elt_sample': True, 'alt_meanonly': True}}], +} + + +def selt(scale): + return pd.DataFrame({'EventId': [1, 1, 2, 2], 'SummaryId': [1, 1, 1, 1], 'SampleId': [-1, 1, -1, 1], + 'Loss': [10.0 * scale, 12.0 * scale, 5.0 * scale, 6.0 * scale]}) + + +def altmeanonly(scale): + return pd.DataFrame({'SummaryId': [1], 'SampleType': [1], 'MeanLoss': [100.0 * scale]}) + + +@pytest.fixture(autouse=True) +def scenarios_config(monkeypatch): + monkeypatch.setenv('OASIS_UI_CONFIG', 'scenarios/ui-config.json') + + +@pytest.fixture +def client(): + analyses = [{'id': i, 'name': f'run {i}', 'portfolio': 1, 'model': 1, 'status': 'RUN_COMPLETED', + 'settings': f'/analyses/{i}/settings/', 'output_file': f'/analyses/{i}/output_file/', + 'input_file': f'/analyses/{i}/input_file/', 'modified': '2026-01-01T00:00:00Z'} + for i in (1, 2)] + client = m.MockApiClient( + portfolios=[{'id': 1, 'name': 'piwind-small', 'location_file': {'stored': 'l.csv'}, + 'accounts_file': None}], + models=[{'id': 1, 'model_id': 'PiWind', 'supplier_id': 'OasisLMF', 'version_id': 'v2', + 'run_mode': 'V2'}], + analyses=analyses) + client.portfolios.location_file.files[1] = pd.DataFrame({ + 'LocNumber': ['1'], 'Latitude': [48.8], 'Longitude': [2.3], 'BuildingTIV': [1000.0], 'CountryCode': ['FR']}) + client.models.settings.data[1] = {'name': 'Oasis test European wind model - Paris', + 'description': 'PiWind test model'} + for i, scale in [(1, 1), (2, 2)]: + client.analyses.settings.data[i] = SETTINGS + client.analyses.input_file.files[i] = {'location.csv': client.portfolios.location_file.files[1]} + client.analyses.output_file.files[i] = {'gul_S1_selt.csv': selt(scale), + 'gul_S1_altmeanonly.csv': altmeanonly(scale)} + return client + + +def test_scenarios_page(client): + at = page_app('pages/scenarios.py', client) + + assert not at.exception + models = at.dataframe[0].value + assert list(models['model_name']) == ['Oasis test European wind model - Paris'] + assert 'Please select a model.' in [i.value for i in at.info] + + +def test_comparison_page_requires_two_analyses(client): + at = page_app('pages/comparison.py', client) + + assert not at.exception + assert 'Select 2 analyses.' in [i.value for i in at.info] + assert [s.label for s in at.selectbox][:2] == ['Select Analysis 1', 'Select Analysis 2'] + + +def test_comparison_page_compares_two_analyses(client): + at = page_app('pages/comparison.py', client) + assert at.selectbox[0].options == ['run 2', 'run 1'] + + first, second = client.analyses.json_data + at.selectbox[0].set_value(first) + at.selectbox[1].set_value(second) + at.run() + + assert not at.exception, [e.value for e in at.exception] + assert 'Select 2 analyses.' not in [i.value for i in at.info] + assert [e.label for e in at.expander] == ['Analysis Summary'] + assert len(at.get('plotly_chart')) >= 1 # output comparison rendered + + +def test_user_guide_page(client): + at = page_app('pages/scenariosGuide.py', client) + assert not at.exception + assert at.title[0].value == 'User Guide: Scenario analysis and comparison' From 51a948a6e7d8d241cc1dc8726c1294269301be48 Mon Sep 17 00:00:00 2001 From: Ben Hayes Date: Thu, 5 Nov 2026 16:03:20 +0000 Subject: [PATCH 12/33] Respect model output limits; join summary info by default #7 - outputs driven by model settings: - Honour the model's valid_output_metrics and the selected event set's valid_metrics / valid_perspectives: unsupported outputs and perspectives are disabled with an explanation, and new summary levels start with supported outputs only - Bundled defaults/ files are only offered as a settings template when the platform has no setting templates for the model #3 - pytools join-summary-info: - join_summary_info on by default in the settings editor (a template that sets it false is respected) and for Scenarios runs - Results use fields already joined into the outputs instead of joining again (no duplicate columns), and don't fail without a summary-info file Co-Authored-By: Claude Opus 5.5 --- modules/visualisation.py | 23 +++++++ pages/analyses.py | 8 ++- pages/components/results.py | 2 +- pages/components/settings_editor.py | 96 +++++++++++++++++++++------ pages/scenarios.py | 2 + tests/fixtures/settings_editor_app.py | 6 +- tests/test_analyses.py | 20 ++++++ tests/test_results.py | 26 ++++++++ tests/test_settings_editor.py | 60 ++++++++++++++++- 9 files changed, 215 insertions(+), 28 deletions(-) diff --git a/modules/visualisation.py b/modules/visualisation.py index ce9de84..29ea63a 100644 --- a/modules/visualisation.py +++ b/modules/visualisation.py @@ -34,6 +34,18 @@ def has_summary_info(self, perspective, summary_level=None): return self._request_to_summary_info_fname(level, perspective, self.file_prefixes.get(perspective, '')) \ in self.output_file_dict + def 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 @@ -106,6 +118,9 @@ def get(self, summary_level, perspective, output_type, **kwargs): summary_info = self.output_file_dict.get( 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) @@ -139,6 +154,14 @@ def _request_to_summary_info_fname(summary_level, perspective, prefix=''): @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/pages/analyses.py b/pages/analyses.py index 694ebd8..ca2cb2c 100644 --- a/pages/analyses.py +++ b/pages/analyses.py @@ -92,9 +92,11 @@ def template_picker(model, key, current=None): f"Template: {t.get('name') or t['id']}", lambda t=t: ci.models.setting_templates.get_contents(model['id'], t['id'])) - 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())) + # 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')): diff --git a/pages/components/results.py b/pages/components/results.py index 8e66a07..3ed5d38 100644 --- a/pages/components/results.py +++ b/pages/components/results.py @@ -107,7 +107,7 @@ def render_results(settings, outputs, locations=None): vis.set_file_prefix(p, prefix) oed_fields = summary.get('oed_fields') or None - if oed_fields and not vis.has_summary_info(p, level_id): + 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 diff --git a/pages/components/settings_editor.py b/pages/components/settings_editor.py index 92a5a8a..c6eb3dc 100644 --- a/pages/components/settings_editor.py +++ b/pages/components/settings_editor.py @@ -74,9 +74,47 @@ def _parse_events(text): return ids or None, ','.join(ranges) or None, None -def perspective_availability(model_settings, portfolio): - '''Which perspectives can be run, with a reason for those that can't.''' - valid = list(model_settings.get('model_settings', {}).get('valid_output_perspectives') or PERSPECTIVES) +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') @@ -86,7 +124,8 @@ def perspective_availability(model_settings, portfolio): reasons = {} for p in PERSPECTIVES: if p not in valid: - reasons[p] = 'Not supported by this model.' + 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']): @@ -102,7 +141,7 @@ def default_settings(model, model_settings): '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': {o: True for o in DEFAULT_ORD_OUTPUTS}}], + 'gul_summaries': [{'id': 1, 'ord_output': default_ord_outputs(valid_metrics(model_settings))}], } @@ -195,8 +234,10 @@ def general_section(base, model_settings, key): 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', False)), - help=entry.get('description'), key=f'{key}_join_summary_info') + _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 @@ -317,20 +358,23 @@ def _levels_state_key(key, scope): return f'{key}_levels_{scope}' -def _init_levels(key, scope, summaries): +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': {o: True for o in DEFAULT_ORD_OUTPUTS}}] + 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): - '''Edit a list of summary levels (group-by fields + ORD outputs).''' - levels = _init_levels(key, scope, summaries) +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 = [] @@ -360,12 +404,15 @@ def summary_levels_editor(key, scope, summaries, field_options): 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 - help_text = flags[k][1] + (' Requires PALT.' if needs_palt else '') - if col.checkbox(flags[k][0], value=bool(ord_output.get(k)) and not needs_palt, - help=help_text, disabled=needs_palt, key=f'{wkey}_{k}') \ - and not needs_palt: + 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')} @@ -389,15 +436,19 @@ def summary_levels_editor(key, scope, summaries, field_options): 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': {o: True for o in DEFAULT_ORD_OUTPUTS}}) + 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=()): +def outputs_section(base, model_settings, portfolio, key, portfolio_fields=(), event_set=None): out, errors = {}, [] - unavailable = perspective_availability(model_settings, portfolio) + 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)) @@ -424,14 +475,14 @@ def outputs_section(base, model_settings, portfolio, key, 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) + 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) + 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'] @@ -470,7 +521,8 @@ def analysis_settings_editor(model, model_settings, portfolio, base_settings, ke with model_tab: ms, ms_errors = model_options_section(base, model_settings, key) with outputs_tab: - outputs, output_errors = outputs_section(base, model_settings, portfolio, key, portfolio_fields) + 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() diff --git a/pages/scenarios.py b/pages/scenarios.py index 377cba0..7c0f349 100644 --- a/pages/scenarios.py +++ b/pages/scenarios.py @@ -313,6 +313,8 @@ def analysis_fragment(): analysis_settings['number_of_samples'] = number_of_samples try: + # Write group-by fields into the outputs (pytools join-summary-info) + analysis_settings.setdefault('join_summary_info', True) client_interface.upload_settings(selected['id'], analysis_settings) except (JSONDecodeError, HTTPError) as e: logger.error(e) diff --git a/tests/fixtures/settings_editor_app.py b/tests/fixtures/settings_editor_app.py index 8cdfdc5..4188413 100644 --- a/tests/fixtures/settings_editor_app.py +++ b/tests/fixtures/settings_editor_app.py @@ -18,7 +18,8 @@ 'model_settings': { 'event_set': { 'name': 'Event Set', 'desc': 'Event set selection', 'default': 'p', - 'options': [{'id': 'p', 'desc': 'Probabilistic'}, {'id': 'h', 'desc': 'Historic'}], + 'options': [{'id': 'p', 'desc': 'Probabilistic'}, {'id': 'h', 'desc': 'Historic'}, + {'id': 'r', 'desc': 'Restricted', 'valid_metrics': ['plt'], 'valid_perspectives': ['gul']}], }, 'valid_output_perspectives': ['gul', 'il'], 'boolean_parameters': [{'name': 'use_surge', 'desc': 'Include storm surge', 'default': True}], @@ -42,6 +43,9 @@ # Accounts file but no reinsurance files: IL possible, RI not PORTFOLIO = {'id': 1, 'name': 'p', 'location_file': {'stored': 'l.csv'}, 'accounts_file': {'stored': 'a.csv'}} +# Tests can add model settings (e.g. valid_output_metrics) via session state +MODEL_SETTINGS['model_settings'].update(st.session_state.get('model_settings_overrides', {})) + settings, valid, problems = analysis_settings_editor( MODEL, MODEL_SETTINGS, PORTFOLIO, st.session_state.get('base_settings'), key='test_editor', portfolio_fields=['LocNumber', 'OccupancyCode', 'BuildingTIV', 'accnumber']) diff --git a/tests/test_analyses.py b/tests/test_analyses.py index 1b6f5b3..2fc695b 100644 --- a/tests/test_analyses.py +++ b/tests/test_analyses.py @@ -83,3 +83,23 @@ def test_create_and_run_analysis(mock_api_client, request): assert created['status'] == 'INPUTS_GENERATION_QUEUED' # Name defaults to " – " assert created['name'] == f"{config.portfolios_data[0]['name']} – {config.models_data[0]['model_id']}" + + +def _template_options(client, request): + at = page_app(PAGE, client, {NEW_ANALYSIS_DEFAULTS: {'portfolio': request.config.portfolio_ID}}) + assert not at.exception + return at.selectbox(key=f'new_{request.config.model_ID}_template').options + + +def test_defaults_files_only_without_platform_templates(mock_api_client, request, monkeypatch): + monkeypatch.setattr('modules.settings.get_analyses_settings', + lambda **kwargs: ['defaults/1_model_supplier-analysis_settings.json']) + + # No platform templates: the bundled defaults file is offered + assert 'Default file: 1_model_supplier-analysis_settings.json' in _template_options(mock_api_client, request) + + # With a platform template, only the template is offered + mock_api_client.models.setting_templates.data[request.config.model_ID] = [{'id': 3, 'name': 'Standard'}] + options = _template_options(mock_api_client, request) + assert options[0] == 'Template: Standard' + assert not any(o.startswith('Default file') for o in options) diff --git a/tests/test_results.py b/tests/test_results.py index c5c16e3..6e5a610 100644 --- a/tests/test_results.py +++ b/tests/test_results.py @@ -130,3 +130,29 @@ def test_output_interface_reads_prefixed_rl_files(): vis.set_file_prefix('rl', 'IP1_') assert vis.get(1, 'rl', 'ept').equals(ept) assert not vis.has_summary_info('rl', 1) + + +def test_join_summary_info_outputs_are_not_joined_twice(): + import pandas as pd + from modules.visualisation import OutputInterface + # Output already carries LocNumber (pytools join-summary-info) and there's no summary-info file + ept = pd.DataFrame({'SummaryId': [1, 2], 'LocNumber': ['a', 'b'], 'EPCalc': [2, 2], 'EPType': [1, 1], + 'ReturnPeriod': [10.0, 10.0], 'Loss': [5.0, 6.0]}) + vis = OutputInterface({'rl_IP1_S1_ept.csv': ept}) + vis.set_file_prefix('rl', 'IP1_') + vis.set_oed_fields('rl', ['LocNumber']) + + assert vis.fields_available('rl', ['LocNumber'], 1) + assert not vis.fields_available('rl', ['CountryCode'], 1) + result = vis.get(1, 'rl', 'ept') + assert list(result.columns) == list(ept.columns) # no LocNumber_ duplicate + + +def test_summary_info_join_still_used_when_fields_missing(): + import pandas as pd + from modules.visualisation import OutputInterface + ept = pd.DataFrame({'SummaryId': [1], 'EPCalc': [2], 'EPType': [1], 'ReturnPeriod': [10.0], 'Loss': [5.0]}) + info = pd.DataFrame({'summary_id': [1], 'LocNumber': ['a']}) + vis = OutputInterface({'gul_S1_ept.csv': ept, 'gul_S1_summary-info.csv': info}) + vis.set_oed_fields('gul', ['LocNumber']) + assert list(vis.get(1, 'gul', 'ept')['LocNumber']) == ['a'] diff --git a/tests/test_settings_editor.py b/tests/test_settings_editor.py index d8a1d44..1142c13 100644 --- a/tests/test_settings_editor.py +++ b/tests/test_settings_editor.py @@ -45,7 +45,8 @@ def test_model_parameters_use_their_defaults(editor): def test_controls_match_parameter_types(editor): at = editor - assert at.selectbox(key='test_editor_ms_event_set').options == ['p – Probabilistic', 'h – Historic'] + assert at.selectbox(key='test_editor_ms_event_set').options == \ + ['p – Probabilistic', 'h – Historic', 'r – Restricted'] assert at.toggle(key='test_editor_param_use_surge').value is True slider = at.slider(key='test_editor_param_demand_surge') assert (slider.min, slider.max, slider.step) == (1.0, 2.0, 0.05) @@ -242,3 +243,60 @@ def test_rl_perspective_needs_reinsurance_files(editor): rl = editor.checkbox(key='test_editor_rl_output') assert rl.label == 'Ceded to reinsurance (RL)' assert rl.disabled # fixture portfolio has no RI files + + +def test_metric_allowed(): + from pages.components.settings_editor import metric_allowed + assert metric_allowed('elt_sample', None) + assert metric_allowed('elt_sample', ['elt']) + assert not metric_allowed('plt_sample', ['elt']) + assert metric_allowed('ept_full_uncertainty_aep', ['ept']) + assert metric_allowed('psept_oep', ['oep']) + assert not metric_allowed('psept_aep', ['oep']) + assert metric_allowed('alct_convergence', ['alt']) + assert metric_allowed('alt_meanonly', ['alt_meanonly']) + assert not metric_allowed('alt_period', ['alt_meanonly']) + + +def _restricted_editor(model_overrides, event_set=None): + at = AppTest.from_file(APP, default_timeout=30) + at.session_state['model_settings_overrides'] = model_overrides + if event_set: + at.session_state['base_settings'] = {'model_settings': {'event_set': event_set}, + 'gul_output': True} + return at.run() + + +def test_model_valid_output_metrics_restrict_outputs(): + at = _restricted_editor({'valid_output_metrics': ['elt', 'ept']}) + assert not at.exception + assert not at.checkbox(key='test_editor_all_1_elt_sample').disabled + assert at.checkbox(key='test_editor_all_1_plt_sample').disabled + assert at.checkbox(key='test_editor_all_1_alt_meanonly').disabled + + # Defaults only include supported outputs + ord_output = at.session_state['editor_settings']['gul_summaries'][0]['ord_output'] + assert {k for k, v in ord_output.items() if v is True} == \ + {'elt_moment', 'ept_full_uncertainty_aep', 'ept_full_uncertainty_oep'} + assert at.session_state['editor_valid'] + + +def test_event_set_overrides_metrics_and_perspectives(): + at = _restricted_editor({'valid_output_metrics': ['elt', 'ept']}, event_set='r') + assert not at.exception + # The 'r' event set only supports PLTs and GUL + assert at.checkbox(key='test_editor_all_1_plt_sample').disabled is False + assert at.checkbox(key='test_editor_all_1_elt_sample').disabled + assert at.checkbox(key='test_editor_il_output').disabled + + +def test_join_summary_info_on_by_default(editor): + assert editor.session_state['editor_settings']['join_summary_info'] is True + + +def test_join_summary_info_respects_template(): + at = AppTest.from_file(APP, default_timeout=30) + at.session_state['base_settings'] = {'join_summary_info': False, 'gul_output': True, + 'gul_summaries': [{'id': 1}]} + at.run() + assert at.session_state['editor_settings']['join_summary_info'] is False From 67c7666f3eebaa749d8a73545165b3b65db1d042 Mon Sep 17 00:00:00 2001 From: Ben Hayes Date: Thu, 5 Nov 2026 16:23:56 +0000 Subject: [PATCH 13/33] Fix ruff and PEP8 findings Mechanical cleanup ahead of the code quality CI: - autopep8 formatting (150 character lines) - remove unused imports and variables (incl. 19 leftover imports in scenariosGuide.py and two never-used st.container() placeholders) - docstring style (triple double quotes, summary on the first line, one-line docstrings) - document missing parameters; fix docstrings that named the wrong parameter (generate_eltcalc_fragment) or listed reinsurance_scope_file twice (PortfoliosEndpointInterface.create) No behaviour changes: 113 tests pass and all pages render against a live 2.5.9 platform. Co-Authored-By: Claude Opus 5.5 --- modules/authorisation.py | 9 +- modules/client.py | 78 ++-- modules/config.py | 6 +- modules/rerun.py | 3 +- modules/schemas.py | 19 +- modules/settings.py | 1 + modules/ui.py | 12 +- modules/validation.py | 11 +- modules/visualisation.py | 30 +- pages/analyses.py | 10 +- pages/comparison.py | 27 +- pages/components/common.py | 54 ++- pages/components/data.py | 19 +- pages/components/display.py | 60 ++- pages/components/footer.py | 3 +- pages/components/logs.py | 3 +- pages/components/model_details.py | 8 +- pages/components/output.py | 347 ++++++++++-------- pages/components/process.py | 10 +- pages/components/results.py | 14 +- pages/components/settings_editor.py | 45 ++- pages/scenarios.py | 46 ++- pages/scenariosGuide.py | 29 +- scripts/add_settings_template.py | 3 +- scripts/prune_analysis.py | 4 +- scripts/utils.py | 4 +- tests/conftest.py | 8 +- .../eltcalc_map_locnumber_mismatch_app.py | 2 +- tests/fixtures/eltcalc_map_no_match_app.py | 2 +- tests/mocks.py | 3 + tests/test_app.py | 8 +- 31 files changed, 436 insertions(+), 442 deletions(-) diff --git a/modules/authorisation.py b/modules/authorisation.py index 19d43a6..5833613 100644 --- a/modules/authorisation.py +++ b/modules/authorisation.py @@ -1,6 +1,4 @@ -''' -Module to handle authorisation. -''' +"""Module to handle authorisation.""" import os import requests from requests.exceptions import HTTPError @@ -42,8 +40,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 diff --git a/modules/client.py b/modules/client.py index aee31f0..d8b1d50 100644 --- a/modules/client.py +++ b/modules/client.py @@ -14,7 +14,7 @@ def tar_to_zip(tar_bytes): - '''Repack a (gzipped) tar archive as a zip archive, keeping paths.''' + """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: @@ -29,9 +29,7 @@ def tar_to_zip(tar_bytes): 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) @@ -41,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) @@ -60,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) @@ -92,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') @@ -103,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 ---------- @@ -125,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: @@ -134,12 +124,11 @@ 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.''' + """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: @@ -151,9 +140,7 @@ def delete(self, 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") @@ -179,7 +166,7 @@ def get_reinsurance_scope_file(self, ID, df=False): } def upload_file(self, ID, file_type, file_bytes, filename): - '''Attach (or replace) one of the portfolio's OED files.''' + """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) @@ -196,18 +183,21 @@ def delete(self, 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, upload): if upload is None: @@ -223,22 +213,21 @@ def prepare_upload_f(fname, upload): ri_scope_f = prepare_upload_f('reinsurance_scope_file', reinsurance_scope_file) 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) + 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') @@ -265,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"]) @@ -276,27 +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).''' + """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..c9cec92 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) @@ -35,10 +37,10 @@ def __init__(self): 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/rerun.py b/modules/rerun.py index 33a1ada..2f409fe 100644 --- a/modules/rerun.py +++ b/modules/rerun.py @@ -1,5 +1,6 @@ import streamlit as st + class RefreshHandler: q_name = "refresh_1" refresh_bool = "refreshing" @@ -56,7 +57,7 @@ def update_queue(self): st.rerun() def run_every(self): - run_every=None + run_every = None if not RefreshHandler.queue_empty(): run_every = self.interval diff --git a/modules/schemas.py b/modules/schemas.py index 9bf0376..b43ebfb 100644 --- a/modules/schemas.py +++ b/modules/schemas.py @@ -1,10 +1,9 @@ -''' -Access to the ODS-tools analysis / model settings JSON schemas. +"""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 @@ -62,18 +61,18 @@ def model_settings_schema(): def analysis_property(key): - '''Schema entry for a top-level analysis settings key (`{}` if unknown).''' + """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.''' + """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.''' + """Schema entry for a top-level model settings key.""" return model_settings_schema()['properties'].get(key, {}) @@ -82,11 +81,11 @@ def title(schema_entry, fallback): def ord_output_options(): - '''Boolean ORD output flags from the schema as `{key: (title, description)}`. + """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'} @@ -113,7 +112,7 @@ def ord_output_options(): def validate_analysis_settings(settings): - '''Validate analysis settings against the ODS analysis settings schema. + """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 @@ -122,5 +121,5 @@ def validate_analysis_settings(settings): 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/ui.py b/modules/ui.py index 39a9e6a..9c08ed3 100644 --- a/modules/ui.py +++ b/modules/ui.py @@ -1,6 +1,4 @@ -''' -Shared page scaffolding and feedback helpers for the standard UI pages. -''' +"""Shared page scaffolding and feedback helpers for the standard UI pages.""" import json import logging @@ -17,7 +15,7 @@ def page_setup(label, title=None): - '''Configure, authorise and add navigation to a page. + """Configure, authorise and add navigation to a page. Args: label: page label as configured in `ui-config.json`. @@ -25,7 +23,7 @@ def page_setup(label, title=None): 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) @@ -37,7 +35,7 @@ def page_setup(label, title=None): def flash(message, icon='✅'): - '''Queue a toast to show after the next rerun (st.toast alone is lost on rerun).''' + """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)) @@ -47,7 +45,7 @@ def show_flash(): def api_error_message(error): - '''Human readable message for an API error, including the server's reason.''' + """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() 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 29ea63a..66004c4 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,23 +8,24 @@ 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.''' + """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): @@ -35,9 +34,10 @@ def has_summary_info(self, perspective, summary_level=None): in self.output_file_dict def fields_available(self, perspective, oed_fields, summary_level=None): - '''Whether outputs can be broken down by `oed_fields`: either a + """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).''' + (written by pytools join-summary-info). + """ if self.has_summary_info(perspective, summary_level): return True level = summary_level or self.summary_level(perspective) @@ -50,19 +50,19 @@ 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.''' + """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 @@ -91,7 +91,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', @@ -154,11 +154,11 @@ def _request_to_summary_info_fname(summary_level, perspective, prefix=''): @staticmethod def add_oed_fields(results, summary_info, oed_fields): - '''Join OED group fields onto `results` from the summary-info file. + """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 diff --git a/pages/analyses.py b/pages/analyses.py index ca2cb2c..6abb05e 100644 --- a/pages/analyses.py +++ b/pages/analyses.py @@ -47,7 +47,7 @@ def close_editor(editor_key=None): def portfolio_fields(portfolio): - '''Columns of the portfolio's location and accounts files (for grouping losses).''' + """Columns of the portfolio's location and accounts files (for grouping losses).""" fields = [] for file_type in ['location_file', 'accounts_file']: try: @@ -61,7 +61,7 @@ def portfolio_fields(portfolio): def start_run(analysis, regenerate=False): - '''Run an analysis, generating inputs first if needed.''' + """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: @@ -73,11 +73,11 @@ def start_run(analysis, regenerate=False): ########################################################################################## def template_picker(model, key, current=None): - '''Choose what to base the analysis settings on. + """Choose what to base the analysis settings on. Returns: (source_id, settings) — settings is None for "model defaults". - ''' + """ sources = {} if current: sources['current'] = ('Current analysis settings', lambda: current) @@ -102,7 +102,7 @@ def template_picker(model, key, current=None): 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)) + lambda a=a: analysis_settings(ci, a)) sources['model'] = ('Model defaults', lambda: None) sources['upload'] = ('Upload a settings file…', None) diff --git a/pages/comparison.py b/pages/comparison.py index 70a93e0..bfb6164 100644 --- a/pages/comparison.py +++ b/pages/comparison.py @@ -20,8 +20,8 @@ validate_page("Comparison") st.set_page_config( - page_title = "Comparison", - layout = "centered" + page_title="Comparison", + layout="centered" ) cols = st.columns([0.1, 0.8, 0.1]) @@ -54,12 +54,12 @@ selected = [] with cols[0]: selected_analysis = st.selectbox("Select Analysis 1", options=analyses, - format_func= lambda x : x['name'], index=None) + 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) + format_func=lambda x: x['name'], index=None) if selected_analysis: selected.append(selected_analysis) @@ -93,18 +93,22 @@ expander = st.expander('Analysis Summary') with expander: cols = st.columns(2) + + @st.cache_data 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, 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,6 +117,7 @@ def get_location_df(inputs): return inputs['location.parquet'] return None + analysis_settings = [] model_settings = [] with cols[0]: @@ -135,15 +140,16 @@ def get_location_df(inputs): with st.spinner('Loading analysis summary...'): summarise_inputs(get_location_df(inputs), analysis_settings[1], model_settings[1], title_prefix='###') + @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 +169,7 @@ def merge_locations(locations_1, locations_2): return locations + perspectives = ['gul', 'il', 'ri'] st.write("# Loss estimates") @@ -173,7 +180,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 +195,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) diff --git a/pages/components/common.py b/pages/components/common.py index 0d4db7f..92d71c5 100644 --- a/pages/components/common.py +++ b/pages/components/common.py @@ -1,32 +1,30 @@ -""" -File containig some common methods for `pages/`. -""" +"""File containig some common methods for `pages/`.""" 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] @@ -54,7 +52,7 @@ def get_page_path(): def format_status(status): - '''e.g. `RUN_COMPLETED` -> `✅ Run completed`.''' + """e.g. `RUN_COMPLETED` -> `✅ Run completed`.""" if not isinstance(status, str): return '' label = status.replace('_', ' ').capitalize() @@ -62,12 +60,12 @@ def format_status(status): def analysis_progress(analysis): - '''Progress of a running analysis as `(fraction or None, description)`. + """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: @@ -82,10 +80,10 @@ def analysis_progress(analysis): def current_task(sub_tasks): - '''Name of the sub-task(s) being worked on, e.g. "Generate losses chunk 0". + """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)) @@ -98,14 +96,14 @@ def current_task(sub_tasks): ########################################################################################## 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`. + """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 [] @@ -122,7 +120,7 @@ def on_select(): def open_record(page, state_key, record_id): - '''Navigate to `page` with `record_id` preselected.''' + """Navigate to `page` with `record_id` preselected.""" st.session_state[state_key] = record_id st.switch_page(page) diff --git a/pages/components/data.py b/pages/components/data.py index d1c373e..0ca4632 100644 --- a/pages/components/data.py +++ b/pages/components/data.py @@ -1,11 +1,10 @@ -''' -Loading and shaping platform records for the standard UI pages. +"""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 @@ -23,7 +22,7 @@ def session_cached(key, loader): - '''Return `loader()` cached in this session under `key`.''' + """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: @@ -56,7 +55,7 @@ def _to_datetime(df, cols=('created', 'modified')): def guess_file_type(filename): - '''Guess the portfolio file type from an uploaded file's name (or None).''' + """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): @@ -65,7 +64,7 @@ def guess_file_type(filename): def portfolios_df(portfolios, analyses=None): - '''Portfolio records as a DataFrame with file-presence and analysis-count columns.''' + """Portfolio records as a DataFrame with file-presence and analysis-count columns.""" rows = [] for p in portfolios: row = {'id': p['id'], 'name': p['name'], @@ -81,7 +80,7 @@ def portfolios_df(portfolios, analyses=None): def portfolio_file_df(ci, portfolio, file_type): - '''Dataframe of one of a portfolio's OED files (cached until it changes).''' + """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'), @@ -94,7 +93,7 @@ def portfolio_file_df(ci, portfolio, file_type): ########################################################################################## def model_settings(ci, model_id): - '''Model settings dict ({} if the model has none registered).''' + """Model settings dict ({} if the model has none registered).""" try: return ci.models.settings.get(model_id) or {} except HTTPError as e: @@ -140,7 +139,7 @@ def cached_model_settings(ci, model): ########################################################################################## def analyses_df(analyses, portfolios, models_frame): - '''Analysis records enriched with portfolio and model names.''' + """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 = [] @@ -173,6 +172,6 @@ def analysis_settings(ci, analysis): def analysis_files(ci, analysis, file_type): - '''Input or output files for an analysis as `{filename: DataFrame}`.''' + """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..dbe9b6c 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}" @@ -262,16 +255,15 @@ def find_zoom_level(lon_range): 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, 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 +307,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 +325,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/footer.py b/pages/components/footer.py index 00a202a..8a3c69a 100644 --- a/pages/components/footer.py +++ b/pages/components/footer.py @@ -6,6 +6,7 @@ logger = get_session_logger() + def generate_footer(ui_config=None): if ui_config is None: ui_config = retrieve_ui_config() @@ -16,7 +17,7 @@ def generate_footer(ui_config=None): assert "path" in ui_config.footer, "No footer path in config." try: - with open(ui_config.footer.get("path") , "r") as f: + with open(ui_config.footer.get("path"), "r") as f: footer_txt = f.read() page_path = get_page_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 index 931c46c..f8de134 100644 --- a/pages/components/model_details.py +++ b/pages/components/model_details.py @@ -1,6 +1,4 @@ -''' -Schema-driven display of a model's settings (`model_settings.json`). -''' +"""Schema-driven display of a model's settings (`model_settings.json`).""" import json import pandas as pd @@ -64,7 +62,7 @@ def model_perils(settings): def model_options(settings): - '''Categorical selectors (event set, footprint set, ...) and their options.''' + """Categorical selectors (event set, footprint set, ...) and their options.""" ms = settings.get('model_settings', {}) found = False for key in CATEGORICAL_MODEL_SETTINGS: @@ -88,7 +86,7 @@ def model_options(settings): def model_parameters(settings): - '''User-settable model parameters, grouped as the model defines.''' + """User-settable model parameters, grouped as the model defines.""" ms = settings.get('model_settings', {}) rows = [] for key, kind in PARAMETER_TYPES.items(): diff --git a/pages/components/output.py b/pages/components/output.py index 57ce614..6f9da9b 100644 --- a/pages/components/output.py +++ b/pages/components/output.py @@ -19,7 +19,6 @@ } - # 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 @@ -64,7 +63,7 @@ def sample_selector(df, vis, key): '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).') + 'model\'s numerically integrated mean (ORD sample index -1).') if choice == SAMPLE_MEAN: return sample_mean(df, n_samples) @@ -101,6 +100,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 = {} @@ -127,6 +127,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)] @@ -184,9 +185,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 @@ -195,12 +196,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 @@ -220,10 +221,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', @@ -255,6 +256,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.') @@ -293,16 +295,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'] @@ -316,8 +319,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. """ @@ -334,8 +336,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: @@ -370,10 +371,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) @@ -391,7 +392,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', []) @@ -402,7 +403,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") @@ -435,6 +436,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 = {} @@ -473,8 +475,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: @@ -493,7 +496,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] @@ -504,8 +507,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)] @@ -515,7 +518,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: @@ -528,6 +531,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: @@ -551,7 +555,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] @@ -564,7 +567,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: @@ -575,11 +578,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 = [] @@ -624,11 +626,11 @@ 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 + """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): @@ -643,9 +645,8 @@ def valid_locations(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. @@ -653,7 +654,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 @@ -661,7 +663,7 @@ 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(output.summary_level(perspective), perspective, 'eltcalc') @@ -693,6 +695,7 @@ 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(vis.summary_level(p), p, 'elt_moment') @@ -712,20 +715,18 @@ def generate_melt_fragment(p, vis, locations=None): key=f'melt_{p}_type_filter') data_df = data_df[data_df[type_col] == selected_type] - map_event_container = st.container() - tab_names = ['table', 'map'] 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: @@ -750,10 +751,10 @@ def generate_melt_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) loss_col = st.radio('Intensity Column:', ['MeanLoss', 'MeanImpactedExposure', 'MaxImpactedExposure'], index=0, horizontal=True, key=f'melt_{p}_intensity_col') @@ -773,23 +774,20 @@ def generate_qelt_fragment(p, vis, locations=None): data_df = data_df[data_df['Quantile'] == quantile_filter] - map_event_container = st.container() - tab_names = ['table', 'map'] 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.") @@ -810,10 +808,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') @@ -822,8 +820,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` @@ -839,7 +836,7 @@ 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). - ''' + """ data_df = vis.get(vis.summary_level(p), p, 'elt_sample') oed_fields = vis.oed_fields.get(p) or [] @@ -851,8 +848,8 @@ def generate_selt_fragment(p, vis, locations=None): 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: @@ -911,14 +908,15 @@ def generate_aalcalc_fragment(p, vis): result = result.groupby(group_field, as_index=False).agg({'mean': 'sum'}) graph = px.bar(result, x='type', y='mean', color=breakdown_field, - labels = {'type': 'Type', 'mean': 'Mean'}, - color_discrete_sequence= px.colors.sequential.RdBu) + labels={'type': 'Type', 'mean': 'Mean'}, + color_discrete_sequence=px.colors.sequential.RdBu) 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(vis.summary_level(p), p, output_type) @@ -948,21 +946,21 @@ def generate_alt_fragment(p, vis, output_type='alt_meanonly'): type_formatted = type_field[0] + type_field[1:] mean_formatted = mean_field[0] + mean_field[1:] graph = px.bar(result, x=type_field, y=mean_field, color=breakdown_field, - labels = {type_field: type_formatted, mean_field: mean_formatted}, - color_discrete_sequence= px.colors.sequential.RdBu) + labels={type_field: type_formatted, mean_field: mean_formatted}, + color_discrete_sequence=px.colors.sequential.RdBu) 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: how the period + """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 [] @@ -1014,7 +1012,7 @@ def generate_leccalc_fragment(p, vis, lec_outputs): else: analysis_type = '_'.join(option.split('_')[:-1]) loss_type = option.split('_')[-1] - result = vis.get(vis.summary_level(p), 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 @@ -1025,14 +1023,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]) @@ -1047,25 +1045,24 @@ def generate_leccalc_fragment(p, vis, lec_outputs): 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 ) @@ -1075,20 +1072,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 @@ -1104,6 +1101,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`. @@ -1127,7 +1130,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}') @@ -1168,7 +1171,7 @@ def format_lec_options(opt): analysis_type = '_'.join(option.split('_')[:-1]) loss_type = option.split('_')[-1] - results = [o.get(o.summary_level(perspective), 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(o.summary_level(perspective), perspective, output_type) for o in outputs] @@ -1199,7 +1202,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] @@ -1226,14 +1229,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 @@ -1244,8 +1246,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 @@ -1258,11 +1260,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 ---------- @@ -1276,7 +1278,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()) @@ -1317,13 +1323,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(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 @@ -1346,20 +1353,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(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 @@ -1393,13 +1401,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(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 @@ -1428,10 +1437,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 @@ -1444,7 +1453,7 @@ 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). - ''' + """ result = vis.get(vis.summary_level(p), p, 'plt_sample') oed_fields = vis.oed_fields.get(p) or [] @@ -1480,10 +1489,10 @@ def generate_ept_fragment(p, vis): 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 = EP_CALC_LABELS @@ -1492,7 +1501,7 @@ def generate_ept_fragment(p, vis): 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] @@ -1509,7 +1518,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: @@ -1531,21 +1540,21 @@ def generate_ept_fragment(p, vis): 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 @@ -1561,22 +1570,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(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] @@ -1584,7 +1593,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: @@ -1611,8 +1620,8 @@ def generate_psept_fragment(p, vis): 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)] @@ -1620,19 +1629,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)] @@ -1643,7 +1653,8 @@ 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): + +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) @@ -1686,21 +1697,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 @@ -1718,6 +1729,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`. @@ -1738,7 +1757,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: @@ -1758,13 +1777,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: @@ -1776,11 +1795,11 @@ 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: @@ -1797,12 +1816,12 @@ def generate_eltcalc_comparison_fragment(perspective, outputs, names=None, 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- @@ -1817,6 +1836,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 @@ -1835,7 +1860,7 @@ 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(o.summary_level(p), p, output_type) for o in outputs] oed_fields = shared_oed_fields(p, outputs) @@ -1886,20 +1911,20 @@ 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(o.summary_level(p), p, output_type) for o in outputs] type_field = 'SampleType' mean_field = 'MeanLoss' @@ -1944,8 +1969,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 index c2a7c5f..4f6637d 100644 --- a/pages/components/process.py +++ b/pages/components/process.py @@ -8,6 +8,7 @@ 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: @@ -29,9 +30,11 @@ def number_rows(portfolio_ids, client_interface, filename='location_file', col_n def number_locations(portfolio_ids, client_interface): return number_rows(portfolio_ids, client_interface, filename='location_file', col_name='number_locations') + def number_accounts(portfolio_ids, client_interface): return number_rows(portfolio_ids, client_interface, filename='accounts_file', col_name='number_accounts') + def portfolio_files(portfolios): enriched = portfolios['id'].to_frame() enriched['contains_location'] = portfolios['location_file.stored'].notna() @@ -73,6 +76,7 @@ def enrich_analyses_with_portfolios(analyses, portfolios): return analyses + def enrich_analyses_with_models(analyses, models): cols = ['id', 'model_id', 'supplier_id'] if 'model_name' in models: @@ -82,6 +86,7 @@ def enrich_analyses_with_models(analyses, models): return analyses + def enrich_analyses(analyses, portfolios=None, models=None): # add portfolio names if portfolios is not None: @@ -102,13 +107,13 @@ def add_model_names_to_models_cached(models: pd.DataFrame, 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. + """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: @@ -120,4 +125,3 @@ def add_model_names_to_models(models, ci, col_name='model_name'): models[col_name] = models[col_name].fillna(models['model_id']) return models - diff --git a/pages/components/results.py b/pages/components/results.py index 3ed5d38..91179db 100644 --- a/pages/components/results.py +++ b/pages/components/results.py @@ -1,6 +1,4 @@ -''' -Render the outputs of a completed analysis, driven by its analysis settings. -''' +"""Render the outputs of a completed analysis, driven by its analysis settings.""" import re import streamlit as st @@ -23,7 +21,7 @@ def _sections(summary, locations): - '''(title, render-callable) for each output enabled in a summary level.''' + """(title, render-callable) for each output enabled in a summary level.""" ord_settings = summary.get('ord_output', {}) sections = [] @@ -60,13 +58,13 @@ def add(enabled, title, render): def render_results(settings, outputs, locations=None): - '''Visualise analysis outputs. + """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. - ''' + """ if not outputs: st.info('No output files were found for this analysis.') return @@ -133,10 +131,10 @@ def level_label(level): def inuring_priorities(outputs, perspective, level_id): - '''File prefixes for the inuring priorities present, final ('') first. + """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)) diff --git a/pages/components/settings_editor.py b/pages/components/settings_editor.py index c6eb3dc..348aef2 100644 --- a/pages/components/settings_editor.py +++ b/pages/components/settings_editor.py @@ -1,11 +1,10 @@ -''' -Schema-driven analysis settings editor. +"""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 @@ -25,7 +24,7 @@ def _label(entry, fallback): def _parse_number_list(text, cast): - '''Parse "10, 50, 100" into a list of numbers. Returns (values, error).''' + """Parse "10, 50, 100" into a list of numbers. Returns (values, error).""" if not text or not text.strip(): return None, None try: @@ -46,11 +45,11 @@ def _events_text(event_ids, event_ranges): def _parse_events(text): - '''Parse "1, 5, 100-120" into (event_ids, event_ranges, error). + """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 = [], [] @@ -75,26 +74,26 @@ def _parse_events(text): def selected_option(model_settings, setting, option_id): - '''The option dict chosen for a categorical model setting (e.g. the event set), or {}.''' + """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). + """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. + """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] @@ -109,10 +108,10 @@ def default_ord_outputs(metrics=None): def perspective_availability(model_settings, portfolio, event_set=None): - '''Which perspectives can be run, with a reason for those that can't. + """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' @@ -134,7 +133,7 @@ def perspective_availability(model_settings, portfolio, event_set=None): def default_settings(model, model_settings): - '''Minimal starting settings for a model when no template is used.''' + """Minimal starting settings for a model when no template is used.""" return { 'model_supplier_id': model['supplier_id'], 'model_name_id': model['model_id'], @@ -146,11 +145,11 @@ def default_settings(model, model_settings): def group_field_options(model_settings, extra=(), portfolio_fields=()): - '''OED fields offered for grouping losses. + """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', []), @@ -236,7 +235,7 @@ def general_section(base, model_settings, key): 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.", + "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 @@ -359,7 +358,7 @@ def _levels_state_key(key, scope): def _init_levels(key, scope, summaries, metrics=None): - '''Track summary levels for `scope` ('all' or a perspective) in session state.''' + """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 [])] @@ -370,10 +369,10 @@ def _init_levels(key, scope, summaries, metrics=None): def summary_levels_editor(key, scope, summaries, field_options, metrics=None): - '''Edit a list of summary levels (group-by fields + ORD outputs). + """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 = [] @@ -501,7 +500,7 @@ def outputs_section(base, model_settings, portfolio, key, portfolio_fields=(), e ########################################################################################## def analysis_settings_editor(model, model_settings, portfolio, base_settings, key, portfolio_fields=()): - '''Render the editor and return `(settings, valid, problems)`. + """Render the editor and return `(settings, valid, problems)`. Args: model: model record from the API. @@ -510,7 +509,7 @@ def analysis_settings_editor(model, model_settings, portfolio, base_settings, ke 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( @@ -554,6 +553,6 @@ def analysis_settings_editor(model, model_settings, portfolio, base_settings, ke def reset_editor(key): - '''Clear editor state stored under `key` (e.g. after saving).''' + """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/scenarios.py b/pages/scenarios.py index 7c0f349..85388a0 100644 --- a/pages/scenarios.py +++ b/pages/scenarios.py @@ -25,7 +25,7 @@ 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 +from pages.components.process import add_model_names_to_models_cached, enrich_analyses, enrich_portfolios logger = get_session_logger() @@ -37,8 +37,8 @@ validate_page("Scenarios") st.set_page_config( - page_title = "Scenarios", - layout = "centered" + page_title="Scenarios", + layout="centered" ) cols = st.columns([0.1, 0.8, 0.1]) @@ -88,11 +88,11 @@ 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' ] + display_cols = ['model_name', 'supplier_id'] column_config = { - 'model_name': 'Scenarios Footprint', - 'supplier_id': 'Supplier' - } + '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() @@ -151,7 +151,7 @@ def filter_valid_rows(df, key, valid_map, filter_col): 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'): + 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: @@ -193,12 +193,13 @@ def show_locations_map(): enable_model_details = validation.is_valid(selected_model) if st.button("Scenario Details", disabled=not enable_model_details, - help = validation.get_message(), width='stretch'): + 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") @@ -221,7 +222,7 @@ def analysis_fragment(): completed_statuses = ['RUN_COMPLETED', 'RUN_CANCELLED', 'RUN_ERROR', 'INPUTS_GENERATION_ERROR'] running_statuses = ['RUN_QUEUED', 'RUN_STARTED', 'INPUTS_GENERATION_QUEUED', - 'INPUTS_GENERATION_STARTED',] + 'INPUTS_GENERATION_STARTED',] running_analyses = analyses[analyses['status'].isin(running_statuses)] if not re_handler.is_refreshing() and not running_analyses.empty: @@ -239,12 +240,11 @@ def analysis_fragment(): display_cols = ['name', 'status', 'portfolio_name', 'model_name', 'model_supplier'] - column_config = { - 'name': 'Analysis Name', - 'model_name': 'Scenarios Footprint', - 'supplier_id': 'Supplier' - } + 'name': 'Analysis Name', + 'model_name': 'Scenarios Footprint', + 'supplier_id': 'Supplier' + } analyses_view = DataframeView(analyses, display_cols=display_cols, selectable='single', column_config=column_config) @@ -256,10 +256,10 @@ def analysis_fragment(): cols = st.columns([0.5, 0.5]) oed_group = cols[0].pills("Group Output by:", - [ "Portfolio", "Country", "Location"], selection_mode="multi") + ["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) + max_value=1000, value=10) group_to_code = { 'Portfolio': 'PortNumber', @@ -283,7 +283,7 @@ def analysis_fragment(): run_started = False with columns[0]: - if st.button('Run', disabled = not run_enabled, help=msg, width='stretch'): + 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']) @@ -296,7 +296,7 @@ def analysis_fragment(): 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] + analysis_settings = get_analyses_settings(model_name_id=model_name_id)[0] with open(analysis_settings, 'r') as f: analysis_settings = json.load(f) @@ -339,7 +339,6 @@ def analysis_fragment(): # 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.') @@ -355,7 +354,6 @@ def display_outputs(ci, analysis_id, model_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. @@ -367,7 +365,7 @@ def display_outputs(ci, analysis_id, model_id): # 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 + 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) @@ -493,7 +491,6 @@ def generate_perspective_visualisation(perspective, summaries_settings): data=fdata, file_name=fname) - valid_statuses = ['RUN_COMPLETED'] validations = ValidationGroup() validations.add_validation(NotNoneValidation('Analysis'), selected) @@ -501,10 +498,9 @@ def generate_perspective_visualisation(perspective, summaries_settings): download_enabled = validations.is_valid() with columns[1]: - if st.button("Show Output", width='stretch', disabled = not download_enabled): + 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) diff --git a/pages/scenariosGuide.py b/pages/scenariosGuide.py index a9a3097..77ee000 100644 --- a/pages/scenariosGuide.py +++ b/pages/scenariosGuide.py @@ -1,29 +1,11 @@ -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 +from modules.authorisation import quiet_login, validate_page import streamlit as st from modules.nav import SidebarNav from modules.config import retrieve_ui_config -from 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__) @@ -36,8 +18,8 @@ validate_page("User Guide") st.set_page_config( - page_title = "User Guide", - layout = "centered" + page_title="User Guide", + layout="centered" ) cols = st.columns([0.1, 0.8, 0.1]) @@ -231,7 +213,6 @@ """) - if os.path.exists("images/STguide_6_Output.png"): # Display the image st.image("images/STguide_6_Output.png") @@ -247,7 +228,6 @@ 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 """) @@ -260,7 +240,6 @@ 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)*") @@ -318,8 +297,6 @@ 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)*") diff --git a/scripts/add_settings_template.py b/scripts/add_settings_template.py index 5ebcffa..41c5da9 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: @@ -61,5 +62,5 @@ def main(): model_analysis_config["settings_path"]) -if __name__=="__main__": +if __name__ == "__main__": main() diff --git a/scripts/prune_analysis.py b/scripts/prune_analysis.py index 3f379c8..ed22cb8 100644 --- a/scripts/prune_analysis.py +++ b/scripts/prune_analysis.py @@ -8,7 +8,6 @@ from requests import HTTPError - def main(): parser = argparse.ArgumentParser(prog='analysis-prune', description='Script to delete old analyses.') @@ -82,5 +81,6 @@ def main(): except HTTPError: logger.error(f'Failed to delete: {id}.') -if __name__=="__main__": + +if __name__ == "__main__": main() diff --git a/scripts/utils.py b/scripts/utils.py index 7936146..ad371e0 100644 --- a/scripts/utils.py +++ b/scripts/utils.py @@ -24,9 +24,7 @@ def parse_initialise_args(**kwargs): def initialise_client(max_retries=1, retry_interval=5): - ''' - Initialise APIClient with retries whilst waiting for the server to come online. - ''' + """Initialise APIClient with retries whilst waiting for the server to come online.""" logger.info("Initialising client") api_url = os.environ.get('API_URL', 'http://ui.oasis.local/api') auth_type = st.secrets.get('auth_type', 'simple') diff --git a/tests/conftest.py b/tests/conftest.py index 0557f88..e29f7e2 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -4,6 +4,7 @@ from tests.mocks import MockApiClient from streamlit.testing.v1 import AppTest + @pytest.fixture(autouse=True) def no_requests(monkeypatch): """Remove requests.sessions.Session.request for all tests.""" @@ -13,7 +14,7 @@ def no_requests(monkeypatch): def pytest_configure(config): config.portfolio_ID = 2 config.portfolios_data = [{ - 'id' : config.portfolio_ID, + 'id': config.portfolio_ID, 'name': 'string', "created": "2023-05-26T06:48:52.524821Z", "modified": "2023-05-26T06:48:52.524821Z", @@ -47,6 +48,7 @@ def pytest_configure(config): } ] + @pytest.fixture() def mock_api_client(request): config = request.config @@ -60,9 +62,10 @@ def mock_api_client(request): }) return client + @pytest.fixture() def mock_client_interface(mock_api_client): - return ClientInterface(client = mock_api_client) + return ClientInterface(client=mock_api_client) def page_app(path, client, state=None): @@ -79,4 +82,3 @@ def page_app(path, client, state=None): @pytest.fixture() def mock_app_test(mock_api_client): return page_app("pages/analyses.py", mock_api_client) - diff --git a/tests/fixtures/eltcalc_map_locnumber_mismatch_app.py b/tests/fixtures/eltcalc_map_locnumber_mismatch_app.py index 7a52a8b..f181e3a 100644 --- a/tests/fixtures/eltcalc_map_locnumber_mismatch_app.py +++ b/tests/fixtures/eltcalc_map_locnumber_mismatch_app.py @@ -20,4 +20,4 @@ }) eltcalc_map(map_df, locations, oed_fields=['LocNumber'], map_type='heatmap', - intensity_col='MeanLoss') + intensity_col='MeanLoss') diff --git a/tests/fixtures/eltcalc_map_no_match_app.py b/tests/fixtures/eltcalc_map_no_match_app.py index 64c4943..b79a264 100644 --- a/tests/fixtures/eltcalc_map_no_match_app.py +++ b/tests/fixtures/eltcalc_map_no_match_app.py @@ -20,4 +20,4 @@ }) eltcalc_map(map_df, locations, oed_fields=['LocNumber'], map_type='heatmap', - intensity_col='MeanLoss') + intensity_col='MeanLoss') diff --git a/tests/mocks.py b/tests/mocks.py index 835f919..a46d01a 100644 --- a/tests/mocks.py +++ b/tests/mocks.py @@ -21,6 +21,7 @@ class MockEndpoint: `get(ID)` looks records up by their `id` field (falling back to list position for records without one), matching the real API. ''' + def __init__(self, json_data=None): self.json_data = [] if json_data is None else json_data # Sub-endpoints wrapped by `modules.client` interfaces @@ -81,6 +82,7 @@ class MockFileEndpoint: Missing files raise a 404 `HTTPError`, as the API does. ''' + def __init__(self): self.files = {} @@ -107,6 +109,7 @@ def __init__(self, text): class MockSubEndpoint: '''Sub-endpoint (e.g. `analyses.settings`) keyed by parent ID.''' + def __init__(self, data=None, missing=None): self.data = {} if data is None else data self.missing = {} if missing is None else missing diff --git a/tests/test_app.py b/tests/test_app.py index 828a6d6..8a3614f 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -3,20 +3,24 @@ from oasis_data_manager.errors import OasisException import tests.mocks as m + @pytest.fixture(autouse=True) def no_requests(monkeypatch): """Remove requests.sessions.Session.request for all tests.""" monkeypatch.delattr("requests.sessions.Session.request") + @pytest.fixture() def at_before_login(): return AppTest.from_file("app.py").run() + def test_login_form_labels(at_before_login): at = at_before_login assert at.text_input(key="username").label == "Username" assert at.text_input(key="password").label == "Password" + @pytest.mark.parametrize("user, password, err_fragment", [("", "", "Username"), ("TestUser", "", "Password"), @@ -29,6 +33,7 @@ def test_login_validation(at_before_login, user, password, err_fragment): at.button[0].click().run() assert err_fragment in at.error[0].value + @pytest.fixture def mock_api_client(monkeypatch): class MockJsonObject: @@ -54,8 +59,9 @@ def server_info(): monkeypatch.setattr("modules.client.APIClient", MockApiClient) return MockApiClient + @pytest.mark.parametrize("user, password, errors", - [("mock_user", "mock_password", ()), + [("mock_user", "mock_password", ()), ("incorrect_user", "incorrect_password", ("Authentication Failed",))]) def test_login_authentication(at_before_login, mock_api_client, user, password, errors): From c038b287c8efee087c93787c7b80ef58286094e0 Mon Sep 17 00:00:00 2001 From: Ben Hayes Date: Thu, 5 Nov 2026 16:23:56 +0000 Subject: [PATCH 14/33] Add code quality CI (ruff, autopep8, pytest) Mirrors OasisLMF's code-quality workflow: ruff (rules in pyproject.toml) and autopep8 --diff --exit-code at 150 characters. Ruff selects all pyflakes (F) checks, as flake8 did, plus OasisLMF's docstring rules. Also runs the pytest suite, which had no CI. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/code-quality.yml | 63 ++++++++++++++++++++++++++++++ README.md | 18 +++++++++ pyproject.toml | 22 +++++++++++ 3 files changed, 103 insertions(+) create mode 100644 .github/workflows/code-quality.yml create mode 100644 pyproject.toml 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/README.md b/README.md index 839403d..ef6cc14 100644 --- a/README.md +++ b/README.md @@ -263,6 +263,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. 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"] From 4a5f05694e6d704eb7eb4feb8b945b2e5dab50b9 Mon Sep 17 00:00:00 2001 From: Ben Hayes Date: Thu, 5 Nov 2026 17:17:48 +0000 Subject: [PATCH 15/33] Read the service account from the environment The UI and setup scripts now take the service account from OASIS_SERVICE_USERNAME_OR_ID / OASIS_SERVICE_PASSWORD_OR_SECRET (exported by install.sh from .env), falling back to .streamlit/secrets.toml. A deployment's credentials only need setting in .env, and secrets.toml can't drift from the platform's admin password. quiet_login also handles failed logins instead of crashing. Co-Authored-By: Claude Opus 5.5 --- app.py | 6 ++---- docker-compose.ui.yml | 3 +++ modules/authorisation.py | 22 ++++++------------- modules/credentials.py | 46 ++++++++++++++++++++++++++++++++++++++++ scripts/utils.py | 20 +++++++---------- 5 files changed, 65 insertions(+), 32 deletions(-) create mode 100644 modules/credentials.py 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/docker-compose.ui.yml b/docker-compose.ui.yml index 23a5fbf..8e9f489 100644 --- a/docker-compose.ui.yml +++ b/docker-compose.ui.yml @@ -25,6 +25,9 @@ services: - API_AUTH_TYPE=${API_AUTH_TYPE} - OASIS_HOSTNAME=${OASIS_UI_HOSTNAME} - OASIS_PROTOCOL=${OASIS_PROTOCOL:-http} + # Service account (set by install.sh from .env); falls back to .streamlit/secrets.toml + - OASIS_SERVICE_USERNAME_OR_ID=${OASIS_SERVICE_USERNAME_OR_ID:-} + - OASIS_SERVICE_PASSWORD_OR_SECRET=${OASIS_SERVICE_PASSWORD_OR_SECRET:-} volumes: - ${UI_DEFAULTS:-./defaults/}:/usr/src/app/defaults/ - ${UI_CONFIG:-./ui-config.json}:/usr/src/app/ui-config.json:ro diff --git a/modules/authorisation.py b/modules/authorisation.py index 5833613..8140f15 100644 --- a/modules/authorisation.py +++ b/modules/authorisation.py @@ -1,10 +1,12 @@ """Module to handle authorisation.""" import os import requests +from oasis_data_manager.errors import OasisException from requests.exceptions import HTTPError from modules.config import retrieve_ui_config import streamlit as st from modules.client import ClientInterface +from modules.credentials import service_client_kwargs import logging logger = logging.getLogger(__name__) @@ -50,13 +52,7 @@ def handle_login(skip_login=False): if skip_login: with st.spinner("Loading platform..."): try: - auth_type = get_auth_type() - if auth_type != 'simple': - st.session_state["client_interface"] = ClientInterface( - auth_type="oidc", client_id=st.secrets["client_id"], client_secret=st.secrets["client_secret"]) - else: - st.session_state["client_interface"] = ClientInterface( - auth_type="simple", username=st.secrets["user"], password=st.secrets["password"]) + st.session_state["client_interface"] = ClientInterface(**service_client_kwargs()) except HTTPError as e: logger.error(e) st.error("Loading platform failed.") @@ -70,16 +66,10 @@ def quiet_login(): if "client_interface" in st.session_state: return - auth_type = get_auth_type() try: - if auth_type != 'simple': - if "client_id" in st.secrets and "client_secret" in st.secrets: - st.session_state["client_interface"] = ClientInterface( - auth_type="oidc", client_id=st.secrets["client_id"], client_secret=st.secrets["client_secret"]) - elif "user" in st.secrets and "password" in st.secrets: - st.session_state["client_interface"] = ClientInterface(auth_type="simple", username=st.secrets["user"], password=st.secrets["password"]) - except HTTPError as e: - logger.error(e) + st.session_state["client_interface"] = ClientInterface(**service_client_kwargs()) + except (HTTPError, OasisException) as e: + logger.error(f'Service login failed: {e}') return diff --git a/modules/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/scripts/utils.py b/scripts/utils.py index ad371e0..579c5b0 100644 --- a/scripts/utils.py +++ b/scripts/utils.py @@ -1,4 +1,9 @@ -import streamlit as st +import sys +from pathlib import Path + +# Allow `python scripts/