PyTraceSuite Documentation

Introduction

This documentation describes the Python interface of TRACE and POST. The TraceSuite offers three different Python interfaces:

  • Python-Calls-TRACE

  • TRACE-Calls-Python

  • FSTrace

This introduction focuses on the first, because the other interfaces build on-top of it. For more details on the other interfaces, see their corresponding pages.

System requirements

In order to use the PyTraceSuite the regular dependencies of TRACE and POST must be installed. Furthermore, the Python module has some additional dependencies, including:

For a complete list of dependencies, including the required versions, look at the requirements list that is distributed with the PyTraceSuite. The PyTraceSuite is developed and tested with Python 3.9, different versions might work but are not officially supported.

The FSDM interface has additional dependencies that you can find on the installation part of this interface: fstrace – FSDM TRACE Interface

Note

When installing mpi4py, you must make sure that the python module is built with the exact same MPI version that you have installed on your system!

One way to make sure that this is the case is to always build the package from source when installing with pip. To do so, use the --no-binary option:

$ pip install --force-reinstall --ignore-installed --no-binary=mpi4py mpi4py

Installation

There are two ways to install the PyTraceSuite: If you have source-code access, the PyTraceSuite can be build alongside the other executables if PYTHON_EXTENSIONS is enabled in CMake, which is the default.

After building the TraceSuite you can install the PyTraceSuite with:

$ pip install <PATH_TO_YOUR_BUILD_FOLDER>

We recommend using a virtual environment.

Otherwise, a pre-build python wheel is included in the release archives of the TraceSuite which can also be installed with pip.

Getting Started

After successfully installing the PyTraceSuite, you can make sure that everything is configured correctly by running

$ python3 -c "import tracesuite; print(tracesuite.__version__)"
9.8.0

which should print the version of the installed PyTraceSuite. The tracesuite module acts as the main python module for the PyTraceSuite. It includes shared functionality between pyTRACE and pyPOST. Those python interfaces to the native tools are implemented in a tracesuite.trace and tracesuite.post submodule respectively.

The following script shows a minimal example of using pyTRACE to control a CFD simulation:

 1from tracesuite.trace import TRACE
 2
 3if __name__ == "__main__":
 4   trace = TRACE("-cgns TRACE.cgns -cntl TRACE_control.cntl")
 5   for block in trace.blocks:
 6      print(f"zone={block.zone_id} name={block.name}"}
 7
 8   trace.run()
 9
10   print(f"TRACE finished after {trace.solver_step} solver steps!")
11   trace.kill()

The TRACE instance is set-up in line 4: The constructor accepts the same arguments as the TRACE command line interface. After the instance is set up, attributes can be read and modified. In this case all blocks with their zone_id and name are printed. Then, the simulation is started using the run() method. An optional parameter would allow to run only a fixed number of iterations. With no parameters however, TRACE runs until the simulation is finished. The instances remains active until the kill() method is called, therefore properties can still be read and written after running solver iterations. This could allow you to execute during solver iterations and perform online changes to the solver instance. It is important that the kill() method is called before exiting to make sure that the MPI environment is properly shut-down.

Similar to TRACE for the simulation, POST also offers a python interface for post processing:

1from tracesuite.post import POST
2
3if __name__ == "__main__":
4   post = POST()
5   dataset = post.input("TRACE.cgns", rbc=True)
6   post.averaging(dataset)
7   post.TurbomachineryAnalysis_0D1D(ds, tecplotASCII="../output/gta/", ulist="../output/GTA.ulst")

In this example, pyPOST is initialized in line 4. The pyPOST interface operates on so called datasets. Those are created by the input(...) task. Similar to POST on the command line, pyPOST offers a set of tasks that operate on a dataset. In the example above, the post tasks averaging and TurbomachineryAnalysis_0D1D are used. Therefore the above Python script is equivalent to the following POST command line:

$ POST -i TRACE.cgns -rbc -avg -glora -tecplotASCII ../output/gta/ -ulist ../output/GTA.ulst

As pyTRACE is fully MPI compatible, it can be executed in parallel by using mpirun:

$ mpirun -np <np> <script>

See next section for more examples regarding the use of the pytracesuite interface.

