Source code for tracesuite.trace.trace

"""Contains general classes and enums to manage simulations and turbomachinery setups."""

from __future__ import annotations

import collections
import pathlib
import typing

from mpi4py import MPI

from tracesuite import AsciiOutputType, BlockGroupType, BoundaryType, OutputType
from tracesuite import simulation_setup as setup
from tracesuite.trace import SimulationState, _trace

from . import block, block_groups, eigenmode, panel_groups
from . import communication as comm
from .trace_bsr_matrix import TraceBSRmatrix


[docs] class TRACE(setup.Setup): """Main Trace simulation handle. This class is used to control one Trace simulation that would be started via a console command for one cgns-file. Currently only one simulation can exist in a python context. A simulation can be initialized, configured and started in distinct steps using the given methods. It further provides functionality to focus the communication context on subsets of e.g. panel or block groups to reduce communication overhead. Developers should note that this class essentially uses _trace.SolverCntl as interfacing class to interact with the underlying Trace c-struct `SolverCntl`. """ _n_instances: typing.ClassVar[int] = 0 def __init__(self, command_line: str, trace_root_communicator: MPI.Comm = MPI.COMM_WORLD, trace_cntl: _trace.SolverCntl | None = None, *, stop_before_simulation_setup: bool = False): """Construct an instance taking the command line to initialize the computation and an optional external MPI communicator. Note that the command line arguments are just forwarded and thus offer the same functionality and requirements as if starting Trace from the console. :param command_line: Trace command line with console syntax commands. :param trace_root_communicator: The root MPI communicator to be used for communication. :param trace_cntl: Control structure of an existing TRACE simulation or None if a new TRACE instance is to be created. :param stop_before_simulation_setup: If 'true', init will stop before setup of meta data. """ assert TRACE._n_instances == 0, "Currently only one TRACE instance is supported!" TRACE._n_instances += 1 assert command_line or trace_cntl assert trace_cntl is None or not stop_before_simulation_setup, "Cannot pass trace_cntl instance and stop before allocating solver structures" self._cntl = trace_cntl if trace_cntl is not None else _trace.SolverCntl.setup(f"pyTRACE {command_line}", trace_root_communicator) self._solver_structures_allocated = trace_cntl is not None self._world_communicator = comm.Communicator.init_world(trace_root_communicator) self._communicator_pool = {self._world_communicator.key: self._world_communicator} self._communicator_stack = [self._world_communicator] self._boundaries = {} self._blocks = {} self._rows = {} self._stages = {} self._components = {} self._all_eigenmodes = [] if not stop_before_simulation_setup: self.setup_simulation() if trace_cntl is not None: self._extract_python_objects_from_trace() def _wrap_spliss_system(self): adata = self._cntl.process_wide_system_matrix if adata is None: self.matrix_a_diag = None self.matrix_a_off_diag = None else: self.matrix_a_diag = TraceBSRmatrix((adata[0]["data"], adata[0]["columnIndices"], adata[0]["rowOffsets"])) self.matrix_a_diag.colors = adata[0]["colors"] n_rows = self.matrix_a_diag.shape[0] self.matrix_a_off_diag = TraceBSRmatrix((adata[1]["data"], adata[1]["columnIndices"], adata[1]["rowOffsets"]), shape=(n_rows, n_rows)) self.matrix_a_off_diag.colors = adata[1]["colors"] self.rhs = self._cntl.rhs_vector self.delta_u = self._cntl.delta_u_vector
[docs] def kill(self): """Cleanup TRACE object by disposing all allocated memory and decrement the number of TRACE instances.""" self._cntl.kill() TRACE._n_instances -= 1
# Ideally we would like to use the automatic __del__ function. However, in the "TRACE-calls- Python" mode this implicitly clears # the TRACE control! Zombie TRACE!!!! # __del__ = kill #alias __del__ # noqa: ERA001 This should stay here for documentation purposes
[docs] def focus_on(self, *args): """Select TRACE entities (block or panel groups) to focus on to improve parallel execution of the python script. This method can only be used in a 'with' context, e.g.:: with trace.focus_on(inlet, outlet) as focus: if focus: CODEBLOCK Here, only the MPI ranks that own parts of the inlet or outlet panel groups will execute the CODEBLOCK. Note that due to restrictions in the python language the return value 'focus' must be checked explicitly, i.e. the CODEBLOCK must be executed only if 'focus' is True. 'focus_on' can be nested, but inner nests can focus on a subset of the focused entities of the outer nests. """ return comm.Focus(self._world_communicator.size, self._communicator_pool, self._communicator_stack, [*self._boundaries.values(), *self._rows.values(), *self._stages.values(), *self._components.values()], args)
[docs] def message(self, *args, **kwargs): """Print a unique message to stdout, i.e. only one rank will print in an MPI environment.""" if self._communicator_stack[-1].rank == 0: # always flush stdout because in MPI environment output can get very delayed kwargs["flush"] = True print(*args, **kwargs)
[docs] @staticmethod def initialize(): """Wrap an already initialized simulation. Note that this function is meant to be used in a TRACE-calls-python context and should be avoided when implementing python-calls-TRACE functionality. :return: New instance of python class TRACE wrapping an already existing Simulation. :rtype: TRACE """ return TRACE("", trace_cntl=_trace.get_trace_cntl())
def _extract_python_objects_from_trace(self): self._wrap_spliss_system() self._all_blocks = [block.Block(self._cntl, b) for b in self._cntl.blocks] self._extract_block_groups() self._extract_panel_groups() self._all_eigenmodes = [eigenmode.Eigenmode(self._cntl, mode) for mode in self._cntl.eigenmodes] def _extract_panel_groups(self): """Extract all available instances of Trace c-struct `PanelGroup` from the simulation handled by cntl. Set up one linked instance of the appropriate type (e.g. Outlet, Inlet, ...) for each. """ for trace_panel_group in self._cntl.panel_groups: # @todo: think about removing periodic boundaries as in post dataset this is an individual property boundary = { BoundaryType.ENTRY: panel_groups.Inlet, BoundaryType.EXIT: panel_groups.Outlet, BoundaryType.SOLID: panel_groups.Solid, BoundaryType.PERIODIC_1TO1: panel_groups.Periodic, }.get(trace_panel_group.boundary_type, panel_groups.PanelGroup)(trace_panel_group, self.rows[trace_panel_group.block_group.name], self._world_communicator, self._cntl) self._boundaries[boundary.name] = boundary def _extract_block_groups(self): """Extract all available instances of Trace c-struct `BlockGroup` from the simulation handled by cntl. Set up one appropriate linked instance of either Row, Stage or Components for each. """ # Generate all instances of Row. They can be constructed directly. for group in self._cntl.block_groups: if group.type == BlockGroupType.BLOCK_GROUP_TYPE_ROW: row = block_groups.Row(group, self._world_communicator, self._cntl, self._all_blocks) self._rows[row.name] = row # Now create the Stages with the row they contain. for group in self._cntl.block_groups: if group.type == BlockGroupType.BLOCK_GROUP_TYPE_STAGE: rows = {row.name: row for row in self._rows.values() if row._trace_block_group.parent_stage_name == group.name} # noqa: SLF001 stage = block_groups.Stage(group, self._world_communicator, self._cntl, self._all_blocks, rows) self._stages[stage.name] = stage for row in rows.values(): row._parent_stage = stage # noqa: SLF001 # Finally create the Components with the stages they contain. for group in self._cntl.block_groups: if group.type == BlockGroupType.BLOCK_GROUP_TYPE_COMPONENT: stages = {stage.name: stage for stage in self._stages.values() if stage._trace_block_group.parent_component_name == group.name} # noqa: SLF001 rows = {row.name: row for row in self._rows.values() if row._trace_block_group.parent_component_name == group.name} # noqa: SLF001 component = block_groups.Component(group, self._world_communicator, self._cntl, self._all_blocks, stages, rows) self._components[component.name] = component for row in rows.values(): row._parent_component = component # noqa: SLF001
[docs] def setup_simulation(self): """Allocate cpp structures and create python wrappers.""" if not self._solver_structures_allocated: self._cntl.allocate_solver_structures() self._solver_structures_allocated = True self._extract_python_objects_from_trace()
[docs] def apply_changed_metadata(self): """Execute Trace meta data setup with input parameters changed by previous user commands.""" self._cntl.apply_changed_metadata()
@property def solver_step(self): """Returns the number of the current Trace (pseudo) time step.""" return self._cntl.get_solver_step() @property def pseudo_time_step(self) -> int: """Returns the number of the current Trace pseudo time step.""" return self._cntl.pseudo_time_step @property def n_pseudo_time_steps(self) -> int: """Returns the total number of the Trace pseudo time steps in one physical time step.""" return self._cntl.n_pseudo_time_steps @property def block_groups(self) -> collections.ChainMap[str, setup.BlockGroup]: """Returns dictionary of all blocks groups.""" return collections.ChainMap(self._rows, self._stages, self._components) @property def blocks(self) -> list[setup.Block]: """Returns a list of all blocks.""" return self._all_blocks @property def rows(self) -> dict[str, setup.Row]: """Returns dictionary of all rows.""" return self._rows @property def stages(self) -> dict[str, setup.Stage]: """Returns dictionary of all stages.""" return self._stages @property def components(self) -> dict[str, setup.Component]: """Returns dictionary of all components.""" return self._components @property def boundaries(self) -> dict[str, setup.Boundary]: """Returns dictionary of all boundaries.""" return self._boundaries @property def eigenmodes(self): """Returns list of all eigenmodes in this Trace simulation.""" return self._all_eigenmodes @property def online_analysis(self): """Get list of online analysis probes.""" return self._cntl.online_analysis
[docs] def reset_iteration_counter_to_beginning_of_time_step(self): """Reset the pseudo time step and stage both to 1 in order to recompute a physical time step instead of advancing the next one.""" self._cntl.reset_iteration_counter_to_beginning_of_time_step()
[docs] def run(self, n_steps = -1): """Perform `n_steps` pseudo time steps (steady/harmonic balance mode) or physical time steps (unsteady mode). Return the status as enum `SimulationState`. If no argument is given, Trace will continue until convergence or end of the simulation. :param n_steps: number of pseudo/physical time steps to run """ self.setup_simulation() return SimulationState(self._cntl.run(n_steps))
[docs] def get_cgns_output_data_file(self, output_type: OutputType) -> pathlib.Path: """Return the path of the cgns output file for the given output type as string.""" return pathlib.Path(self._cntl.get_cgns_output_data_file(output_type))
[docs] def set_cgns_output_data_file(self, output_type: OutputType, path: pathlib.Path, *, isActive: bool = True, interleave: int | None = None) -> None: """Set cgns output for the given output type.""" self._cntl.set_cgns_output_data_file(output_type, str(path), isActive, interleave or -1)
[docs] def set_ascii_output(self, ascii_output_type: AsciiOutputType, path: pathlib.Path, # noqa: PLR0913 Number of parameters inherited from C++ function *, is_active: bool = True, interleave: int = 1, sub_iteration_output_on: bool = False, binary_hdf5: bool = False) -> None: """Set output for the given output ascii type.""" return self._cntl.set_ascii_output(ascii_output_type, str(path), is_active, interleave, sub_iteration_output_on, binary_hdf5)
[docs] def reset_finished_flags(self): """Reset (multiple) Trace solver finish flags to suppress an immediate stop in a (new) call to `run()`.""" self._cntl.reset_finished_flags()
[docs] def increase_maximum_timestep_by_adding_value(self, n_timesteps): """Add 'n_timesteps' to the current number of maximum (pseudo) time steps.""" self._cntl.increase_maximum_timestep_by_adding_value(n_timesteps)
[docs] def reset_maximum_timestep(self, n_timesteps): """Set the number of maximum time steps to `n_timesteps`.""" self._cntl.reset_maximum_timestep(n_timesteps)
[docs] def set_reynolds_stress_uq(self, uq_method, *, limit_state_turbulence=None, # noqa: PLR0913 Number of parameters inherited from C++ function target_delta_b=0.0, tke_production_update=False, rotation_angle=float("nan"), rotation_angle_fraction=float("nan"), delta_b_ramp=(float("nan"), float("nan"))): """Set up uncertainty quantification method in order to disturb reynolds stresses.""" self._cntl.set_reynolds_stress_uq(uq_method, limit_state_turbulence, target_delta_b, tke_production_update, rotation_angle, rotation_angle_fraction, delta_b_ramp[0], delta_b_ramp[1])
@property def outlets(self) -> list[panel_groups.Outlet]: """Return a list containing panel groups of type Outlet.""" return [group for group in self._boundaries.values() if isinstance(group, panel_groups.Outlet)]
[docs] def write_output_files(self) -> None: """Write the current solution into the output files as specified (before) in the output settings.""" self._cntl.write_output_files()
[docs] def get_block(self, zone_id: int) -> block.Block: """Return the block with the given zoneID as python class `Block`. :param zone_id: ID of the block (i.e. zone) as specified in the cgns file. :return: Reference to the Trace block with the zoneID `zoneID`. """ return next(block for block in self._all_blocks if block.zone_id == zone_id)