pytrnsys_process.api package#
Module contents#
pytrnsys_process package for processing TRNSYS simulation results.
This package provides tools and utilities for analyzing and processing TRNSYS simulation output data.
- pytrnsys_process.api.line_plot(df: DataFrame, columns: list[str], use_legend: bool = True, size: tuple[float, float] = (7.8, 3.9), **kwargs: Any) tuple[Figure, Axes][source]#
Create a line plot using the provided DataFrame columns.
- Parameters:
df (pandas.DataFrame) – the dataframe to plot
use_legend (bool, default 'True') – whether to show the legend or not
size (tuple of (float, float)) – size of the figure (width, height)
**kwargs – Additional keyword arguments are documented in
pandas.DataFrame.plot().
- Return type:
tuple of (
matplotlib.figure.Figure,matplotlib.axes.Axes)
Examples
>>> api.line_plot(simulation.hourly, ["QSrc1TIn", "QSrc1TOut"])
- pytrnsys_process.api.bar_chart(df: DataFrame, columns: list[str], use_legend: bool = True, size: tuple[float, float] = (7.8, 3.9), **kwargs: Any) tuple[Figure, Axes][source]#
Create a bar chart with multiple columns displayed as grouped bars. The **kwargs are currently not passed on.
- Parameters:
df (pandas.DataFrame) – the dataframe to plot
use_legend (bool, default 'True') – whether to show the legend or not
size (tuple of (float, float)) – size of the figure (width, height)
**kwargs – Additional keyword arguments to pass on to
pandas.DataFrame.plot().
- Return type:
tuple of (
matplotlib.figure.Figure,matplotlib.axes.Axes)
Examples
>>> api.bar_chart(simulation.monthly, ["QSnk60P","QSnk60PauxCondSwitch_kW"])
- pytrnsys_process.api.stacked_bar_chart(df: DataFrame, columns: list[str], use_legend: bool = True, size: tuple[float, float] = (7.8, 3.9), **kwargs: Any) tuple[Figure, Axes][source]#
Bar chart with stacked bars
- Parameters:
df (pandas.DataFrame) – the dataframe to plot
use_legend (bool, default 'True') – whether to show the legend or not
size (tuple of (float, float)) – size of the figure (width, height)
**kwargs – Additional keyword arguments to pass on to
pandas.DataFrame.plot().
- Return type:
tuple of (
matplotlib.figure.Figure,matplotlib.axes.Axes)
Examples
>>> api.stacked_bar_chart(simulation.monthly, ["QSnk60P","QSnk60PauxCondSwitch_kW"])
- pytrnsys_process.api.histogram(df: DataFrame, columns: list[str], use_legend: bool = True, size: tuple[float, float] = (7.8, 3.9), bins: int = 50, **kwargs: Any) tuple[Figure, Axes][source]#
Create a histogram from the given DataFrame columns.
- Parameters:
df (pandas.DataFrame) – the dataframe to plot
use_legend (bool, default 'True') – whether to show the legend or not
size (tuple of (float, float)) – size of the figure (width, height)
bins (int) – number of histogram bins to be used
**kwargs – Additional keyword arguments to pass on to
pandas.DataFrame.plot().
- Return type:
tuple of (
matplotlib.figure.Figure,matplotlib.axes.Axes)
Examples
>>> api.histogram(simulation.hourly, ["QSrc1TIn"], ylabel="")
- pytrnsys_process.api.energy_balance(df: DataFrame, q_in_columns: list[str], q_out_columns: list[str], q_imb_column: str | None = None, use_legend: bool = True, size: tuple[float, float] = (7.8, 3.9), **kwargs: Any) tuple[Figure, Axes][source]#
Create a stacked bar chart showing energy balance with inputs, outputs and imbalance. This function creates an energy balance visualization where:
Input energies are shown as positive values
Output energies are shown as negative values
Energy imbalance is either provided or calculated as (sum of inputs + sum of outputs)
- Parameters:
df (pandas.DataFrame) – the dataframe to plot
q_in_columns (list of str) – column names representing energy inputs
q_out_columns (list of str) – column names representing energy outputs
q_imb_column (list of str, optional) – column name containing pre-calculated energy imbalance
use_legend (bool, default 'True') – whether to show the legend or not
size (tuple of (float, float)) – size of the figure (width, height)
**kwargs – Additional keyword arguments to pass on to
pandas.DataFrame.plot().
- Return type:
tuple of (
matplotlib.figure.Figure,matplotlib.axes.Axes)
Examples
>>> api.energy_balance( >>> simulation.monthly, >>> q_in_columns=["QSnk60PauxCondSwitch_kW"], >>> q_out_columns=["QSnk60P", "QSnk60dQlossTess", "QSnk60dQ"], >>> q_imb_column="QSnk60qImbTess", >>> xlabel="" >>> )
- pytrnsys_process.api.scatter_plot(df: DataFrame, x_column: str, y_column: str, group_by_color: str | None = None, group_by_marker: str | None = None, use_legend: bool = True, size: tuple[float, float] = (7.8, 3.9), **kwargs: Any) tuple[Figure, Axes][source]#
Create a scatter plot with up to two grouping variables. This visualization allows simultaneous analysis of:
Numerical relationships between x and y variables
Categorical grouping through color encoding
Secondary categorical grouping through marker styles
Note
The way to changing colors depends on how this function is used. Categorical grouping -> use eg: cmap=”viridis” No grouping -> use eg: color=”red”
- Parameters:
df (pandas.DataFrame) – the dataframe to plot
x_column (str) – coloumn name for x-axis values
y_column (str) – coloumn name for y-axis values
group_by_color (str, optional) – column name for color grouping
group_by_marker (str, optional) – column name for marker style grouping
use_legend (bool, default 'True') – whether to show the legend or not
size (tuple of (float, float)) – size of the figure (width, height)
**kwargs – Additional keyword arguments to pass on to
pandas.DataFrame.plot().
- Return type:
tuple of (
matplotlib.figure.Figure,matplotlib.axes.Axes)
Examples
Simple scatter plot
>>> api.scatter_plot( ... simulation.monthly, x_column="QSnk60dQlossTess", y_column="QSnk60dQ" ... )
Compare plot
>>> api.scatter_plot( ... comparison_data, ... "VIceSscaled", ... "VIceRatioMax", ... "yearly_demand_GWh", ... "ratioDHWtoSH_allSinks", ... )
- pytrnsys_process.api.process_whole_result_set_parallel(results_folder: Path, processing_scenario: Callable[[Simulation], None] | Sequence[Callable[[Simulation], None]], max_workers: int | None = None) SimulationsData[source]#
Process all simulation folders in a results directory in parallel.
Uses a ProcessPoolExecutor to process multiple simulations concurrently.
- Parameters:
results_folder – Path to the directory containing simulation folders. Each subfolder should contain valid simulation data files.
processing_scenario – Single callable or sequence of callables that implement the processing logic for each simulation. Each callable should take a Simulation object as its only parameter.
max_workers – Maximum number of worker processes to use. If None, defaults to the number of processors on the machine.
- Returns:
SimulationsData –
monthly: Dict mapping simulation names to monthly DataFrame results
hourly: Dict mapping simulation names to hourly DataFrame results
scalar: DataFrame containing scalar/deck values from all simulations
- Return type:
- Raises:
ValueError – If results_folder doesn’t exist or is not a directory:
Exception – Individual simulation failures are logged but not re-raised:
Example
>>> import pathlib as _pl >>> from pytrnsys_process import api ... >>> def processing_step_1(sim): ... # Process simulation data ... pass >>> def processing_step_2(sim): ... # Process simulation data ... pass >>> results = api.process_whole_result_set_parallel( ... _pl.Path("path/to/results"), ... [processing_step_1, processing_step_2] ... )
- pytrnsys_process.api.process_single_simulation(sim_folder: Path, processing_scenarios: Callable[[Simulation], None] | Sequence[Callable[[Simulation], None]]) Simulation[source]#
Process a single simulation folder using the provided processing scenario(s).
- Parameters:
sim_folder – Path to the simulation folder to process
processing_scenarios – Single callable or sequence of callables that implement the processing logic for a simulation. Each callable should take a Simulation object as its only parameter.
- Return type:
Simulation object containing the processed data
Example
>>> from process import data_structures >>> import pathlib as _pl >>> from pytrnsys_process import api ... >>> def processing_step_1(sim: data_structures.Simulation): ... # Process simulation data ... pass >>> results = api.process_single_simulation( ... _pl.Path("path/to/simulation"), ... processing_step_1 ... )
- pytrnsys_process.api.process_whole_result_set(results_folder: Path, processing_scenario: Callable[[Simulation], None] | Sequence[Callable[[Simulation], None]]) SimulationsData[source]#
Process all simulation folders in a results directory sequentially.
Processes each simulation folder found in the results directory one at a time, applying the provided processing scenario(s) to each simulation.
- Parameters:
results_folder – Path to the directory containing simulation folders. Each subfolder should contain valid simulation data files.
processing_scenario – Single callable or sequence of callables that implement the processing logic for each simulation. Each callable should take a Simulation object as its only parameter and modify it in place.
- Returns:
SimulationsData –
monthly: Dict mapping simulation names to monthly DataFrame results
hourly: Dict mapping simulation names to hourly DataFrame results
scalar: DataFrame containing scalar/deck values from all simulations
- Return type:
- Raises:
ValueError – If results_folder doesn’t exist or is not a directory:
Exception – Individual simulation failures are logged but not re-raised:
Example
>>> import pathlib as _pl >>> from pytrnsys_process import api ... >>> def processing_step_1(sim): ... # Process simulation data ... pass >>> def processing_step_2(sim): ... # Process simulation data ... pass >>> results = api.process_whole_result_set( ... _pl.Path("path/to/results"), ... [processing_step_1, processing_step_2] ... )
- pytrnsys_process.api.do_comparison(comparison_scenario: Callable[[SimulationsData], None] | Sequence[Callable[[SimulationsData], None]], simulations_data: SimulationsData | None = None, results_folder: Path | None = None) None[source]#
Execute comparison scenarios on processed simulation results.
- Parameters:
comparison_scenario – Single callable or sequence of callables that implement the comparison logic. Each callable should take a SimulationsData object as its only parameter.
simulations_data – Optional SimulationsData object containing the processed simulation data to be compared.
results_folder – Optional Path to the directory containing simulation results. Used if simulations_data is not provided.
Example
>>> from pytrnsys_process import api ... >>> def comparison_step(simulations_data: ds.SimulationsData): ... # Compare simulation results ... pass ... >>> api.do_comparison(comparison_step, simulations_data=processed_results)
- pytrnsys_process.api.export_plots_in_configured_formats(fig: Figure, path_to_directory: str, plot_name: str, plots_folder_name: str = 'plots') None[source]#
Save a matplotlib figure in multiple formats and sizes.
Saves the figure in all configured formats (png, pdf, emf) and sizes (A4, A4_HALF) as specified in the plot settings (api.settings.plot). For EMF format, the figure is first saved as SVG and then converted using Inkscape.
- Parameters:
fig – The matplotlib Figure object to save.
path_to_directory – Directory path where the plots should be saved.
plot_name – Base name for the plot file (will be appended with size and format).
plots_folder_name – leave empty if you don’t want to save in a new folder
Note
Creates a ‘plots’ subdirectory if it doesn’t exist
For EMF files, requires Inkscape to be installed at the configured path
File naming format: {plot_name}-{size_name}.{format}
Example
>>> from pytrnsys_process import api, data_structures >>> def processing_of_monthly_data(simulation: data_structures.Simulation): >>> monthly_df = simulation.monthly >>> columns_to_plot = ["QSnk60P", "QSnk60PauxCondSwitch_kW"] >>> fig, ax = api.bar_chart(monthly_df, columns_to_plot) >>> >>> # Save the plot in multiple formats >>> api.export_plots_in_configured_formats(fig, simulation.path, "monthly-bar-chart") >>> # Creates files like: >>> # results/simulation1/plots/monthly-bar-chart-A4.png >>> # results/simulation1/plots/monthly-bar-chart-A4.pdf >>> # results/simulation1/plots/monthly-bar-chart-A4.emf >>> # results/simulation1/plots/monthly-bar-chart-A4_HALF.png >>> # etc.
- class pytrnsys_process.api.Defaults(*values)[source]#
Bases:
EnumDefault settings for different use cases
- DEFAULT = Settings(plot=Plot(file_formats=['.png', '.pdf', '.emf'], figure_sizes={'A4': (7.8, 3.9), 'A4_HALF': (3.8, 3.9)}, inkscape_path='C://Program Files//Inkscape//bin//inkscape.exe', x_label='', y_label='', title='', date_format='%b %Y', color_map='viridis', label_font_size=10, legend_font_size=8, title_font_size=12, markers=['x', 'o', '^', 'D', 'v', '<', '>', 'p', '*', 's']), reader=Reader(folder_name_for_printer_files='temp', read_step_files=False, read_deck_files=True, force_reread_prt=False))#
- class pytrnsys_process.api.Simulation(path: str, monthly: DataFrame, hourly: DataFrame, step: DataFrame, scalar: DataFrame)[source]#
Bases:
objectClass representing a TRNSYS simulation with its associated data.
This class holds the simulation data organized in different time resolutions (monthly, hourly, timestep) along with the path to the simulation files.
- monthly#
Monthly aggregated simulation data. Each column represents a different variable and each row represents a month.
- Type:
- hourly#
Hourly simulation data. Each column represents a different variable and each row represents an hour.
- Type:
- step#
Simulation data at the smallest timestep resolution. Each column represents a different variable and each row represents a timestep.
- Type:
- class pytrnsys_process.api.SimulationsData(simulations: dict[str, pytrnsys_process.process.data_structures.Simulation] = <factory>, scalar: pandas.core.frame.DataFrame = <factory>, path_to_simulations: str = <factory>)[source]#
Bases:
object- __init__(simulations: dict[str, ~pytrnsys_process.process.data_structures.Simulation] = <factory>, scalar: ~pandas.core.frame.DataFrame = <factory>, path_to_simulations: str = <factory>) None#
- simulations: dict[str, Simulation]#
- pytrnsys_process.api.load_simulations_data_from_pickle(path: ~pathlib.Path, logger: ~logging.Logger = <Logger default_pytrnsys_process (WARNING)>) SimulationsData[source]#
Load ResultsForComparison data from a pickle file.
This function loads a previously saved ResultsForComparison object from a pickle file.
- Parameters:
path – Path to the pickle file to load
logger – Logger object that will log any messages, warnings, and/or errors
- Returns:
SimulationsData – Reconstructed SimulationsData object
- Return type:
pytrnsys_processing.data_structures.SimulationsData- Raises:
OSError – If there’s an error reading the file:
pickle.UnpicklingError – If the file is corrupted or invalid:
- pytrnsys_process.api.load_simulation_from_pickle(path: ~pathlib.Path, logger: ~logging.Logger = <Logger default_pytrnsys_process (WARNING)>) Simulation[source]#