Skip to content

Convergence fit

convergence_fit

Classes

ConvergenceFitPlotter

ConvergenceFitPlotter(
    root_directory: str | Path = root_directory,
    directory_naming_method: DirectoryNamingMethod = NUMBERED,
    working_directory: str | Path = working_directory,
    **options
)

Bases: Plotter

A line plot of the output versus the element size, gathering every estimate of the converged value at a null element size.

It overlays, when available:

  • the reference (literature) Richardson extrapolation;
  • the power-law fit palliative (least-squares q_conv + C h^p over all grids, with its fitted order and RMS residual);
  • the model-free robust median palliative (median of the finest grids with its uncertainty band).

Unlike the Richardson-based plots, it stays informative when the three-point Richardson extrapolation fails (nan). The title states which estimate the tool selected as the converged value and flags explicitly when a palliative was used instead of Richardson.

Examples:

>>> from vimseo.tools.example_tool import MyTool
>>> tool = MyTool()
>>> tool.execute()
>>> print(tool.result)
# The result can be saved on disk.
>>> tool.save_results()
# Optionnaly, the current options of the tool can be saved on disk.
>>> tool.result.save_metadata_to_disk()
# The result saved on disk can be loaded.
>>> results = BaseTool.load_results(tool.working_directory /
>>> 'Tool_result.pickle')
# Then, the tool can plot the result. Note that the :meth:`plot_results` method
# takes the result as input. In the future, this method will be moved from the
# tools to a post processor class.
>>> tool.plot_results(results, save=True, show=False)
TODO allow passing pydantic model

Parameters:

  • root_directory (str | Path, default: root_directory ) –

    The path to the root directory, wherein unique directories will be created at each execution. If set to empty string, use the current working directory.

  • directory_naming_method (DirectoryNamingMethod, default: NUMBERED ) –

    The method to create the execution directories.

  • working_directory (str | Path, default: working_directory ) –

    The directory within which to save the results. If empty, save the results into the unique generated directory. Note that the use of a user-defined working_directory or an automatically generated unique directory is exclusive, and the choice is controlled by using leaving or not working_directory to its default value.

  • **options –

    The description is missing.

Source code in src\vimseo\tools\post_tools\base_plot.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def __init__(
    self,
    root_directory: str | Path = config.root_directory,
    directory_naming_method: DirectoryNamingMethod = DirectoryNamingMethod.NUMBERED,
    working_directory: str | Path = config.working_directory,
    **options,
):
    super().__init__(
        root_directory=root_directory,
        directory_naming_method=directory_naming_method,
        working_directory=working_directory,
        **options,
    )
    self.result = PlotResult()
Attributes
grammar property
grammar

The validation grammar.

option_names property
option_names

The names of the options that can be passed to execute().

options property
options

The options of the tool.

results instance-attribute
results: PlotResult

The results of the tool.

Methods:
execute
execute(
    result: SolutionVerificationResult,
    /,
    show: bool = False,
    save: bool = True,
)

The user-defined treatment called by :meth:execute.

Parameters:

  • options –

    The options of the execution.