Exemplary python scripts

A comprehensive list of python scripts that apply the pytracesuite can be found in trace_suite/pytracesuite/examples.

Using pyPOST to intersect and create turbomachinery analysis

This example can be found at trace_suite/pytracesuite/examples/post/s3_and_gta.py.

#!/usr/bin/env python3
"""Example using pyPOSTs 'intersectPanel' and 'GTA' tasks."""
from __future__ import annotations

import pathlib

from tracesuite.post import POST

# Parameters
input_file_abs = pathlib.Path.cwd() / "TRACE.cgns"
xi_cut_file_abs = pathlib.Path.cwd() / "xi_cuts.dat"
s2m_file_abs = pathlib.Path.cwd() / "S2M_average_flux.dat"
band_cut_file_abs = pathlib.Path.cwd() / "band_definitions.dat"

output_dir_abs = pathlib.Path.cwd() / "output"
output_file_abs = output_dir_abs / "POST_S3.plt"
output_ulst_file_name = output_dir_abs / "GTA.ulst"

# POST scripting starts here

# Create a POST instance
post = POST()

# Read input CGNS with additional boundary condition information
ds = post.input(input_file_abs.as_posix(), rbc=True)

# Create bands for all interfaces
post.createBandedInterfaces(ds)

# s2m file provided for local coordinates (xi,eta)
# xiCutFile defines the s3 cut positions
# bandFiles for gta
post.intersectPanel(ds, gf=s2m_file_abs.as_posix(), cf=xi_cut_file_abs.as_posix(), bf=band_cut_file_abs.as_posix())

# Average data on bands and panels
post.averaging(ds)

# Apply the main task to create 0D and 1D turbomachinery data
post.TurbomachineryAnalysis_0D1D(ds, tecplotASCII=output_dir_abs.as_posix(), ulist=output_ulst_file_name.as_posix())

# Reduce memory by deleting unwanted 3d data
post.deleteBlock(ds, dim=3)

# Interpolate data for better tecplot visualization
ds_interpolated = post.interpolateCellCenteredToVertexData(ds)

# Output s3 and panels
post.output(ds_interpolated, filename=output_file_abs.as_posix())

Using pyTRACE to run a speedline simulation

This example can be found at trace_suite/pytracesuite/examples/trace/speedline_pythonCallsTRACE.py.

#!/usr/bin/env python3
"""Example workflow for TRACE user story 'speedline'.

This script is intended to be called directly.
"""
from __future__ import annotations

import pathlib
import sys

from tracesuite import OutputType
from tracesuite.trace import TRACE, SimulationState

###############################################################################
# Global parameters and operating points ######################################
###############################################################################
INITIAL_BACKPRESSURE = 100332
DEFAULT_OUTPUT_DIRECTORY = pathlib.Path.cwd().parent / "output"
OPERATING_POINT_LIST = [("OP1", INITIAL_BACKPRESSURE, 40),
                        ("OP2", 1.00001 * INITIAL_BACKPRESSURE, 60)]

###############################################################################
# Start process chain #########################################################
###############################################################################

# Get arguments from command line
command_line = " ".join(sys.argv[1:])

# Setup TRACE instance and initialize with defined command settings
trace = TRACE(command_line)

# Get exit panel
exit_panel = trace.panel_groups["outflow"]

# Get defined default output path and file name
output_path_standard_2d = trace.get_cgns_output_data_file(OutputType.STANDARD_2D)
output_path_standard_3d = trace.get_cgns_output_data_file(OutputType.STANDARD_3D)
base_filename_standard_2d = pathlib.Path(output_path_standard_2d).name
base_filename_standard_3d = pathlib.Path(output_path_standard_3d).name

n_maximum_timesteps = 0
for _, _, n_timesteps in OPERATING_POINT_LIST:

    n_maximum_timesteps += n_timesteps

trace.reset_maximum_timestep(n_maximum_timesteps + 1)

