Skip to content

Heat Conduction Results Extractor: A Practical Example

In this section, we explore how a simulation extractor works by example of the heat conduction simulator plugin. The extractor is the key component that brings simulation results into the Sim4Life postprocessing pipeline, making them available for visualization, analysis, and reporting.


Overview

The heat conduction extractor reads the output files generated by the solver (see Solver Implementation), including the temperature and heat flux fields, as well as summary statistics. It exposes these results as output ports in the Sim4Life post-processing environment, where they can be visualized or further processed.

The extractor is implemented in Python in simulation_extractor.py and is designed to work with the output produced by the solver script main.py.


Output Files from the Solver

The solver (main.py) produces the following output files in the specified output directory:

  • Temperature.vtr: VTK rectilinear grid file containing the computed temperature field.
  • HeatFlux.vtr: VTK rectilinear grid file containing the computed heat flux vector field.
  • summary.json: JSON file with summary statistics (min/max/mean temperature, total heat input, etc.).

Extractor Structure and Functionality

The extractor is implemented as a Python class (SimulationExtractorImpl) that:

  • Imports the VTK field data using xp.VtkFieldImporter.
  • Loads summary statistics from the JSON file into a structured data object.
  • Exposes these results as output ports for use in the S4L post-processor.

The extractor is initialized with a reference to its parent algorithm, which provides access to the output directory and simulation settings. For each field ("Temperature", "HeatFlux"), a VTK importer is created and configured to read the corresponding .vtr file. The summary JSON file is loaded and its contents are mapped to a structured data object for display in the post-processor.

The extractor exposes one output port for each field, plus one for the summary data. These can be connected to visualization or analysis modules in S4L.


Example: Summary of Extractor Implementation

class SimulationExtractorImpl:
    FIELD_NAMES = ["Temperature", "HeatFlux"]

    def __init__(self, parent: "IExtractorParent"):
        self._parent = parent
        self._outputs = []
        self._extractors = []
        self._json_data_object = xp.JsonDataObject()

    def _create_vtk_importer(self, filepath: Path):
        extractor = xp.VtkFieldImporter()
        extractor.FileName.Value = str(filepath)
        extractor.GridUnit.Value = 2  # mm
        return extractor

    def _load_json_data(self, filepath: Path):
        with open(filepath) as fh:
            json_data = json.load(fh)
        # ... populate self._json_data_object ...

    def DoComputeOutputAttributes(self):
        self._extractors = []
        for field_name in self.FIELD_NAMES:
            filepath = self._parent.output_files_dir / f"{field_name}.vtr"
            extractor = self._create_vtk_importer(filepath)
            self._extractors.append(extractor)
        # ... set up output ports and load summary ...

Summary Data Example

The summary.json file written by the solver contains statistics like:

{
  "min_temperature": 293.0,
  "max_temperature": 310.5,
  "mean_temperature": 298.7,
  "argmin_index": [0, 0, 0],
  "argmax_index": [10, 10, 10],
  "total_heat_input": 5.0,
  "iterations": 1200
}

These values are loaded and made available in the post-processor for reporting and further analysis.


Plotly Plot Integration

The extractor can also provide interactive plots using Plotly. In the heat conduction example, a set of example plots is available via the UI, implemented in example_plots.py. These plots can be selected and displayed directly in the Sim4Life postprocessing environment, providing immediate visual feedback and analysis tools for users.

Example: Plotly Line Plot Definition

Below is a simplified example of how a Plotly line plot is defined in Python for use in the extractor:

def generate_line_plot() -> dict:
    import numpy as np
    id = "1"
    title = "Line Plot"
    x_values = list(np.linspace(0, 10, 100))
    y_values = [np.sin(x) for x in x_values]
    plot_config = {
        "id": id,
        "title": title,
        "data": [
            {
                "name": "Line Trace",
                "type": "scattergl",
                "showlegend": True,
                "visible": True,
                "x": x_values,
                "y": y_values,
                "line": {"color": "rgb(0,83,138)", "dash": "0"},
                "mode": "lines"
            }
        ],
        "layout": {
            "title": {"text": title},
            "xaxis": {"title": "X Axis"},
            "yaxis": {"title": "Y Axis"},
            "legend": {"x": 0.98, "xanchor": "right", "y": 0.98, "yanchor": "top"}
        }
    }
    return plot_config

This dictionary structure is compatible with Plotly and can be rendered interactively in the Sim4Life UI.

Using the Plot in the Extractor

To display a plot in the extractor, the code typically looks like this (see AlgorithmImpl in simulation_extractor.py):

import heat_conduction.model.example_plots as example_plots
import s4l_core.simulator_plugins.common.plugin_plot_manager as ppm

# ... inside AlgorithmImpl ...
# Add a property to select the plot type
prop = plots_group.Add("plots", xc.PropertyEnum([
    "generate_line_plot",
    "generate_multi_line_plot",
    "generate_scatter_plot",
    "generate_bar_plot",
    "generate_heatmap",
    "generate_3d_scatter",
    "generate_3d_surface",
    "generate_contour_plot",
    "generate_histogram",
    "generate_box_plot",
], 0))
prop.Description = "Example Plots"
self.plot_selector_prop = prop

# Add a button to show the plot
prop = plots_group.Add("show_plot", xc.PropertyPushButton())
prop.Description = "Show Plot"
self.show_plot_prop = prop

# Connect the button to the plot display logic
def show_plot():
    plot_name = self.plot_selector_prop.ValueDescription  # e.g., 'generate_line_plot'
    plot_data = getattr(example_plots, plot_name)()
    ppm.create_plot(plot_data)
self.show_plot_prop.OnClicked.Connect(show_plot)

This allows the user to select a plot type from the UI, generate the corresponding Plotly plot data, and display it interactively in Sim4Life.


Customization and Extension

The extractor is designed to be extensible. You can add new output fields or summary statistics by:

  • Modifying the solver to write additional data.
  • Updating the extractor to import and expose the new data.
  • Adding new plot types or UI elements for enhanced analysis.

Next Steps

End of documentation.