Skip to content

Verification vs model from parameter space

verification_vs_model_from_parameter_space

A tool to verify a model against another model.

The parameter space explored during the verificationc can be a dataset or a ParameterSpace, e.g. built from a SpaceTool.

Attributes

Classes

CodeVerificationAgainstModelFromParameterSpace

CodeVerificationAgainstModelFromParameterSpace(
    root_directory: str | Path = root_directory,
    directory_naming_method: DirectoryNamingMethod = NUMBERED,
    working_directory: str | Path = working_directory,
)

Bases: BaseVerification

Perform a code verification on a model based on another model and a ParameterSpace.

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 description is missing.

  • directory_naming_method (DirectoryNamingMethod, default: NUMBERED ) –

    The description is missing.

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

    The description is missing.

Source code in src\vimseo\tools\verification\verification_vs_model_from_parameter_space.py
69
70
71
72
73
74
75
76
77
78
79
80
def __init__(
    self,
    root_directory: str | Path = config.root_directory,
    directory_naming_method: DirectoryNamingMethod = DirectoryNamingMethod.NUMBERED,
    working_directory: str | Path = config.working_directory,
):
    super().__init__(
        subtools=[DOETool(), DOETool(name="ReferenceDOETool")],
        root_directory=root_directory,
        directory_naming_method=directory_naming_method,
        working_directory=working_directory,
    )
Attributes
grammar property
grammar

The validation grammar.

metric_names instance-attribute
metric_names: Iterable[str]

The name of the metrics used to compute the error between predictions and references.

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

The results of the tool.

Methods:
execute
execute(
    inputs: (
        CodeVerificationAgainstModelFromPSInputs | None
    ) = None,
    settings: (
        CodeVerificationAgainstModelFromPSSettings | None
    ) = None,
    **options
) -> VerificationResult

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

Parameters:

  • options –

    The options of the execution.

Source code in src\vimseo\tools\verification\verification_vs_model_from_parameter_space.py
 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
@BaseCompositeTool.validate
def execute(
    self,
    inputs: CodeVerificationAgainstModelFromPSInputs | None = None,
    settings: CodeVerificationAgainstModelFromPSSettings | None = None,
    **options,
) -> VerificationResult:
    model = options["model"]
    reference_model = options["reference_model"]

    self._output_names = (
        reference_model.get_output_data_names(remove_metadata=True)
        if not options["output_names"]
        else options["output_names"]
    )
    check_output_names(self._output_names, model)

    self.result._fill_metadata(options["description"], model.description)
    self.result.metadata.misc["reference_model"] = reference_model.description

    doe_dataset = (
        self
        ._subtools["DOETool"]
        .execute(
            model=model,
            parameter_space=options["parameter_space"],
            output_names=self.get_extended_output_names(),
            n_samples=options["n_samples"],
            algo=options["algo"],
            # algo_options=options["algo_options"],
        )
        .dataset
    )
    reference_doe_dataset = (
        self
        ._subtools["ReferenceDOETool"]
        .execute(
            model=reference_model,
            parameter_space=options["parameter_space"],
            output_names=self._output_names,
            n_samples=options["n_samples"],
            algo=options["algo"],
            # algo_options=options["algo_options"],
        )
        .dataset
    )

    element_wise_metrics, integrated_metrics = self._compute_comparison(
        reference_doe_dataset, doe_dataset
    )
    simulation_and_reference, element_wise_metrics = self._post(
        doe_dataset, reference_doe_dataset, element_wise_metrics
    )
    self.result.simulation_and_reference = simulation_and_reference
    self.result.element_wise_metrics = element_wise_metrics
    self.result.integrated_metrics = integrated_metrics

    return self.result
get_extended_output_names
get_extended_output_names()

Adds the CPU_TIME metadata variable name to the output names.

Source code in src\vimseo\tools\verification\base_verification.py
350
351
352
353
354
355
356
def get_extended_output_names(self):
    """Adds the CPU_TIME metadata variable name to the output names."""
    return (
        [*self._output_names, MetaDataNames.cpu_time]
        if [MetaDataNames.cpu_time] not in self._output_names
        else self._output_names
    )
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
plot_results(
    result: VerificationResult,
    metric_name,
    output_name: str,
    save=False,
    show=True,
    directory_path: str | Path = "",
    file_format="html",
) -> Mapping[str, Figure]

Plot a line plot of simulated versus reference results, and a bar plot of metrics values.

Parameters:

  • result (VerificationResult) –

    The result of the tool.

  • metric_name –

    The name of the metric to visualize.

  • output_name (str) –

    The name of the output variable to visualize.

  • save –

    Whether to save the plot on disk.

  • show –

    Whether to show the plot.

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

    The path under which the plots are saved.

  • file_format –

    The format to which plots are generated.

Source code in src\vimseo\tools\verification\base_verification.py
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
def plot_results(
    self,
    result: VerificationResult,
    metric_name,
    output_name: str,
    save=False,
    show=True,
    directory_path: str | Path = "",
    file_format="html",
) -> Mapping[str, Figure]:
    """Plot a line plot of simulated versus reference results, and a bar plot of
    metrics values.

    Args:
        metric_name: The name of the metric to visualize.
        output_name: The name of the output variable to visualize.
        file_format: The format to which plots are generated.
    """
    working_directory = (
        self.working_directory if directory_path == "" else Path(directory_path)
    )

    figures = {}

    if metric_name:
        ds = prepare_overall_dataset(
            result,
            [metric_name],
            result.simulation_and_reference.get_variable_names(
                IODataset.OUTPUT_GROUP
            ),
            renamer=comparison_renaming,
            add_output_data=True,
        )
    else:
        ds = result.element_wise_metrics

    if get_nb_input_variables(result.element_wise_metrics) > 1:
        scatter_matrix = ScatterMatrix(
            ds,
            variable_names=result.element_wise_metrics.get_variable_names(
                group_name=IODataset.INPUT_GROUP
            ),
            kde=False,
        )
        fig = scatter_matrix.execute(
            save=save,
            show=show,
            file_format="png",
            directory_path=(
                self.working_directory
                if directory_path == ""
                else Path(directory_path)
            ),
            file_name="scatter_matrix",
        )[0]
        figures["input_scatter_matrix"] = fig

    histogram = ErrorMetricHistogramPlotter()
    histogram.working_directory = (
        working_directory if directory_path == "" else Path(directory_path)
    )
    histogram.execute(
        result.element_wise_metrics, metric_name, output_name, show=show, save=save
    )
    figures["error_metric_histogram"] = histogram.result.figure

    return figures
save_results
save_results(
    prefix: str = "", file_format: str = "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.

Parameters:

  • prefix (str, default: '' ) –

    The description is missing.

  • file_format (str, default: 'hdf5' ) –

    The description is missing.

Source code in src\vimseo\tools\base_composite_tool.py
72
73
74
75
def save_results(self, prefix: str = "", file_format: str = "hdf5") -> None:
    super().save_results(prefix, file_format=file_format)
    for tool in self._subtools.values():
        tool.save_results(prefix, file_format=file_format)
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

Functions: