aphin.utils package
Subpackages
- aphin.utils.data package
- Submodules
- aphin.utils.data.data module
Data
Data.Data
Data.calculate_errors()
Data.calculate_latent_errors()
Data.calculate_rms_error()
Data.calculate_state_errors()
Data.data
Data.decrease_num_simulations()
Data.decrease_num_time_steps()
Data.features_to_states()
Data.filter_data()
Data.from_data()
Data.get_initial_conditions()
Data.ph_matrices
Data.read_data_from_npz()
Data.rescale_X()
Data.save_data()
Data.save_state_traj_as_csv()
Data.save_traj_as_csv()
Data.scale_Mu()
Data.scale_U()
Data.scale_X()
Data.scale_all()
Data.scale_quantity()
Data.shape
Data.split_state_into_domains()
Data.states_to_features()
Data.train_test_split()
Data.train_test_split_sim_idx()
Data.truncate_time()
LTIDataset
PHIdentifiedData
- aphin.utils.data.dataset module
Dataset
Dataset.Data
Dataset.Data_test
Dataset.calculate_errors()
Dataset.data
Dataset.decrease_num_simulations()
Dataset.decrease_num_time_steps()
Dataset.features_to_states()
Dataset.ph_matrices
Dataset.ph_matrices_test
Dataset.rescale_X()
Dataset.scale_Mu()
Dataset.scale_U()
Dataset.scale_X()
Dataset.scale_all()
Dataset.shape
Dataset.shape_test
Dataset.split_state_into_domains()
Dataset.states_to_features()
Dataset.test_data
Dataset.train_test_split()
Dataset.train_test_split_sim_idx()
Dataset.truncate_time()
DiscBrakeDataset
PHIdentifiedDataset
- Module contents
Submodules
aphin.utils.callbacks_tensorflow module
- aphin.utils.callbacks_tensorflow.callbacks(weight_dir, monitor='loss', tensorboard=True, log_dir=None, earlystopping=False, patience=100)[source]
Create a list of TensorFlow Keras callbacks for model training.
This function generates a set of callbacks to be used during model training in TensorFlow Keras. It includes mandatory callback for saving the best model weights and optional callbacks for TensorBoard logging, early stopping, and learning rate scheduling.
Parameters:
- weight_dirstr
Path to the directory where the best model weights will be saved.
- monitorstr, optional
The metric to monitor for saving the best model and early stopping. Default is “loss”.
- tensorboardbool, optional
If True, enables TensorBoard logging. Default is True.
- log_dirstr, optional
Path to the directory where TensorBoard logs will be saved. If None, a default log directory with a timestamp is created. Default is None.
- earlystoppingbool, optional
If True, enables early stopping based on the monitored metric. Default is False.
- patienceint, optional
Number of epochs with no improvement after which training will be stopped if early stopping is enabled. Default is 100.
Returns:
- list of tf.keras.callbacks.Callback
A list of TensorFlow Keras callbacks configured according to the provided parameters.
aphin.utils.configuration module
- class aphin.utils.configuration.Configuration(working_dir, config_info=None, overwrite_results=False)[source]
Bases:
object
Handles the setup and management of configuration for an experiment.
This class manages the reading of configuration files, creation of necessary directories, and saving of the configuration to ensure all necessary data is stored and organized. It supports both identifying and loading results based on the provided configuration information.
- check_config_dict()[source]
Validates the configuration dictionary by ensuring all mandatory keys are present.
This method checks that the configuration dictionary (self.cfg_dict) contains all required entries necessary for the proper functioning of the experiment setup. If any mandatory key is missing, an exception is raised, prompting the user to update the configuration file.
Parameters:
None
Raises:
- ValueError
If any mandatory key is missing from self.cfg_dict, a ValueError is raised, specifying the missing key.
Notes:
- The method checks for the presence of the following mandatory keys in self.cfg_dict:
experiment: Specifies the name of the experiment.
load_network: Indicates whether to load a pre-existing network.
This validation ensures that critical configuration settings are not overlooked, helping prevent runtime errors due to missing configurations.
- create_directories(overwrite_results=False)[source]
Creates necessary directories for storing data, logs, weights, and results based on the current configuration. If the directories already exist, they are preserved unless overwrite_results is explicitly set to True.
Parameters:
- overwrite_resultsbool, optional
If set to True, existing result directories and files (e.g., .weights.h5) are overwritten. Default is False, meaning that the method will abort if existing results are found.
Returns:
- None
This method does not return any value. It sets up the directory structure required for the experiment.
- property directories
Returns the paths to the directories used in the experiment setup.
This property provides access to the directory paths for data, logs, weights, and results.
Returns:
- tuple of str
A tuple containing the paths to the following directories: - data_dir: Directory for data storage. - log_dir: Directory for log files. - weight_dir: Directory for storing model weights. - result_dir: Directory for storing results.
- read_config(config_info)[source]
Reads and loads configuration settings from a specified source, determining whether to proceed with model identification or to load existing results. The method sets up paths to configuration files, weight directories, and checks the existence of necessary files.
Parameters:
- config_infostr or None
Specifies the source of the configuration file or directory: - None: Uses the default config.yml in the working directory for identification.
If load_network is True in the config, it checks for the existence of weights in the default path.
- config_filename.yml: An absolute path to a custom configuration file ending with .yml for identification.
It uses the specified config file, and if load_network is True, checks for the weights in the file path.
- /folder/name/: An absolute path to a directory containing config.yml and .weights.h5.
This is used for loading results.
- result_folder_name: A folder name under the working directory that contains
config.yml and .weights.h5. This is also used for loading results.
Returns:
- None
This method sets up internal paths and configuration dictionary (self.cfg_dict) based on the provided input.
- save_config()[source]
Saves the configuration file to the results directory.
This method uses the save_config function to copy the current configuration file (config.yml) to the results directory (result_dir). It consolidates all experiment data and configuration in one location. The method checks if the network is loaded by referring to the load_network flag in the configuration dictionary.
Parameters:
None
Returns:
- None
This method does not return any value. It performs the file copy operation.
aphin.utils.experiments module
- aphin.utils.experiments.create_modified_config_files(parameter_variation_dict, basis_config_yml_path, result_dir)[source]
Generate modified YAML configuration files based on variations in parameter values.
This function takes a base configuration file and creates new configuration files for each combination of parameter values provided. Each generated configuration file is named uniquely based on the experiment name and parameter values. If a parameter value is a float, it is formatted to avoid scientific notation and unnecessary decimal points.
Parameters:
- parameter_variation_dictdict
Dictionary where keys are configuration parameter names and values are lists of possible values for those parameters. The function will generate configuration files for every combination of these parameter values.
- basis_config_yml_pathstr
File path to the base YAML configuration file used as the template for modifications.
- result_dirstr
Directory where the modified configuration files will be saved.
Returns:
- yaml_paths_listlist of str
List of file paths to the generated YAML configuration files.
- aphin.utils.experiments.dict_product(d)[source]
Generate all possible combinations of parameter values from a dictionary.
This function yields all combinations of the values in the dictionary d, where each key in the dictionary corresponds to a parameter with multiple possible values. The combinations are generated by creating a Cartesian product of the values for all keys.
Parameters:
- ddict
A dictionary where each key is a parameter and the corresponding value is a list of possible values for that parameter. The function will generate all combinations of these values.
Yields:
- dict
A dictionary representing a single combination of parameter values. Each dictionary has the same keys as the input dictionary d, with values corresponding to one combination of the possible values.
Examples:
>>> param_dict = {'param1': [1, 2], 'param2': ['a', 'b']} >>> list(dict_product(param_dict)) [{'param1': 1, 'param2': 'a'}, {'param1': 1, 'param2': 'b'}, {'param1': 2, 'param2': 'a'}, {'param1': 2, 'param2': 'b'}]
- aphin.utils.experiments.find_all_yaml_files(working_dir)[source]
Locate all YAML files (.yml) within a specified directory and its subdirectories.
This function searches through the given working directory and all its subfolders to find files with a .yml extension.
Parameters:
- working_dirstr
The root directory where the search for YAML files begins.
Returns:
- yaml_fileslist of str
A list of file paths to all YAML files found within the working directory and its subfolders.
- aphin.utils.experiments.run_all_yaml_files(experiment_main_script, yaml_paths_list, log_dir)[source]
Execute a main experiment script for each YAML configuration file and log the results.
This function iterates over a list of YAML configuration file paths, executes the provided experiment_main_script for each configuration, and logs the results to a separate log file for each experiment.
Parameters:
- experiment_main_scriptcallable
A function that executes the main experiment. It should accept a config_path_to_file keyword argument, which is the path to the YAML configuration file. This function runs the experiment based on the provided configuration.
- yaml_paths_listlist of str
A list of file paths to YAML configuration files. Each file specifies a different set of parameters for the experiment.
- log_dirstr
Directory where the log files will be saved. Each experiment will have a corresponding log file named after the experiment.
Returns:
- None
This function does not return any value.
- aphin.utils.experiments.run_various_experiments(experiment_main_script, parameter_variation_dict, basis_config_yml_path, result_dir, log_dir, force_calculation=False)[source]
Runs multiple experiments by creating several config files.
- Parameters:
experiment_main_script (function) – main script that runs the desired example
parameter_variation_dict (dict) –
dict.keys need to match with keyword in basic config file dict.values are a list of desired configurations e.g. {“scaling_values”:[“Null”,[10,100,0.1]],
”r”: [2,6,10]}
basis_config_yml_path ((str)) – absolute path to basic config file which shall be manipulated
result_dir ((str)) – absolute path to where the results
aphin.utils.integrators module
- aphin.utils.integrators.implicit_midpoint(E, A, t, z_init, B=None, u=None, decomp_option='lu')[source]
Calculate time integration of a linear ODE system using the implicit midpoint rule.
- This function solves the ODE system defined by:
E * dz_dt = A * z + B * u
Parameters:
- Enumpy.ndarray
Descriptor matrix of the ODE system.
- Anumpy.ndarray
System matrix of the ODE system.
- tnumpy.ndarray
Time vector with equidistant time steps.
- z_initnumpy.ndarray
Initial state vector.
- Bnumpy.ndarray, optional
Input matrix. Defaults to None, which sets B to zero.
- unumpy.ndarray, optional
Input function at time midpoints. Defaults to None, which sets u to zero.
- decomp_optionstr, optional
Option for matrix decomposition or solving. Choices are ‘lu’ for LU decomposition or ‘linalg_solve’ for solving without decomposition. Defaults to ‘lu’.
Returns:
- znumpy.ndarray
Array of state vectors at each time step.
- tnumpy.ndarray
Array of time points.
Theory:
we got a pH-system E*Dx = (J-R)*Q*x + B*u we define A:=(J-R)*Q and the RHS as f(t,x) use the differential slope equation at midpoint (x(t+h)-x(t))/h=Dx(t+h/2)=E^-1 * f(t+h/2,x(t+h/2)) since x(t+h/2) is unknown we use the approximation x(t+h/2) = 1/2*(x(t)+x(t+h)) insert the linear system into the differential equation leads to x(t+h) = x(t) + h * E^-1 *(1/2*A*(x(t)+x(t+h))+ B*u(t+h/2)) reformulate the equation to (E-h/2*A)x(t+h) = (E+h/2*A)*x(t) + h*B*u(t+h/2) solve the linear equation system, e.g. via LU-decomposition
The linear system is solved for x(t + h) using the specified decomposition method.
Examples:
>>> E = np.array([[1, 0], [0, 1]]) >>> A = np.array([[0, -1], [1, 0]]) >>> t = np.linspace(0, 10, 100) >>> z_init = np.array([1, 0]) >>> z, t = implicit_midpoint(E, A, t, z_init)
aphin.utils.print_matrices module
- aphin.utils.print_matrices.matprint(name, mat, decimals=2)[source]
Pretty print a matrix with specified formatting.
This function prints the matrix with a label and formats the floating-point numbers to a specified number of decimal places for better readability.
Parameters:
- namestr
Label to display before printing the matrix.
- matnumpy.ndarray
The matrix to be printed.
- decimalsint, optional
Number of decimal places to format the floating-point numbers. Defaults to 2.
Examples:
>>> mat = np.array([[1.123456, 2.345678], [3.456789, 4.567890]]) >>> matprint("My Matrix", mat, decimals=3) My Matrix: [[1.123 2.346] [3.457 4.568]]
- aphin.utils.print_matrices.print_matrices(layer, mu=None, n_t=None, sim_idx=0, data=None, decimals=2, use_train_data=False)[source]
Print system matrices and their original counterparts, if available.
This function extracts and prints the system matrices (J, R, B, Q) from a given layer and compares them with their original counterparts if provided. It also logs the minimum eigenvalues of matrices Q and R.
Parameters:
- layerinstance of LTILayer or its children
An object that provides the get_system_matrices method to retrieve the system matrices.
- muarray-like, optional
Parameter values. Defaults to None.
- n_tint or None, optional
Number of time steps. Defaults to None.
- sim_idxint, optional
Simulation index for selecting specific matrices from a list of matrices. Defaults to 0.
- dataobject from PHIdentifiedDataset or None, optional
An object containing original matrices for comparison. Defaults to None.
- decimalsint, optional
Number of decimal places to format the matrix values. Defaults to 2.
- use_train_databool, optional
If True, uses training data for original matrices; otherwise, uses test data. Defaults to False.
aphin.utils.save_results module
- aphin.utils.save_results.save_config(path_to_config, result_dir, load_network)[source]
Copies the configuration file to the results directory to consolidate all relevant data.
This function ensures that the configuration file (config.yml) is copied to the specified result_dir for convenience. This helps in keeping all experiment data and configuration in a single folder. If load_network is True, the function does not perform any action.
Parameters:
- path_to_configstr
The path to the configuration file (config.yml). This file should be a YAML file with the experiment’s configuration.
- result_dirstr
The destination directory where the results are stored. The configuration file will be copied to this directory.
- load_networkbool
A flag indicating whether a network is loaded in this experiment run. If True, no action is taken. If False, the configuration file is copied.
Returns:
- None
The function does not return any value. It performs a file copy operation.
- aphin.utils.save_results.save_evaluation_times(data_id, result_dir)[source]
Save the evaluation times to a CSV file.
This function saves the evaluation times of the model to a CSV file in the specified result_dir.
Parameters:
- data_idIdentified dataset of class aphin.utils.data.Dataset
DataIdentification object that contains the evaluation times.
- result_dirstr
Destination directory where the results are stored.
- aphin.utils.save_results.save_results(weight_dir, path_to_config, config_dict, result_dir, load_network)[source]
calls the functions to save weights, config and writes to overview .csv
Parameters:
- weight_dirstr
Directory where the neural network weights are saved.
- path_to_configstr
The path to the configuration file (config.yml). This file should be a YAML file with the experiment’s configuration.
- config_dictdict
Configuration dictionary, typically obtained from the Configuration class.
- result_dirstr
Destination directory where the results are stored. The overview CSV is written to the parent directory.
- aphin.utils.save_results.save_training_times(tran_hist, result_dir)[source]
Save the training times to a CSV file.
Parameters:
- tran_histHistory object from a Keras model
History object that contains the training times.
- result_dirstr
Destination directory where the results are stored.
- aphin.utils.save_results.save_weights(weight_dir, result_dir, load_network)[source]
Copy neural network weights from the weight directory to the result directory.
This function copies the weights file from weight_dir to result_dir, ensuring that all relevant data is consolidated in one location. If load_network is True, no action is taken.
Parameters:
- weight_dirstr
Directory where the neural network weights are saved.
- result_dirstr
Destination directory where the results are stored.
- load_networkbool
Boolean indicating if the network is loaded in this experiment run. If True, weights are not copied.
- aphin.utils.save_results.write_to_experiment_overview(config_dict, result_dir, load_network)[source]
Append experiment configuration details to an overview CSV file.
This function updates a CSV file named experiments_overview.csv with the configuration details of the current experiment. If load_network is True, no new entry is added. If False, the configuration is added to the overview.
Parameters:
- config_dictdict
Configuration dictionary, typically obtained from the Configuration class.
- result_dirstr
Destination directory where the results are stored. The overview CSV is written to the parent directory.
- load_networkbool
Boolean indicating if the network is loaded in this experiment run. If True, no new entry is added to the CSV.
aphin.utils.transformations module
- aphin.utils.transformations.Q_to_I_transformation(Qeye_system_exists, A_ph, B, C, D, X)[source]
Perform a transformation of the system matrices based on the solution of the Riccati equation.
This function checks the properties of the solution X to the Riccati equation, verifies the Kalman-Yakubovich-Popov (KYP) inequality, and performs a transformation to obtain a pH representation in transformed coordinates. It returns the transformed system matrices and the transformation matrices.
Parameters:
- Qeye_system_existsbool
Flag indicating whether the Riccati equation was successfully solved.
- A_phnumpy.ndarray
Descriptor matrix of the system.
- Bnumpy.ndarray
Input matrix of the system.
- Cnumpy.ndarray
Output matrix of the system.
- Dnumpy.ndarray
Direct transmission matrix of the system.
- Xnumpy.ndarray
Solution to the Riccati equation.
Returns:
- J_Tnumpy.ndarray
Transformed matrix representing the pH system in T-coordinates.
- R_Tnumpy.ndarray
Transformed matrix representing the pH system in T-coordinates.
- B_T_phnumpy.ndarray
Transformed input matrix in T-coordinates.
- C_T_phnumpy.ndarray
Transformed output matrix in T-coordinates.
- Tnumpy.ndarray
Transformation matrix used for the coordinate change.
- T_invnumpy.ndarray
Inverse of the transformation matrix.
- aphin.utils.transformations.checkPR(A_ph, B, C, D)[source]
Check if a system is positive-real.
This function evaluates the positive-realness of a linear system defined by the matrices (A_{ph}), (B), (C), and (D). It checks if the system’s transfer function matrix is positive semidefinite for several frequencies on the imaginary axis.
Parameters:
- A_phnumpy.ndarray
System matrix of the system.
- Bnumpy.ndarray
Input matrix of the system.
- Cnumpy.ndarray
Output matrix of the system.
- Dnumpy.ndarray
Feedthrough matrix of the system.
Notes:
Positive-realness requires that (Phi(s) = T(-s)^dagger + T(s)) is positive semidefinite for all (omega) in (mathbb{R}).
The function checks this for 100 points between 0.1 and 1000 rad/s.
For stability, it is sufficient to check if the (1,1) block of (W(X)) is positive semidefinite.
- aphin.utils.transformations.reshape_features_to_states(x, n_sim, n_t, x_dt=None, n_n=None, n_dn=None, n_f=None)[source]
Transforms the feature array ‘x’ back into a state array ‘X’, either 3-dimensional or 4-dimensional.
Parameters:
- xndarray
Feature array of size (n_s, n_f), where: - n_s: number of samples (n_sim * n_t) - n_f: number of features (n_n * n_dn) if n_n and n_dn are provided, otherwise it is n_f.
- n_simint
Number of simulations.
- n_tint
Number of time steps.
- x_dtndarray, optional
Feature array of the time derivatives with the same shape as ‘x’. Default is None.
- n_nint, optional
Number of nodes. Required if n_dn is provided. Default is None.
- n_dnint, optional
Number of degrees of freedom per node. Required if n_n is provided. Default is None.
- n_fint, optional
Number of features. Default is None.
Returns:
- Xndarray
State array of size (n_sim, n_t, n_n, n_dn) if n_n and n_dn are provided, otherwise (n_sim, n_t, n_f).
- X_dtndarray, optional
State array of the time derivatives with the same shape as ‘X’. Returned only if x_dt is not None.
Raises:
- ValueError
If both (n_n and n_dn) and n_f are provided.
Notes:
Either n_f should be provided or both n_n and n_dn should be provided, but not both.
If n_n and n_dn are provided, the function reshapes the feature array to (n_sim, n_t, n_n, n_dn).
If n_f is provided, the function reshapes the feature array to (n_sim, n_t, n_f).
If x_dt is provided, it is reshaped similarly and returned alongside X.
- aphin.utils.transformations.reshape_inputs_to_features(U)[source]
Transforms the input array ‘U’ into a feature array ‘u’, which is required for identification. The function reshapes the input array from (n_sim, n_t, n_u) to (n_s, n_u).
Parameters:
- Undarray
Input array of size (n_sim, n_t, n_u), where: - n_sim: number of simulations - n_t: number of time steps - n_u: number of input features
Returns:
- undarray
Feature array of size (n_s, n_u), where: - n_s: number of samples (n_sim * n_t) - n_u: number of input features
- aphin.utils.transformations.reshape_states_to_features(X, X_dt=None)[source]
Transforms the state array ‘X’ into a feature array ‘x’, which is required for identification.
Parameters:
- Xndarray
State array of size (n_sim, n_t, n_n, n_dn) or (n_sim, n_t, n_f), where: - n_sim: number of simulations - n_t: number of time steps - n_n: number of nodes (only if X has 4 dimensions) - n_dn: number of degrees of freedom per node (only if X has 4 dimensions) - n_f: number of features (only if X has 3 dimensions)
- X_dtndarray, optional
Time derivatives of the state array with the same shape as X. Default is None.
Returns:
- xndarray
Feature array of size (n_s, n_f), where: - n_s: number of samples (n_sim * n_t) - n_f: number of features (n_n * n_dn) or n_f
- dx_dtndarray, optional
Feature array of the time derivatives of size (n_s, n_f). Returned only if X_dt is not None.
Notes:
If X has 4 dimensions, it is reshaped from (n_sim, n_t, n_n, n_dn) to (n_s, n_f).
If X has 3 dimensions, it is assumed to be already in the shape (n_sim, n_t, n_f).
If X_dt is provided, it is reshaped similarly and returned alongside x.
- aphin.utils.transformations.solve_Riccati(A_ph, B, C, D, solver)[source]
Solve the continuous-time algebraic Riccati equation (CARE) for a given system. The function supports solving using two different solvers: scipy and pymor.
Parameters:
- A_phnumpy.ndarray
System matrix of the system.
- Bnumpy.ndarray
Input matrix of the system.
- Cnumpy.ndarray
Output matrix of the system.
- Dnumpy.ndarray
Feedthrough matrix of the system.
- solverstr
Solver to use for solving the Riccati equation. Options are: - “scipy”: Uses scipy.linalg.solve_continuous_are. - “pymor”: Uses pymor’s LTIModel for solution.
Returns:
- Xnumpy.ndarray
Solution to the Riccati equation, if the solver was successful.
- Qeye_system_existsbool
Flag indicating whether the Riccati equation was successfully solved.
- aphin.utils.transformations.transform_pH_to_Q_identity(J, R, Q, B, C, solver='Q', seed=1)[source]
Transform a port-Hamiltonian (pH) system to one with Q = I (identity matrix).
This function transforms a given port-Hamiltonian system to a new representation where the matrix Q is replaced by the identity matrix. The transformation is described in [BeattieMehrmannVanDooren18] and involves solving a Riccati equation or using Q directly as a solution to the KYP (Kalman-Yakubovich-Popov) inequality.
- Parameters:
J (array-like, shape (n, n)) – The port-Hamiltonian J matrix, which should be skew-symmetric.
R (array-like, shape (n, n)) – The port-Hamiltonian R matrix, which should be symmetric positive semi-definite.
Q (array-like, shape (n, n)) – The port-Hamiltonian Q matrix to be transformed to the identity matrix.
B (array-like, shape (n, n_u)) – The input matrix of the system.
C (array-like, shape (n_u, n)) – The output matrix of the system.
solver ({'scipy', 'pymor', 'Q'}, optional) – Method for solving the transformation: - ‘scipy’ or ‘pymor’: Use the Riccati equation solver. - ‘Q’: Use the provided Q matrix directly.
seed (int, optional) – Random seed for generating a dummy input matrix when the Riccati equation is solved.
- Returns:
J_T (ndarray, shape (n, n)) – The transformed J matrix.
R_T (ndarray, shape (n, n)) – The transformed R matrix.
B_T_ph (ndarray, shape (n, n_u)) – The transformed input matrix.
C_T_ph (ndarray, shape (n_u, n)) – The transformed output matrix.
T (ndarray, shape (n, n)) – The transformation matrix.
T_inv (ndarray, shape (n, n)) – The inverse of the transformation matrix.
input_used (bool) – Whether the input matrix was used in the transformation.
Qeye_system_exists (bool) – Whether a valid transformation to Q = I was found.
aphin.utils.visualizations module
Utilities for the use in the examples
- aphin.utils.visualizations.animate_parameter_sweep(ph_layer, mu, mu_names, param_id=0, directory='results', save=False)[source]
Creates an animation of the parameter sweep for system matrices and saves it as a GIF.
This function generates an animation that visualizes the effect of varying a specific parameter on the system matrices ( J ), ( R ), ( B ), and ( Q ). The animation is created by sweeping through a range of values for the selected parameter and updating the plot accordingly.
Parameters:
- ph_layerobject
The layer object responsible for computing the system matrices. It should have a method get_system_matrices that returns the matrices based on the input parameters.
- munumpy.ndarray
An array of parameters used to compute the system matrices. It should have dimensions (n_parameters, n_samples).
- mu_nameslist of str
A list of names for the parameters, where each name corresponds to a column in mu.
- param_idint, optional
The index of the parameter to sweep through. Defaults to 0.
- directorystr, optional
Directory where the animation GIF will be saved if save is True. Defaults to “results”.
- savebool, optional
If True, saves the animation as a GIF in the specified directory. Defaults to False.
- aphin.utils.visualizations.chessboard_visualisation(test_ids, system_layer, data, result_dir)[source]
Visualizes and compares predicted and test matrices by generating various plots.
This function generates a comprehensive visualization of the predicted and test matrices from a system layer. It creates a grid of images showing the matrices and their absolute errors, saves these images, and exports the colormap used for visualizations. Additionally, it visualizes the matrices as animations and saves them as images.
Parameters:
- test_idslist of int
List of indices for the test samples to visualize and compare.
- system_layerobject
The system layer object that provides methods to get predicted system matrices.
- dataobject
The dataset containing test data and matrices. This object should have attributes such as test_data and ph_matrices_test.
- result_dirstr
The directory path where the result images, colormaps, and limits will be saved.
Returns:
- None
The function generates and saves various plots and files related to matrix visualizations and comparisons.
- aphin.utils.visualizations.get_quantities_of_interest(data, quantity_1: str, quantity_2: str, use_train_data=False, data_type='X', idx_gen='rand')[source]
Extracts and returns selected quantities of interest from a dataset for further analysis.
This function retrieves two specified quantities (e.g., state variables, time derivatives, etc.) from either the training or test data of a given dataset object. It also generates indices for simulation, nodes, and features, which can be used for subsequent plotting or analysis tasks.
Parameters:
- dataobject
The dataset object containing the time series data. The object should have attributes for accessing the training and test data, as well as the time variable (t).
- quantity_1str
The name of the first quantity to retrieve from the dataset object (e.g., “X”, “dx_dt”, etc.).
- quantity_2str
The name of the second quantity to retrieve from the dataset object. This can be another state variable or a reconstructed quantity.
- use_train_databool, optional
If True, the function retrieves the data from the training dataset; otherwise, it uses the test dataset. Default is False.
- data_typestr, optional
The type of data being analyzed, such as “X” for state variables or “Z” for latent variables. Default is “X”.
- idx_genstr, optional
Method for generating indices for selecting nodes, degrees of freedom, or features. Options are “rand” (random selection) or “first” (select the first N features). Default is “rand”.
Returns:
- tuple
A tuple containing the following elements: - t (array-like): The time variable from the dataset. - quantity_1 (array-like): The first quantity of interest from the dataset. - quantity_2 (array-like): The second quantity of interest from the dataset. - idx_n_n (array-like): Indices for the nodes. - idx_n_dn (array-like): Indices for the degrees of freedom. - idx_sim (int): The index of the selected simulation. - idx_n_f (array-like): Indices for the selected features. - num_plots (int): The number of plots to be generated.
- aphin.utils.visualizations.get_quantity_of_interest(original_data, identified_data, og_quantity: str, id_quantity: str, use_train_data=False, data_type='X', idx_gen='rand')[source]
Retrieves and prepares quantities of interest for comparison between original and identified data.
This function extracts specified quantities from both the original and identified datasets, based on the type of data (training or test) and the indices generation method. It provides the necessary time vector, quantities for comparison, and indices for plotting.
Parameters:
- original_dataobject
Dataset containing the original state variables. Should have attributes for training and testing data.
- identified_dataobject
Dataset containing the identified state variables. Should have attributes for training and testing data.
- og_quantitystr
The name of the quantity to retrieve from the original data.
- id_quantitystr
The name of the quantity to retrieve from the identified data.
- use_train_databool, optional
If True, the training data will be used from both datasets. If False, the test data will be used. Defaults to False.
- data_typestr, optional
Specifies the type of data to be retrieved. Defaults to “X”.
- idx_genstr, optional
Method for generating indices. Defaults to “rand” for random indices.
Returns:
- tarray-like
Time vector from the identified data.
- quantity_1array-like
Quantity retrieved from the original data.
- quantity_2array-like
Quantity retrieved from the identified data.
- idx_n_nlist
Indices for the nodes variables.
- idx_n_dnlist
Indices for the dof per node variables.
- idx_simint
Index for simulation selection.
- idx_n_flist
Indices for the feature variables.
- num_plotsint
Number of plots to be generated.
- aphin.utils.visualizations.get_sim_idx(data_instance, data_type='X', num_plots_max=6, idx_gen='rand')[source]
Generates indices for plotting based on the type of data and the number of plots desired.
This function determines which indices to use for plotting the results based on the data type (“X” for state results or “Z” for latent results), the maximum number of plots, and the method for index generation. It provides indices for states or latent variables, as well as a random simulation index.
Parameters:
- data_instanceobject
The instance of the data containing the results and necessary attributes for indexing.
- data_typestr, optional
The type of data to be indexed. Can be “X” for state results or “Z” for latent results. Defaults to “X”.
- num_plots_maxint, optional
The maximum number of plots to be generated. Defaults to 6.
- idx_genstr, optional
Method for generating indices. Options are “rand” for random indices or “first” for sequential indices. Defaults to “rand”.
Returns:
- idx_n_nnp.ndarray
Indices for the state variables (nodes).
- idx_n_dnnp.ndarray
Indices for the state variables (degrees of freedom).
- idx_simint
Random index for simulation selection.
- idx_n_fnp.ndarray
Indices for the feature variables (states or latent variables).
- num_plotsint
The actual number of plots to be generated.
- aphin.utils.visualizations.new_fig(num_plots)[source]
Creates a new figure with subplots for plotting.
This function generates a figure and a set of subplots that can be used for plotting multiple variables or features in a vertically stacked layout.
Parameters:
- num_plotsint
The number of subplots to create. Each subplot will be arranged vertically in a single column.
Returns:
- figmatplotlib.figure.Figure
The created figure object containing the subplots.
- axnumpy.ndarray or matplotlib.axes.Axes
An array of Axes objects for the subplots. If num_plots is 1, ax will be a single Axes object; otherwise, it will be an array of Axes objects.
- aphin.utils.visualizations.plot_X(num_plots, t, X, X_id, idx_n_n, idx_n_dn, idx_sim, variable_names, save_name=None, save_path='')[source]
Plots multiple time series of the states from the provided data and optionally saves the plot. Data needs to be in the state format (n_sim, n_t, n_n, n_dn).
This function creates a series of plots comparing the time evolution of system variables across different indices. Each plot shows the simulated variable and its corresponding reference or ideal value. The function also supports saving the plot to a specified directory.
Parameters:
- num_plotsint
The number of individual plots to generate.
- tnumpy.ndarray
The time vector for the x-axis.
- Xnumpy.ndarray of size (n_sim, n_t, n_n, n_dn)
The simulated data array with shape (num_simulations, num_time_points, num_n, num_dn).
- X_idnumpy.ndarray of size (n_sim, n_t, n_n, n_dn)
The reference or ideal data array with the same shape as X.
- idx_n_nlist of int
List of indices for the ‘n_n’ dimension of X and X_id.
- idx_n_dnlist of int
List of indices for the ‘n_dn’ dimension of X and X_id.
- idx_simint
Index of the simulation to plot.
- variable_nameslist of str
List of two variable names used for labeling the plot.
- save_namestr, optional
The name of the file to save the plot as. If None, uses the first variable name from variable_names.
- save_pathstr, optional
The directory path where the plot image will be saved if save_name is provided. Defaults to the current directory.
- aphin.utils.visualizations.plot_X_comparison(original_data, identified_data, use_train_data=False, idx_gen='rand', save_path='')[source]
Plots a comparison of state results between original and identified data. Identified state means that the results are time integrated in the latent space and decoded.
This function generates plots comparing the state variables of the original and identified data instances. The comparison is made using randomly selected or sequentially generated indices for the state variables, based on the specified idx_gen method.
Parameters:
- original_dataobject
The instance of the original data containing the true state results.
- identified_dataobject
The instance of the identified data containing the identified state results.
- use_train_databool, optional
If True, use training data for plotting. If False, use test data. Defaults to False.
- idx_genstr, optional
Method for generating indices. Options are “rand” for random indices or “first” for sequential indices. Defaults to “rand”.
- save_pathstr, optional
Directory path to save the plot image. If empty, the plot will not be saved. Defaults to “”.
Returns:
None
- aphin.utils.visualizations.plot_X_dt_comparison(original_data, identified_data, use_train_data=False, idx_gen='rand', save_path='')[source]
Plots a comparison of state derivatives between original and identified data. Identified state derivative means that the results are time integrated in the latent space and retransformed/decoded through automatic differentiation.
This function generates plots comparing the state derivatives (i.e., time derivatives of the states) of the original and identified data instances. The comparison is made using randomly selected or sequentially generated indices for the state variables, based on the specified idx_gen method.
Parameters:
- original_dataobject
The instance of the original data containing the true state derivatives.
- identified_dataobject
The instance of the identified data containing the estimated state derivatives.
- use_train_databool, optional
If True, use training data for plotting. If False, use test data. Defaults to False.
- idx_genstr, optional
Method for generating indices. Options are “rand” for random indices or “first” for sequential indices. Defaults to “rand”.
- save_pathstr, optional
Directory path to save the plot image. If empty, the plot will not be saved. Defaults to “”.
Returns:
None
- aphin.utils.visualizations.plot_X_dt_reconstruction(original_data, identified_data, use_train_data=False, idx_gen='rand', save_path='')[source]
Plots a comparison of original state derivatives and reconstructed state derivatives from an autoencoder. The data is only encoded and decoded, the pHIN layer is not involved.
This function generates plots comparing the original time derivatives of the states with the state derivatives reconstructed by an autoencoder from the identified data. It selects a specified number of indices for plotting based on the idx_gen method.
Parameters:
- original_dataobject
The instance of the original data containing the true state derivatives.
- identified_dataobject
The instance of the identified data containing the state derivatives reconstructed by the autoencoder.
- use_train_databool, optional
If True, use training data for plotting. If False, use test data. Defaults to False.
- idx_genstr, optional
Method for generating indices. Options are “rand” for random indices or “first” for sequential indices. Defaults to “rand”.
- save_pathstr, optional
Directory path to save the plot image. If empty, the plot will not be saved. Defaults to “”.
Returns:
None
- aphin.utils.visualizations.plot_X_reconstruction(original_data, identified_data, use_train_data=False, idx_gen='rand', save_path='')[source]
Plots a comparison of original states and reconstructed states from an autoencoder. The data is only encoded and decoded, the pHIN layer is not involved.
This function generates plots comparing the original states with the states reconstructed by an autoencoder from the identified data. It selects a specified number of indices to plot based on the idx_gen method.
Parameters:
- original_dataobject
The instance of the original data containing the true states.
- identified_dataobject
The instance of the identified data containing the reconstructed states from the autoencoder.
- use_train_databool, optional
If True, use training data for plotting. If False, use test data. Defaults to False.
- idx_genstr, optional
Method for generating indices. Options are “rand” for random indices or “first” for sequential indices. Defaults to “rand”.
- save_pathstr, optional
Directory path to save the plot image. If empty, the plot will not be saved. Defaults to “”.
Returns:
None
- aphin.utils.visualizations.plot_Z(num_plots, t, Z, Z_id, idx_n_f, idx_sim, variable_names, save_name=None, save_path='')[source]
Plots the comparison between original and identified latent variables over time. Data needs to be in the latent state format (n_sim, n_t, n_f).
This function generates a series of subplots comparing the original latent variables (Z) with their identified counterparts (Z_id) for a specified number of features. The plots are generated for a selected simulation, and each subplot represents a different feature.
Parameters:
- num_plotsint
The number of subplots to generate.
- tarray-like
The time variable, common to both the original and identified data.
- Zarray-like of size (n_sim, n_t, n_f).
The original latent variables, with shape (num_simulations, num_time_steps, num_features).
- Z_idarray-like of size (n_sim, n_t, n_f).
The identified or reconstructed latent variables, with the same shape as Z.
- idx_n_farray-like
Indices of the selected features to plot.
- idx_simint
Index of the simulation to plot.
- variable_nameslist of str
A list containing the names of the variables to be used in the plot labels. The first element should be the label for Z, and the second element should be the label for Z_id.
- save_namestr, optional
The base name for the saved plot image. If not provided, the first element of variable_names is used. Default is None.
- save_pathstr, optional
The directory path where the plot image will be saved. Default is an empty string (current directory).
Returns:
- None
The function generates and displays the plots, and saves the image to the specified path.
- aphin.utils.visualizations.plot_Z_dt_ph(identified_data, use_train_data=False, idx_gen='rand', save_path='')[source]
Plots the comparison between the time derivatives of the reduced latent features (Z_dt) and their corresponding port-Hamiltonian versions (Z_dt_ph). Where
Z_dt: obtained through automatic differentiation (chain rule) of the original data through the encoder
Z_dt_ph: obtained through time integration of the identified system in the latent space and inserting Z into the pH system Z_dt = (J-R)QZ + Bu
The function allows the selection of data from either the training or test set, and indices can be generated either randomly or sequentially.
Parameters:
- identified_dataobject
The dataset containing the identified features. This object should have attributes TRAIN and TEST representing the training and testing data, respectively.
- use_train_databool, optional
If True, the function will use the training data for plotting. If False, it will use the test data. Default is False.
- idx_genstr, optional
Method for generating indices of features to plot. Options are: - “rand”: Randomly selects indices. - “first”: Selects the first few indices. Default is “rand”.
- save_pathstr, optional
The directory path where the plot will be saved. If not provided, the plot will not be saved.
Returns:
- None
The function does not return anything. It generates and displays the plot(s), and optionally saves them.
- aphin.utils.visualizations.plot_Z_dt_ph_map(identified_data, use_train_data=False, idx_gen='rand', save_path='')[source]
Plots the comparison between the time derivatives of the latent features (Z_dt) and their corresponding port-Hamiltonian mapped versions (Z_dt_ph_map). Where
Z_dt: obtained through automatic differentiation (chain rule) of the original data through the encoder
Z_dt_ph_map: obtained by inserting the encoded original state into the pH network, i.e. inserting z into the pH equation. z_dt=(J-R)Q + Bu (no time integration)
This function generates a series of plots that compare the time derivatives of the latent features Z_dt with their port-Hamiltonian mapped counterparts Z_dt_ph_map, as extracted from a dataset. The data can be selected from either the training or test set, and specific indices can be chosen either randomly or sequentially.
Parameters:
- identified_dataobject
The dataset containing the identified features. This object should have attributes TRAIN and TEST representing the training and testing data, respectively.
- use_train_databool, optional
If True, the function will use the training data for plotting. If False, it will use the test data. Default is False.
- idx_genstr, optional
Method for generating indices of features to plot. Options are: - “rand”: Randomly selects indices. - “first”: Selects the first few indices. Default is “rand”.
- save_pathstr, optional
The directory path where the plot will be saved. If not provided, the plot will not be saved.
Returns:
- None
The function does not return anything. It generates and displays the plot(s), and optionally saves them.
- aphin.utils.visualizations.plot_Z_ph(identified_data, use_train_data=False, idx_gen='rand', save_path='')[source]
Plots the comparison between identified latent variables (Z) and their corresponding port-Hamiltonian versions (Z_ph). where
Z: obtained from the encoded original data
Z_ph: obtained through the encoded initial condition of x0 and time integration with the identified system
This function generates a series of plots that compare the latent variables Z with their port-Hamiltonian counterparts Z_ph, as computed by a model. The data can be selected from either the training or test set, and specific indices can be chosen randomly or in a sequential manner.
Parameters:
- identified_dataobject
The dataset containing the identified variables. This object should have attributes TRAIN and TEST representing the training and testing data, respectively.
- use_train_databool, optional
If True, the function will use the training data for plotting. If False, it will use the test data. Default is False.
- idx_genstr, optional
Method for generating indices of features to plot. Options are: - “rand”: Randomly selects indices. - “first”: Selects the first few indices. Default is “rand”.
- save_pathstr, optional
The directory path where the plot will be saved. If not provided, the plot will not be saved.
Returns:
- None
The function does not return anything. It generates and displays the plot(s), and optionally saves them.
- aphin.utils.visualizations.plot_errors(data, use_train_data=False, t=None, save_name='rms_error', domain_names=None, save_to_csv=False, yscale='linear')[source]
Generates and saves plots of RMS errors for state and latent errors from the given dataset.
This function plots RMS errors for different domains and latent features. The plots can be saved as PNG files and optionally as CSV files. The function handles multiple domains by iterating over them and calling single_error_plot for each domain’s state error. It also plots the latent error if available.
Parameters:
- dataobject
The dataset containing error information. This object should have attributes TRAIN and TEST representing the training and testing data, respectively, and state_error_list and latent_error containing the RMS errors.
- use_train_databool, optional
If True, the function will use the training data for plotting. If False, it will use the test data. Default is False.
- tnumpy.ndarray or None, optional
A 1D array representing time points corresponding to the error data. If None, defaults to the range of indices for the time points. Default is None.
- save_namestr, optional
The base name for the files to which the plots will be saved. The name will be prefixed with “state_” for state errors and “latent_” for latent errors. Default is “rms_error”.
- domain_nameslist of str or None, optional
A list of domain names corresponding to the state errors. If None, domain names will be generated automatically based on the number of state error domains. The length of the list must match the length of data.state_error_list. Default is None.
- save_to_csvbool, optional
If True, the error data will be saved to a CSV file. Default is False.
- yscalestr, optional
The scale of the y-axis for the plots. Options are “linear” or “log”. Default is “linear”.
Returns:
- None
The function does not return anything. It generates and displays plots, and optionally saves them to files.
- aphin.utils.visualizations.plot_time_trajectories_all(data, data_id, use_train_data=False, idx_gen='rand', result_dir='')[source]
Generates and saves a series of plots comparing and reconstructing time trajectories of state and latent features.
This function iterates through predefined lists of plotting functions for state and latent features, calling each function to generate and save the corresponding plots. It allows for plotting time trajectories, comparing reconstructed states, and visualizing latent feature errors and reconstructions.
Parameters:
- dataobject
The dataset containing state and latent feature information. This object should have attributes suitable for plotting functions such as plot_X_comparison and plot_Z_ph.
- data_idobject
The dataset containing identified features and results used for comparison and reconstruction. This object should have attributes for plotting functions that need identified data.
- use_train_databool, optional
If True, the function will use the training data for plotting. If False, it will use the test data. Default is False.
- idx_genstr, optional
Method for generating indices of features to plot. Options are: - “rand”: Randomly selects indices. - “first”: Selects the first few indices. Default is “rand”.
- result_dirstr, optional
The directory path where the plots will be saved. If not provided, the plots will not be saved. Default is an empty string.
Returns:
- None
The function does not return anything. It generates and displays plots, and optionally saves them to files.
- aphin.utils.visualizations.plot_train_history(train_hist)[source]
Plots the training history of a machine learning model.
This function generates a plot of the training history for different loss metrics, including the overall loss, derivative losses, reconstruction loss, and regularization loss. The losses are plotted on a logarithmic scale to better visualize the convergence and performance of the training process.
Parameters:
- train_histobject
An object containing the training history. This object should have a history attribute, which is a dictionary with keys corresponding to different loss metrics (e.g., “loss”, “dz_loss”, “dx_loss”, “rec_loss”, “reg_loss”) and values as lists or arrays of loss values recorded during training.
Returns:
- None
The function does not return any value. It generates and displays a plot of the training history.
- aphin.utils.visualizations.plot_x(num_plots, x, x_id, idx_n_f, variable_names, save_name=None, save_path='')[source]
Plots and compares multiple time series data from the state in the feature shape. Data needs to be in the feature format (n_s, n_f)
This function creates a series of subplots to compare the provided time series data (x) with identified data (x_id) for multiple features. Each subplot shows the data for one feature, with the original data plotted as a solid line and the identified data plotted as a dashed line. The function allows for saving the resulting figure as a PNG file.
Parameters:
- num_plotsint
The number of subplots to create. Determines how many features will be plotted.
- xnp.ndarray of size (n_s, n_f)
Array containing the original time series data. Expected shape is (n_time_steps, n_features).
- x_idnp.ndarray of size (n_s, n_f)
Array containing the identified or reconstructed time series data. Expected shape is (n_time_steps, n_features).
- idx_n_flist or np.ndarray
Indices of the features to be plotted. Should have the same length as num_plots.
- variable_nameslist of str
Names of the variables to be used in the plot labels. Should contain two elements: the name for x and the name for x_id.
- save_namestr, optional
The name of the file to save the plot as (without file extension). If None, uses the first element of variable_names.
- save_pathstr, optional
Directory where the plot will be saved. If not provided, the plot will be saved in the current working directory.
Returns:
None
- aphin.utils.visualizations.plot_x_comparison(original_data, identified_data, use_train_data=False, idx_gen='rand', save_path='')[source]
Plots a comparison of the original latent features with their identified counterparts. Identified state means that the results are time integrated in the latent space and decoded.
This function generates plots to compare the original latent features (x) with their corresponding identified or predicted features (x_id). It uses either training or test data based on the use_train_data parameter, and the indices of features to be plotted can be chosen either randomly or sequentially.
Parameters:
- original_dataobject
The dataset containing the original latent features. This object should have attributes TRAIN and TEST representing the training and testing data, respectively.
- identified_dataobject
The dataset containing the identified or predicted latent features. This object should also have attributes TRAIN and TEST similar to original_data.
- use_train_databool, optional
If True, the function will use the training data for plotting. If False, it will use the test data. Default is False.
- idx_genstr, optional
Method for generating indices of features to plot. Options are: - “rand”: Randomly selects indices. - “first”: Selects the first few indices. Default is “rand”.
- save_pathstr, optional
The directory path where the plot will be saved. If not provided, the plot will not be saved.
Returns:
- None
The function does not return anything. It generates and displays the plot(s), and optionally saves them.
- aphin.utils.visualizations.plot_x_dt_reconstruction(original_data, identified_data, use_train_data=False, idx_gen='rand', save_path='')[source]
Plots and compares the original and autoencoder-reconstructed time derivative of the data. The data is only encoded and decoded, the pHIN layer is not involved.
This function generates plots comparing the original time derivative data (dx_dt) with the reconstructed data (x_rec_dt) produced by an autoencoder model. It creates subplots for each feature, displaying both the original and reconstructed time derivatives. The resulting figure can be saved as a PNG file if specified.
Parameters:
- original_dataobject
The dataset object containing the original time derivative data. Must have attributes to access time series data.
- identified_dataobject
The dataset object containing the autoencoder-reconstructed time derivative data. Must have attributes to access time series data.
- use_train_databool, optional
If True, use the training data from original_data and identified_data; otherwise, use the test data. Default is False.
- idx_genstr, optional
Method for generating indices for the features to plot. Options are “rand” (random) or “first” (first N features). Default is “rand”.
- save_pathstr, optional
Directory where the plot will be saved. If not provided, the plot will be saved in the current working directory.
Returns:
None
- aphin.utils.visualizations.plot_x_reconstruction(original_data, identified_data, use_train_data=False, idx_gen='rand', save_path='')[source]
Plots and compares the original and autoencoder-reconstructed time series data for multiple features. The data is only encoded and decoded, the pHIN layer is not involved.
This function generates plots comparing the original time series data (x) with the reconstructed data (x_rec) produced by an autoencoder model. The function creates subplots for each feature, displaying both the original and reconstructed data. It saves the resulting figure as a PNG file if specified.
Parameters:
- original_dataobject
The dataset object containing the original data. Must have attributes to access time series data.
- identified_dataobject
The dataset object containing the autoencoder-reconstructed data. Must have attributes to access time series data.
- use_train_databool, optional
If True, use the training data from original_data and identified_data; otherwise, use the test data. Default is False.
- idx_genstr, optional
Method for generating indices for the features to plot. Options are “rand” (random) or “first” (first N features). Default is “rand”.
- save_pathstr, optional
Directory where the plot will be saved. If not provided, the plot will be saved in the current working directory.
Returns:
None
- aphin.utils.visualizations.plot_z(num_plots, z, z_id, idx_n_f, variable_names, save_name=None, save_path='')[source]
Plots a comparison between original and identified latent variables. Data needs to be in the feature format (n_s, n_f).
This function creates a series of subplots to compare the original latent variables (z) with the identified or reconstructed ones (z_id). Each subplot corresponds to a specific feature as indicated by idx_n_f.
Parameters:
- num_plotsint
The number of subplots to create, corresponding to the number of features to plot.
- zarray-like, shape (n_s, n_f)
The original latent variables, where n_s is the number of samples (time steps) and n_f is the number of features.
- z_idarray-like, shape (n_s, n_f)
The identified or reconstructed latent variables, with the same shape as z.
- idx_n_farray-like
Indices of the selected features to plot, corresponding to columns of z and z_id.
- variable_nameslist of str
A list containing the names of the variables for the plot labels. The first element should correspond to z, and the second element to z_id.
- save_namestr, optional
The base name for the saved plot image. If not provided, the first element of variable_names is used. Default is None.
- save_pathstr, optional
The directory path where the plot image will be saved. Default is an empty string (current directory).
Returns:
- None
The function generates and displays the plots, and saves the image to the specified path.
- aphin.utils.visualizations.plot_z_dt_ph(identified_data, use_train_data=False, idx_gen='rand', save_path='')[source]
Plots the comparison between the time derivatives of the reduced latent features (z_dt) and their corresponding port-Hamiltonian versions (z_dt_ph). Where
z_dt: obtained through automatic differentiation (chain rule) of the original data through the encoder
z_dt_ph: obtained through time integration of the identified system in the latent space and inserting z into the pH system z_dt = (J-R)Qz + Bu
The function allows the selection of data from either the training or test set, and indices can be generated either randomly or sequentially.
Parameters:
- identified_dataobject
The dataset containing the identified features. This object should have attributes TRAIN and TEST representing the training and testing data, respectively.
- use_train_databool, optional
If True, the function will use the training data for plotting. If False, it will use the test data. Default is False.
- idx_genstr, optional
Method for generating indices of features to plot. Options are: - “rand”: Randomly selects indices. - “first”: Selects the first few indices. Default is “rand”.
- save_pathstr, optional
The directory path where the plot will be saved. If not provided, the plot will not be saved.
Returns:
- None
The function does not return anything. It generates and displays the plot(s), and optionally saves them.
- aphin.utils.visualizations.plot_z_dt_ph_map(identified_data, use_train_data=False, idx_gen='rand', save_path='')[source]
Plots a comparison of the derivative of latent features (z_dt) with their corresponding port-Hamiltonian variables (z_dt_ph_map) from the identified data. Where
z_dt: obtained through automatic differentiation (chain rule) of the original data through the encoder
z_dt_ph_map: obtained by inserting the encoded original state into the pH network, i.e. inserting z into the pH equation. z_dt=(J-R)Qz + Bu (no time integration)
This function generates plots to compare the derivative of latent features (z_dt) with their corresponding phase map (z_dt_ph_map). The function uses either training or test data based on the use_train_data parameter. The indices of features to be plotted are chosen based on the idx_gen parameter, which can either be random or sequential.
Parameters:
- identified_dataobject
The dataset containing the identified or predicted latent features. This object should have attributes TRAIN and TEST representing the training and testing data, respectively.
- use_train_databool, optional
If True, the function will use the training data for plotting. If False, it will use the test data. Default is False.
- idx_genstr, optional
Method for generating indices of features to plot. Options are: - “rand”: Randomly selects indices. - “first”: Selects the first few indices. Default is “rand”.
- save_pathstr, optional
The directory path where the plot will be saved. If not provided, the plot will not be saved.
Returns:
- None
The function does not return anything. It generates and displays the plot(s), and optionally saves them.
- aphin.utils.visualizations.plot_z_ph(identified_data, use_train_data=False, idx_gen='rand', save_path='')[source]
Plots the comparison between identified latent variables (Z) and their corresponding port-Hamiltonian versions (Z_ph). where
Z: obtained from the encoded original data
Z_ph: obtained through the encoded initial condition of x0 and time integration with the identified system
This function generates a series of plots that compare the latent features z with their port-Hamiltonian counterparts z_ph, as extracted from a dataset. The data can be selected from either the training or test set, and specific indices can be chosen either randomly or sequentially.
Parameters:
- identified_dataobject
The dataset containing the identified features. This object should have attributes TRAIN and TEST representing the training and testing data, respectively.
- use_train_databool, optional
If True, the function will use the training data for plotting. If False, it will use the test data. Default is False.
- idx_genstr, optional
Method for generating indices of features to plot. Options are: - “rand”: Randomly selects indices. - “first”: Selects the first few indices. Default is “rand”.
- save_pathstr, optional
The directory path where the plot will be saved. If not provided, the plot will not be saved.
Returns:
- None
The function does not return anything. It generates and displays the plot(s), and optionally saves them.
- aphin.utils.visualizations.save_as_png(save_path)[source]
Saves the current matplotlib figure as a PNG file.
This function saves the current matplotlib figure to the specified path as a PNG file. If the provided path does not end with “.png”, the function appends “.png” to the path. If a file already exists at the path, it is removed before saving the new PNG file. The function handles potential runtime errors related to saving figures, including issues with LaTeX processing and unsupported backends. If an error occurs, the function attempts to use different matplotlib backends to save the figure.
Parameters:
- save_pathstr
The file path where the PNG file will be saved. The path should include the desired filename and, optionally, the directory.
Returns:
None
- aphin.utils.visualizations.setup_matplotlib(save_plots=False)[source]
Set up matplotlib for generating plots, with an option to save them as PGF files.
This function configures matplotlib to produce high-quality plots with LaTeX formatting. If save_plots is set to True, the plots will be saved directly as PGF files, and the necessary directories will be created if they do not exist.
Parameters:
- save_plotsbool, optional
If True, plots will be saved directly to PGF files in the “results” directory instead of being shown. Defaults to False.
Notes:
When save_plots is True, matplotlib is configured to use PGF backend for creating plots, which are suitable for LaTeX documents.
The function also sets up the LaTeX preamble to include packages like amsmath and bm for advanced mathematical typesetting.
The default settings ensure that the font used is “Computer Modern Roman” with a font size of 11, and labels on the axes are large.
The function updates rcParams multiple times to apply the desired settings for either saving or displaying plots.
- aphin.utils.visualizations.single_error_plot(norm_rms_error, t=None, title_label='', save_name='rms_error', save_to_csv=False, yscale='linear')[source]
Generates a plot of RMS error across simulations and optionally saves it to a PNG file and/or a CSV file.
This function plots the root mean square (RMS) error values over time for a set of simulations. It computes the mean RMS error across all simulations and plots both the individual simulation errors and the mean error. The plot can be customized with a title, and the y-axis scale can be adjusted. Optionally, the data can be saved to a CSV file.
Parameters:
- norm_rms_errornumpy.ndarray
A 2D array where each row represents RMS errors from a different simulation, and each column represents errors at a specific time point. Shape should be (n_simulations, n_time_points).
- tnumpy.ndarray or None, optional
A 1D array representing time points corresponding to the columns of norm_rms_error. If None, default to the range of indices for the time points. Default is None.
- title_labelstr, optional
A string to be appended to the plot title to provide additional context or labeling. Default is an empty string.
- save_namestr, optional
The name of the file (without extension) to which the plot will be saved as a PNG. Default is “rms_error”.
- save_to_csvbool, optional
If True, the RMS error data along with the mean error will be saved to a CSV file. Default is False.
- yscalestr, optional
The scale of the y-axis. Options are “linear” or “log”. Default is “linear”.
Returns:
- None
The function does not return anything. It generates and displays the plot(s), and optionally saves them as a PNG and/or CSV file.