dymoval.dataset module¶
Module containing everything related to datasets. Here are defined special datatypes, classes and auxiliary functions.
- class Dataset(name, signal_list, u_names, y_names, target_sampling_period=None, tin=None, tout=None, full_time_interval=False, overlap=False, verbosity=0)¶
Bases:
object
The
Dataset
class stores the candidate signals to be used as a dataset and it provides methods for analyzing and manipulating them.A
Signal
list shall be passed to the initializer along with:the list of signal names that shall be considered as input
the list of signal names that shall be considered as output
The initializer will attempt to resample all the signals to have the same sampling period. Signals that cannot be resampled will be excluded from the
Dataset
and will be stored in the<~dymoval.dataset.Dataset.excluded_signals>
attribute.Furthermore, all the signals will be trimmed to have the same length.
If none of tin, tout and full_time_interval arguments are passed, then the
Dataset
time-interval selection is done graphically.Example
>>> # How to create a Dataset object from a list of Signals >>> >>> import numpy as np >>> import dymoval as dmv >>> >>> signal_names = [ >>> "SpeedRequest", >>> "AccelPedalPos", >>> "OilTemp", >>> "ActualSpeed", >>> "SteeringAngleRequest", >>> ] >>> signal_values = np.random.rand(5, 100) >>> signal_units = ["m/s", "%", "°C", "m/s", "deg"] >>> sampling_periods = [0.1, 0.1, 0.1, 0.1, 0.1] >>> # Create dymoval signals >>> signals = [] >>> for ii, val in enumerate(signal_names): >>> tmp: dmv.Signal = { >>> "name": val, >>> "samples": signal_values[ii], >>> "signal_unit": signal_units[ii], >>> "sampling_period": sampling_periods[ii], >>> "time_unit": "s", >>> } >>> signals.append(tmp) >>> # Validate signals >>> dmv.validate_signals(*signals) >>> # Specify which signals are inputs and which signals are output >>> input_labels = ["SpeedRequest", "AccelPedalPos", "SteeringAngleRequest"] >>> output_labels = ["ActualSpeed", "OilTemp"] >>> # Create dymoval Dataset objects >>> ds = dmv.Dataset("my_dataset", signals, input_labels, output_labels) >>> >>> # At this point you can plot, trim, manipulate, analyze, etc you dataset >>> # through the Dataset class methods.
You can also create
Dataset
objects from pandas DataFrames if the DataFrames have a certain structure. Look atvalidate_dataframe()
for more information about this option.Example
>>> # How to create a Dataset object from a pandas DataFrame >>> >>> import dymoval as dmv >>> import pandas as pd >>> >>> # Signals names, units and values >>> signal_names = [ >>> "SpeedRequest", >>> "AccelPedalPos", >>> "OilTemp", >>> "ActualSpeed", >>> "SteeringAngleRequest", >>> ] >>> signal_units = ["m/s", "%", "°C", "m/s", "deg"] >>> signal_values = np.random.rand(100, 5) >>> >>> # time axis >>> sampling_period = 0.1 >>> timestamps = np.arange(0, 10, sampling_period) >>> >>> # Build a candidate DataFrame >>> cols = list(zip(signal_names, signal_units)) >>> index_name = ("Time", "s") >>> >>> # Create dymoval signals >>> df = pd.DataFrame(data=signal_values, columns=cols) >>> df.index = pd.Index(data=timestamps, name=index_name) >>> >>> # Check if the dataframe is suitable for a dymoval Dataset >>> dmv.validate_dataframe(df) >>> >>> # Specify input and output signals >>> input_labels = ["SpeedRequest", "AccelPedalPos", "SteeringAngleRequest"] >>> output_labels = ["ActualSpeed", "OilTemp"] >>> >>> # Create dymoval Dataset objects >>> ds = dmv.Dataset("my_dataset", df, input_labels, output_labels)
- Parameters:
name (
str
) – Dataset name.signal_list (
list
[Signal
] |DataFrame
) – Signals to be included in theDataset
object.u_names (
str
|list
[str
]) – List of input signal names. Each signal name must be unique and must be contained in the passed signal_list names.y_names (
str
|list
[str
]) – List of input signal names. Each signal name must be unique and must be contained in the passed signal_list names.target_sampling_period (
float
|None
) – The passed signals will be re-sampled at this sampling period. If some signal could not be resampled, then its name will be added in theexcluded_signals
attr.tin (
float
|None
) – Initial time instant of theDataset
.tout (
float
|None
) – Final time instant of theDataset
.full_time_interval (
bool
) – If True, theDataset
time interval will be equal to the longest time interval among all of the signals included in the signal_list parameter. This is overriden if the parameters tin and tout are specified.overlap (
bool
) – If True it will overlap the input and output signals plots in theDataset
time interval graphical selection. The units of the outputs are displayed on the secondary y-axis.verbosity (
int
) – Display information depending on its level. Higher numbers correspond to higher verbosity.
- add_input(*signals)¶
Add input signals to the
Dataset
object.Signals will be trimmed to the length of the
Dataset
. Shorter signals will be padded with NaN:s.- Parameters:
*signals (
Signal
) – Input signals to be added.- Return type:
Self
- add_output(*signals)¶
Add output signals to the
Dataset
object.Signals will be trimmed to the length of the
Dataset
. Shorter signals will be padded with NaN:s.- Parameters:
*signals (
Signal
) – Output signals to be added.- Return type:
Self
- apply(*signal_function, **kwargs)¶
Apply a function to specified signals and change their unit.
Note
If you need to heavily manipulate your signals, it is suggested to dump the Dataset into Signals through
dump_to_signals()
, manipulate them, and then create a brand new Dataset object.Warning
This function may be removed in the future.
- Parameters:
signal_function (
tuple
[str
,Any
,str
]) – Signals where to apply a function. This argument shall have the form (name, func, new_unit).**kwargs (
Any
) – Additional keyword arguments to pass as keywords arguments to the underlying pandas DataFrame apply method.
- Return type:
Self
- dataset_values()¶
Return the dataset values as a tuple (t,u,y) of numpy ndarrays.
- Return type:
tuple
[ndarray
,ndarray
,ndarray
]- Returns:
t – The dataset time interval.
u – The values of the input signal.
y – The values of the output signal.
- dump_to_signals()¶
Dump a
Dataset
object into a list ofSignals
objects.- Return type:
dict
[Literal
['INPUT'
,'OUTPUT'
],list
[Signal
]]
Warning
Additional information contained in the Dataset, such as NaNs intervals, coverage region, etc. are lost.
- export_to_mat(filename)¶
Write the dataset in a .mat file.
- Parameters:
filename (
str
) – Target filename.- Return type:
None
- fft(*signals)¶
Return the FFT of the dataset as pandas DataFrame.
It only works with real-valued signals.
- Parameters:
signals (
str
) – The FFT is computed for these signals.- Return type:
DataFrame
- low_pass_filter(*signals_values)¶
Low-pass filter a list of specified signals.
The low-pass filter is first-order IIR filter.
- Parameters:
*signals_values (
tuple
[str
,float
]) – Tuples of the form (signal_name, cutoff_frequency). The values of signal_name are low-pass filtered with a first-order low-pass filter with cutoff frequency cutoff_frequency- Return type:
Self
- plot(*signals, overlap=False, linecolor_input='blue', linestyle_fg='-', alpha_fg=1.0, linecolor_output='green', linestyle_bg='--', alpha_bg=1.0, _grid=None, layout='tight', ax_height=1.8, ax_width=4.445)¶
Plot the
Dataset
.If two signals are passed as a tuple, then they will be placed in the same subplot. For example, if ds is a
Dataset
object with signals s1, s2, … sn, then ds.plot((“s1”, “s2”), “s3”, “s4”) will plot s1 and s2 on the same subplot and it will plot s3 and s4 on separate subplots, thus displaying the total of three subplots.Possible values for the parameters describing the line used in the plot (e.g. linecolor_input , alpha_output. etc). are the same for the corresponding plot function in matplotlib.
The method return a matplotlib.figure.Figure, so you can perform further plot manipulations by resorting to the matplotlib API.
Note
It is possible to overlap at most two signals (this to avoid adding too many y-axes in the same subplot).
Example
>>> fig = ds.plot() # ds is a dymoval Dataset >>> fig = ds.plot(("u1","y3"),"y1") # Signals u1 and y3 will be placed # in the same subplot whereas y1 will be placed in another subplot # The following are methods of the class `matplotlib.figure.Figure` >>> fig.set_size_inches(10,5) >>> fig.set_layout_engine("constrained") >>> fig.savefig("my_plot.svg")
- Parameters:
*signals (
str
|tuple
[str
,str
] |None
) – Signals to be plotted.overlap (
bool
) – If True overlap input the output signals plots pairwise. Eventual signals passed as argument will be discarded. The units of the outputs are displayed on the secondary y-axis.linecolor_input (
Union
[Tuple
[float
,float
,float
,float
],str
]) – Line color of the input signals.linestyle_fg (
str
) – Line style of the first signal of the tuple if two signals are passed as a tuple.alpha_fg (
float
) – Transparency value of the first signal of the tuple if two signals are passed as a tuple.linecolor_output (
Union
[Tuple
[float
,float
,float
,float
],str
]) – Line color of the output signals.linestyle_bg (
str
) – Line style of the second signal of the tuple if two signals are passed as a tuple.alpha_bg (
float
) – Transparency value of the second signal of the tuple if two signals are passed as a tuple._grid (
GridSpec
|None
) – Grid where the spectrum ploat will be placed (Used only internally.)layout (
Literal
['constrained'
,'compressed'
,'tight'
,'none'
]) – Figure layout.ax_height (
float
) – Approximative height (inches) of each subplot.ax_width (
float
) – Approximative width (inches) of each subplot.
- Return type:
Figure
- plot_coverage(*signals, nbins=100, linecolor_input='b', linecolor_output='g', alpha=1.0, histtype='bar', _grid=None, layout='tight', ax_height=1.8, ax_width=4.445)¶
Plot the dataset
Dataset
coverage in histograms.The method return a matplotlib.figure.Figure, so you can perform further plot manipulations by resorting to the matplotlib API.
Example
>>> fig = ds.plot_coverage() # ds is a dymoval Dataset >>> fig = ds.plot_coverage("u1","y3","y1") # The following are methods of the class `matplotlib.figure.Figure` >>> fig.set_size_inches(10,5) >>> fig.set_layout_engine("constrained") >>> fig.savefig("my_plot.svg")
- Parameters:
*signals (
str
) – The coverage of these signals will be plotted.nbins (
int
) – The number of bins in the x-axis.linecolor_input (
Union
[Tuple
[float
,float
,float
,float
],str
]) – Line color for the input signals.linecolor_output (
Union
[Tuple
[float
,float
,float
,float
],str
]) – Line color for the output signals.alpha (
float
) – Transparency value for the plots.histtype (
Literal
['bar'
,'barstacked'
,'step'
,'stepfilled'
]) – Histogram aesthetic._grid (
GridSpec
|None
) – Grid where the spectrum ploat will be placed (Used only internally.)layout (
Literal
['constrained'
,'compressed'
,'tight'
,'none'
]) – Figure layout.ax_height (
float
) – Approximative height (inches) of each subplot.ax_width (
float
) – Approximative width (inches) of each subplot.
- Return type:
Figure
- plot_spectrum(*signals, kind='power', overlap=False, linecolor_input='blue', linestyle_fg='-', alpha_fg=1.0, linecolor_output='green', linestyle_bg='--', alpha_bg=1.0, _grid=None, layout='tight', ax_height=1.8, ax_width=4.445)¶
Plot the spectrum of the specified signals in the dataset in different format.
If some signals have NaN values, then the FFT cannot be computed and an error is raised.
The method return a matplotlib.figure.Figure, so you can perform further plot manipulations by resorting to the matplotlib API.
Example
>>> fig = ds.plot_spectrum() # ds is a dymoval Dataset >>> fig = ds.plot_spectrum(("u1","y3"),"u2", kind ="amplitude") # The following are methods of the class `matplotlib.figure.Figure` >>> fig.set_size_inches(10,5) >>> fig.set_layout_engine("constrained") >>> fig.savefig("my_plot.svg")
- Parameters:
*signals (
str
|tuple
[str
,str
] |None
) – The spectrum of these signals will be plotted.kind (
Literal
['amplitude'
,'power'
,'psd'
]) –amplitude plot both the amplitude and phase spectrum. If the signal has unit V, then the amplitude has unit V. Angle is in degrees.
power plot the auto-power spectrum. If the signal has unit V, then the amplitude has unit V^2.
psd plot the power density spectrum. If the signal has unit V and the time is s, then the amplitude has unit V^2/Hz.
overlap (
bool
) – If True it overlaps the input and the output signals plots. The units of the outputs are displayed on the secondary y-axis.linecolor_input (
Union
[Tuple
[float
,float
,float
,float
],str
]) – Line color of the input signals.linestyle_fg (
str
) – Line style of the foreground signal in case of overlapping plots.alpha_fg (
float
) – Transparency value of the foreground signal in case of overlapping plots.linecolor_output (
Union
[Tuple
[float
,float
,float
,float
],str
]) – Line color for the output signals.linestyle_bg (
str
) – Line style for the background signal in case of overlapping plots.alpha_bg (
float
) – Transparency value of background signal in case of overlapping plots._grid (
GridSpec
|None
) – Grid where the spectrum ploat will be placed (Used only internally.)layout (
Literal
['constrained'
,'compressed'
,'tight'
,'none'
]) – Figure layout.ax_height (
float
) – Approximative height (inches) of each subplot.ax_width (
float
) – Approximative width (inches) of each subplot.
- Return type:
Figure
Example
>>> fig = ds.plot() # ds is a dymoval Dataset # The following are methods of the class `matplotlib.figure.Figure` >>> fig.set_size_inches(10,5) >>> fig.set_layout_engine("constrained") >>> fig.savefig("my_plot.svg")
- plotxy(*signal_pairs, layout='tight', ax_height=1.8, ax_width=4.445)¶
Plot a signal against another signal in a plane (XY-plot).
The signal_pairs shall be passed as tuples. If no signal_pairs is passed then the function will zip the input and output signals.
The method return a matplotlib.figure.Figure, so you can perform further plot manipulations by resorting to the matplotlib API.
Example
>>> fig = ds.plotxy() # ds is a dymoval Dataset >>> fig = ds.plotxy(("u1","y3"),("u2","y1")) # The following are methods of the class `matplotlib.figure.Figure` >>> fig.set_size_inches(10,5) >>> fig.set_layout_engine("constrained") >>> fig.savefig("my_plot.svg")
- Parameters:
signals_pairs – Pairs of signals to plot in a XY-diagram.
layout (
Literal
['constrained'
,'compressed'
,'tight'
,'none'
]) – Figure layout.ax_height (
float
) – Approximative height (inches) of each subplot.ax_width (
float
) – Approximative width (inches) of each subplot.
- Return type:
Figure
- remove_NaNs(**kwargs)¶
Replace NaN:s values in the
Dataset
.It uses pandas DataFrame.interpolate() method, so that the **kwargs are directly routed to such a method.
- Parameters:
**kwargs (
Any
) – Keyword arguments to pass on to the interpolating function.- Return type:
Self
- remove_means(*signals)¶
Remove the mean value to the specified signals.
- Parameters:
*signals (
str
) – Remove means to the specified signals. If not specified, then the mean value is removed to all the input signals in the dataset.- Return type:
Self
- remove_offset(*signals_values)¶
Remove specified offsets to the specified signals.
For each target signal a tuple of the form (name,value) shall be passed. The value specified in the offset parameter is removed from the signal with name name.
Example
>>> fig = ds.remove_offset(("u1",0.4),("u2",-1.5)) # ds is a Dataset
- Parameters:
*signals – Tuples of the form (name, offset). The name parameter must match the name of a signal stored in the
Dataset
. The offset parameter is the value to remove to the name signal.- Return type:
Self
- remove_signals(*signals)¶
Remove signals from the
Dataset
.- Parameters:
signals (
str
) – Signal name to be removed.- Return type:
Self
- signal_list()¶
Return the list of signals in form ([“INPUT” | “OUTPUT”], name, unit)
- Return type:
list
[tuple
[str
,str
,str
]]
- trim(*signals, tin=None, tout=None, verbosity=0, **kwargs)¶
Trim the Dataset
Dataset
object.If not tin or tout are passed, then the selection is made graphically.
- Parameters:
*signals (
str
|tuple
[str
,str
] |None
) – Signals to be plotted in case of trimming from a plot.tin (
float
|None
) – Initial time of the desired time intervaltout (
float
|None
) – Final time of the desired time interval.verbosity (
int
) – Depending on its level, more or less info is displayed. The higher the value, the higher is the verbosity.**kwargs (
Any
) – kwargs to be passed to theDataset
method.
- Return type:
Self
- class Signal¶
Bases:
TypedDict
Signals
are used to represent real-world measurements.They are used to instantiate
Dataset
objects. Before instantiating aDataset
object, it is good practice to validateSignals
through thevalidate_signals()
function.Although
Signals
have compulsory attribtues, there is freedom to append additional ones.Example
>>> # How to create a simple dymoval Signal >>> import dymoval as dmv >>> >>> my_signal: dmv.Signal = { "name": "speed", "samples": np.random.rand(100), "signal_unit": "mps", "sampling_period": 0.1, "time_unit": "s", } >>> dmv.plot_signals(my_signal)
- samples¶
Signal values.
- Type:
np.ndarray
-
name:
str
¶ Signal name.
-
samples:
ndarray
¶
-
sampling_period:
float
¶ Signal sampling period.
-
signal_unit:
str
¶ Signal unit.
-
time_unit:
str
¶ Signal sampling period.
- change_axes_layout(fig, nrows, ncols)¶
Change Axes layout of an existing Matplotlib Figure.
- Parameters:
fig (
Figure
) – Reference figure.nrwos – New number or rows.
ncols (
int
) – New number of columns
- Return type:
tuple
[Figure
,list
[Axes
]]
- compare_datasets(*datasets, kind='time', layout='tight', ax_height=1.8, ax_width=4.445)¶
Compare different
Datasets
graphically by overlapping them.The method return a matplotlib.figure.Figure, so you can perform further plot manipulations by resorting to the matplotlib API.
Example
>>> import dymoval as dmv >>> fig = dmv.compare_datasets(ds,ds1,ds2, kind="coverage") # The following are methods of the class `matplotlib.figure.Figure` >>> fig.set_size_inches(10,5) >>> fig.set_layout_engine("constrained") >>> fig.savefig("my_plot.svg")
- Parameters:
kind (
Union
[Literal
['time'
,'coverage'
],Literal
['amplitude'
,'power'
,'psd'
]]) – Kind of graph to be plotted.layout (
Literal
['constrained'
,'compressed'
,'tight'
,'none'
]) – Figure layout.ax_height (
float
) – Approximative height (inches) of each subplot.ax_width (
float
) – Approximative width (inches) of each subplot.
- Return type:
Figure
- plot_signals(*signals)¶
Plot
Signals
.The method return a matplotlib.figure.Figure, so you can perform further plot manipulations by resorting to the matplotlib API.
Example
>>> fig = dmv.plot_signals(s1,s2,s3) # s1, s2 and s3 are dymoval Signal objects. # The following are methods of the class `matplotlib.figure.Figure` >>> fig.set_size_inches(10,5) >>> fig.set_layout_engine("constrained") >>> fig.savefig("my_plot.svg")
- validate_dataframe(df)¶
Check if a pandas DataFrame is suitable for instantiating a
Dataset
object.The index of the DataFrame shall represent the common timeline for all the signals, whereas the j-th column values shall represents the realizations of the j-th signal.
The column names are tuples of strings of the form (signal_name, signal_unit).
It must be specified which signal(s) are the input through the u_names and which signal(s) is the output through the y_names parameters.
The candidate DataFrame shall meet the following requirements
Columns names shall be unique,
Columns name shall be a tuple of str of the form (name, unit),
The index shall represent the common timeline for all and its name shall be ‘(Time, time_unit)’, where time_unit is a string.
Each signal must have at least two samples (i.e. the DataFrame has at least two rows),
Only one index and columns levels are allowed (no MultiIndex),
There shall be at least two signals representing one input and one output,
Both the index values and the column values must be float and the index values must be a a 1D vector of monotonically, equi-spaced, increasing floats.
Example
>>> # How to create a Dataset object from a pandas DataFrame >>> >>> import dymoval as dmv >>> import pandas as pd >>> >>> # Signals names, units and values >>> signal_names = [ >>> "SpeedRequest", >>> "AccelPedalPos", >>> "OilTemp", >>> "ActualSpeed", >>> "SteeringAngleRequest", >>> ] >>> signal_units = ["m/s", "%", "°C", "m/s", "deg"] >>> signal_values = np.random.rand(100, 5) >>> >>> # time axis >>> sampling_period = 0.1 >>> timestamps = np.arange(0, 10, sampling_period) >>> >>> # Build a candidate DataFrame >>> cols = list(zip(signal_names, signal_units)) >>> index_name = ("Time", "s") >>> >>> # Create dymoval signals >>> df = pd.DataFrame(data=signal_values, columns=cols) >>> df.index = pd.Index(data=timestamps, name=index_name) >>> >>> # Check if the dataframe is suitable for a dymoval Dataset >>> dmv.validate_dataframe(df) >>> >>> # Specify input and output signals >>> input_labels = ["SpeedRequest", "AccelPedalPos", "SteeringAngleRequest"] >>> output_labels = ["ActualSpeed", "OilTemp"] >>> >>> # Create dymoval Dataset objects >>> ds = dmv.Dataset("my_dataset", df, input_labels, output_labels)
- Parameters:
df (
DataFrame
) – DataFrame to be validated.- Return type:
None
- validate_signals(*signals)¶
Perform a number of checks to verify that the passed list of
Signals
can be used to create a Dataset.Every
Signal
in signals must have all the attributes adequately set.A
Signal
is a TypedDict with the following keysname: str
values: 1D np.array
signal_unit: str
sampling_period: float
time_unit: str
Example
>>> # How to create a Dataset object from a list of Signals >>> >>> import numpy as np >>> import dymoval as dmv >>> >>> signal_names = [ >>> "SpeedRequest", >>> "AccelPedalPos", >>> "OilTemp", >>> "ActualSpeed", >>> "SteeringAngleRequest", >>> ] >>> signal_values = np.random.rand(5, 100) >>> signal_units = ["m/s", "%", "°C", "m/s", "deg"] >>> sampling_periods = [0.1, 0.1, 0.1, 0.1, 0.1] >>> # Create dymoval signals >>> signals = [] >>> for ii, val in enumerate(signal_names): >>> tmp: dmv.Signal = { >>> "name": val, >>> "samples": signal_values[ii], >>> "signal_unit": signal_units[ii], >>> "sampling_period": sampling_periods[ii], >>> "time_unit": "s", >>> } >>> signals.append(tmp) >>> # Validate signals >>> dmv.validate_signals(*signals) >>> # Specify which signals are inputs and which signals are output >>> input_labels = ["SpeedRequest", "AccelPedalPos", "SteeringAngleRequest"] >>> output_labels = ["ActualSpeed", "OilTemp"] >>> # Create dymoval Dataset objects >>> ds = dmv.Dataset("my_dataset", signals, input_labels, output_labels) >>> >>> # At this point you can plot, trim, manipulate, analyze, etc you dataset >>> # through the Dataset class methods.
- Parameters:
*signals (
Signal
) – Signal to be validated.- Return type:
None
dymoval.validation module¶
Module containing everything related to validation.
- class ValidationSession(name, validation_dataset, nlags=None, input_nlags=None, input_local_statistic_name_1st='mean', input_global_statistic_name_1st='max', input_local_statistic_name_2nd='max', input_global_statistic_name_2nd='max', input_local_weights=None, input_global_weights=None, acorr_local_statistic_name_1st='mean', acorr_global_statistic_name_1st='max', acorr_local_statistic_name_2nd='max', acorr_global_statistic_name_2nd='max', acorr_local_weights=None, acorr_global_weights=None, xcorr_local_statistic_name_1st='mean', xcorr_global_statistic_name_1st='max', xcorr_local_statistic_name_2nd='max', xcorr_global_statistic_name_2nd='max', xcorr_local_weights=None, xcorr_global_weights=None)¶
Bases:
object
The ValidationSession class is used to validate models against a given dataset.
A ValidationSession object is instantiated from a Dataset class object. A validation session name shall be also provided.
Multiple simulation results can be appended to the same ValidationSession instance, but for each ValidationSession instance only a Dataset class object is condsidered.
If the Dataset class object changes, it is recommended to create a new ValidationSession instance.
- append_simulation(sim_name, y_names, y_data)¶
Append simulation results. The results are stored in the
<dymoval.validation.ValidationSession.simulations_values>
attribute.The validation statistics are automatically computed and stored in the
<dymoval.validation.ValidationSession.validation_results>
attribute.- Parameters:
sim_name (
str
) – Simulation name.y_label – Simulation output signal names.
y_data (
ndarray
) – Signal realizations expressed as Nxq 2D array of type float with N observations of q signals.
- Return type:
Self
- clear()¶
Clear all the stored simulation results.
- Return type:
Self
- drop_simulations(*sims)¶
Drop simulation results from the validation session.
- Parameters:
*sims (
str
) – Name of the simulations to be dropped.- Return type:
Self
-
name:
str
¶ The validation session name.
- plot_residuals(list_sims=None, *, plot_input=True, layout='tight', ax_height=1.8, ax_width=4.445)¶
Plot the residuals.
- Parameters:
list_sims (
str
|list
[str
] |None
) – List of simulations. If empty, all the simulations are plotted.layout (
Literal
['constrained'
,'compressed'
,'tight'
,'none'
]) – Figures layout.ax_height (
float
) – Approximative height (inches) of each subplot.ax_width (
float
) – Approximative width (inches) of each subplot.
- Return type:
tuple
[Figure
,Figure
,Figure
]
You are free to manipulate the returned figure as you want by using any method of the class matplotlib.figure.Figure.
Please, refer to matplotlib docs for more info.
Example
>>> fig = vs.plot_residuals() # vs is a dymoval ValidationSession object # The following are methods of the class `matplotlib.figure.Figure` >>> fig.set_size_inches(10,5) >>> fig.set_layout_engine("constrained") >>> fig.savefig("my_plot.svg")
- plot_simulations(list_sims=None, dataset=None, layout='tight', ax_height=1.8, ax_width=4.445)¶
Plot the stored simulation results.
Possible values of the parameters describing the plot aesthetics, such as the linecolor_input or the alpha_output, are the same for the corresponding plot function of matplotlib.
You are free to manipulate the returned figure as you want by using any method of the class matplotlib.figure.Figure.
Please, refer to matplotlib docs for more info.
Example
>>> fig = vs.plot_simulations() # ds is a dymoval ValidationSession object # The following are methods of the class `matplotlib.figure.Figure` >>> fig.set_size_inches(10,5) >>> fig.set_layout_engine("constrained") >>> fig.savefig("my_plot.svg")
- Parameters:
list_sims (
str
|list
[str
] |None
) – List of simulation names.dataset (
Optional
[Literal
['in'
,'out'
,'both'
]]) –Specify whether the dataset shall be datasetped to the simulations results.
in: dataset only the input signals of the dataset.
out: dataset only the output signals of the dataset.
both: dataset both the input and the output signals of the dataset.
layout (
Literal
['constrained'
,'compressed'
,'tight'
,'none'
]) – Figure layout.ax_height (
float
) – Approximative height (inches) of each subplot.ax_width (
float
) – Approximative width (inches) of each subplot.
- Return type:
Figure
- simulation_signals_list(sim_name)¶
Return the signal name list of a given simulation result.
- Parameters:
sim_name (
str
|list
[str
]) – Simulation name.- Raises:
KeyError – If the requested simulation is not in the simulation list.
- Return type:
list
[str
]
- property simulations_names: list[str]¶
Return a list of names of the stored simulations.
- simulations_values()¶
- Return type:
DataFrame
- trim(tin=None, tout=None, verbosity=0, **kwargs)¶
Trim the Validation session
ValidationSession
object.If not tin or tout are passed, then the selection is made graphically.
- Parameters:
*signals – Signals to be plotted in case of trimming from a plot.
tin (
float
|None
) – Initial time of the desired time intervaltout (
float
|None
) – Final time of the desired time interval.verbosity (
int
) – Depending on its level, more or less info is displayed. The higher the value, the higher is the verbosity.**kwargs (
Any
) – kwargs to be passed to theValidationSession
method.
- Return type:
Self
- validation_values(sim_name)¶
- Return type:
Any
- class XCorrelation(name, X, Y=None, nlags=None, local_statistic='mean', local_weights=None, global_statistic='max', global_weights=None)¶
Bases:
object
Type used to store MIMO cross-correlations.
- values¶
Values of the correlation tensor. It is a Nxpxq tensor, where p is the dimension of the first signals, q is the dimension of the second signal and N is the number of lags.
- Type:
np.ndarray
- Return the normalized cross-correlation of two MIMO signals.
- If X = Y then it return the normalized auto-correlation of X.
- Parameters:
name (
str
) – The XCorrelation name.X (
ndarray
) – MIMO signal realizations expressed as Nxp 2D array of N observations of p signals.Y (
ndarray
|None
) – MIMO signal realizations expressed as Nxq 2D array of N observations of q signals.
- R_matrix¶
Lags of the cross-correlation. It is a vector of length N, where N is the number of lags.
- plot()¶
- Return type:
Figure
- whiteness¶
Lags of the cross-correlation. It is a vector of length N, where N is the number of lags.
- rsquared(x, y)¶
Return the \(R^2\) value of two signals.
Signals can be MIMO.
- Parameters:
x (
ndarray
) – First input signal.y (
ndarray
) – Second input signal.
- Raises:
IndexError – If x and y don’t have the same number of samples.
- Return type:
float
- whiteness_level(data, nlags=None, local_statistic='mean', local_weights=None, global_statistic='max', global_weights=None)¶
- Return type:
tuple
[floating
,ndarray
,XCorrelation
]
dymoval.utils module¶
Module containing some useful functions.
- difference_lists_of_str(A, B)¶
Return the strings contained in the list A but not in the list B.
In set formalism, this function return a list representing the set difference \(A \backslash ( A \cap B)\). Note that the operation is not commutative.
- Parameters:
A (
str
|list
[str
]) – list of strings A.B (
str
|list
[str
]) – list of strings B.
- Return type:
list
[str
]
- factorize(n)¶
Find the smallest and closest integers (a,b) such that \(n \le ab\).
- Return type:
tuple
[int
,int
]
- is_interactive_shell()¶
- Return type:
bool
- open_tutorial()¶
Create a dymoval_tutorial folder containing all the files needed to run the tutorialin your home folder. All you have to do is to run Jupyter notebook named dymoval_tutorial.ipynb. You need an app for opening .ipynb files.
The content of the dymoval_tutorial folder will be overwritten every time this function is called.
- Return type:
Any
- str2list(x)¶
Convert obj of type T into list[obj] of type T.
If obj is already a list, then it return it as-is.
- Parameters:
x (
Union
[TypeVar
(T
),List
[TypeVar
(T
)]]) – Input object.- Return type:
List
[TypeVar
(T
)]