Utils Module¶
- firescipy.utils.calculate_RMSE(residuals)[source]¶
Compute the Root Mean Squared Error (RMSE) from residuals.
RMSE is the square root of the average of the squared residuals. It provides an estimate of the standard deviation of the prediction errors and is commonly used to quantify the accuracy of a model.
- Parameters
residuals (array-like) – The residuals (differences between observed and predicted values).
- Returns
The RMSE value, representing the standard deviation of residual errors.
- Return type
float
- firescipy.utils.calculate_R_squared(residuals, data_y)[source]¶
Calculate the coefficient of determination (R-squared) for a set of data.
R-squared is defined as:
\[R^2 = 1 - (SS_{res} / SS_{tot})\]where SS_res is the sum of squares of residuals (the differences between the observed and predicted values) and SS_tot is the total sum of squares (the differences between the observed values and their mean). This metric indicates the proportion of the variance in the dependent variable that is explained by the model.
- Parameters
residuals (array-like) – The residuals (errors) from the fitted model, typically computed as (observed - predicted).
data_y (array-like) – The observed data values.
- Returns
The R-squared value. Higher values indicate a better fit. Note: R² can be negative if the model performs worse than a constant mean.
- Return type
float
- firescipy.utils.calculate_residuals(data_y, fit_y)[source]¶
Compute the residuals between observed data and fitted values.
Residuals are calculated as the difference between actual values (data_y) and predicted values (fit_y). Useful for evaluating the quality of regression or curve fitting results.
- Parameters
data_y (array-like) – The observed data values.
fit_y (array-like) – The predicted or fitted values.
- Returns
The residuals, calculated as data_y - fit_y.
- Return type
np.ndarray
- firescipy.utils.cubic_max_exact(coeffs, x1, x2)[source]¶
Find the exact maximum of a cubic polynomial on the interval [x1, x2].
Evaluates the polynomial at its critical points (where the derivative is zero) and at both endpoints, then returns the location and value of the global maximum on that interval.
- Parameters
coeffs (array-like) – Polynomial coefficients in descending order, as returned by
numpy.polyfitwith degree 3.x1 (float) – Left boundary of the search interval.
x2 (float) – Right boundary of the search interval.
- Returns
x_max (float) – The x-value at which the polynomial reaches its maximum.
y_max (float) – The maximum value of the polynomial on [x1, x2].
- firescipy.utils.dynamic_local_change_simplification(time, temperature, basis_tolerance=0.2)[source]¶
Simplify a time-temperature dataset by dynamically assessing local changes against a “basis” change.
This function allows to remove data points from a series but preserves the shape. This is helpful when defining a RAMP for FDS. For example, when a simulation is to be conducted where the temperature development of a heater over time is to be used as input, e.g. TGA, or cone calorimeter. It works as follows:
The first point is retained. Then, the change between the first and second data point is established (basis change). A range is defined around the basis change, using the basis_tolerance. Next, it is determined if the change between the first and third point is inside that range. If this is true, the point is excluded and the change between first and fourth point is assessed. This process is repeated until a point is outside the range. This point is retained and the process starts again. The last point in the series is always retained.
- Parameters
time (ndarray) – Time values.
temperature (ndarray) – Temperature values.
basis_tolerance (float) – Tolerance range for deviations from the basis change (e.g., 0.2 = 20%).
- Returns
Indices of the retained points in the original data.
- Return type
ndarray
- firescipy.utils.ensure_nested_dict(nested_dict, keys)[source]¶
Ensures a nested dictionary structure exists the given sequence of keys.
- Parameters
nested_dict (dict) – The dictionary to operate on. It will be modified in place to include the full nested structure.
keys (Sequence) – Sequence of keys representing the path of nested dictionaries to create.
- Returns
The final nested dictionary at the end of the path.
- Return type
dict
- firescipy.utils.format_export_df(data_frame, column_decimals)[source]¶
Create a formatted export copy of a pandas DataFrame.
Each specified column is converted to a fixed-decimal string representation, which ensures consistent formatting when writing results to CSV or Markdown tables.
- Parameters
data_frame (pd.DataFrame) – The DataFrame to format. It is not modified in place.
column_decimals (dict) – Mapping of column name to the number of decimal places, e.g.
{"Temperature (K)": 2, "HRR (kW/m²)": 1}.
- Returns
A copy of
data_framewith the specified columns formatted as strings.- Return type
pd.DataFrame
- firescipy.utils.gaussian(x, mu, sigma, a=1.0)[source]¶
Compute the Gaussian (normal) distribution function.
The Gaussian function is defined as shown below.
\[f(x) = \frac{a}{\sigma \sqrt{2\pi}} \exp\left( -\frac{1}{2} \left( \frac{x - \mu}{\sigma} \right)^2 \right)\]- Parameters
x (float or ndarray) – The input value(s) where the Gaussian function is evaluated.
mu (float) – The mean (center) of the Gaussian distribution.
sigma (float) – The standard deviation (spread) of the Gaussian distribution. Must be positive.
a (float) – A scaling factor of the Gaussian distribution, default: 1.0.
- Returns
The computed value(s) of the Gaussian function at x.
- Return type
float or ndarray
- firescipy.utils.get_git_commit_hash(path_to_git_repo)[source]¶
Retrieve the short and long commit hashes of the current HEAD in a local Git repository.
This function runs
git rev-parsein the specified repository directory and returns both the short and full (long) forms of the current HEAD commit hash. Note that uncommitted changes in the working tree are not reflected in these hashes.- Parameters
path_to_git_repo (str or os.PathLike) – Path to the local clone of a Git repository.
- Returns
rev_short (str) – Short form of the current HEAD commit hash (e.g.,
a1b2c3d).rev_long (str) – Full (long) form of the current HEAD commit hash (e.g.,
a1b2c3d4e5f6...).
- Raises
RuntimeError – If the path is not a Git repository, Git is not installed, or HEAD cannot be resolved.
- firescipy.utils.get_nested_value(nested_dict, keys)[source]¶
Retrieve a value from a nested dictionary, using a sequence of keys.
- Parameters
nested_dict (dict) – The nested dictionary to traverse.
keys (Sequence) – A sequence of keys (e.g., list or tuple) specifying the path to the data.
- Returns
The data at the specified location in the nested dictionary.
- Return type
Any
- firescipy.utils.get_peak_value(x_values, y_values)[source]¶
Find the peak (maximum) of a data series and return its coordinates and index.
- Parameters
x_values (array-like or pd.Series) – The independent variable (e.g. time or temperature).
y_values (array-like or pd.Series) – The dependent variable whose maximum is sought.
- Returns
x_peak (float) – The x-value at the peak.
y_peak (float) – The y-value at the peak.
peak_idx (int) – The index of the peak in the input arrays.
- firescipy.utils.get_window_points(phi, delta_phi)[source]¶
Compute the number of data points required to cover a given window width.
Useful for determining the window size for smoothing operations where the desired window is specified in physical units (e.g. temperature in K or time in s) rather than in number of points.
The result is always an odd number (required by most smoothing filters) and at least 5.
- Parameters
phi (array-like) – The independent variable series (e.g. temperature or time).
delta_phi (float) – Desired window width in the same units as phi.
- Returns
Odd number of data points covering the requested window width.
- Return type
int
- firescipy.utils.interpolate_experiment_data(time, temp, signal_1, signal_2=None, T_step=0.5, mode='temperature_grid', nominal_heating_rate=None, non_monotonic='raise')[source]¶
Interpolate experimental data to achieve a uniform temperature or time spacing.
Accepts up to two signal columns, for example for STA data such as mass and heat flow.
Two processing modes are available:
"temperature_grid": A temperature grid with spacingT_stepis created and used for interpolation. This assumes strictly increasing temperature."nominal_rate": Time is treated as the independent variable and a time grid is built from the nominal heating rate and the desired temperature step sizeT_step.
- Parameters
time (array-like or pd.Series) – Time series from the experimental data.
temp (array-like or pd.Series) – Temperature series from the experimental data.
signal_1 (array-like or pd.Series) – First signal from the experimental data, e.g. mass (TGA).
signal_2 (array-like or pd.Series, optional) – Second signal from the experimental data, e.g. heat flow (STA).
T_step (float) – Desired temperature step size in Kelvin, e.g. 0.5 K.
mode (str) – Interpolation mode:
"nominal_rate"or"temperature_grid".nominal_heating_rate (float, optional) – Nominal heating rate in K/min. Required when
mode="nominal_rate".non_monotonic (str) – How to handle non-monotonic temperature data in
"temperature_grid"mode. Options are"raise","warn", or"ignore".
- Returns
(new_time, new_temp, new_signal_1)or(new_time, new_temp, new_signal_1, new_signal_2)if signal_2 is provided.- Return type
tuple
- Raises
ValueError – If
T_stepis not positive, input arrays have inconsistent lengths,non_monotonicreceives an unknown value, or the mode is unknown.
- firescipy.utils.series_to_numpy(data: Union[numpy.ndarray, pandas.Series]) numpy.ndarray[source]¶
Helper function that converts a Pandas Series to a NumPy array if necessary.
- Parameters
data (np.ndarray or pd.Series) – Input data to be converted. If already a NumPy array, it is returned unchanged.
- Returns
The input data as a NumPy array.
- Return type
np.ndarray
- firescipy.utils.store_in_nested_dict(nested_dict, new_data, keys)[source]¶
Stores data in a nested dictionary structure, for the given keys. Intermediate levels will be created if they do not already exist.
- Parameters
nested_dict (dict) – The dictionary to operate on. It will be modified in place
new_data (Any) – Data to store at the specified nested location.
keys (Sequence) – Sequence of keys representing the nested path.
- Returns
The nested dictionary is changed in place.
- Return type
None