# Iterate over each defined operation point
for op_name, backpressure_value, n_timesteps in OPERATING_POINT_LIST:

    trace.message(f"Running iteration for {op_name}...")

    # Set specific operating point output path
    specific_operating_point_path_standard_2d = DEFAULT_OUTPUT_DIRECTORY / op_name / "cgns" / base_filename_standard_2d
    specific_operating_point_path_standard_3d = DEFAULT_OUTPUT_DIRECTORY / op_name / "cgns" / base_filename_standard_3d
    trace.set_cgns_output_data_file(OutputType.STANDARD_2D, specific_operating_point_path_standard_2d.as_posix())
    trace.set_cgns_output_data_file(OutputType.STANDARD_3D, specific_operating_point_path_standard_3d.as_posix())

    # Set specific operating point back pressure
    exit_panel.set_static_pressure(backpressure_value)

    # apply metadata changes
    trace.apply_changed_metadata()

    # Run iteration
    state = trace.run(n_timesteps)
    trace.write_output_files()

    # Check for simulation status
    if state not in (SimulationState.SIMULATION_CONVERGED,
                     SimulationState.SIMULATION_REACHED_MAXIMAL_NUMBER_OF_TIME_STEPS,
                     SimulationState.SIMULATION_RUNNING):
        trace.message("Simulation failed: ", state)
        break

    # Reset flags for next iteration
    trace.reset_finished_flags()

trace.run()

trace.message("\nComputation of speedline terminated successfully.\n")

Using pyPOST while running pyTRACE to check convergence based on GTA data

This example can be found at trace_suite/pytracesuite/examples/trace/traceWithPostCoupling.py.

"""Prototype coupling of pyTRACE and pyPOST.

POST performs the GTA task based on TRACE integral data and creates a JSON file with the results.
This file is read via Python and one could depend the termination on some GTA information.
As this is a minimal example the simulation is terminated after certain amount of iterations.
"""
from __future__ import annotations

import argparse
import pathlib
import typing

from tracesuite import OutputType, SpatialAveraging, mpi_helper
from tracesuite.post import POST
from tracesuite.trace import TRACE

if typing.TYPE_CHECKING:
    from tracesuite.post.dataset import DataSet


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("cgns", type=pathlib.Path)
    parser.add_argument("--cntl", type=pathlib.Path, dest="control_file")
    parser.add_argument("--interleave", type=int, default=10)
    return parser.parse_args()


class ConvergenceData:
    def __init__(self):
        self.history = []

    def update(self, data_set: DataSet) -> None:
        gta = data_set.families["CFD_testsuite__Alfa__hpc,THD"].gta
        self.history.append(gta.get_integral_value("EfficiencyPolytropic", averaging=SpatialAveraging.AREA))

    def check_for_termination(self) -> bool:
        return len(self.history) > 1 # controls number of time steps to be run


def main():

    args = parse_args()
    control_arg = ""
    if args.control_file:
        control_arg = f"-cntl {args.control_file}"
    trace = TRACE(f"-cgns {args.cgns} {control_arg}")

    output_file = trace.get_cgns_output_data_file(OutputType.STANDARD_3D)
    trace.set_cgns_output_data_file(OutputType.STANDARD_3D, output_file, interleave=args.interleave)
    trace.apply_changed_metadata()

    post_path = pathlib.Path.cwd().parent / "output" / "post"
    ulst_path = post_path / "GTA.ulst"
    convergence_data = ConvergenceData()

    # perform POST on all procs
    post = POST()
    data_set = post.input(args.cgns.as_posix(), rbc=True)
    post.createBandedInterfaces(data_set)
    post.averaging(data_set)

    converged = False

    while not converged:
        # run TRACE for specified interleave
        trace.run(args.interleave)

        # update post data set and perform GTA task
        post.updateInterfaceIntegrals(data_set, trace)
        post.TurbomachineryAnalysis_0D1D(data_set, cda=True, tecplotASCII=post_path.as_posix(), ulist=ulst_path.as_posix())

        if mpi_helper.is_master():
            ConvergenceData.update(convergence_data, data_set=data_set)
            converged = ConvergenceData.check_for_termination(convergence_data)

        converged = mpi_helper.broadcast(converged, root=0)

    trace.kill()


if __name__ == "__main__":
    main()

Indices and tables

Contact

This Library is developed at AT-NUM of the DLR.

For further details please consult trace-info@dlr.de.