Source code in src\vimseo\tools\post_tools\verification_plots\convergence_fit.py
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
@BaseTool.validate
def execute(
    self,
    result: SolutionVerificationResult,
    /,
    show: bool = False,
    save: bool = True,
):
    df = result.simulation_and_reference.copy()
    df.columns = result.simulation_and_reference.get_columns()
    if result.metadata.misc["element_size_variable_name"] == "degrees_of_freedom":
        element_size_variable_name = _DOF_ABSCISSA_NAME
    else:
        element_size_variable_name = result.metadata.misc[
            "element_size_variable_name"
        ]
    output_name = result.metadata.settings["output_name"]
    extrapolation = result.extrapolation

    element_sizes = df[element_size_variable_name].to_numpy()
    outputs = df[output_name].to_numpy()

    fig = Figure()
    fig.add_traces(
        go.Scatter(
            x=element_sizes,
            y=outputs,
            name=output_name,
            mode="lines+markers",
            marker_color="blue",
        )
    )

    # Reference (literature) Richardson extrapolation, if it could be computed.
    q_extrap = extrapolation.get("q_extrap")
    if q_extrap is not None and isfinite(q_extrap):
        fig.add_traces(
            go.Scatter(
                x=[0.0],
                y=[q_extrap],
                name="Richardson extrapolation",
                mode="markers",
                marker={"color": "red", "symbol": "circle", "size": 11},
                error_y={
                    "type": "data",
                    "array": [2.0 * extrapolation.get("q_extrap_mad", 0.0)],
                },
            )
        )

    # Palliative 1: least-squares power-law fit q_converged + C * h^order.
    q_converged_fit = extrapolation.get("q_converged_fit")
    order_fit = extrapolation.get("order_fit")
    coefficient_fit = extrapolation.get("fit_coefficient")
    if (
        q_converged_fit is not None
        and isfinite(q_converged_fit)
        and isfinite(order_fit)
    ):
        dense_sizes = linspace(0.0, float(element_sizes.max()), 100)
        fig.add_traces(
            go.Scatter(
                x=dense_sizes,
                y=q_converged_fit + coefficient_fit * dense_sizes**order_fit,
                name=(
                    f"power-law fit palliative (order={order_fit:.2f}, "
                    f"rmse={extrapolation['fit_rmse']:.2g})"
                ),
                mode="lines",
                line={"color": "green", "dash": "dash"},
            )
        )
        fig.add_traces(
            go.Scatter(
                x=[0.0],
                y=[q_converged_fit],
                name="q converged (power-law fit)",
                mode="markers",
                marker={"color": "green", "symbol": "square", "size": 10},
            )
        )

    # Palliative 2: model-free finest-grid median with its uncertainty band.
    q_converged_robust = extrapolation.get("q_converged_robust")
    band = extrapolation.get("q_converged_robust_band")
    if q_converged_robust is not None and isfinite(q_converged_robust):
        fig.add_traces(
            go.Scatter(
                x=[0.0],
                y=[q_converged_robust],
                name="q converged (robust median)",
                mode="markers",
                marker={"color": "chocolate", "symbol": "diamond", "size": 10},
                error_y={"type": "data", "array": [band]},
            )
        )

    # State the selected converged value and, crucially, whether it is the
    # reference Richardson method or a palliative substituted for it.
    q_converged = extrapolation.get("q_converged")
    method = extrapolation.get("q_converged_method", "")
    if q_converged is not None and isfinite(q_converged):
        title = f"Converged {output_name} = {q_converged:.4g}  (method: {method})"
    else:
        title = f"Convergence of {output_name}"
    fig.update_layout(title=title)
    fig.update_xaxes(title=element_size_variable_name)
    fig.update_yaxes(title=output_name)
    if save:
        fig.write_html(
            self.working_directory / f"convergence_fit_{output_name}.html"
        )
    if show:
        fig.show()
    self.result.figure = fig
    return fig
load_options_from_metadata
load_options_from_metadata(
    file_path: str | Path | None = None,
)

Load a result of a tool from the disk.

Parameters:

  • file_path (str | Path | None, default: None ) –

    The path to the file.

Source code in src\vimseo\tools\base_tool.py
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
def load_options_from_metadata(self, file_path: str | Path | None = None):
    """Load a result of a tool from the disk.

    Args:
        file_path: The path to the file.
    """
    file_path = (
        self._working_directory / f"{self.result.__class__.__name__}_metadata.json"
        if file_path is None
        else file_path
    )
    with Path(file_path).open() as f:
        loaded_metadata = json.load(f)
        if ToolResultMetadata._OPTIONS_KEY not in loaded_metadata:
            msg = f"Loaded options must contain the key '{ToolResultMetadata._OPTIONS_KEY}'"
            raise KeyError(msg)
        loaded_options = loaded_metadata[ToolResultMetadata._OPTIONS_KEY]
        if self._has_check_options:
            self._check_options(**loaded_options)
        self._options.update(loaded_options)
load_results classmethod
load_results(path: Path)

Load a result of a tool from the disk.

For a JSON file, only SpaceToolResult is supported. This method must be called from class SpaceTool. JSON format for tool results is deprecated.

Parameters:

  • path (Path) –

    The path to the file.

  • tool_name –

    The name of the tool associated with the result under stored

