tsunami_ip_utils.viz package
Submodules
tsunami_ip_utils.viz.matrix_plot module
This module contains the InteractiveMatrixPlot
class, which is a wrapper around a Dash app that displays a matrix of
interactive plots. The matrix is constructed from a 2D numpy array of plot objects, where each plot object is an instance of
either tsunami_ip_utils.viz.scatter_plot.InteractiveScatterLegend
or
tsunami_ip_utils.viz.pie_plot.InteractivePieLegend
. The matrix is displayed in a Dash app, where each plot object is
displayed in a separate cell. The user can interact with the plots by clicking on the legend to hide or show traces. The user
can also save the state of the interactive matrix plot to a pickle file and load it back later. The load_interactive_matrix_plot()
function is a convenience function that loads an interactive matrix plot from a saved state pickle file.
- class tsunami_ip_utils.viz.matrix_plot.InteractiveMatrixPlot(app, plot_objects_array, labels=None)[source]
Bases:
object
Interactive matrix plot class that displays a matrix of interactive plots in a Dash app. The matrix is constructed from a 2D numpy array of plot objects, where each plot object is an instance of either
tsunami_ip_utils.viz.scatter_plot.InteractiveScatterLegend
ortsunami_ip_utils.viz.pie_plot.InteractivePieLegend
. The matrix is displayed in a Dash app, where each plot object is displayed in a separate cell. The user can interact with the plots by clicking on the legend to hide or show traces. The user can also save the state of the interactive matrix plot to a pickle file and load it back later.- __init__(app, plot_objects_array, labels=None)[source]
Initialize the InteractiveMatrixPlot object with the Dash app and the 2D numpy array of plot objects.
- Parameters:
app (
Dash
) – Dash app object that displays the interactive matrix plot.plot_objects_array (
ndarray
) – 2D numpy array of plot objects to be displayed in the matrix plot.labels (
Optional
[Dict
[str
,List
]]) – Dictionary of lists containing the labels for the rows and columns of the matrix plot. Keys are'applications'
and'experiments'
. Default isNone
.
- show(open_browser=True, silent=False)[source]
Start the Flask server and open the browser to display the interactive sunburst chart
- Parameters:
open_browser (
bool
) – Whether to open the browser automatically to display the chart.silent (
bool
) – Whether to suppress Flask’s startup and runtime messages.
- save_state(filename)[source]
Save the state of the interactive matrix plot to a pickle file. The state includes the 2D numpy array of plot objects and the types of the plot objects.
- Parameters:
filename (
Union
[str
,Path
]) – Name of the pickle file to save the state to. The file extension should be'.pkl'
.- Return type:
None
- classmethod load_state(filename)[source]
Loads an interactive matrix plot from a saved state pickle file.
- Parameters:
filename (
Union
[str
,Path
]) – Name of the pickle file to load the state from.- Return type:
- Returns:
An reserialized instance of the
InteractiveMatrixPlot
class.
- write_html(filename=None)[source]
Write the HTML content of the interactive matrix plot to a file.
- Parameters:
filename (
Union
[str
,Path
,None
]) – Name of the HTML file to write the content to. The file extension should be ‘.html’.- Return type:
None
- to_image(filename)[source]
Write the initial state of the InteractiveMatrixPlot to an image file. This function saves the matrix plot as an image by using selenium webdriver.
- Parameters:
filename (
Union
[str
,Path
]) – Name of the image file to save the matrix plot to. The file extension should be'.png'
,.jpg
, etc.
- tsunami_ip_utils.viz.matrix_plot.load_interactive_matrix_plot(filename)[source]
Loads an interactive matrix plot from a saved state pickle file. This function is purely for convenience and is a wrapper of the
InteractiveMatrixPlot.load_state()
class method
tsunami_ip_utils.viz.pie_plot module
Tools for creating pie charts of contributions to integral indices.
- class tsunami_ip_utils.viz.pie_plot.InteractivePieLegend(fig, df)[source]
Bases:
object
A class for creating an interactive legend for a sunburst chart.
- __init__(fig, df)[source]
Create a flask webapp that will display an interactive legend for the sunburst chart.
- Parameters:
fig (
Figure
) – The sunburst chart for which the interactive legend is being created.df (
DataFrame
) – The dataframe used to create the sunburst chart.
-
fig:
Figure
The sunburst chart for which the interactive legend is being created.
-
df:
DataFrame
The dataframe used to create the sunburst chart.
- show(open_browser=True, silent=False)[source]
Start the Flask server and open the browser to display the interactive sunburst chart
- Parameters:
open_browser (
bool
) – Whether to open the browser automatically to display the chart.silent (
bool
) – Whether to suppress Flask’s startup and runtime messages.
- serve()[source]
Start the Flask server to display the interactive sunburst chart without a browser tab.
- write_html(filename=None)[source]
Write the HTML content of the interactive sunburst chart to a file.
- Parameters:
filename (
Union
[str
,Path
,None
]) – The path of the file to which the HTML content will be written. If not provided, the content will be returned.- Return type:
Optional
[str
]- Returns:
If
filename
is not provided, the HTML content of the interactive sunburst chart.
- save_state(filename=None)[source]
Save the figure (with interactive legend) as a pickle that can be deserialized for plotting later with full interactivity.
- Parameters:
filename (
Union
[str
,Path
,None
]) – Path to the file to store the pickle of the plot object (should have a.pkl
extension).- Return type:
Optional
[Dict
[str
,Union
[Figure
,DataFrame
]]]- Returns:
If
filename
is not provided, a dictionary containing the figure and dataframe used to create the plot. This data can be used to researialize the plot later.
Notes
This data can be loaded later using the
load_state()
method.
- classmethod load_state(filename=None, data_dict=None)[source]
Researilize an
InteractivePieLegend
plot from a pickle file or a data dictionary (produced bysave_state()
).- Parameters:
filename (
Union
[str
,Path
,None
]) – Path to the file containing the pickle of the plot object.data_dict (
Optional
[dict
]) – A dictionary containing the figure and dataframe used to create the plot.
- Return type:
- Returns:
A new instance of the
InteractivePieLegend
class with the same state as the original instance whose data was provided.
- to_image(filename)[source]
Write the initial state of the interactive plot to an image file. This function saves the plot as an image by using selenium webdriver.
- Parameters:
filename (
Union
[str
,Path
]) – Name of the image file to save the matrix plot to. The file extension should be'.png'
,.jpg
, etc.- Return type:
None
tsunami_ip_utils.viz.plot_utils module
Various utility functions for creating interactive plots, including functions for generating plot objects from
contributions and perturbations. These functions are used in the interactive plotting functions in the viz
module.
- tsunami_ip_utils.viz.plot_utils.generate_plot_objects_array_from_contributions(contributions, integral_index_name, plot_dissimilar_nuclides=True, **kwargs)[source]
Generate a matrix of plot objects (for creating a matrix plot) for the given contributions to an arbitrary integral index. This is valid for plots of \(\Delta k/k\) contributions, \(E\) contributions, \(c_k\) contributions, etc..
- Parameters:
contributions (
Dict
[str
,List
[uarray
]]) – Dictionary of a list of contributions to the integral index keyed by application or experiment.integral_index_name (
str
) – Name of the integral index being plotted.plot_dissimilar_nuclides (
bool
) – Whether to plot points with an application or experiment contribution of zero in the scatter plots. These points correspond to nuclides which are present in an application but not the experiment (or vice versa).kwargs (
dict
) –Additional keyword arguments. The following are supported:
- diagonal_type (str)
Type of plot to create on the diagonal. Default is
'interactive_pie'
which creates an interactive pie chart.
- off_diagonal_type (str)
Type of plot to create off the diagonal. Default is
'interactive_scatter'
which creates an interactive scatter plot.
- interactive_contribution_legend (bool)
Whether to make the legend interactive for the contribution plots. Default is
True
.
- interactive_correlation_legend (bool)
Whether to make the legend interactive for the correlation plots. Default is
True
.
- Return type:
- Returns:
2D numpy array of plot objects to be plotted with the
tsunami_ip_utils.viz.viz.matrix_plot()
function.
- tsunami_ip_utils.viz.plot_utils.generate_plot_objects_array_from_perturbations(points_array, **kwargs)[source]
Generate a matrix of plot objects (for creating a matrix plot) from a numpy array of perturbation points. This is used for a matrix of perturbation plots only.
- Parameters:
points_array (
ndarray
) – 2D numpy array of points generated from the perturbation test. Shape( num_applications, num_experiments )
.- Return type:
- Returns:
2D numpy array of plot objects to be plotted with the
tsunami_ip_utils.viz.viz.matrix_plot()
function.
tsunami_ip_utils.viz.scatter_plot module
Tools for creating interactive and static scatter plots with error bars, linear regression lines, and correlation coefficient calculations.
- class tsunami_ip_utils.viz.scatter_plot.EnhancedPlotlyFigure(*args, **kwargs)[source]
Bases:
Figure
This class wraps a plotly express figure object (intended for a scatter plot) and adds additional attributes for the summary statistics and linear regression data. This class is intended to be used with the
InteractiveScatterPlotter
class.-
statistics:
dict
A dictionary containing the Pearson and Spearman correlation coefficients.
-
regression:
dict
A dictionary containing the slope and intercept of the linear regression line.
- __init__(*args, **kwargs)[source]
Initializes an EnhancedPlotlyFigure object from a Plotly Express figure object.
Intended Use
This class should be initialized from a plotly expres Figure object via:
fig = px.scatter(...) fig = EnhancedPlotlyFigure(fig.to_dict())
Additional
statistics
andregression
attributions can be added to this “enhanced” figure viafig.statistics = { 'pearson': 0.123456, 'spearman': 0.123456 } fig.regression = { 'slope': 0.123456, 'intercept': 0.123456 }
unlike a regular Plotly Express figure object, which will throw an error if you try to add these attributes directly.
-
statistics:
- tsunami_ip_utils.viz.scatter_plot.load_interactive_scatter_plot(filename)[source]
Loads an interactive scatter plot (with interactive legend) from a saved state file. This function is purely for convenience and is a wrapper of the
InteractiveScatterLegend.load_state()
method- Parameters:
filename (
Union
[str
,Path
]) – The filename of the saved state file to load the interactive scatter plot from.- Return type:
- Returns:
A reseralized instance of the interactive scatter plot that can be plotted with
InteractiveScatterLegend.show()
.
- class tsunami_ip_utils.viz.scatter_plot.InteractiveScatterLegend(interactive_scatter_plot, df)[source]
Bases:
_InteractiveScatterPlotter
An implementation of an interactive legend (that automatically updates the regression and summary statistics following the exclusion of certain data in the scatter plot) for an interactive (Plotly) scatter plot.
- __init__(interactive_scatter_plot, df)[source]
Initializes an
InteractiveScatterPlotter
object with the given options.- Parameters:
integral_index_name – The name of the integral index (whose contributions) being plotted.
nested – Whether the contributions are nested or not.
plot_redundant – Whether to plot redundant reactions or not.
kwargs –
Additional keyword arguments.
- interactive_legend (bool)
Whether to include an interactive legend in the plot. Default is
False
.
-
fig:
EnhancedPlotlyFigure
The Plotly figure object containing the interactive scatter plot.
-
df:
DataFrame
The DataFrame containing the data for the scatter plot.
-
statistics:
dict
A dictionary containing the Pearson and Spearman correlation coefficients.
-
regression:
dict
A dictionary containing the slope and intercept of the linear regression line.
- show()[source]
Display the interactive scatter plot with the interactive legend in a web browser.
- Return type:
None
- save_state(filename=None)[source]
Save the current state of the interactive scatter plot to a file. This method saves the state of the interactive scatter plot as a dictionary containing the figure, DataFrame, excluded isotopes, index name, and nested status. This can be later reserialized by the
InteractiveScatterLegend.load_state()
method, or theload_interactive_scatter_plot()
function.- Parameters:
filename – The filename to save the state to. If not provided, the state dictionary is returned instead of being saved to a file.
- Returns:
If
filename
is not provided, the state dictionary is returned.Otherwise,
None
is returned.
- classmethod load_state(filename=None, data_dict=None)[source]
Load a saved state of an interactive scatter plot from a file. This method loads the state of the interactive scatter plot from a dictionary containing the figure, DataFrame, excluded isotopes, index name, and nested status. This can be reserialized by the
InteractiveScatterLegend.load_state()
method, or theload_interactive_scatter_plot()
function.- Parameters:
filename (
Union
[str
,Path
,None
]) – The filename of the saved state file to load the interactive scatter plot from.data_dict (
Optional
[dict
]) – A dictionary containing the saved state of the interactive scatter plot. This is an alternative to providing the filename.
- Return type:
- Returns:
An instance of the interactive scatter plot that can be plotted with
InteractiveScatterLegend.show()
.
- write_html(filename=None)[source]
Save the current state of the interactive scatter plot to an HTML file. This method saves the current state of the interactive scatter plot to an HTML file that can be viewed in a web browser.
- Parameters:
filename (
Union
[str
,Path
,None
]) – The filename to save the interactive scatter plot to.- Return type:
Optional
[str
]
Notes
Since the legend interactivity is implemented via python, saving the plot as HTML will only save the current state of the plot. The interactivity will not be preserved in the saved HTML file.
- to_image(filename)[source]
Write the initial state of the interactive plot to an image file. This function saves the plot as an image by using selenium webdriver.
- Parameters:
filename (
Union
[str
,Path
]) – Name of the image file to save the matrix plot to. The file extension should be'.png'
,.jpg
, etc.- Return type:
None
tsunami_ip_utils.viz.viz module
- tsunami_ip_utils.viz.viz.contribution_plot(contributions, plot_type='bar', integral_index_name='E', plot_redundant_reactions=True, **kwargs)[source]
Plots the contributions to an arbitrary similarity parameter for a single experiment application pair
- Parameters:
contributions (
List
[Dict
]) – List of dictionaries containing the contributions to the similarity parameter for each nuclide or nuclide-reaction pair.plot_type (
str
) –Type of plot to create. Default is
'bar'
which creates a matplotlib bar plot. Other options are:'pie'
Creates a
matplotlib
pie chart.
'interactive_pie'
Creates an interactive Plotly sunburst chart.
integral_index_name (
str
) – Name of the integral index being plotted. Default is'E'
.plot_redundant_reactions (
bool
) – Whether to plot redundant reactions (or irrelevant reactions) when considering nuclide-reaction-wise contributions. Default isTrue
.kwargs (
dict
) – Additional keyword arguments to pass to the plotting function.
- Return type:
Union
[Tuple
[Figure
,Axes
],Figure
,InteractivePieLegend
]- Returns:
If
plot_type
is'bar'
, returns a tuple containing the matplotlib figure and axes objects. These can be used to further style the plot or save it to a file. Can be plotted by callingplt.show()
.If
plot_type
is'pie'
, returns a Plotly figure object which can be displayed by callingfig.show()
If
plot_type
is'interactive_pie'
, returns aInteractivePieLegend
object which can be displayed by callingfig.show()
- tsunami_ip_utils.viz.viz.correlation_plot(application_contributions, experiment_contributions, plot_type='scatter', integral_index_name='E', plot_redundant_reactions=True, plot_dissimilar_nuclides=True, **kwargs)[source]
Creates a correlation plot for a given application-experiment pair for which the contributions to the similarity parameter are given.
- Parameters:
application_contributions (
List
[dict
]) – List of dictionaries containing the contributions to the similarity parameter for the application.experiment_contributions (
List
[dict
]) – List of dictionaries containing the contributions to the similarity parameter for the experiment.plot_type (
str
) – Type of plot to create. Default is'scatter'
which creates a matplotlib scatter plot. Other options are'interactive_scatter'
, which creates a Plotly scatter plot.integral_index_name (
str
) – Name of the integral index being plotted. Default is'E'
plot_redundant_reactions (
bool
) – Whether to plot redundant reactions (or irrelevant reactions) when considering nuclide-reaction-wise contributions. Default isTrue
.plot_dissimilar_nuclides (
bool
) – Whether to plot points with an application or experiment contribution of zero. These points correspond to nuclides which are present in an application but not the experiment (or vice versa).kwargs (
dict
) –Additional keyword arguments to pass to the plotting function.
interactive_legend
: boolWhether to include an interactive legend in the plot. Default is
False
. Only applicable ifplot_type
is'interactive_scatter'
.
- Return type:
Union
[Tuple
[Figure
,Axes
],EnhancedPlotlyFigure
,InteractiveScatterLegend
]- Returns:
If
plot_type
is'scatter'
, returns a tuple containing the matplotlib figure and axes objects. These can be used to further style the plot or save it to a file. Can be plotted by callingplt.show()
.If
plot_type
is'interactive_scatter'
andinteractive_legend
isFalse
, returns a Plotly figure object which can be displayed by callingfig.show()
If
plot_type
is'interactive_scatter'
andinteractive_legend
isTrue
, returns aInteractiveScatterLegend
object which can be displayed by callingfig.show()
Notes
Technically, if
plot_type
isinteractive_scatter
andinteractive_legend
isFalse
, the function will return aEnhancedPlotlyFigure
object, which is a wrapper of Plotly’sFigure
class, which has additional attributes related to the statistics of the scatter plot.
- tsunami_ip_utils.viz.viz.perturbation_plot(points, plot_type='interactive_scatter')[source]
Plots the perturbation points for a given application-experiment pair for which the perturbation points have already been calculated.
- Parameters:
points (
List
[Tuple
[ufloat
,ufloat
]]) – List of tuples containing the perturbation points for the application-experiment pair.plot_type (
str
) – Type of plot to create. Default is'scatter'
which creates a matplotlib scatter plot. Other options are'interactive_scatter'
, which creates a Plotly scatter plot.
- Return type:
- Returns:
A (enhanced) Plotly figure object which can be displayed by calling
fig.show()
.
- tsunami_ip_utils.viz.viz.matrix_plot(plot_objects_array, plot_type, labels=None)[source]
Creates a Dash app to display a matrix of plots from a numpy object array of figure objects.
- Parameters:
plot_objects_array (
ndarray
) – A 2D numpy array of figure objects.plot_type (
str
) – Type of plot to create. Default is'interactive'
which creates an interactive matrix plot (served by a Dash app). Other options are'static'
, which creates a static matplotlib matrix plot.labels (
Optional
[Dict
[str
,List
]]) – Dictionary of lists containing the labels for the rows and columns of the matrix plot. Keys are'expeirments'
and'applications'
. Default isNone
. Most commonly, this is the sdf filename for the given application/experiment.
- Return type:
- Returns:
If
plot_type
is'interactive'
, returns aInteractiveMatrixPlot
object which can be run by callingapp.show()
.If
plot_type
is'static'
, raises aNotImplementedError
.
- class tsunami_ip_utils.viz.viz.BlockingFigureWrapper(figure)[source]
Bases:
object
This class wraps a
matplotlib.figure.Figure
instance and blocks the execution of the program until the figure is closed. This is useful for displaying figures in a Jupyter notebook or other interactive environments where the program would otherwise continue executing and close the figure immediately, i.e.figure.show()
is non-blocking. This is nice for creating multiple plots programmatically via a plotting function, then returning the relevant figure and axs objects, after which the user can make changes and plot or save the figures individually. This functionality is not allowed withplt.show()
, because it shows all plots created in a given session (and so will show multiple plots instead of just a selected one).
- tsunami_ip_utils.viz.viz.generate_heatmap_from_comparison(comparisons, base_fontsize=6)[source]
Generates a heatmap from a comparison excel file generated by
tsunami_ip_utils.comparisons.correlation_comparison()
.- Parameters:
comparisons (
Union
[str
,Path
,DataFrame
]) – Path to the comparison excel file OR the the pandas dataframe containing the comparison data.base_fontsize (
int
) – Base font size for the heatmap (there is some heuristic for scaling fontsize with matrix size). Default is 6.
- Return type:
Dict
[str
,Tuple
[Figure
,Axes
]]- Returns:
A dictionary containing the matplotlib figure and axes objects for each unique header in the comparison excel file.