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/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/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..9ecdbaf --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,22 @@ +# Code quality configuration, mirroring OasisLMF (.github/workflows/code-quality.yml). + +[tool.ruff] +# ruff replaces flake8; autopep8 covers PEP8 formatting. +line-length = 150 +exclude = [".git", ".venv", "venv", "OasisPiWind", "scenarios", "oidc", "certs"] +# required for the DOC* (pydoclint) rules below, which are preview-only. +preview = true + +[tool.ruff.lint] +select = [ + # All pyflakes checks (flake8's F rules): unused imports/variables, undefined names, ... + "F", + # Docstring style rules used by OasisLMF + "D200", "D201", "D202", "D206", "D207", "D208", "D209", "D210", "D212", + "D214", "D300", "D301", "D403", "D405", "D410", "D411", "D412", "D414", + "D416", "D417", "D419", + "DOC202", "DOC402", +] + +[tool.ruff.lint.per-file-ignores] +"tests/**" = ["D"] diff --git a/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):