Source code in src\vimseo\tools\base_tool.py
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
@classmethod
def load_results(cls, path: Path):
    """Load a result of a tool from the disk.

    For a `JSON` file, only `SpaceToolResult` is supported.
    This method must be called from class `SpaceTool`.
    `JSON` format for tool results is deprecated.

    Args:
        path: The path to the file.
        tool_name: The name of the tool associated with the result under stored
        in ``path``.
    """
    import h5py

    path = Path(path)
    if path.suffix == ".hdf5":
        class_name = ""
        with h5py.File(path, "r") as f:
            class_name = f.attrs["__class__"]
        tmp_result = ToolResultsFactory().create(class_name)
        return type(tmp_result).from_hdf5(path)
    # TODO remove support for json
    if path.suffix == ".json":
        if cls.__name__ == "BaseTool":
            msg = (
                "Loading tool result from JSON format requires to call "
                "load_results from the tool class associated with the result stored "
                "in the JSON file."
            )
            raise ValueError(msg)
        LOGGER.warning("Loading tool results from JSON format is deprecated.")
        io = IOFactory().create(f"{cls.__name__}FileIO")
        return io.read(
            file_name=path,
        )
    if path.suffix == ".pickle":
        with Path(path).open("rb") as f:
            return pickle.load(f)

    msg = f"Unknow file format {path.suffix}. Supported formats are {cls._RESULT_FORMATS}"
    raise ValueError(msg)
plot_results abstractmethod
plot_results(
    result: BaseResult,
    directory_path: str | Path = "",
    save=False,
    show=True,
    **options
) -> Mapping[str, Figure]

Plot criteria for a given variable name.

Parameters:

  • result (BaseResult) –

    The result of the tool.

  • directory_path (str | Path, default: '' ) –

    The path under which the plots are saved.

  • save –

    Whether to save the plot on disk.

  • show –

    Whether to show the plot.

  • options –

    The options of the plot.

Source code in src\vimseo\tools\base_tool.py
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
@abstractmethod
def plot_results(
    self,
    result: BaseResult,
    directory_path: str | Path = "",
    save=False,
    show=True,
    **options,
) -> Mapping[str, Figure]:
    """Plot criteria for a given variable name.

    Args:
        result: The result of the tool.
        directory_path: The path under which the plots are saved.
        save: Whether to save the plot on disk.
        show: Whether to show the plot.
        options: The options of the plot.
    """
save_results
save_results(prefix: str = '', file_format='hdf5') -> None

Save the results of the tool on disk. The file path is BaseTool.working_directory / {filename}_result.{file_format}.

Args: prefix: The prefix of the filename result.

Source code in src\vimseo\tools\base_tool.py
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
def save_results(self, prefix: str = "", file_format="hdf5") -> None:
    """Save the results of the tool on disk. The file path is
    `BaseTool.working_directory` / ``{filename}_result.{file_format}``.

     Args:
         prefix: The prefix of the filename result.
    """
    prefix_separator = ""
    if prefix != "":
        prefix_separator = "_"

    path = (
        self.working_directory
        / f"{prefix}{prefix_separator}{self.name}{self._RESULT_SUFFIX}.{file_format}"
    )
    LOGGER.info(f"Saving result to {path.absolute().resolve()}")

    if file_format not in self._RESULT_FORMATS:
        msg = f"File format should be in {self._RESULT_FORMATS}"
        raise ValueError(msg)

    if file_format == "hdf5":
        self.result.to_hdf5(path)
    elif file_format == "json":
        io = IOFactory().create(f"{self.name}FileIO")
        io.write(self.result, directory_path=path.parent, file_base_name=path.stem)
    elif file_format == "pickle":
        self.result.to_pickle(path)
set_plot
set_plot(class_name, **options) -> None

Set the type of plot to show the results of this tool.

Parameters:

  • class_name –

    The name of the plot class.

  • **options –

    The options of the plot constructor.

Source code in src\vimseo\tools\base_tool.py
264
265
266
267
268
269
270
271
272
273
def set_plot(self, class_name, **options) -> None:
    """Set the type of plot to show the results of this tool.

    Args:
        class_name: The name of the plot class.
        **options: The options of the plot constructor.
    """
    if self._plot_factory:
        self._plot = self._plot_factory.create(class_name, **options)
    self._plot_class = class_name