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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions modules/scenarios.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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())
16 changes: 15 additions & 1 deletion scenarios_ui/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand Down
9 changes: 6 additions & 3 deletions scenarios_ui/compare.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
""")

Expand Down Expand Up @@ -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]}")
Expand All @@ -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
Expand Down
3 changes: 2 additions & 1 deletion scenarios_ui/explore.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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)

Expand Down
34 changes: 33 additions & 1 deletion scenarios_ui/guide.py
Original file line number Diff line number Diff line change
@@ -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()
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion scenarios_ui/showcase.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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']
Expand Down
33 changes: 31 additions & 2 deletions tests/test_scenarios.py
Original file line number Diff line number Diff line change
Expand Up @@ -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] = {
Expand All @@ -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)
Expand Down Expand Up @@ -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'))
Expand All @@ -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):
Expand All @@ -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'])
Expand Down
Loading