"""Wrap a POST instance."""
from __future__ import annotations
import gc
import itertools
import logging
import pydoc
import typing
from mpi4py import MPI
from tracesuite import BoundaryType, SpatialAveraging, TemporalAveraging
from . import _post, postTasks
from .dataset import AccumulatorDataSet, DataSet
if typing.TYPE_CHECKING:
from tracesuite.trace import _trace
[docs]
class POST(postTasks.TasksMixin):
"""Representation of a POST instance."""
_n_instances: typing.ClassVar[int] = 0
def __init__(self, post_communicator: MPI.Comm = MPI.COMM_WORLD, *,
root_communicator: MPI.Comm = MPI.COMM_WORLD, show_splashscreen: bool = True):
"""Create a POST instance.
Only members of 'post_communicator' will actually do something in subsequent POST calls.
For tasks that interact with a TRACE instance the 'root_communicator' is used.
All processes that participate in TRACE or POST have to be members of this communicator.
:param post_communicator: MPI communicator of all processes that shall execute POST tasks.
:param root_communicator: MPI communicator of all processes that may execute POST or TRACE.
:param show_splashscreen: Print or not print the POST splashscreen.
"""
gc.collect() # Trigger garbage collection explicitly to ensure that old POST instances are wiped
assert POST._n_instances == 0, "Currently only one POST instance is supported!"
POST._n_instances += 1
super().__init__()
self._post_communicator = post_communicator
self._root_communicator = root_communicator
self._post_cntl = None
if self._post_communicator != MPI.COMM_NULL: # process is member of POST communicator
self._post_cntl = _post.PostCntl.setup(self._post_communicator, show_splashscreen)
logging.info(f"POST module using {'double' if _post.is_double_precision() else 'single'} precision")
@property
def is_comm_member(self) -> bool:
"""Return 'True' if the process is member of the POST root communicator."""
return False if self._post_cntl is None else self._post_cntl.comm.member
[docs]
@staticmethod
def help(specific_task: None | str = None) -> None:
"""Print POST general help or help of a specific task."""
all_tasks = dir(postTasks.TasksMixin)
if specific_task is None:
print("pyPOST tasks:")
public_tasks = [t for t in all_tasks if not t.startswith("_")]
indent = max(len(t) for t in public_tasks)
for task_name in public_tasks:
task = getattr(postTasks.TasksMixin, task_name)
print(f" {task_name: <{indent}} {task.__doc__.splitlines()[0]}")
else:
specific_task = specific_task.strip()
if specific_task not in all_tasks:
msg = f"pyPOST task '{specific_task}' not available."
raise ValueError(msg)
print(f"pyPOST task '{specific_task}':")
print(f" {pydoc.TextDoc().document(getattr(postTasks.TasksMixin, specific_task))}")
[docs]
def updateInterfaceIntegrals(self, data_set: DataSet, trace: _trace.TRACE, *,
time_average_type: TemporalAveraging = TemporalAveraging.TIME_AVERAGE) -> None:
"""Read 0D/1D interface data from a pyTRACE instance.
This is the in-memory pendant to the 'readInterfaceFiles' [py]POST task.
:param data_set: dataset
:param trace: pyTRACE instance
:param time_average_type: Time averaging type used. For unsteady simulations 'TemporalAveraging.INSTANTANEOUS' can be explicitly requested.
"""
if time_average_type not in {TemporalAveraging.TIME_AVERAGE, TemporalAveraging.INSTANTANEOUS}:
message = (f"'time_average_type' must be either {TemporalAveraging.TIME_AVERAGE} or {TemporalAveraging.INSTANTANEOUS}, "
f"but is '{time_average_type}'.")
raise ValueError(message)
spatial_average_types = (SpatialAveraging.AREA, SpatialAveraging.FLUX, SpatialAveraging.MASS)
for panel_group in trace.panel_groups.values():
if panel_group.boundary_type not in {BoundaryType.ENTRY, BoundaryType.EXIT, BoundaryType.INTERFACE}:
continue
member = self.is_comm_member or panel_group.old_comm.master
key = 0 if panel_group.old_comm.master else 1 # ensure panel group master becomes master of the new communicator
used_comm = self._root_communicator.Split(color=0 if member else MPI.UNDEFINED, key=key)
if not member:
continue
radial_distributions = []
for spatial_average_type in spatial_average_types:
radial_distributions.append(panel_group.interface_data_0d(time_average_type, spatial_average_type, do_broadcast=False))
if panel_group.n_bands > 0:
radial_distributions.append(panel_group.interface_data_1d(time_average_type, spatial_average_type, do_broadcast=False))
radial_distributions = used_comm.bcast(radial_distributions, root=0)
if self.is_comm_member:
data_set.merge_radial_distributions(*radial_distributions)
def __del__(self):
assert self._post_cntl is None or self.is_comm_member
if self.is_comm_member:
self._post_cntl.kill()
POST._n_instances -= 1
@staticmethod
def _check_dataset(dataset: DataSet, *, is_accumulator_task: bool = False) -> None:
if dataset is None:
msg = ("A input dataset is None, but must be of type PostDataSet.\n"
"Maybe the return value of a post task which does only modify a given dataset, and as such returning None, has been used.")
raise TypeError(msg)
if not isinstance(dataset, DataSet):
msg = f"All list entries must be of type PostDataSet. Got type '{type(dataset)}'."
raise TypeError(msg)
if not is_accumulator_task and isinstance(dataset, AccumulatorDataSet) and 0 < dataset.n_executions != dataset.i_execution:
msg = f"The accumulator dataset has only passed {dataset.i_execution} of {dataset.n_executions} iterations."
raise ValueError(msg)
if not dataset.is_valid:
msg = "The input data set is already destroyed."
raise ValueError(msg)
def _execute_input_task(self, cmd_line: str) -> DataSet | None:
"""Run the POST input task.
:param cmd_line: POST command line
:return: the new and freshly created dataset or 'None' for processes not in the POST communicator
"""
if not self.is_comm_member:
return None
n_input_datasets = 0
logging.debug(f"Setting up scheduler with task {cmd_line} ...")
self._post_cntl.scheduler_setup(cmd_line, n_input_datasets)
logging.debug(f"Executing task {cmd_line} ...")
data_set, state_buffer = self._post_cntl.scheduler_execute(n_input_datasets)
assert(data_set is not None)
assert(state_buffer is None)
logging.debug(f"Executing line {cmd_line} finished.")
logging.debug("A new dataset has been created.")
return DataSet(data_set)
def _execute_default_task(self, cmd_line: str, input_data_sets: DataSet | list[DataSet] | None) -> DataSet | None:
"""Run a POST default task.
This task takes one or more datasets and executes all scheduled executions in order to complete the task.
:param cmd_line: POST command line
:param input_data_sets: one or more input datasets
:return: a new dataset or 'None' for processes not in the POST communicator
"""
if not self.is_comm_member:
return None
input_data_sets = input_data_sets if isinstance(input_data_sets, list) else [input_data_sets]
for dataset in input_data_sets:
self._check_dataset(dataset)
n_input_datasets = len(input_data_sets)
logging.debug(f"Setting up scheduler with task {cmd_line} ...")
self._post_cntl.scheduler_setup(cmd_line, n_input_datasets)
for dataset in input_data_sets:
dataset.schedule(self._post_cntl, n_input_datasets)
logging.debug(f"Executing task {cmd_line} ...")
dataset, state_buffer = self._post_cntl.scheduler_execute(n_input_datasets)
assert state_buffer is None
logging.debug(f"Executing line {cmd_line} finished.")
if dataset is None:
logging.debug("No new dataset has been created.")
return None
logging.debug("A new dataset has been created.")
return DataSet(dataset)
def _execute_loop_task(self, cmd_line: str, dataset: DataSet | None, n_pics: int) -> typing.Generator[DataSet | None]:
"""Run a POST loop task.
This task starts a loop task and returns an iterator for the generated datasets.
An example is the reconstructTimeHistory task which generates 'n_pics' datasets from Fourier data.
:param cmd_line: POST command line
:param dataset: input dataset
:param n_pics: number of generated datasets
:return: a generator over newly created datasets or a generator over 'None' for processes not in the POST communicator
"""
if not self.is_comm_member:
return itertools.repeat(None, n_pics)
self._check_dataset(dataset)
n_input_datasets = 1
logging.debug(f"Setting up scheduler with task {cmd_line} ...")
self._post_cntl.scheduler_setup(cmd_line, n_input_datasets)
dataset.schedule(self._post_cntl, n_input_datasets)
state_buffer = None
while True:
logging.debug(f"Executing task {cmd_line} ...")
dataset, state_buffer = self._post_cntl.scheduler_execute(n_input_datasets, state_buffer=state_buffer)
assert dataset is not None
logging.debug(f"Executing line {cmd_line} finished.")
logging.debug("A new dataset has been created. Execution paused, Iterator returned")
yield DataSet(dataset)
if state_buffer is None:
break
def _execute_accumulator_task(self, cmd_line: str, dataset: DataSet | None, accumulator_data_set: AccumulatorDataSet | None,
n_pics: int) -> DataSet | None:
"""Run a POST accumulator task.
The accumulator task must be called 'n_pics' times in a loop and accumulates data in the 'accumulator_data_set'.
An example is the 'discreteFourierTransform' task.
:param cmd_line: POST command line
:param dataset: the dataset which is appended in the current iteration
:param accumulator_data_set: the dataset which accumulates the data, is 'None' in the first iteration
:param n_pics: the overall number of datasets that are accumulated
:return: the accumulated dataset or 'None' for processes not in the POST communicator
"""
if not self.is_comm_member:
return None
self._check_dataset(dataset)
n_input_datasets = 1 # accumulator dataset does not count as input dataset
logging.debug(f"Setting up scheduler with task {cmd_line} ...")
self._post_cntl.scheduler_setup(cmd_line, n_input_datasets)
dataset.schedule(self._post_cntl, n_input_datasets)
if isinstance(accumulator_data_set, AccumulatorDataSet):
self._check_dataset(accumulator_data_set, is_accumulator_task=True)
if accumulator_data_set.n_executions != n_pics:
raise RuntimeError("Number of executions changed")
accumulator_data_set.schedule(self._post_cntl, n_input_datasets, rewind=True)
elif accumulator_data_set is not None:
msg = f"accumulator_data_set must be of type AccumulatorDataSet or None. Got type '{type(accumulator_data_set)}'."
raise TypeError(msg)
i_execution = 0 if accumulator_data_set is None else accumulator_data_set.i_execution
if 0 < n_pics <= i_execution:
msg = f"All {n_pics} iterations have been used up, no further accumulation calls should be executed on this dataset."
raise RuntimeError(msg)
logging.debug(f"Executing task {cmd_line} ...")
updated_accumulator_dataset, state_buffer = self._post_cntl.scheduler_execute(n_input_datasets, i_execution=i_execution, n_executions=n_pics)
assert state_buffer is None
assert updated_accumulator_dataset is not None
logging.debug(f"Executing line {cmd_line} finished.")
logging.debug("The updated accumulator data set is returned.")
return AccumulatorDataSet(updated_accumulator_dataset, i_execution + 1, n_pics)