From 9dda200c2fd08a8f4837d943c3bc0d2850d39304 Mon Sep 17 00:00:00 2001 From: Ben Hayes Date: Fri, 6 Nov 2026 16:54:07 +0000 Subject: [PATCH] Show each scenario's vulnerability functions Scenarios describe their vulnerability functions in their model settings (data_settings.vulnerability). Show them: - Run a scenario: in the chosen scenario's details - Showcase: under the scenario description - Compare: for each run, with a note that losses depend on the vulnerability functions as well as the hazard - Guide: what vulnerability functions are, which each scenario uses (from the model settings), and how to run a scenario with different ones Scenarios that don't describe them say so. Addresses #27. Co-Authored-By: Claude Opus 5.5 --- modules/scenarios.py | 13 +++++++++++++ scenarios_ui/common.py | 16 +++++++++++++++- scenarios_ui/compare.py | 9 ++++++--- scenarios_ui/explore.py | 3 ++- scenarios_ui/guide.py | 34 +++++++++++++++++++++++++++++++++- scenarios_ui/showcase.py | 3 ++- tests/test_scenarios.py | 33 +++++++++++++++++++++++++++++++-- 7 files changed, 102 insertions(+), 9 deletions(-) diff --git a/modules/scenarios.py b/modules/scenarios.py index 84f2ae5..e5c45f5 100644 --- a/modules/scenarios.py +++ b/modules/scenarios.py @@ -140,6 +140,18 @@ def _column(df, name): return df[match] if match is not None else None +def vulnerability_info(model_settings): + """The vulnerability functions a scenario uses, from its model settings. + + Scenarios describe them in `data_settings.vulnerability`: `source`, `description` + and optionally `url`. Returns None when a scenario doesn't. + """ + info = ((model_settings or {}).get('data_settings') or {}).get('vulnerability') + if not isinstance(info, dict) or not info.get('source'): + return None + return {key: info[key] for key in ('source', 'description', 'url') if info.get(key)} + + def scenario_catalogue(models, portfolios, ui_config, settings_for, locations_for=None): """Scenarios to browse, with title, peril, countries, provider and description. @@ -176,5 +188,6 @@ def scenario_catalogue(models, portfolios, ui_config, settings_for, locations_fo 'countries': [country_name(c) for c in countries or []], 'provider': model.get('supplier_id') or '', 'description': settings.get('description') or '', + 'vulnerability': vulnerability_info(settings), }) return sorted(catalogue, key=lambda e: e['title'].lower()) diff --git a/scenarios_ui/common.py b/scenarios_ui/common.py index a7c761b..2d8b878 100644 --- a/scenarios_ui/common.py +++ b/scenarios_ui/common.py @@ -9,7 +9,7 @@ from requests.exceptions import HTTPError from modules.config import retrieve_ui_config -from modules.scenarios import GROUP_BY_OPTIONS, ScenarioLimits, display_name, is_showcase, visitor_id +from modules.scenarios import GROUP_BY_OPTIONS, ScenarioLimits, display_name, is_showcase, visitor_id, vulnerability_info from modules.schemas import PERSPECTIVES from modules.settings import get_analyses_settings from pages.components.common import format_status @@ -58,6 +58,20 @@ def footer(ui_config): st.caption(text) +def vulnerability_note(model_settings): + """Which vulnerability functions a scenario uses (from its model settings).""" + info = vulnerability_info(model_settings) + if info is None: + st.caption('**Vulnerability:** not documented for this scenario.') + return + source = f"[{info['source']}]({info['url']})" if info.get('url') else info['source'] + st.markdown(f'**Vulnerability:** {source}', + help='How much damage the hazard causes to a building, as a share of its value. ' + 'See the Guide for more on vulnerability functions.') + if info.get('description'): + st.caption(info['description']) + + def run_settings(ci, model, number_of_samples, group_fields): """Analysis settings for a scenario run. diff --git a/scenarios_ui/compare.py b/scenarios_ui/compare.py index 7a882c5..73a03ba 100644 --- a/scenarios_ui/compare.py +++ b/scenarios_ui/compare.py @@ -9,7 +9,7 @@ generate_alt_comparison_fragment, generate_eltcalc_comparison_fragment, generate_leccalc_comparison_fragment, generate_pltcalc_comparison_fragment, summarise_inputs) -from scenarios_ui.common import Context, footer +from scenarios_ui.common import Context, footer, vulnerability_note ctx = Context() ui_config = ctx.ui_config @@ -63,8 +63,9 @@ def option_label(analysis): st.subheader("Analysis Summary") st.markdown(""" This section summarises the analyses selected for comparison: the number and value of buildings in the portfolio; -the hazard footprint selected, and the outputs available. -Under 'output settings', 'gul' referes to ground up loss, before insurance contract terms apply; 'aalcal' denotes that the +the hazard footprint selected, the vulnerability functions used, and the outputs available. Losses depend on the +vulnerability functions as well as the hazard, so runs of different scenarios may not be directly comparable. +Under 'output settings', 'gul' refers to ground up loss, before insurance contract terms apply; 'aalcal' denotes that the Annual Average Loss has been estimated; 'eltcalc' denotes that the per-event loss has been estimated. """) @@ -107,6 +108,7 @@ def get_location_df(inputs): with st.spinner('Loading analysis summary...'): summarise_inputs(get_location_df(inputs), analysis_settings[0], model_settings[0], title_prefix='###') + vulnerability_note(model_settings[0]) with cols[1]: st.write(f"## {selected['name'][1]}") @@ -117,6 +119,7 @@ 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='###') + vulnerability_note(model_settings[1]) @st.cache_data diff --git a/scenarios_ui/explore.py b/scenarios_ui/explore.py index d175605..92e55c1 100644 --- a/scenarios_ui/explore.py +++ b/scenarios_ui/explore.py @@ -15,7 +15,7 @@ from pages.components.common import analysis_progress, current_task, status_label from pages.components.data import cached_model_settings, portfolio_file_df from pages.components.exposure import exposure_overview -from scenarios_ui.common import Context, analysis_results, footer, run_settings +from scenarios_ui.common import Context, analysis_results, footer, run_settings, vulnerability_note SELECTED_MODEL = 'sc_model_id' SELECTED_PORTFOLIO = 'sc_portfolio_id' @@ -106,6 +106,7 @@ def on_select(): f"Provided by {chosen['provider']}"] if x)) if chosen['description']: st.write(chosen['description']) + vulnerability_note(cached_model_settings(ci, models_by_id[chosen['id']])) model = models_by_id.get(selected_model_id) diff --git a/scenarios_ui/guide.py b/scenarios_ui/guide.py index 99d2831..84d690a 100644 --- a/scenarios_ui/guide.py +++ b/scenarios_ui/guide.py @@ -1,6 +1,8 @@ """Guide: what the Scenarios tool is and how to use it.""" import streamlit as st +from modules.scenarios import scenario_models, vulnerability_info +from pages.components.data import cached_model_settings from scenarios_ui.common import Context, footer ctx = Context() @@ -31,9 +33,39 @@ Oasis combines them to estimate the loss to each building, then adds the losses up. """) +st.header('Vulnerability functions') +st.markdown(""" +A vulnerability function gives the damage to a building, as a share of its value, for each level of hazard - +for example how much a house is damaged by one metre of flood water. Functions usually depend on what the +building is used for (its *occupancy*) and sometimes on how it is built, and they can include uncertainty: a +spread of possible damage at each hazard level, which is what the samples draw from. + +The same hazard footprint can give very different losses with different vulnerability functions, so they are +as important to the result as the event itself. The scenarios here use these functions: +""") +ci = ctx.ci +by_source = {} +for model in scenario_models(ci.models.get(), ci.portfolios.get(), ctx.ui_config): + info = vulnerability_info(cached_model_settings(ci, model)) or {'source': 'Not documented'} + entry = by_source.setdefault(info['source'], {'url': info.get('url'), 'scenarios': []}) + entry['scenarios'].append(ctx.scenario_name(model)) +lines = [] +for source, entry in sorted(by_source.items()): + label = f"[{source}]({entry['url']})" if entry['url'] else source + lines.append(f"- **{label}**: {', '.join(sorted(entry['scenarios']))}") +st.markdown('\n'.join(lines)) +st.markdown(""" +Each scenario's functions are described in full when you choose it. They are part of the scenario's model +data and cannot be changed in this tool. To run a scenario with different functions, download it from the +[Oasis Scenarios repository](https://github.com/OasisLMF/Scenarios) and replace its vulnerability files - for +example with functions from the [Oasis Vulnerability Library](https://github.com/OasisLMF/VulnerabilityLibrary) - +then run it with the [Oasis MDK](https://github.com/OasisLMF/OasisLMF). +""") + st.header('Running a scenario') st.markdown(f""" -1. **Choose a scenario** on the *Run a scenario* page. Each card says who provided it and what it represents. +1. **Choose a scenario** on the *Run a scenario* page. Filter the list by peril, country or provider; the + chosen scenario shows what it represents, who provided it and which vulnerability functions it uses. 2. **Check the exposure.** The map and figures show the buildings the scenario will be run against. 3. **Run it.** Choose: - **Number of samples** (up to {limits.max_samples}) - damage is uncertain, so Oasis draws several diff --git a/scenarios_ui/showcase.py b/scenarios_ui/showcase.py index 257879c..aef6427 100644 --- a/scenarios_ui/showcase.py +++ b/scenarios_ui/showcase.py @@ -3,7 +3,7 @@ from modules.scenarios import VISITOR_PARAM, showcase_analyses from pages.components.data import cached_model_settings -from scenarios_ui.common import Context, analysis_results, footer +from scenarios_ui.common import Context, analysis_results, footer, vulnerability_note ctx = Context() ci = ctx.ci @@ -35,6 +35,7 @@ description = cached_model_settings(ci, model).get('description') if description: st.caption(description) + vulnerability_note(cached_model_settings(ci, model)) if st.button('Run this scenario yourself', icon=':material/play_circle:'): st.session_state['sc_model_id'] = model['id'] st.session_state['sc_portfolio_id'] = analysis['portfolio'] diff --git a/tests/test_scenarios.py b/tests/test_scenarios.py index f881413..f2a4d08 100644 --- a/tests/test_scenarios.py +++ b/tests/test_scenarios.py @@ -48,7 +48,8 @@ def client(): 'LocNumber': ['1', '2'], 'CountryCode': ['MA', 'MA'], 'Latitude': [31.1, 31.2], 'Longitude': [-8.4, -8.5], 'BuildingTIV': [1000.0, 2000.0], 'LocPerilsCovered': ['QEQ', 'QEQ']}) client.models.settings.data[1] = {'name': 'Morocco earthquake, Sep 2023', - 'description': 'Morocco earthquake test model'} + 'description': 'Morocco earthquake test model', + 'data_settings': {'vulnerability': VULNERABILITY}} for i in (1, 2, 3): client.analyses.settings.data[i] = SETTINGS client.analyses.output_file.files[i] = { @@ -58,6 +59,9 @@ def client(): return client +VULNERABILITY = {'source': 'Test damage functions', 'description': 'By occupancy.', 'url': 'https://example.org/vuln'} + + def app(client, page=None, vid=VID, state=None): at = AppTest.from_file('scenarios_app.py', default_timeout=30) at.session_state['client_interface'] = ClientInterface(client=client) @@ -187,6 +191,28 @@ def test_run_a_scenario(client): assert all(level['oed_fields'] == ['LocNumber'] for level in settings['gul_summaries']) +def test_vulnerability_info(): + assert sc.vulnerability_info({'data_settings': {'vulnerability': VULNERABILITY}}) == VULNERABILITY + assert sc.vulnerability_info({'data_settings': {'vulnerability': {'source': 'S', 'url': ''}}}) == {'source': 'S'} + # No source, or nothing at all: not documented + assert sc.vulnerability_info({'data_settings': {'vulnerability': {'description': 'd'}}}) is None + assert sc.vulnerability_info({'data_settings': {}}) is None + assert sc.vulnerability_info(None) is None + + +def test_chosen_scenario_shows_vulnerability(client): + at = app(client, state={'sc_model_id': 1}) + assert not at.exception, [e.value for e in at.exception] + assert '**Vulnerability:** [Test damage functions](https://example.org/vuln)' in [m.value for m in at.markdown] + assert 'By occupancy.' in [c.value for c in at.caption] + + +def test_vulnerability_not_documented(client): + client.models.settings.data[1].pop('data_settings') + at = app(client, state={'sc_model_id': 1}) + assert '**Vulnerability:** not documented for this scenario.' in [c.value for c in at.caption] + + def test_run_blocked_at_visitor_limit(client): for i in (10, 11): client.analyses.json_data.append(analysis(i, f'busy [v:{VID}]', 'RUN_STARTED')) @@ -202,6 +228,7 @@ def test_showcase_page(client): # Showcase runs are named by their scenario's name from the model settings, not the run name assert at.selectbox[0].options == ['Morocco earthquake, Sep 2023'] assert at.subheader[0].value == 'Morocco earthquake, Sep 2023' + assert '**Vulnerability:** [Test damage functions](https://example.org/vuln)' in [m.value for m in at.markdown] def test_compare_offers_own_and_showcase_runs(client): @@ -219,8 +246,10 @@ def test_compare_offers_own_and_showcase_runs(client): def test_guide_page(client): at = app(client, 'scenarios_ui/guide.py') - assert not at.exception + assert not at.exception, [e.value for e in at.exception] assert at.title[0].value == 'Guide' + # Scenarios listed by the vulnerability functions they use, from their model settings + assert '- **[Test damage functions](https://example.org/vuln)**: Morocco earthquake, Sep 2023' in [m.value for m in at.markdown] @pytest.mark.parametrize('page', ['pages/portfolios.py', 'pages/analyses.py', 'pages/models.py'])