Visualize

To visualize the data effectively several plotting functions have been created.

Note

Please see the extensive example for some examples on how to use this module.

class visualize.VisualizeModel(image_path, model=None, models=None, rate_constant_optimizer=None, plot_title=None, hide_params=None, dpi=600, extensions=None, overwrite_image=False)

Contains several methods which help creating plots. The methods are split into three main groups:

  1. Visualization of OptimizedModels

  2. Visualization of OptimizedMultipleModels

  3. Visualization of other data that is provided by the user.

Each method will save the figure where the name is equal to the function name.

Parameters:
  • image_path (str | pathlib.Path) – The path to the folder where the created images should be stored.

  • model (Optional[OptimizedModel]) – A single optimized model of which plots should be created. If None, and models is not None, the best model in models will be used instead. This will issue a warning once.

  • models (Optional[OptimizedMultipleModels]) – Multiple optimized models of which plots should be created. If model is None, the best model in models will be used instead.

  • rate_constant_optimizer (Optional[RateConstantOptimizerTemplate]) – The user implemented class of optimize.RateConstantOptimizerTemplate. Required by some functions.

  • plot_title (Optional[str]) – The title (plt.Figure.suptitle) that will be given to each plot. If None (default), no title will be given.

  • hide_params (Optional[np.ndarray]) – A boolean array, which indicate if the respective parameter should be hidden If None (default), all parameters will be shown.

  • dpi (int) – The ‘density per inch’ that will be used when saving the images.

  • extensions (Optional[Iterable[str] | str]) – The file format(s) to which the image will be saved.

  • overwrite_image (bool) – If false (default), an FileExistsError will be raised if the image already exists. If true, the image will be overwritten.

Raises:

FileExistError – Raised if the image already exists.

save_image(fig, file_name, tight_layout=True)

Saves an image with all relevant extensions, and the correct dpi. It will be stored in the folder, specified by the image_path.

Parameters:
  • fig – The figure that is to be saved.

  • file_name – The file name for the figure.

  • tight_layout – If fig.tight_layout() should be called. Does not work with plot_path_in_pca.

plot_optimization_progress(*, file_name=None, ratio=None, n_points=100, **fig_kwargs)

Shows the error as function of the iteration number.

requires a single model

Parameters:
  • file_name (Optional[str]) – The file name for the image. This should not include any extension. If None (default), it is equal to ‘plot_optimization_progress’.

  • ratio (Optional[tuple[str, list[str]]]) – If None (default), only the error ratio will be shown. If given, the first element indicates the chemical of interest, and the second element the chemicals it is compared to. For example (‘A’, [‘A’, ‘B’]), calculates \(A / (A+B)\). It will plot the ratio for the last point in each prediction.

  • n_points (int) – The number of iterations for which the ratio will be re-calculated. These are uniformly distributed over all possible iterations.

  • **fig_kwargs – Additional keyword arguments that are passed on to plt.subplots().

Return type:

tuple[plt.Figure, plt.Axes]

plot_grouped_by(*args, file_name=None, group_by=None, show_remaining=True, xtick_rotation=0, **fig_kwargs)

Plots a bar plot of the data in args, and allows easy grouping with respect to their index. For example, plot_grouped_by(x1, x2) would create a bar plot of the two series, where, for each parameter, the values in x1 and x2 would be compared.

requires no model

Parameters:
  • *args (pd.Series) – The data that should be plotted. The name of each pd.Series will be used in the legend. The index of the first pd.Series object will be used to sort the groups with.

  • file_name (Optional[str]) – The file name for the image. This should not include any extension. If None (default), it is equal to ‘plot_grouped_by’.

  • group_by (Optional[list[str]]) – Group the parameters by a key. Each parameter can only be matched with one key exactly.

  • show_remaining (bool) – Show the parameters which were not matched by any key in group_as.

  • xtick_rotation (float) – The rotation of the x ticks in degrees.

  • **fig_kwargs – Additional keyword arguments that are passed on to plt.subplots().

Return type:

tuple[plt.Figure, np.ndarray[plt.Axes]]

plot_path_in_pca(*, file_name=None, pc1=0, pc2=1, **fig_kwargs)

Plots the path in the dimensionally reduced space (by means of principal component analysis). The data is standard-scaled (mean=0, std=1) before any analysis, to ensure that it is not the scale of a parameter, but its deviation, which impacts the plot.

requires a single model

Parameters:
  • file_name (Optional[str]) – The file name for the image. This should not include any extension. If None (default), it is equal to ‘plot_path_in_pca’.

  • pc1 (int) – The principal components that should be plotted against each other.

  • pc2 (int) – The principal components that should be plotted against each other.

  • **fig_kwargs – Additional keyword arguments that are passed on to plt.Figure().

Returns:

The figure, and axes of the plot. Axes[0] is the main plot, axes[1] describes the loadings of PC1, whereas axes[2] describes the loadings of PC2.

Return type:

tuple[plt.Figure, np.ndarray[plt.Axes]]

plot_enantiomer_ratio(group_by, ratio_of, experimental, prediction, *, file_name=None, last_N=100, warn_label_assumption=True, **fig_kwargs)

Groups the data (experimental or predicted), and calculates the fraction each chemical contributes to the total sum. E.g. group_as=[‘1’, ‘2’] and ratio_of=[‘A’, ‘B’, ‘C’] would look for hits with respect to those keys, and one of the calculated data points would be: 1_A / (1_A + 1_B + 1_C)

requires a single model

