From 9fa61e34a90b73b2d0f7fe148910223469247c2e Mon Sep 17 00:00:00 2001 From: Andreas Eknes Lie Date: Fri, 3 May 2024 13:43:55 +0200 Subject: [PATCH] Resolve pylint reported issues Refactor Unnecessarily calls dunder method __getitem__ Remove useless bad-continuation keyword from pylint Remove useless pylint suppressions Replace dict calls with dict syntax Avoid uneccessary list lookup Avoid constructing additional lists in memory Formatting single line Iterate over enum class instead of list comprehension Use shim to use StrEnum depending on python version Be more liberal with type defs Classes are not StrEnum but Enum Classes that are IntEnum not StrEnums Avoid using extra lists when calculating Use different escape for the multiply sign in markdown --- .pylintrc | 2 +- webviz_subsurface/_components/color_picker.py | 2 +- .../_components/tornado/_tornado_bar_chart.py | 60 ++--- .../_datainput/eclipse_init_io/pvt_common.py | 6 +- .../_datainput/eclipse_init_io/pvt_gas.py | 8 +- .../_datainput/eclipse_init_io/pvt_oil.py | 8 +- .../_datainput/eclipse_init_io/pvt_water.py | 6 +- webviz_subsurface/_datainput/units.py | 1 - webviz_subsurface/_figures/px_figure.py | 37 +-- webviz_subsurface/_figures/scatterplot.py | 4 +- .../_figures/timeseries_figure.py | 4 +- .../_provider_impl_file.py | 4 +- .../provider_impl_egrid.py | 7 +- .../provider_impl_roff.py | 4 +- .../ensemble_summary_provider/_resampling.py | 2 - .../ensemble_summary_provider.py | 5 +- .../_provider_impl_file.py | 4 +- .../ensemble_surface_provider.py | 5 +- webviz_subsurface/_utils/enum_shim.py | 13 ++ .../plugins/_co2_leakage/_plugin.py | 5 +- .../_co2_leakage/_utilities/co2volume.py | 4 +- .../_co2_leakage/_utilities/generic.py | 8 +- .../plugins/_grid_viewer_fmu/_types.py | 6 +- .../_utils/_ensemble_group_tree_data.py | 9 +- .../figures/plotly_line_plot.py | 2 +- .../plugins/_map_viewer_fmu/_layer_model.py | 5 +- .../_tmp_well_pick_provider.py | 5 +- .../plugins/_map_viewer_fmu/_types.py | 8 +- .../plugins/_map_viewer_fmu/callbacks.py | 8 +- .../plugins/_map_viewer_fmu/layout.py | 16 +- .../_prod_misfit/utils/make_figures.py | 14 +- .../_views/_pvt/_settings/_data_settings.py | 25 ++- ...eservoir_simulation_timeseries_onebyone.py | 4 +- .../plugins/_running_time_analysis_fmu.py | 2 +- webviz_subsurface/plugins/_seismic_misfit.py | 210 +++++++++--------- .../_utils/_onebyone_timeseries_figure.py | 4 +- .../figures/intersection.py | 4 +- .../_surface_with_grid_cross_section.py | 3 +- .../plugins/_swatinit_qc/_business_logic.py | 25 ++- .../plugins/_swatinit_qc/_figures.py | 10 +- .../plugins/_swatinit_qc/_layout.py | 6 +- .../plugins/_swatinit_qc/_markdown.py | 3 +- .../_vfp_view/_utils/_vfp_figure_builder.py | 18 +- .../controllers/distribution_controllers.py | 39 ++-- .../controllers/tornado_controllers.py | 3 +- .../utils/table_and_figure_utils.py | 27 +-- .../_utils/_well_control_figure.py | 1 - 47 files changed, 338 insertions(+), 318 deletions(-) create mode 100644 webviz_subsurface/_utils/enum_shim.py diff --git a/.pylintrc b/.pylintrc index 33e394749..c6da4b4cd 100644 --- a/.pylintrc +++ b/.pylintrc @@ -5,7 +5,7 @@ init-hook = "import astroid; astroid.context.InferenceContext.max_inferred = 500 [MESSAGES CONTROL] -disable = bad-continuation, missing-docstring, duplicate-code, logging-fstring-interpolation, unspecified-encoding +disable = missing-docstring, duplicate-code, logging-fstring-interpolation, unspecified-encoding enable = useless-suppression [DESIGN] diff --git a/webviz_subsurface/_components/color_picker.py b/webviz_subsurface/_components/color_picker.py index acd632898..519157fba 100644 --- a/webviz_subsurface/_components/color_picker.py +++ b/webviz_subsurface/_components/color_picker.py @@ -174,7 +174,7 @@ def _show_color_picker( return dash_daq.ColorPicker( # pylint: disable=not-callable {"id": self._uuid, "element": "picker"}, label=f"Color for {[col for col in self._dframe.iloc[row_no] if col != 'COLOR']}", - value=dict(hex=current_color_store[row_no]), + value={"hex": current_color_store[row_no]}, ) @app.callback( diff --git a/webviz_subsurface/_components/tornado/_tornado_bar_chart.py b/webviz_subsurface/_components/tornado/_tornado_bar_chart.py index aebd04d83..d936064a1 100644 --- a/webviz_subsurface/_components/tornado/_tornado_bar_chart.py +++ b/webviz_subsurface/_components/tornado/_tornado_bar_chart.py @@ -140,46 +140,46 @@ def hover_labels(self) -> List: def data(self) -> List: colors = self.create_color_list(self._tornadotable["sensname"].unique()) return [ - dict( - type="bar", - y=self._tornadotable["sensname"], - x=self._tornadotable["low"], - name="low", - base=self._tornadotable["low_base"] + { + "type": "bar", + "y": self._tornadotable["sensname"], + "x": self._tornadotable["low"], + "name": "low", + "base": self._tornadotable["low_base"] if not self._use_true_base else (self._reference_average + self._tornadotable["low_base"]), - customdata=self._tornadotable["low_reals"], - text=self.bar_labels("low"), - textposition="auto", - insidetextanchor="middle", - hoverinfo="text", - hovertext=self.hover_labels(), - orientation="h", - marker={ + "customdata": self._tornadotable["low_reals"], + "text": self.bar_labels("low"), + "textposition": "auto", + "insidetextanchor": "middle", + "hoverinfo": "text", + "hovertext": self.hover_labels(), + "orientation": "h", + "marker": { "line": {"width": 1.5, "color": "black"}, "color": colors if self._color_by_sens else None, }, - ), - dict( - type="bar", - y=self._tornadotable["sensname"], - x=self._tornadotable["high"], - name="high", - base=self._tornadotable["high_base"] + }, + { + "type": "bar", + "y": self._tornadotable["sensname"], + "x": self._tornadotable["high"], + "name": "high", + "base": self._tornadotable["high_base"] if not self._use_true_base else (self._reference_average + self._tornadotable["high_base"]), - customdata=self._tornadotable["high_reals"], - text=self.bar_labels("high"), - textposition="auto", - insidetextanchor="middle", - hoverinfo="text", - hovertext=self.hover_labels(), - orientation="h", - marker={ + "customdata": self._tornadotable["high_reals"], + "text": self.bar_labels("high"), + "textposition": "auto", + "insidetextanchor": "middle", + "hoverinfo": "text", + "hovertext": self.hover_labels(), + "orientation": "h", + "marker": { "line": {"width": 1.5, "color": "black"}, "color": colors if self._color_by_sens else None, }, - ), + }, ] def calculate_scatter_value(self, case_values: pd.Series) -> List: diff --git a/webviz_subsurface/_datainput/eclipse_init_io/pvt_common.py b/webviz_subsurface/_datainput/eclipse_init_io/pvt_common.py index 9e596fd70..0b2f38d6d 100644 --- a/webviz_subsurface/_datainput/eclipse_init_io/pvt_common.py +++ b/webviz_subsurface/_datainput/eclipse_init_io/pvt_common.py @@ -632,15 +632,15 @@ def surface_mass_density( else: raise AttributeError("Phase must be Liquid, Water or Vapour.") - tabdims = ecl_file.__getitem__("TABDIMS") - tab = ecl_file.__getitem__("TAB") + tabdims = ecl_file["TABDIMS"] + tab = ecl_file["TAB"] start = tabdims[InitFileDefinitions.TABDIMS_IBDENS_OFFSET_ITEM] - 1 nreg = tabdims[InitFileDefinitions.TABDIMS_NTDENS_ITEM] rho = tab[start + nreg * (col + 0) : start + nreg * (col + 1)] - intehead = ecl_file.__getitem__(InitFileDefinitions.INTEHEAD_KW) + intehead = ecl_file[InitFileDefinitions.INTEHEAD_KW] unit_system = EclUnits.create_unit_system( intehead[InitFileDefinitions.INTEHEAD_UNIT_INDEX] ) diff --git a/webviz_subsurface/_datainput/eclipse_init_io/pvt_gas.py b/webviz_subsurface/_datainput/eclipse_init_io/pvt_gas.py index 452241a61..23da83b28 100644 --- a/webviz_subsurface/_datainput/eclipse_init_io/pvt_gas.py +++ b/webviz_subsurface/_datainput/eclipse_init_io/pvt_gas.py @@ -527,7 +527,7 @@ def from_ecl_init_file( A Gas object or None if the data in the Eclipse file was invalid """ - intehead = ecl_init_file.__getitem__(InitFileDefinitions.INTEHEAD_KW) + intehead = ecl_init_file[InitFileDefinitions.INTEHEAD_KW] intehead_phase = intehead[InitFileDefinitions.INTEHEAD_PHASE_INDEX] if (intehead_phase & (1 << 2)) == 0: @@ -535,8 +535,8 @@ def from_ecl_init_file( raw = EclPropertyTableRawData() - tab_dims = ecl_init_file.__getitem__("TABDIMS") - tab = ecl_init_file.__getitem__("TAB") + tab_dims = ecl_init_file["TABDIMS"] + tab = ecl_init_file["TAB"] num_rv = tab_dims[InitFileDefinitions.TABDIMS_NRPVTG_ITEM] num_pg = tab_dims[InitFileDefinitions.TABDIMS_NPPVTG_ITEM] @@ -547,7 +547,7 @@ def from_ecl_init_file( if raw.num_tables == 0: return None - logihead = ecl_init_file.__getitem__(InitFileDefinitions.LOGIHEAD_KW) + logihead = ecl_init_file[InitFileDefinitions.LOGIHEAD_KW] if logihead[InitFileDefinitions.LOGIHEAD_RV_INDEX]: raw.num_primary = num_pg diff --git a/webviz_subsurface/_datainput/eclipse_init_io/pvt_oil.py b/webviz_subsurface/_datainput/eclipse_init_io/pvt_oil.py index c507b2e20..63ff4381b 100644 --- a/webviz_subsurface/_datainput/eclipse_init_io/pvt_oil.py +++ b/webviz_subsurface/_datainput/eclipse_init_io/pvt_oil.py @@ -753,15 +753,15 @@ def from_ecl_init_file( An Oil object or None if the data in the Eclipse file was invalid """ - intehead = ecl_init_file.__getitem__(InitFileDefinitions.INTEHEAD_KW) + intehead = ecl_init_file[InitFileDefinitions.INTEHEAD_KW] - logihead = ecl_init_file.__getitem__(InitFileDefinitions.LOGIHEAD_KW) + logihead = ecl_init_file[InitFileDefinitions.LOGIHEAD_KW] is_is_const_compr = bool(logihead[is_const_compr_index()]) raw = EclPropertyTableRawData() - tab_dims = ecl_init_file.__getitem__("TABDIMS") - tab = ecl_init_file.__getitem__("TAB") + tab_dims = ecl_init_file["TABDIMS"] + tab = ecl_init_file["TAB"] num_rs = tab_dims[InitFileDefinitions.TABDIMS_NRPVTO_ITEM] diff --git a/webviz_subsurface/_datainput/eclipse_init_io/pvt_water.py b/webviz_subsurface/_datainput/eclipse_init_io/pvt_water.py index c194c3efe..a98a4790d 100644 --- a/webviz_subsurface/_datainput/eclipse_init_io/pvt_water.py +++ b/webviz_subsurface/_datainput/eclipse_init_io/pvt_water.py @@ -394,7 +394,7 @@ def from_ecl_init_file( A Water object or None if the data in the Eclipse file was invalid """ - intehead = ecl_init_file.__getitem__(InitFileDefinitions.INTEHEAD_KW) + intehead = ecl_init_file[InitFileDefinitions.INTEHEAD_KW] intehead_phase = intehead[InitFileDefinitions.INTEHEAD_PHASE_INDEX] if (intehead_phase & (1 << 2)) == 0: @@ -402,8 +402,8 @@ def from_ecl_init_file( raw = EclPropertyTableRawData() - tab_dims = ecl_init_file.__getitem__("TABDIMS") - tab = ecl_init_file.__getitem__("TAB") + tab_dims = ecl_init_file["TABDIMS"] + tab = ecl_init_file["TAB"] raw.num_primary = 1 # Single record per region raw.num_rows = 1 # Single record per region diff --git a/webviz_subsurface/_datainput/units.py b/webviz_subsurface/_datainput/units.py index 00677a8fe..75245ef83 100644 --- a/webviz_subsurface/_datainput/units.py +++ b/webviz_subsurface/_datainput/units.py @@ -152,7 +152,6 @@ class Base(UnitBase): care of keeping its symbol tidy. """ - # pylint: disable=super-init-not-called def __init__( self, value: Union[float, UnitBase], # type: ignore[name-defined] diff --git a/webviz_subsurface/_figures/px_figure.py b/webviz_subsurface/_figures/px_figure.py index 80fe4fa89..08fbc94ce 100644 --- a/webviz_subsurface/_figures/px_figure.py +++ b/webviz_subsurface/_figures/px_figure.py @@ -129,7 +129,7 @@ def update_traces(figure: go.Figure, **kwargs: Any) -> go.Figure: ), selector=lambda t: t["type"] in ["scatter", "scattergl"], ) - .update_traces(textposition="inside", selector=dict(type="pie")) + .update_traces(textposition="inside", selector={"type": "pie"}) .for_each_trace(lambda t: set_marker_color(t)) .for_each_trace( lambda t: ( @@ -139,7 +139,7 @@ def update_traces(figure: go.Figure, **kwargs: Any) -> go.Figure: if is_numeric_dtype(t["x"]) else None ), - selector=dict(type="histogram"), + selector={"type": "histogram"}, ) ) @@ -154,7 +154,7 @@ def set_marker_color(trace: go) -> go: opacity = marker_attributes.get( "opacity", 0.5 if trace.type in ["scatter", "scattergl"] else 0.7 ) - trace.update(marker_line=dict(color=trace.marker.color, width=1)) + trace.update(marker_line={"color": trace.marker.color, "width": 1}) trace.update(marker_color=hex_to_rgb(trace.marker.color, opacity=opacity)) trace.update(marker_opacity=1) return trace @@ -180,20 +180,20 @@ def for_each_annotation(figure: go.Figure, **kwargs: Any) -> go.Figure: def empty_figure_layout() -> go.Figure: return go.Figure( - layout=dict( - xaxis={"visible": False}, - yaxis={"visible": False}, - plot_bgcolor="white", - annotations=[ - dict( - text="No data available for figure", - xref="paper", - yref="paper", - showarrow=False, - font={"size": 20}, - ) + layout={ + "xaxis": {"visible": False}, + "yaxis": {"visible": False}, + "plot_bgcolor": "white", + "annotations": [ + { + "text": "No data available for figure", + "xref": "paper", + "yref": "paper", + "showarrow": False, + "font": {"size": 20}, + } ], - ) + }, ) @@ -246,7 +246,10 @@ def create_hover_boxes_for_violin_plots( showlegend=False, text=hover_text, hoverinfo="text", - hoverlabel=dict(bgcolor="#E6FAEC", font=dict(color="#243746", size=15)), + hoverlabel={ + "bgcolor": "#E6FAEC", + "font": {"color": "#243746", "size": 15}, + }, ) ) return hovertraces diff --git a/webviz_subsurface/_figures/scatterplot.py b/webviz_subsurface/_figures/scatterplot.py index 629ce1ab0..1e2d9afdf 100644 --- a/webviz_subsurface/_figures/scatterplot.py +++ b/webviz_subsurface/_figures/scatterplot.py @@ -76,7 +76,7 @@ def add_trace( x=x_values, y=y_values, mode=mode, - line=dict(dash=dash, color=color), + line={"dash": dash, "color": color}, showlegend=showlegend, hovertext=text, name=text, @@ -110,4 +110,4 @@ def add_vertical_line_with_error( "Observation Error", dash="dash", ) - self._figure.update_layout(legend=dict(orientation="h")) + self._figure.update_layout(legend={"orientation": "h"}) diff --git a/webviz_subsurface/_figures/timeseries_figure.py b/webviz_subsurface/_figures/timeseries_figure.py index d180dde84..972102500 100644 --- a/webviz_subsurface/_figures/timeseries_figure.py +++ b/webviz_subsurface/_figures/timeseries_figure.py @@ -1,18 +1,18 @@ import datetime -from enum import Enum from typing import Dict, List, Optional import numpy as np import pandas as pd from webviz_subsurface._utils.colors import find_intermediate_color, rgba_to_str +from webviz_subsurface._utils.enum_shim import StrEnum from webviz_subsurface._utils.simulation_timeseries import ( get_simulation_line_shape, set_simulation_line_shape_fallback, ) -class Colors(str, Enum): +class Colors(StrEnum): RED = rgba_to_str((255, 18, 67, 1)) MID = rgba_to_str((220, 220, 220, 1)) GREEN = rgba_to_str((62, 208, 62, 1)) diff --git a/webviz_subsurface/_providers/ensemble_fault_polygons_provider/_provider_impl_file.py b/webviz_subsurface/_providers/ensemble_fault_polygons_provider/_provider_impl_file.py index 1c7dcf514..ff2f5f75d 100644 --- a/webviz_subsurface/_providers/ensemble_fault_polygons_provider/_provider_impl_file.py +++ b/webviz_subsurface/_providers/ensemble_fault_polygons_provider/_provider_impl_file.py @@ -1,12 +1,12 @@ import logging import shutil -from enum import Enum from pathlib import Path from typing import List, Optional import pandas as pd import xtgeo +from webviz_subsurface._utils.enum_shim import StrEnum from webviz_subsurface._utils.perf_timer import PerfTimer from ._fault_polygons_discovery import FaultPolygonsFileInfo @@ -31,7 +31,7 @@ class Col: REL_PATH = "rel_path" -class FaultPolygonsType(str, Enum): +class FaultPolygonsType(StrEnum): SIMULATED = "simulated" diff --git a/webviz_subsurface/_providers/ensemble_grid_provider/provider_impl_egrid.py b/webviz_subsurface/_providers/ensemble_grid_provider/provider_impl_egrid.py index ce0f30104..be27e4fe9 100644 --- a/webviz_subsurface/_providers/ensemble_grid_provider/provider_impl_egrid.py +++ b/webviz_subsurface/_providers/ensemble_grid_provider/provider_impl_egrid.py @@ -1,6 +1,5 @@ import logging import shutil -from enum import Enum from pathlib import Path from typing import List, Optional @@ -8,6 +7,7 @@ import pandas as pd import xtgeo +from webviz_subsurface._utils.enum_shim import StrEnum from webviz_subsurface._utils.perf_timer import PerfTimer from ._egrid_file_discovery import EclipseCaseFileInfo @@ -16,15 +16,14 @@ LOGGER = logging.getLogger(__name__) -# pylint: disable=too-few-public-methods -class Col: +class Col(StrEnum): REAL = "realization" EGRID = "egrid_path" INIT = "init_path" UNRST = "unrst_path" -class GridType(str, Enum): +class GridType(StrEnum): GEOMETRY = "geometry" STATIC_PROPERTY = "static_property" DYNAMIC_PROPERTY = "dynamic_property" diff --git a/webviz_subsurface/_providers/ensemble_grid_provider/provider_impl_roff.py b/webviz_subsurface/_providers/ensemble_grid_provider/provider_impl_roff.py index 156bf3cda..94c0dde43 100644 --- a/webviz_subsurface/_providers/ensemble_grid_provider/provider_impl_roff.py +++ b/webviz_subsurface/_providers/ensemble_grid_provider/provider_impl_roff.py @@ -1,6 +1,5 @@ import logging import shutil -from enum import Enum from pathlib import Path from typing import List, Optional @@ -8,6 +7,7 @@ import pandas as pd import xtgeo +from webviz_subsurface._utils.enum_shim import StrEnum from webviz_subsurface._utils.perf_timer import PerfTimer from ._roff_file_discovery import GridFileInfo, GridParameterFileInfo @@ -27,7 +27,7 @@ class Col: REL_PATH = "rel_path" -class GridType(str, Enum): +class GridType(StrEnum): GEOMETRY = "geometry" STATIC_PROPERTY = "static_property" DYNAMIC_PROPERTY = "dynamic_property" diff --git a/webviz_subsurface/_providers/ensemble_summary_provider/_resampling.py b/webviz_subsurface/_providers/ensemble_summary_provider/_resampling.py index 38d7771b6..d06cbdf7f 100644 --- a/webviz_subsurface/_providers/ensemble_summary_provider/_resampling.py +++ b/webviz_subsurface/_providers/ensemble_summary_provider/_resampling.py @@ -74,7 +74,6 @@ def generate_normalized_sample_dates( def interpolate_backfill( x: np.ndarray, xp: np.ndarray, yp: np.ndarray, yleft: float, yright: float ) -> np.ndarray: - # pylint: disable=invalid-name """Do back-filling interpolation of the coordinates in xp and yp, evaluated at the x-coordinates specified in x. Note that xp and yp must be arrays of the same length. @@ -253,7 +252,6 @@ def resample_segmented_multi_real_table(table: pa.Table, freq: Frequency) -> pa. def _compute_interpolation_weight( d: np.datetime64, d0: np.datetime64, d1: np.datetime64 ) -> float: - # pylint: disable=invalid-name d_as_uint = d.astype(np.uint64) d0_as_uint = d0.astype(np.uint64) d1_as_uint = d1.astype(np.uint64) diff --git a/webviz_subsurface/_providers/ensemble_summary_provider/ensemble_summary_provider.py b/webviz_subsurface/_providers/ensemble_summary_provider/ensemble_summary_provider.py index 4022e62ec..cd53bc03c 100644 --- a/webviz_subsurface/_providers/ensemble_summary_provider/ensemble_summary_provider.py +++ b/webviz_subsurface/_providers/ensemble_summary_provider/ensemble_summary_provider.py @@ -1,13 +1,14 @@ import abc import datetime from dataclasses import dataclass -from enum import Enum from typing import List, Optional, Sequence import pandas as pd +from webviz_subsurface._utils.enum_shim import StrEnum -class Frequency(Enum): + +class Frequency(StrEnum): DAILY = "daily" WEEKLY = "weekly" MONTHLY = "monthly" diff --git a/webviz_subsurface/_providers/ensemble_surface_provider/_provider_impl_file.py b/webviz_subsurface/_providers/ensemble_surface_provider/_provider_impl_file.py index f29f02bc8..ae8d3ef2c 100644 --- a/webviz_subsurface/_providers/ensemble_surface_provider/_provider_impl_file.py +++ b/webviz_subsurface/_providers/ensemble_surface_provider/_provider_impl_file.py @@ -1,7 +1,6 @@ import logging import shutil import warnings -from enum import Enum from pathlib import Path from typing import List, Optional, Set @@ -9,6 +8,7 @@ import pandas as pd import xtgeo +from webviz_subsurface._utils.enum_shim import StrEnum from webviz_subsurface._utils.perf_timer import PerfTimer from ._stat_surf_cache import StatSurfCache @@ -40,7 +40,7 @@ class Col: REL_PATH = "rel_path" -class SurfaceType(str, Enum): +class SurfaceType(StrEnum): OBSERVED = "observed" SIMULATED = "simulated" diff --git a/webviz_subsurface/_providers/ensemble_surface_provider/ensemble_surface_provider.py b/webviz_subsurface/_providers/ensemble_surface_provider/ensemble_surface_provider.py index fa9a2bb97..2485e68e2 100644 --- a/webviz_subsurface/_providers/ensemble_surface_provider/ensemble_surface_provider.py +++ b/webviz_subsurface/_providers/ensemble_surface_provider/ensemble_surface_provider.py @@ -1,12 +1,13 @@ import abc from dataclasses import dataclass -from enum import Enum from typing import List, Optional, Union import xtgeo +from webviz_subsurface._utils.enum_shim import StrEnum -class SurfaceStatistic(str, Enum): + +class SurfaceStatistic(StrEnum): MEAN = "Mean" STDDEV = "StdDev" MINIMUM = "Minimum" diff --git a/webviz_subsurface/_utils/enum_shim.py b/webviz_subsurface/_utils/enum_shim.py new file mode 100644 index 000000000..4df03fe6d --- /dev/null +++ b/webviz_subsurface/_utils/enum_shim.py @@ -0,0 +1,13 @@ +import sys + +if sys.version_info < (3, 11): + from enum import Enum + from enum import EnumMeta as EnumType + + class StrEnum(str, Enum): + pass + +else: + from enum import EnumType, StrEnum + +__all__ = ["StrEnum", "EnumType"] diff --git a/webviz_subsurface/plugins/_co2_leakage/_plugin.py b/webviz_subsurface/plugins/_co2_leakage/_plugin.py index 5464283eb..190d8d3e1 100644 --- a/webviz_subsurface/plugins/_co2_leakage/_plugin.py +++ b/webviz_subsurface/plugins/_co2_leakage/_plugin.py @@ -371,10 +371,7 @@ def toggle_date_slider(attribute: str) -> Dict[str, str]: ) def make_unit_list( attribute: str, - ) -> Union[ - Tuple[List[Co2MassScale], Co2MassScale], - Tuple[List[Co2VolumeScale], Co2VolumeScale], - ]: + ) -> Union[Tuple[List[Any], Co2MassScale], Tuple[List[Any], Co2VolumeScale],]: if attribute == GraphSource.CONTAINMENT_ACTUAL_VOLUME: return list(Co2VolumeScale), Co2VolumeScale.BILLION_CUBIC_METERS return list(Co2MassScale), Co2MassScale.MTONS diff --git a/webviz_subsurface/plugins/_co2_leakage/_utilities/co2volume.py b/webviz_subsurface/plugins/_co2_leakage/_utilities/co2volume.py index 29ce1fb3f..335513094 100644 --- a/webviz_subsurface/plugins/_co2_leakage/_utilities/co2volume.py +++ b/webviz_subsurface/plugins/_co2_leakage/_utilities/co2volume.py @@ -1,4 +1,3 @@ -from enum import Enum from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np @@ -7,6 +6,7 @@ import plotly.graph_objects as go from webviz_subsurface._providers import EnsembleTableProvider +from webviz_subsurface._utils.enum_shim import StrEnum from webviz_subsurface.plugins._co2_leakage._utilities.generic import ( Co2MassScale, Co2VolumeScale, @@ -14,7 +14,7 @@ ) -class _Columns(Enum): +class _Columns(StrEnum): REALIZATION = "realization" VOLUME = "volume" CONTAINMENT = "containment" diff --git a/webviz_subsurface/plugins/_co2_leakage/_utilities/generic.py b/webviz_subsurface/plugins/_co2_leakage/_utilities/generic.py index c66f5d5e6..48752b4d5 100644 --- a/webviz_subsurface/plugins/_co2_leakage/_utilities/generic.py +++ b/webviz_subsurface/plugins/_co2_leakage/_utilities/generic.py @@ -1,9 +1,7 @@ -from enum import Enum +from webviz_subsurface._utils.enum_shim import StrEnum -from webviz_config.utils import StrEnum - -class MapAttribute(Enum): +class MapAttribute(StrEnum): MIGRATION_TIME = "Migration Time" MAX_SGAS = "Maximum SGAS" MAX_AMFG = "Maximum AMFG" @@ -32,7 +30,7 @@ class GraphSource(StrEnum): CONTAINMENT_ACTUAL_VOLUME = "Containment Data (volume, actual)" -class LayoutLabels(str, Enum): +class LayoutLabels(StrEnum): """Text labels used in layout components""" SHOW_FAULTPOLYGONS = "Show fault polygons" diff --git a/webviz_subsurface/plugins/_grid_viewer_fmu/_types.py b/webviz_subsurface/plugins/_grid_viewer_fmu/_types.py index 742f26e18..a2d1218d1 100644 --- a/webviz_subsurface/plugins/_grid_viewer_fmu/_types.py +++ b/webviz_subsurface/plugins/_grid_viewer_fmu/_types.py @@ -1,12 +1,12 @@ -from enum import Enum +from webviz_subsurface._utils.enum_shim import StrEnum -class PROPERTYTYPE(str, Enum): +class PROPERTYTYPE(StrEnum): STATIC = "Static" DYNAMIC = "Dynamic" -class GRIDDIRECTION(str, Enum): +class GRIDDIRECTION(StrEnum): I = "I" J = "J" K = "K" diff --git a/webviz_subsurface/plugins/_group_tree/_utils/_ensemble_group_tree_data.py b/webviz_subsurface/plugins/_group_tree/_utils/_ensemble_group_tree_data.py index fdf27dded..9f3663cd3 100644 --- a/webviz_subsurface/plugins/_group_tree/_utils/_ensemble_group_tree_data.py +++ b/webviz_subsurface/plugins/_group_tree/_utils/_ensemble_group_tree_data.py @@ -412,7 +412,6 @@ def extract_tree( works recursively and is initially called with the terminal node of the tree (usually FIELD) """ - # pylint: disable=too-many-locals node_sumvecs = sumvecs[sumvecs["NODENAME"] == nodename] nodedict = get_nodedict(gruptree, nodename) @@ -593,15 +592,11 @@ def create_leafnodetype_maps( ) sumprod = sum( - [ - smry[sumvec].sum() - for sumvec in prod_sumvecs - if sumvec in smry.columns - ] + smry[sumvec].sum() for sumvec in prod_sumvecs if sumvec in smry.columns ) suminj = sum( - [smry[sumvec].sum() for sumvec in inj_sumvecs if sumvec in smry.columns] + smry[sumvec].sum() for sumvec in inj_sumvecs if sumvec in smry.columns ) is_prod_map[nodename] = sumprod > 0 diff --git a/webviz_subsurface/plugins/_line_plotter_fmu/figures/plotly_line_plot.py b/webviz_subsurface/plugins/_line_plotter_fmu/figures/plotly_line_plot.py index 4856e9379..4259bcea2 100644 --- a/webviz_subsurface/plugins/_line_plotter_fmu/figures/plotly_line_plot.py +++ b/webviz_subsurface/plugins/_line_plotter_fmu/figures/plotly_line_plot.py @@ -207,7 +207,7 @@ def get_figure(self) -> Dict: traces.extend(self._statistical_traces) if self._observation_traces: traces.extend(self._observation_traces) - return dict(layout=self._layout, data=traces) + return {"layout": self._layout, "data": traces} def set_real_color(df_norm: pd.DataFrame, real_no: str) -> str: diff --git a/webviz_subsurface/plugins/_map_viewer_fmu/_layer_model.py b/webviz_subsurface/plugins/_map_viewer_fmu/_layer_model.py index 6772d5666..227cf3e25 100644 --- a/webviz_subsurface/plugins/_map_viewer_fmu/_layer_model.py +++ b/webviz_subsurface/plugins/_map_viewer_fmu/_layer_model.py @@ -1,7 +1,8 @@ import warnings -from enum import Enum from typing import Dict, List +from webviz_subsurface._utils.enum_shim import StrEnum + from ._types import LayerTypes @@ -11,7 +12,7 @@ class DeckGLMapLayersModel: def __init__(self, layers: List[Dict]) -> None: self._layers = layers - def _update_layer_by_type(self, layer_type: Enum, layer_data: Dict) -> None: + def _update_layer_by_type(self, layer_type: StrEnum, layer_data: Dict) -> None: """Update a layer specification by the layer type. If multiple layers are found, no update is performed.""" layers = list(filter(lambda x: x["@@type"] == layer_type, self._layers)) diff --git a/webviz_subsurface/plugins/_map_viewer_fmu/_tmp_well_pick_provider.py b/webviz_subsurface/plugins/_map_viewer_fmu/_tmp_well_pick_provider.py index 8e92708d9..0ed96028b 100644 --- a/webviz_subsurface/plugins/_map_viewer_fmu/_tmp_well_pick_provider.py +++ b/webviz_subsurface/plugins/_map_viewer_fmu/_tmp_well_pick_provider.py @@ -1,11 +1,12 @@ -from enum import Enum from typing import Dict, List, Optional import geojson import pandas as pd +from webviz_subsurface._utils.enum_shim import StrEnum -class WellPickTableColumns(str, Enum): + +class WellPickTableColumns(StrEnum): X_UTME = "X_UTME" Y_UTMN = "Y_UTMN" Z_TVDSS = "Z_TVDSS" diff --git a/webviz_subsurface/plugins/_map_viewer_fmu/_types.py b/webviz_subsurface/plugins/_map_viewer_fmu/_types.py index 025bb306a..7f786e743 100644 --- a/webviz_subsurface/plugins/_map_viewer_fmu/_types.py +++ b/webviz_subsurface/plugins/_map_viewer_fmu/_types.py @@ -1,7 +1,7 @@ -from enum import Enum +from webviz_subsurface._utils.enum_shim import StrEnum -class LayerTypes(str, Enum): +class LayerTypes(StrEnum): HILLSHADING = "Hillshading2DLayer" MAP3D = "MapLayer" COLORMAP = "ColormapLayer" @@ -12,7 +12,7 @@ class LayerTypes(str, Enum): GEOJSON = "GeoJsonLayer" -class LayerNames(str, Enum): +class LayerNames(StrEnum): HILLSHADING = "Surface (hillshading)" MAP3D = "3D Map" COLORMAP = "Surface (color)" @@ -23,7 +23,7 @@ class LayerNames(str, Enum): GEOJSON = "GeoJsonLayer" -class SurfaceMode(str, Enum): +class SurfaceMode(StrEnum): MEAN = "Mean" REALIZATION = "Single realization" OBSERVED = "Observed" diff --git a/webviz_subsurface/plugins/_map_viewer_fmu/callbacks.py b/webviz_subsurface/plugins/_map_viewer_fmu/callbacks.py index a49980b7a..85f08e7a2 100644 --- a/webviz_subsurface/plugins/_map_viewer_fmu/callbacks.py +++ b/webviz_subsurface/plugins/_map_viewer_fmu/callbacks.py @@ -539,9 +539,7 @@ def _update_map( colorTables=color_tables, ), wsc.ViewFooter( - children=make_viewport_label( - surface_elements[idx], tab_name, multi - ) + children=make_viewport_label(data, tab_name, multi) ), ], ) @@ -558,7 +556,7 @@ def _update_map( f"{LayoutElements.FAULTPOLYGONS_LAYER}-{idx}", f"{LayoutElements.WELLS_LAYER}-{idx}", ], - "name": make_viewport_label(surface_elements[idx], tab_name, multi), + "name": make_viewport_label(data, tab_name, multi), } ) updated_view_layout = view_layout(len(surface_elements), view_columns) @@ -1041,7 +1039,7 @@ def view_layout(views: int, columns: Optional[int] = None) -> List[int]: columns = ( columns if columns is not None - else min([x for x in range(1, 20, 1) if (x * x) >= views]) + else min(x for x in range(1, 20, 1) if (x * x) >= views) ) rows = math.ceil(views / columns) return [rows, columns] diff --git a/webviz_subsurface/plugins/_map_viewer_fmu/layout.py b/webviz_subsurface/plugins/_map_viewer_fmu/layout.py index b7cb940fa..492b55499 100644 --- a/webviz_subsurface/plugins/_map_viewer_fmu/layout.py +++ b/webviz_subsurface/plugins/_map_viewer_fmu/layout.py @@ -1,16 +1,18 @@ -from enum import Enum, unique +from enum import unique from typing import Any, Callable, Dict, List, Union import webviz_core_components as wcc from dash import dcc, html from webviz_subsurface_components import DashSubsurfaceViewer # type: ignore +from webviz_subsurface._utils.enum_shim import StrEnum + from ._types import LayerNames, LayerTypes, SurfaceMode from ._utils import create_colormap_image_string, round_to_significant @unique -class LayoutElements(str, Enum): +class LayoutElements(StrEnum): """Contains all ids used in plugin. Note that some id's are used as combinations of LEFT/RIGHT_VIEW together with other elements to support pattern matching callbacks.""" @@ -48,7 +50,7 @@ class LayoutElements(str, Enum): OPTIONS_DIALOG = "options-dialog" -class LayoutLabels(str, Enum): +class LayoutLabels(StrEnum): """Text labels used in layout components""" ATTRIBUTE = "Surface attribute" @@ -99,21 +101,21 @@ class LayoutStyle: } -class Tabs(str, Enum): +class Tabs(StrEnum): CUSTOM = "custom" STATS = "stats" DIFF = "diff" SPLIT = "split" -class TabsLabels(str, Enum): +class TabsLabels(StrEnum): CUSTOM = "Custom view" STATS = "Map statistics" DIFF = "Difference between two maps" SPLIT = "Maps per selector" -class MapSelector(str, Enum): +class MapSelector(StrEnum): ENSEMBLE = "ensemble" ATTRIBUTE = "attribute" NAME = "name" @@ -122,7 +124,7 @@ class MapSelector(str, Enum): REALIZATIONS = "realizations" -class ColorSelector(str, Enum): +class ColorSelector(StrEnum): COLORMAP = "colormap" COLOR_RANGE = "color_range" diff --git a/webviz_subsurface/plugins/_prod_misfit/utils/make_figures.py b/webviz_subsurface/plugins/_prod_misfit/utils/make_figures.py index 5de6d1bf2..a903ae953 100644 --- a/webviz_subsurface/plugins/_prod_misfit/utils/make_figures.py +++ b/webviz_subsurface/plugins/_prod_misfit/utils/make_figures.py @@ -243,9 +243,13 @@ def _calculate_misfits( plot_phases = [] color_phases = {} - phase_misfit_name = dict(Oil="OIL_MISFIT", Water="WAT_MISFIT", Gas="GAS_MISFIT") - diff_name = dict(Oil="DIFF_WOPT", Water="DIFF_WWPT", Gas="DIFF_WGPT") - color = dict(Oil="#2ca02c", Water="#1f77b4", Gas="#d62728") + phase_misfit_name = { + "Oil": "OIL_MISFIT", + "Water": "WAT_MISFIT", + "Gas": "GAS_MISFIT", + } + diff_name = {"Oil": "DIFF_WOPT", "Water": "DIFF_WWPT", "Gas": "DIFF_WGPT"} + color = {"Oil": "#2ca02c", "Water": "#1f77b4", "Gas": "#d62728"} for phase in phases: phase_columns = [x for x in all_columns if x.startswith(diff_name[phase])] @@ -310,7 +314,7 @@ def _create_fig_barplot( fig.update_yaxes(title_text="Cumulative misfit") fig.add_hline(mean_misfit) fig.add_annotation(average_arrow_annotation(mean_misfit)) - fig.update_layout(margin=dict(l=20, r=20, t=30, b=20)) + fig.update_layout(margin={"l": 20, "r": 20, "t": 30, "b": 20}) # fig.update_layout(coloraxis_colorbar_thickness=20) # fig.update(layout_coloraxis_showscale=False) @@ -342,7 +346,7 @@ def _create_fig_diffplot( phase_columns = [x for x in all_columns if x.startswith(phase_vector[phase])] phase_well_labels = [col.split(":")[1] for col in phase_columns] - text_labels = dict(value=f"{phase} diff (sim-obs)", variable="Well name") + text_labels = {"value": f"{phase} diff (sim-obs)", "variable": "Well name"} if boxplot_points == "strip": fig_phase = px.strip( diff --git a/webviz_subsurface/plugins/_pvt_plot/_views/_pvt/_settings/_data_settings.py b/webviz_subsurface/plugins/_pvt_plot/_views/_pvt/_settings/_data_settings.py index 3e4f0ac84..52de9f20b 100644 --- a/webviz_subsurface/plugins/_pvt_plot/_views/_pvt/_settings/_data_settings.py +++ b/webviz_subsurface/plugins/_pvt_plot/_views/_pvt/_settings/_data_settings.py @@ -55,18 +55,19 @@ def phases(self) -> Dict[str, str]: return phase_descriptions def layout(self) -> List[Component]: - self._ensemble_properties = dict( - id=self.register_component_unique_id(DataSettings.Ids.ENSEMBLES), - label="Ensembles", - options=[{"label": x, "value": x} for x in self.ensembles], - vertical=True, - ) - self._pvtnum_properties = dict( - id=self.register_component_unique_id(DataSettings.Ids.PVTNUM), - label="Pvtnum", - options=[{"label": x, "value": x} for x in self.pvtnum], - vertical=True, - ) + self._ensemble_properties = { + "id": self.register_component_unique_id(DataSettings.Ids.ENSEMBLES), + "label": "Ensembles", + "options": [{"label": x, "value": x} for x in self.ensembles], + "vertical": True, + } + + self._pvtnum_properties = { + "id": self.register_component_unique_id(DataSettings.Ids.PVTNUM), + "label": "Pvtnum", + "options": [{"label": x, "value": x} for x in self.pvtnum], + "vertical": True, + } return [ wcc.RadioItems( diff --git a/webviz_subsurface/plugins/_reservoir_simulation_timeseries_onebyone.py b/webviz_subsurface/plugins/_reservoir_simulation_timeseries_onebyone.py index 5d4cb846f..1849638f7 100644 --- a/webviz_subsurface/plugins/_reservoir_simulation_timeseries_onebyone.py +++ b/webviz_subsurface/plugins/_reservoir_simulation_timeseries_onebyone.py @@ -594,8 +594,8 @@ def _render_tornado( # pylint: disable=too-many-branches, too-many-locals date = date_click["points"][0]["x"] if figure is None: raise PreventUpdate - ymin = min([min(trace["y"]) for trace in figure["data"]]) - ymax = max([max(trace["y"]) for trace in figure["data"]]) + ymin = min(min(trace["y"]) for trace in figure["data"]) + ymax = max(max(trace["y"]) for trace in figure["data"]) figure["layout"]["shapes"] = [ {"type": "line", "x0": date, "x1": date, "y0": ymin, "y1": ymax} ] diff --git a/webviz_subsurface/plugins/_running_time_analysis_fmu.py b/webviz_subsurface/plugins/_running_time_analysis_fmu.py index e4c7bd118..365b4695c 100644 --- a/webviz_subsurface/plugins/_running_time_analysis_fmu.py +++ b/webviz_subsurface/plugins/_running_time_analysis_fmu.py @@ -522,7 +522,7 @@ def render_parcoord( layout.update(theme["layout"]) # Ensure sufficient spacing between each dimension and margin for labels width = len(dimensions) * 100 + 250 - margin_b = max([len(param) for param in params]) * 8 + margin_b = max(len(param) for param in params) * 8 layout.update({"width": width, "height": 800, "margin": {"b": margin_b, "t": 30}}) return {"data": [data], "layout": layout} diff --git a/webviz_subsurface/plugins/_seismic_misfit.py b/webviz_subsurface/plugins/_seismic_misfit.py index cd508ecc8..285f92548 100644 --- a/webviz_subsurface/plugins/_seismic_misfit.py +++ b/webviz_subsurface/plugins/_seismic_misfit.py @@ -2114,7 +2114,7 @@ def update_misfit_plot( fig.update_yaxes(title_text="Cumulative misfit") fig.add_hline(mean_diff) fig.add_annotation(average_arrow_annotation(mean_diff, "y")) - fig.update_layout(margin=dict(l=20, r=20, t=30, b=20)) + fig.update_layout(margin={"l": 20, "r": 20, "t": 30, "b": 20}) fig.update_layout(coloraxis_colorbar_thickness=20) # fig.update(layout_coloraxis_showscale=False) @@ -2273,7 +2273,7 @@ def update_obsdata_map( fig.update_layout(coloraxis_colorbar_yanchor="top") fig.update_layout(coloraxis_colorbar_len=0.9) fig.update_layout(coloraxis_colorbar_thickness=20) - fig.update_traces(marker=dict(size=marker_size), selector=dict(mode="markers")) + fig.update_traces(marker={"size": marker_size}, selector={"mode": "markers"}) fig.update_layout(uirevision="true") # don't update layout during callbacks @@ -2350,18 +2350,18 @@ def update_obs_sim_map_plot( x=ensdf_stat["east"], y=ensdf_stat["north"], mode="markers", - marker=dict( - size=marker_size, - color=ensdf["obs"], - colorscale=color_scale, - colorbar_x=0.29, - colorbar_thicknessmode="fraction", - colorbar_thickness=0.02, - colorbar_len=0.9, - cmin=range_col[0], - cmax=range_col[1], - showscale=True, - ), + marker={ + "size": marker_size, + "color": ensdf["obs"], + "colorscale": color_scale, + "colorbar_x": 0.29, + "colorbar_thicknessmode": "fraction", + "colorbar_thickness": 0.02, + "colorbar_len": 0.9, + "cmin": range_col[0], + "cmax": range_col[1], + "showscale": True, + }, showlegend=False, text=ensdf.obs, customdata=list(zip(ensdf.region, ensdf.east)), @@ -2379,18 +2379,18 @@ def update_obs_sim_map_plot( x=ensdf_stat["east"], y=ensdf_stat["north"], mode="markers", - marker=dict( - size=marker_size, - color=ensdf_stat["sim_mean"], - colorscale=color_scale, - colorbar_x=0.63, - colorbar_thicknessmode="fraction", - colorbar_thickness=0.02, - colorbar_len=0.9, - cmin=range_col[0], - cmax=range_col[1], - showscale=True, - ), + marker={ + "size": marker_size, + "color": ensdf["sim_mean"], + "colorscale": color_scale, + "colorbar_x": 0.63, + "colorbar_thicknessmode": "fraction", + "colorbar_thickness": 0.02, + "colorbar_len": 0.9, + "cmin": range_col[0], + "cmax": range_col[1], + "showscale": True, + }, showlegend=False, text=ensdf_stat.sim_mean, customdata=list(zip(ensdf.region, ensdf.east)), @@ -2409,18 +2409,18 @@ def update_obs_sim_map_plot( x=ensdf_stat["east"], y=ensdf_stat["north"], mode="markers", - marker=dict( - size=marker_size, - color=ensdf_stat["diff_mean"], - cmin=0, - cmax=obs_range[1] * scale_col_range, - colorscale=SEISMIC_DIFF, - colorbar_x=0.97, - colorbar_thicknessmode="fraction", - colorbar_thickness=0.02, - colorbar_len=0.9, - showscale=True, - ), + marker={ + "size": marker_size, + "color": ensdf_stat["diff_mean"], + "cmin": 0, + "cmax": obs_range[1] * scale_col_range, + "colorscale": SEISMIC_DIFF, + "colorbar_x": 0.97, + "colorbar_thicknessmode": "fraction", + "colorbar_thickness": 0.02, + "colorbar_len": 0.9, + "showscale": True, + }, showlegend=False, text=ensdf_stat.diff_mean, customdata=list(zip(ensdf.region, ensdf.east)), @@ -2439,23 +2439,22 @@ def update_obs_sim_map_plot( x=ensdf_stat["east"], y=ensdf_stat["north"], mode="markers", - marker=dict( - size=marker_size, - color=ensdf_stat[coverage], - cmin=-1.0, - cmax=2.0, - colorscale=SEISMIC_COVERAGE, - colorbar=dict( - # title="Coverage", - tickvals=[-0.5, 0.5, 1.5], - ticktext=["Overmodelled", "Coverage", "Undermodelled"], - ), - colorbar_x=0.97, - colorbar_thicknessmode="fraction", - colorbar_thickness=0.02, - colorbar_len=0.9, - showscale=True, - ), + marker={ + "size": marker_size, + "color": ensdf_stat["coverage"], + "cmin": -1.0, + "cmax": 2.0, + "colorscale": SEISMIC_COVERAGE, + "colorbar": { + "tickvals": [-0.5, 0.5, 1.5], + "ticktext": ["Overmodelled", "Coverage", "Undermodelled"], + }, + "colorbar_x": 0.97, + "colorbar_thicknessmode": "fraction", + "colorbar_thickness": 0.02, + "colorbar_len": 0.9, + "showscale": True, + }, opacity=0.5, showlegend=False, text=ensdf_stat[coverage], @@ -2474,16 +2473,16 @@ def update_obs_sim_map_plot( x=ensdf["east"], y=ensdf["north"], mode="markers", - marker=dict( - size=marker_size, - color=ensdf.region, - colorscale=px.colors.qualitative.Plotly, - colorbar_x=0.97, - colorbar_thicknessmode="fraction", - colorbar_thickness=0.02, - colorbar_len=0.9, - showscale=False, - ), + marker={ + "size": marker_size, + "color": ensdf.region, + "colorscale": px.colors.qualitative.Plotly, + "colorbar_x": 0.97, + "colorbar_thicknessmode": "fraction", + "colorbar_thickness": 0.02, + "colorbar_len": 0.9, + "showscale": False, + }, opacity=0.8, showlegend=False, hovertemplate="Region: %{text}", @@ -2550,8 +2549,8 @@ def update_obs_sim_map_plot( x=df_sliced_stat["east"], y=df_sliced_stat["obs"], mode="markers+lines", - marker=dict(color="red", size=5), - line=dict(width=2, dash="solid"), + marker={"color": "red", "size": 5}, + line={"width": 2, "dash": "solid"}, showlegend=True, ), go.Scatter( @@ -2559,8 +2558,8 @@ def update_obs_sim_map_plot( x=df_sliced_stat["east"], y=df_sliced_stat["sim_mean"], mode="markers+lines", - marker=dict(color="green", size=3), - line=dict(width=1, dash="dot"), + marker={"color": "green", "size": 3}, + line={"width": 1, "dash": "dot"}, showlegend=True, ), go.Scatter( @@ -2568,16 +2567,16 @@ def update_obs_sim_map_plot( x=df_sliced_stat["east"], y=df_sliced_stat["sim_p10"], mode="lines", - marker=dict(color="#444"), - line=dict(width=1), + marker={"color": "#444"}, + line={"width": 1}, showlegend=True, ), go.Scatter( name="Sim p90", x=df_sliced_stat["east"], y=df_sliced_stat["sim_p90"], - marker=dict(color="#444"), - line=dict(width=1), + marker={"color": "#444"}, + line={"width": 1}, mode="lines", fillcolor="rgba(68, 68, 68, 0.3)", fill="tonexty", @@ -2588,7 +2587,7 @@ def update_obs_sim_map_plot( x=df_sliced_stat["east"], y=df_sliced_stat["sim_min"], mode="lines", - line=dict(width=1, dash="dot", color="grey"), + line={"width": 1, "dash": "dot", "color": "grey"}, showlegend=True, ), go.Scatter( @@ -2596,7 +2595,7 @@ def update_obs_sim_map_plot( x=df_sliced_stat["east"], y=df_sliced_stat["sim_max"], mode="lines", - line=dict(width=1, dash="dot", color="grey"), + line={"width": 1, "dash": "dot", "color": "grey"}, showlegend=True, ), ] @@ -2630,8 +2629,8 @@ def update_obs_sim_map_plot( x=df_sliced_reals["east"], y=df_sliced_reals["obs"], mode="markers+lines", - marker=dict(color="red", size=7), - line=dict(width=5, dash="solid"), + marker={"color": "red", "size": 7}, + line={"width": 5, "dash": "solid"}, showlegend=True, ), ], @@ -2645,7 +2644,7 @@ def update_obs_sim_map_plot( y=df_sliced_reals[col], mode="lines", # "markers+lines", line_shape="linear", - line=dict(width=1, dash="dash"), + line={"width": 1, "dash": "dash"}, name=col, showlegend=True, hoverinfo="name", @@ -2758,7 +2757,7 @@ def update_crossplot( "data_number": True, }, ) - fig.update_traces(marker=dict(sizemode="area"), error_y_thickness=1.0) + fig.update_traces(marker={"sizemode": "area"}, error_y_thickness=1.0) fig.update_layout(uirevision="true") # don't update layout during callbacks # add zero/diagonal line @@ -2781,8 +2780,8 @@ def update_crossplot( # set marker line color = black (default is white) if sizeby is None: fig.update_traces( - marker=dict(line=dict(width=0.4, color="black")), - selector=dict(mode="markers"), + marker={"line": {"width": 0.4, "color": "black"}}, + selector={"mode": "markers"}, ) figures.append(wcc.Graph(figure=fig.to_dict(), style={"height": total_height})) @@ -2893,11 +2892,16 @@ def update_errorbarplot( "data_number": True, }, ) - fig.update_traces(error_y_thickness=1.0, selector=dict(type="scatter")) + fig.update_traces(error_y_thickness=1.0, selector={"type": "scatter"}) # ----------------------- obserrory = ( - dict(type="data", array=df_stat["obs_error"], visible=True, thickness=1.0) + { + "type": "data", + "array": df_stat["obs_error"], + "visible": True, + "thickness": 1.0, + } if showerrorbarobs is not None else None ) @@ -2969,12 +2973,12 @@ def update_errorbarplot_superimpose( errory = None if showerrorbar == "sim_std": - errory = dict( - type="data", - array=ensdf_stat[ens_name]["sim_std"], - visible=True, - thickness=1.0, - ) + errory = { + "type": "data", + "array": ensdf_stat[ens_name]["sim_std"], + "visible": True, + "thickness": 1.0, + } elif showerrorbar == "sim_p10_p90": ensdf_stat[ens_name]["error_plus"] = abs( ensdf_stat[ens_name]["sim_mean"] - ensdf_stat[ens_name]["sim_p10"] @@ -2982,14 +2986,14 @@ def update_errorbarplot_superimpose( ensdf_stat[ens_name]["error_minus"] = abs( ensdf_stat[ens_name]["sim_mean"] - ensdf_stat[ens_name]["sim_p90"] ) - errory = dict( - type="data", - symmetric=False, - array=ensdf_stat[ens_name]["error_plus"], - arrayminus=ensdf_stat[ens_name]["error_minus"], - visible=True, - thickness=1.0, - ) + errory = { + "type": "data", + "symmetric": False, + "array": ensdf_stat[ens_name]["error_plus"], + "arrayminus": ensdf_stat[ens_name]["error_minus"], + "visible": True, + "thickness": 1.0, + } # ------------------------------------------------------------- ensdf_stat[ens_name] = ensdf_stat[ens_name].sort_values(by=["region"]) @@ -3008,12 +3012,12 @@ def update_errorbarplot_superimpose( obserrory = None if showerrorbarobs is not None: - obserrory = dict( - type="data", - array=ensdf_stat[ens_name]["obs_error"], - visible=True, - thickness=1.0, - ) + obserrory = { + "type": "data", + "array": ensdf_stat[ens_name]["obs_error"], + "visible": True, + "thickness": 1.0, + } fig.add_scattergl( x=ensdf_stat[ens_name]["counter"], diff --git a/webviz_subsurface/plugins/_simulation_time_series_onebyone/_utils/_onebyone_timeseries_figure.py b/webviz_subsurface/plugins/_simulation_time_series_onebyone/_utils/_onebyone_timeseries_figure.py index 29445b679..92544f626 100644 --- a/webviz_subsurface/plugins/_simulation_time_series_onebyone/_utils/_onebyone_timeseries_figure.py +++ b/webviz_subsurface/plugins/_simulation_time_series_onebyone/_utils/_onebyone_timeseries_figure.py @@ -1,5 +1,4 @@ import datetime -from enum import Enum from typing import Dict, List, Optional import numpy as np @@ -12,13 +11,14 @@ rgba_to_str, scale_rgb_lightness, ) +from webviz_subsurface._utils.enum_shim import StrEnum from webviz_subsurface._utils.simulation_timeseries import ( get_simulation_line_shape, set_simulation_line_shape_fallback, ) -class Colors(str, Enum): +class Colors(StrEnum): RED = rgba_to_str((255, 18, 67, 1)) MID = rgba_to_str((220, 220, 220, 1)) GREEN = rgba_to_str((62, 208, 62, 1)) diff --git a/webviz_subsurface/plugins/_structural_uncertainty/figures/intersection.py b/webviz_subsurface/plugins/_structural_uncertainty/figures/intersection.py index 3f9933c1a..fd92b4351 100644 --- a/webviz_subsurface/plugins/_structural_uncertainty/figures/intersection.py +++ b/webviz_subsurface/plugins/_structural_uncertainty/figures/intersection.py @@ -1,4 +1,3 @@ -from enum import Enum from typing import Any, Dict, List, Optional import numpy as np @@ -7,6 +6,7 @@ from webviz_subsurface._models import SurfaceSetModel from webviz_subsurface._utils.colors import hex_to_rgba_str +from webviz_subsurface._utils.enum_shim import StrEnum from ...._utils.fanchart_plotting import ( FanchartData, @@ -16,7 +16,7 @@ ) -class FanChartStatistics(str, Enum): +class FanChartStatistics(StrEnum): MINIMUM = "Min" MAXIMUM = "Max" P10 = "P10" diff --git a/webviz_subsurface/plugins/_surface_with_grid_cross_section.py b/webviz_subsurface/plugins/_surface_with_grid_cross_section.py index 69696c2d0..cf48dcc30 100644 --- a/webviz_subsurface/plugins/_surface_with_grid_cross_section.py +++ b/webviz_subsurface/plugins/_surface_with_grid_cross_section.py @@ -344,8 +344,7 @@ def _render_fence(coords, gridparameter, surfacepath, color_values, colorscale): grid = load_grid(get_path(self.gridfile)) if ( grid.subgrids is not None - and sum([len(subgrid) for subgrid in grid.subgrids.values()]) - != grid.nlay + and sum(len(subgrid) for subgrid in grid.subgrids.values()) != grid.nlay ): warnings.warn( ( diff --git a/webviz_subsurface/plugins/_swatinit_qc/_business_logic.py b/webviz_subsurface/plugins/_swatinit_qc/_business_logic.py index 2ee7b43f8..987006e29 100644 --- a/webviz_subsurface/plugins/_swatinit_qc/_business_logic.py +++ b/webviz_subsurface/plugins/_swatinit_qc/_business_logic.py @@ -1,5 +1,4 @@ import re -from enum import Enum from pathlib import Path from typing import Callable, Dict, List, Optional, Tuple @@ -9,8 +8,10 @@ from webviz_config.common_cache import CACHE from webviz_config.webviz_store import webvizstore +from webviz_subsurface._utils.enum_shim import StrEnum -class QcFlags(str, Enum): + +class QcFlags(StrEnum): """Constants for use by check_swatinit""" FINE_EQUIL = "FINE_EQUIL" @@ -102,14 +103,14 @@ def colors(self) -> List[str]: def qc_flag_colors(self) -> Dict[str, str]: """Predefined colors for the QC_FLAG column""" return { - QcFlags.FINE_EQUIL.value: self.colors[8], - QcFlags.HC_BELOW_FWL.value: self.colors[5], - QcFlags.PC_SCALED.value: self.colors[2], - QcFlags.PPCWMAX.value: self.colors[9], - QcFlags.SWATINIT_1.value: self.colors[6], - QcFlags.SWL_TRUNC.value: self.colors[3], - QcFlags.UNKNOWN.value: self.colors[1], - QcFlags.WATER.value: self.colors[0], + QcFlags.FINE_EQUIL: self.colors[8], + QcFlags.HC_BELOW_FWL: self.colors[5], + QcFlags.PC_SCALED: self.colors[2], + QcFlags.PPCWMAX: self.colors[9], + QcFlags.SWATINIT_1: self.colors[6], + QcFlags.SWL_TRUNC: self.colors[3], + QcFlags.UNKNOWN: self.colors[1], + QcFlags.WATER: self.colors[0], } @property @@ -272,7 +273,7 @@ def get_percent_of_match(df: pd.DataFrame, condition: Optional[int]) -> float: def table_data_qc_vol_overview(self) -> tuple: """Return data and columns for dash_table showing overview of qc volumes""" - skip_if_zero = [QcFlags.UNKNOWN.value, QcFlags.WATER.value] + skip_if_zero = [QcFlags.UNKNOWN, QcFlags.WATER] column_order = [ "", "Response", @@ -293,7 +294,7 @@ def table_data_qc_vol_overview(self) -> tuple: } ) # Then report the volume change per QC_FLAG - for key in [x.value for x in QcFlags]: + for key in QcFlags: if key in skip_if_zero and np.isclose(qc_vols[key], 0, atol=1): # Tolerance is 1 rm3, which is small in relevant contexts. continue diff --git a/webviz_subsurface/plugins/_swatinit_qc/_figures.py b/webviz_subsurface/plugins/_swatinit_qc/_figures.py index 8c05c1443..73c7f1654 100644 --- a/webviz_subsurface/plugins/_swatinit_qc/_figures.py +++ b/webviz_subsurface/plugins/_swatinit_qc/_figures.py @@ -28,11 +28,11 @@ class WaterfallPlot: # Ensure fixed order of plot elements: ORDER = [ "SWATINIT_WVOL", - QcFlags.SWL_TRUNC.value, - QcFlags.PPCWMAX.value, - QcFlags.FINE_EQUIL.value, - QcFlags.HC_BELOW_FWL.value, - QcFlags.SWATINIT_1.value, + QcFlags.SWL_TRUNC, + QcFlags.PPCWMAX, + QcFlags.FINE_EQUIL, + QcFlags.HC_BELOW_FWL, + QcFlags.SWATINIT_1, "SWAT_WVOL", ] MEASURES = [ diff --git a/webviz_subsurface/plugins/_swatinit_qc/_layout.py b/webviz_subsurface/plugins/_swatinit_qc/_layout.py index d244b8012..c3adf4e3c 100644 --- a/webviz_subsurface/plugins/_swatinit_qc/_layout.py +++ b/webviz_subsurface/plugins/_swatinit_qc/_layout.py @@ -1,4 +1,4 @@ -from enum import Enum, auto +from enum import IntEnum, auto from typing import Any, Callable, List, Optional import pandas as pd @@ -15,7 +15,7 @@ # pylint: disable = too-few-public-methods -class LayoutElements(str, Enum): +class LayoutElements(IntEnum): PLOT_WRAPPER = auto() PLOT_SELECTOR = auto() TABLE_WRAPPER = auto() @@ -125,7 +125,7 @@ def __init__(self, children: List[Any]) -> None: class TabQqPlotLayout: - class MainPlots(str, Enum): + class MainPlots(IntEnum): WATERFALL = auto() PROP_VS_DEPTH = auto() diff --git a/webviz_subsurface/plugins/_swatinit_qc/_markdown.py b/webviz_subsurface/plugins/_swatinit_qc/_markdown.py index 2aef89e77..da14f2481 100644 --- a/webviz_subsurface/plugins/_swatinit_qc/_markdown.py +++ b/webviz_subsurface/plugins/_swatinit_qc/_markdown.py @@ -44,7 +44,6 @@ def check_swatinit_description() -> str: """ -# pylint: disable=anomalous-backslash-in-string def pc_columns_description() -> str: return f""" > **Column descriptions** @@ -53,7 +52,7 @@ def pc_columns_description() -> str: > - **PPCW** - Maximum capillary pressure after scaling > - **{SwatinitQcDataModel.COLNAME_THRESHOLD}** - Column showing how many percent of the pc-scaled dataset that match the user-selected threshold -*PPCW = PCOW_MAX \* PC_SCALING* +**PPCW = PCOW_MAX `*` PC_SCALING** A threshold for the maximum capillary scaling can be set in the menu. The table will show how many percent of the dataset that exceeds this value, and cells above the threshold will be shown in the map ➡️ diff --git a/webviz_subsurface/plugins/_vfp_analysis/_views/_vfp_view/_utils/_vfp_figure_builder.py b/webviz_subsurface/plugins/_vfp_analysis/_views/_vfp_view/_utils/_vfp_figure_builder.py index 8e2e69075..1418120a5 100644 --- a/webviz_subsurface/plugins/_vfp_analysis/_views/_vfp_view/_utils/_vfp_figure_builder.py +++ b/webviz_subsurface/plugins/_vfp_analysis/_views/_vfp_view/_utils/_vfp_figure_builder.py @@ -68,15 +68,15 @@ def add_vfp_curve( "hoverinfo": "y+x+text", "showlegend": False, "mode": "markers+lines", - "marker": dict( - cmax=cmax, - cmin=cmin, - cmid=(cmin + cmax) / 2, - color=[cvalue] * len(rates), - colorscale=[[0, RED], [0.5, MID_COLOR], [1, GREEN]], - showscale=showscale, - colorbar={"title": vfp_table.param_types[color_by].value}, - ), + "marker": { + "cmax": cmax, + "cmin": cmin, + "cmid": (cmin + cmax) / 2, + "color": [cvalue] * len(rates), + "colorscale": [[0, RED], [0.5, MID_COLOR], [1, GREEN]], + "showscale": showscale, + "colorbar": {"title": vfp_table.param_types[color_by].value}, + }, "line": {"color": _get_color(cmax, cmin, cvalue)}, } ) diff --git a/webviz_subsurface/plugins/_volumetric_analysis/controllers/distribution_controllers.py b/webviz_subsurface/plugins/_volumetric_analysis/controllers/distribution_controllers.py index b79f41dc2..725d7f1e6 100644 --- a/webviz_subsurface/plugins/_volumetric_analysis/controllers/distribution_controllers.py +++ b/webviz_subsurface/plugins/_volumetric_analysis/controllers/distribution_controllers.py @@ -117,23 +117,23 @@ def _update_page_custom(selections: dict, page_selected: str) -> tuple: ) if selections["Plot type"] == "bar" else False, - layout=dict( - title=dict( - text=( - f"{volume_description(selections['X Response'])}" + layout={ + "title": ( + { + "text": f"{volume_description(selections['X Response'])}" + ( f" [{volume_unit(selections['X Response'])}]" if selections["X Response"] in volumemodel.volume_columns else "" - ) - ), - x=0.5, - xref="paper", - font=dict(size=18), + ), + "x": 0.5, + "xref": "paper", + "font": {"size": 18}, + } ), - ), - yaxis=dict(showticklabels=True), + }, + yaxis={"showticklabels": True}, ) .add_annotation(fluid_annotation(selections)) .update_xaxes({"matches": None} if not selections["X axis matches"] else {}) @@ -236,8 +236,8 @@ def _update_page_per_zr(selections: dict, page_selected: str) -> list: color_discrete_sequence=selections["Colorscale"], color=selector, ) - .update_traces(marker_line=dict(color="#000000", width=1)) - .update_layout(margin=dict(l=10, b=10)) + .update_traces(marker_line={"color": "#000000", "width": 1}) + .update_layout(margin={"l": 10, "b": 10}) ) if not color else [] @@ -252,7 +252,12 @@ def _update_page_per_zr(selections: dict, page_selected: str) -> list: layout={"bargap": 0.05}, color_discrete_sequence=selections["Colorscale"], color=selections["Color by"], - xaxis=dict(type="category", tickangle=45, tickfont_size=17, title=None), + xaxis={ + "type": "category", + "tickangle": 45, + "tickfont_size": 17, + "title": None, + }, text_auto=get_text_format_bar_plot( responses=[selections["X Response"]], selections=selections, @@ -327,7 +332,7 @@ def _update_page_conv(selections: dict, page_selected: str) -> go.Figure: color="calculation", custom_data=["calculation", "index"], title=title, - yaxis=dict(showticklabels=True), + yaxis={"showticklabels": True}, ) .update_traces( hovertemplate=( @@ -339,10 +344,10 @@ def _update_page_conv(selections: dict, page_selected: str) -> go.Figure: ) .update_traces(line_color="black", selector={"name": "mean"}) .update_traces( - line=dict(color="firebrick", dash="dash"), selector={"name": "p10"} + line={"color": "firebrick", "dash": "dash"}, selector={"name": "p10"} ) .update_traces( - line=dict(color="royalblue", dash="dash"), selector={"name": "p90"} + line={"color": "royalblue", "dash": "dash"}, selector={"name": "p90"} ) .update_xaxes({"matches": None} if not selections["X axis matches"] else {}) .update_yaxes({"matches": None} if not selections["Y axis matches"] else {}) diff --git a/webviz_subsurface/plugins/_volumetric_analysis/controllers/tornado_controllers.py b/webviz_subsurface/plugins/_volumetric_analysis/controllers/tornado_controllers.py index 3fa1660cf..ce14fd89c 100644 --- a/webviz_subsurface/plugins/_volumetric_analysis/controllers/tornado_controllers.py +++ b/webviz_subsurface/plugins/_volumetric_analysis/controllers/tornado_controllers.py @@ -158,7 +158,8 @@ def _update_tornado_pages( else tornado_error_layout( "No data left after filtering" if dframe.empty - else f"Reference sensitivity '{selections['Reference']}' not in input data" + else f"Reference sensitivity '{selections['Reference']}' " + + "not in input data" ) ), "conditions": {"page": page_selected}, diff --git a/webviz_subsurface/plugins/_volumetric_analysis/utils/table_and_figure_utils.py b/webviz_subsurface/plugins/_volumetric_analysis/utils/table_and_figure_utils.py index 0d6555bd8..738a88f73 100644 --- a/webviz_subsurface/plugins/_volumetric_analysis/utils/table_and_figure_utils.py +++ b/webviz_subsurface/plugins/_volumetric_analysis/utils/table_and_figure_utils.py @@ -111,18 +111,19 @@ def fluid_table_style() -> list: def fluid_annotation(selections: dict) -> dict: fluid_text = (" + ").join(selections["filters"]["FLUID_ZONE"]) - return dict( - visible=bool(selections["Fluid annotation"]) + + return { + "visible": bool(selections["Fluid annotation"]) and selections["Subplots"] != "FLUID_ZONE", - x=1, - y=1, - xref="paper", - yref="paper", - showarrow=False, - text="Fluid zone
" + fluid_text, - font=dict(size=15, color="black"), - bgcolor="#E8E8E8", - ) + "x": 1, + "y": 1, + "xref": "paper", + "yref": "paper", + "showarrow": False, + "text": "Fluid zone
" + fluid_text, + "font": {"size": 15, "color": "black"}, + "bgcolor": "#E8E8E8", + } def add_correlation_line(figure: go.Figure, xy_min: float, xy_max: float) -> go.Figure: @@ -135,7 +136,7 @@ def add_correlation_line(figure: go.Figure, xy_min: float, xy_max: float) -> go. y0=xy_min, x1=xy_max, y1=xy_max, - line=dict(color="black", width=2, dash="dash"), + line={"color": "black", "width": 2, "dash": "dash"}, ) @@ -156,7 +157,7 @@ def update_tornado_figures_xaxis(figures: List[go.Figure]) -> None: Update the x-axis range for a list of tornado figures with the maximum absolute x-value from all figures. Axis will be centered around 0. """ - x_absmax = max([max(abs(trace.x)) for fig in figures for trace in fig.data]) + x_absmax = max(max(abs(trace.x)) for fig in figures for trace in fig.data) for fig in figures: fig.update_layout(xaxis_range=[-x_absmax, x_absmax]) diff --git a/webviz_subsurface/plugins/_well_analysis/_views/_well_control_view/_utils/_well_control_figure.py b/webviz_subsurface/plugins/_well_analysis/_views/_well_control_view/_utils/_well_control_figure.py index 8539f5e89..31af39740 100644 --- a/webviz_subsurface/plugins/_well_analysis/_views/_well_control_view/_utils/_well_control_figure.py +++ b/webviz_subsurface/plugins/_well_analysis/_views/_well_control_view/_utils/_well_control_figure.py @@ -162,7 +162,6 @@ def add_network_pressure_traces( def add_ctrlmode_bar( fig: go.Figure, node_info: Dict, smry: pd.DataFrame, real: int, chart_row: int ) -> None: - # pylint: disable=too-many-locals """Adding area traces to the single realization control mode bar""" sumvec = node_info["ctrlmode_sumvec"] categories = get_ctrlmode_categories(node_info["type"])