Source code for tracesuite.trace.block

"""Contains the general representation of a Trace Block as well as related classes and methods."""
from __future__ import annotations

import typing

import numpy as np

from tracesuite import simulation_setup as setup
from tracesuite.trace import _trace

from .trace_entity_base import TraceEntityBase

if typing.TYPE_CHECKING:
    from . import block_groups


[docs] class Block(setup.Block, TraceEntityBase): """Python class representing a general block in the Trace context. I.e. a structured or unstructured part of the computational domain handled by an instance of `SolverCntl`. Note that Trace holds meta information of all blocks on each rank but only allocates actual (e.g. solution) data on blocks that are assigned to its own rank (i.e. local blocks). If this is a local block, dimensionalized access to the underlying data fields is provided. Furthermore, iterators can be used to loop over all cells in a single loop. All methods and properties are valid on each rank. Nevertheless, if the block is not local, fields will be empty and iterators loop length will be zero. """ variable_names: typing.ClassVar[tuple[str]] = ( "WallDistance", "Mach", "ViscosityEddy", "ViscosityEddyRatio", "TurbulentEnergyKinetic", "TurbulentDissipationRate", "TurbulenceIntensity", "TurbulentProduction", "ReynoldsStressXX", "ReynoldsStressXY", "ReynoldsStressXZ", "ReynoldsStressYY", "ReynoldsStressYZ", "ReynoldsStressZZ", "StrainNorm", "StrainRateXX", "StrainRateXY", "StrainRateXZ", "StrainRateYY", "StrainRateYZ", "StrainRateZZ", "VorticityNorm", "VorticityXY", "VorticityXZ", "VorticityYZ", "TkeGradientX", "TkeGradientY", "TkeGradientZ", "PressureGradientX", "PressureGradientY", "PressureGradientZ", "VelocityXGradientX", "VelocityXGradientY", "VelocityXGradientZ", "VelocityYGradientX", "VelocityYGradientY", "VelocityYGradientZ", "VelocityZGradientX", "VelocityZGradientY", "VelocityZGradientZ", "PerturbationMagnitudeUQ", ) def __init__(self, cntl: _trace.SolverCntl, trace_block: _trace.Block): """Construct a new instance using the associated trace_block and the Simulation handle it belongs to. If this is a local block (i.e. has actual data stored in it) this constructor will prepare python access via numpy arrays to all available variable fields. :param trace_block: Uniquely links this class to a Trace c-struct of type `Block`. :param cntl: Links this Block to the associated Trace computation and allows convenient access to e.g. its global metadata. """ TraceEntityBase.__init__(self, cntl) self._n_ghost_layers = _trace.get_no_of_ghost_layers() self.trace_block = trace_block self._family = None if self.is_local: self.non_dimensional_data = trace_block.get_fields() assert self.non_dimensional_data is not None # Block must be local assert self.non_dimensional_data["CenterX"].ndim in (1, 3) # structured or unstructured dimensions = 3 # because of Pylint self.structured = self.non_dimensional_data["CenterX"].ndim == dimensions self.pressure = DimensionalArrayAccess(self.non_dimensional_data["Pressure"], "Pressure") self.temperature = DimensionalArrayAccess(self.non_dimensional_data["Temperature"], "Temperature") self.velocity_x = DimensionalArrayAccess(self.non_dimensional_data["VelocityX"], "VelocityX") self.velocity_y = DimensionalArrayAccess(self.non_dimensional_data["VelocityY"], "VelocityY") self.velocity_z = DimensionalArrayAccess(self.non_dimensional_data["VelocityZ"], "VelocityZ") self.density = DimensionalArrayAccess(self.non_dimensional_data["Density"], "Density") self.vertex_x = DimensionalArrayAccess(self.non_dimensional_data["VertexX"], "CoordinateX") self.vertex_y = DimensionalArrayAccess(self.non_dimensional_data["VertexY"], "CoordinateY") self.vertex_z = DimensionalArrayAccess(self.non_dimensional_data["VertexZ"], "CoordinateZ") self.center_x = DimensionalArrayAccess(self.non_dimensional_data["CenterX"], "CoordinateX") self.center_y = DimensionalArrayAccess(self.non_dimensional_data["CenterY"], "CoordinateY") self.center_z = DimensionalArrayAccess(self.non_dimensional_data["CenterZ"], "CoordinateZ") self.reciprocal_volume = DimensionalArrayAccess(self.non_dimensional_data["Jacobian"], "Jacobian") for variable_name in set(self.variable_names).intersection(self.non_dimensional_data): setattr(self, variable_name[:1].lower() + variable_name[1:], DimensionalArrayAccess(self.non_dimensional_data[variable_name], variable_name)) @property def name(self) -> str: """Return the name of this block as specified by the cgns-file.""" return self.trace_block.name @property def zone_id(self) -> int: """Return the zone_id of this block as specified by the cgns-file. Enumeration starts with 1.""" return self.trace_block.zone_id @property def _block_id(self): """Return the blockId of this block. (= zone_id -1).""" return self.zone_id - 1 @property def cells(self): """Return an iterator that loops only over all cells of a block including ghost cells.""" if self.structured: return structured_cell_iterator(self, 0) raise NotImplementedError("Unstructured mesh iterator not yet implemented.") @property def inner_cells(self): """Return an iterator that loops only over the inner cells of a block omitting the ghost cells.""" if self.structured: return structured_cell_iterator(self, self._n_ghost_layers) raise NotImplementedError("Unstructured mesh iterator not yet implemented.") @property def dim(self): """Return the dimension of this block including the ghost cell layers as CellIndex.""" shape = self.non_dimensional_data["CenterX"].shape return CellIndex(shape[0], shape[1], shape[2]) if self.structured else CellIndex(shape[0], 0, 0) @property def is_local(self): """Return a boolean flag indicating whether this block is associated to this rank. Note that Trace holds meta information of all blocks on each rank but only allocates actual (e.g. solution) data on blocks that are assigned to its own rank (i.e. local blocks). """ return self.trace_block.is_local @property def family(self) -> block_groups.BlockGroup: """Return the block family.""" return self._family
class DimensionalArrayAccess: """Wrapper class for numpy arrays to allow dimensionalized access opaque to the user. It hides the application of a dimensionalization factor by overloading the indexing operator. """ def __init__(self, memview: memoryview, trace_variable_name: str): """Create instance from numpy array to wrap and the associated dimensionalization factor. :param memview: memoryview to be wrapped. Can have arbitrary dimensions :param trace_variable_name: Name of the variable in TRACE. Used for getting the dimensionalization factor """ self._ndarray = np.array(memview, copy=False) self._dim_factor = _trace.get_dimension_factor_by_name(trace_variable_name) self._dim_factor_inv = 1 / self._dim_factor def __getitem__(self, indices): """Overloads the read access via the []-operator.""" return self._ndarray[indices] * self._dim_factor def __setitem__(self, indices, value): """Overloads the write access via the []-operator.""" self._ndarray[indices] = value * self._dim_factor_inv def __str__(self): """Create pretty string representation.""" return f"Array object with dimensionalized access:\n{self._ndarray * self._dim_factor}" def __repr__(self): """Create parsable object representation.""" return f"DimensionalArrayAccess({self._ndarray}, {self._dim_factor})" class CellIndex(typing.NamedTuple): """Python class describing a three-dimensional structured cell index to be used as an iterator. For unstructured blocks the values of j and k are set to zero. """ i: int j: int k: int def structured_cell_iterator(block, n_ghost_layers): """Create a generator yielding all cell indices of a 3D structured Trace block. Ghost layers can be omitted by specifying the number of rind indices to be skipped with variable `n_ghost_layers`. """ for i in range(n_ghost_layers, block.dim.i - n_ghost_layers): for k in range(n_ghost_layers, block.dim.k - n_ghost_layers): for j in range(n_ghost_layers, block.dim.j - n_ghost_layers): yield CellIndex(i, j, k)