Parameters:
  • group_by (list[str]) – Groups the data by a key. Each index can only be matched with one key exactly.

  • ratio_of (list[str]) – Calculate the fraction each chemical contributes to the total sum of all chemicals in this group.

  • experimental (pd.DataFrame) – The experimental data of the experiment.

  • prediction (pd.DataFrame) – The predicted data. This is not computed within the class to allow the user to specify the indices of the prediction in more detail.

  • last_N (int) – The number of points counting from the end will be used to calculate the average ratio with.

  • file_name (Optional[str]) – The file name for the image. This should not include any extension. If None (default), it is equal to ‘plot_enantiomer_ratio’.

  • warn_label_assumption (bool) – If true (default), a warning will be issued when exactly two matches are found for each combination of the elements in group_as and ratio_of. This can be caused by e.g. both ‘3’ and ‘D’ being present in the strings “3_bla_D” and “3_bla_D-custom_label”. To resolve this tie the shorted string will be used as it is most likely to be the non-labeled compound.

  • **fig_kwargs – Additional keyword arguments that are passed on to plt.subplots().

Return type:

tuple[plt.Figure, plt.Axes]

plot_rate_over_time(*, file_name=None, x_min=None, x_max=None, log_scale=False, **fig_kwargs)

Plots the parameters, x, as a function of time.

requires a single model

Parameters:
  • file_name (Optional[str]) – The file name for the image. This should not include any extension. If None (default), it is equal to ‘plot_rate_over_time’.

  • x_min (Optional[float]) – The values smaller than x_min will be plotted as x_min.

  • x_max (Optional[float]) – The values larger than x_max will be plotted as x_max.

  • log_scale (bool) – If true the data will be plotted on log_scale.

  • **fig_kwargs – Additional keyword arguments that are passed on to plt.subplots().

Return type:

tuple[plt.Figure, plt.Axes]

plot_rate_sensitivity(x_min, x_max, *, file_name=None, max_error=None, steps=101, **fig_kwargs)

Plot the sensitivity of each parameter, x, to modifications. Only a single parameter is modified at once.

requires a single model

Parameters:
  • x_min (float) – The minimum value of x.

  • x_max (float) – The maximum value of x.

  • file_name (Optional[str]) – The file name for the image. This should not include any extension. If None (default), it is equal to ‘plot_rate_sensitivity’.

  • max_error (Optional[float]) – All values larger the maximum value will be plotted as the maximum error. If None (default), 3 times the lowest value error will be used.

  • steps (int) – The number of different values that will be modeled for each parameter.

  • **fig_kwargs – Additional keyword arguments that are passed on to plt.subplots().

Return type:

tuple[plt.Figure, plt.Axes]

plot_error_all_runs(top_n=None, *, file_name=None, **fig_kwargs)

Plots the error of each model.

requires multiple model

Parameters:
  • top_n (Optional[int]) – How many of the best runs should be plotted. If None (default), all runs will be plotted.

  • file_name (Optional[str]) – The file name for the image. This should not include any extension. If None (default), it is equal to ‘plot_error_all_runs’.

  • **fig_kwargs – Additional keyword arguments that are passed on to plt.subplots().

Return type:

tuple[plt.Figure, plt.Axes]

plot_ratio_all_runs(ratio, *, file_name=None, top_n=20, **fig_kwargs)

Plots the expected ratio with respect to each model, which are sorted on their performance.

requires multiple model

Parameters:
  • ratio (tuple[str, list[str]]) – The first element indicates the chemical of interest, and the second element the chemicals it is compared to. For example (‘A’, [‘A’, ‘B’]), calculates \(A/(A+B)\). It will plot the ratio for the last time point in each model.

  • top_n (Optional[int]) – How many of the best runs should be plotted.

  • file_name (Optional[str]) – The file name for the image. This should not include any extension. If None (default), it is equal to ‘plot_ratio_all_runs’.

  • **fig_kwargs – Additional keyword arguments that are passed on to plt.subplots().

Return type:

tuple[plt.Figure, plt.Axes]

plot_x_all_runs(index, *, file_name=None, **fig_kwargs)

Plots a boxplot of the parameters for the selected runs.

requires multiple model

Parameters:
  • index (slice) – The indices of the runs for which the parameters should be plotted. index=slice(1, 5) would plot the results of runs 1 upto and including 4, but the best run (0) would be skipped. index=slice(-5, None) would plot the results for the 5 worst models.

  • file_name (Optional[str]) – The file name for the image. This should not include any extension. If None (default), it is equal to ‘plot_x_all_runs’.

  • **fig_kwargs – Additional keyword arguments that are passed on to plt.subplots().

Return type:

tuple[plt.Figure, plt.Axes]

plot_biplot_all_runs(index, *, file_name=None, pc1=0, pc2=1, **fig_kwargs)

Plots a biplot of the initial and optimal parameters per run. This is a dimensionally reduced PCA plot, where the loadings and scores are plotted simultaneously. The data is standard-scaled (mean=0, std=1) before any analysis, to ensure that it is not the scale of a parameter, but its deviation, which impacts the plot.

requires multiple model

Parameters:
  • index (slice) – The indices of the runs, when sorted by error, for which the parameters should be plotted. index=slice(1, 5) would plot the results of runs 1 upto and including 4, but the best run (0) would be skipped. index=slice(-5, None) would plot the results for the 5 worst models.

  • pc1 (int) – The principal components that should be plotted against each other.

  • pc2 (int) – The principal components that should be plotted against each other.

  • file_name (Optional[str]) – The file name for the image. This should not include any extension. If None (default), it is equal to ‘plot_biplot_all_runs’.

  • **fig_kwargs – Additional keyword arguments that are passed on to plt.subplots().

Return type:

tuple[plt.Figure, plt.Axes]