4.7.4. pde.trackers.trackers module

Module defining classes for tracking results from simulations.

The trackers defined in this module are:

CallbackTracker

Tracker calling a function periodically

ProgressTracker

Tracker showing the progress of the simulation

PrintTracker

Tracker printing data to a stream (default: stdout)

PlotTracker

Tracker plotting data on screen, to files, or writes a movie

LivePlotTracker

PlotTracker with defaults for live plotting

DataTracker

Tracker storing custom data obtained by calling a function

SteadyStateTracker

Tracker aborting the simulation once steady state is reached

RuntimeTracker

Tracker interrupting the simulation once a duration has passed

ConsistencyTracker

Tracker interrupting the simulation when the state is not finite

MaterialConservationTracker

Tracking interrupting the simulation when material conservation is broken

class CallbackTracker(func: Callable, interval: Union[InterruptsBase, float, str, Sequence[float], ndarray] = 1)[source]

Bases: TrackerBase

Tracker calling a function periodically

Example

The callback tracker can be used to check for conditions during the simulation:

def check_simulation(state, time):
    if state.integral < 0:
        raise StopIteration

tracker = CallbackTracker(check_simulation, interval="0:10")

Adding tracker to the simulation will perform a check every 10 real time seconds. If the integral of the entire state falls below zero, the simulation will be aborted.

Parameters
  • func – The function to call periodically. The function signature should be (state) or (state, time), where state contains the current state as an instance of FieldBase and time is a float value indicating the current time. Note that only a view of the state is supplied, implying that a copy needs to be made if the data should be stored. The function can thus adjust the state by modifying it in-place and it can even interrupt the simulation by raising the special exception StopIteration.

  • interval – Determines how often the tracker interrupts the simulation. Simple numbers are interpreted as durations measured in the simulation time variable. Alternatively, a string using the format ‘hh:mm:ss’ can be used to give durations in real time. Finally, instances of the classes defined in interrupts can be given for more control.

handle(field: FieldBase, t: float) None[source]

handle data supplied to this tracker

Parameters
  • field (FieldBase) – The current state of the simulation

  • t (float) – The associated time

class ConsistencyTracker(interval: Optional[Union[InterruptsBase, float, str, Sequence[float], ndarray]] = None)[source]

Bases: TrackerBase

Tracker interrupting the simulation when the state is not finite

Parameters

interval – Determines how often the tracker interrupts the simulation. Simple numbers are interpreted as durations measured in the simulation time variable. Alternatively, a string using the format ‘hh:mm:ss’ can be used to give durations in real time. Finally, instances of the classes defined in interrupts can be given for more control. The default value None checks for consistency approximately every (real) second.

handle(field: FieldBase, t: float) None[source]

handle data supplied to this tracker

Parameters
  • field (FieldBase) – The current state of the simulation

  • t (float) – The associated time

name = 'consistency'
class DataTracker(func: Callable, interval: Union[InterruptsBase, float, str, Sequence[float], ndarray] = 1, filename: str = None)[source]

Bases: CallbackTracker

Tracker storing custom data obtained by calling a function

times

The time points at which the data is stored

Type

list

data

The actually stored data, which is a list of the objects returned by the callback function.

Type

list

Parameters
  • func – The function to call periodically. The function signature should be (state) or (state, time), where state contains the current state as an instance of FieldBase and time is a float value indicating the current time. Note that only a view of the state is supplied, implying that a copy needs to be made if the data should be stored. Typical return values of the function are either a single number, a numpy array, a list of number, or a dictionary to return multiple numbers with assigned labels.

  • interval – Determines how often the tracker interrupts the simulation. Simple numbers are interpreted as durations measured in the simulation time variable. Alternatively, a string using the format ‘hh:mm:ss’ can be used to give durations in real time. Finally, instances of the classes defined in interrupts can be given for more control.

  • filename (str) – A path to a file to which the data is written at the end of the tracking. The data format will be determined by the extension of the filename. ‘.pickle’ indicates a python pickle file storing a tuple (self.times, self.data), whereas any other data format requires pandas.

property dataframe: pandas.DataFrame

the data in a dataframe

If func returns a dictionary, the keys are used as column names. Otherwise, the returned data is enumerated starting with ‘0’. In any case the time point at which the data was recorded is stored in the column ‘time’.

Type

pandas.DataFrame

finalize(info: Optional[Dict[str, Any]] = None) None[source]

finalize the tracker, supplying additional information

Parameters

info (dict) – Extra information from the simulation

handle(field: FieldBase, t: float) None[source]

handle data supplied to this tracker

Parameters
  • field (FieldBase) – The current state of the simulation

  • t (float) – The associated time

to_file(filename: str, **kwargs)[source]

store data in a file

The extension of the filename determines what format is being used. For instance, ‘.pickle’ indicates a python pickle file storing a tuple (self.times, self.data), whereas any other data format requires pandas. Supported formats include ‘csv’, ‘json’.

Parameters
  • filename (str) – Path where the data is stored

  • **kwargs – Additional parameters may be supported for some formats

class LivePlotTracker(interval: Union[InterruptsBase, float, str, Sequence[float], ndarray] = '0:03', *, show: bool = True, max_fps: float = 2, **kwargs)[source]

Bases: PlotTracker

PlotTracker with defaults for live plotting

The only difference to PlotTracker are the changed default values, where output is by default shown on screen and the interval is set something more suitable for interactive plotting. In particular, this tracker can be enabled by simply listing ‘plot’ as a tracker.

Parameters
  • interval – Determines how often the tracker interrupts the simulation. Simple numbers are interpreted as durations measured in the simulation time variable. Alternatively, a string using the format ‘hh:mm:ss’ can be used to give durations in real time. Finally, instances of the classes defined in interrupts can be given for more control.

  • title (str) – Text to show in the title. The current time point will be appended to this text, so include a space for optimal results.

  • output_file (str, optional) – Specifies a single image file, which is updated periodically, so that the progress can be monitored (e.g. on a compute cluster)

  • output_folder (str, optional) – Specifies a folder to which all images are written. The files will have names with increasing numbers.

  • movie_file (str, optional) – Specifies a filename to which a movie of all the frames is written after the simulation.

  • show (bool, optional) – Determines whether the plot is shown while the simulation is running. If False, the files are created in the background. This option can slow down a simulation severely.

  • max_fps (float) – Determines the maximal rate (frames per second) at which the plots are updated. Some plots are skipped if the tracker receives data at a higher rate. A larger value (e.g., math.inf) can be used to ensure every frame is drawn, which might penalizes the overall performance.

  • plot_args (dict) – Extra arguments supplied to the plot call. For example, this can be used to specify axes ranges when a single panel is shown. For instance, the value {‘ax_style’: {‘ylim’: (0, 1)}} enforces the y-axis to lie between 0 and 1.

name = 'plot'
class MaterialConservationTracker(interval: Union[InterruptsBase, float, str, Sequence[float], ndarray] = 1, atol: float = 0.0001, rtol: float = 0.0001)[source]

Bases: TrackerBase

Tracking interrupting the simulation when material conservation is broken

Parameters
  • interval – Determines how often the tracker interrupts the simulation. Simple numbers are interpreted as durations measured in the simulation time variable. Alternatively, a string using the format ‘hh:mm:ss’ can be used to give durations in real time. Finally, instances of the classes defined in interrupts can be given for more control.

  • atol (float) – Absolute tolerance for amount deviations

  • rtol (float) – Relative tolerance for amount deviations

handle(field: FieldBase, t: float) None[source]

handle data supplied to this tracker

Parameters
  • field (FieldBase) – The current state of the simulation

  • t (float) – The associated time

initialize(field: FieldBase, info: Optional[Dict[str, Any]] = None) float[source]
Parameters
  • field (FieldBase) – An example of the data that will be analyzed by the tracker

  • info (dict) – Extra information from the simulation

Returns

The first time the tracker needs to handle data

Return type

float

name = 'material_conservation'
class PlotTracker(interval: Union[InterruptsBase, float, str, Sequence[float], ndarray] = 1, *, title: Union[str, Callable] = 'Time: {time:g}', output_file: str = None, movie: Union[str, Path, Movie] = None, show: bool = None, max_fps: float = inf, plot_args: Dict[str, Any] = None)[source]

Bases: TrackerBase

Tracker plotting data on screen, to files, or writes a movie

This tracker can be used to create movies from simulations or to simply update a single image file on the fly (i.e. to monitor simulations running on a cluster). The default values of this tracker are chosen with regular output to a file in mind.

Parameters
  • interval – Determines how often the tracker interrupts the simulation. Simple numbers are interpreted as durations measured in the simulation time variable. Alternatively, a string using the format ‘hh:mm:ss’ can be used to give durations in real time. Finally, instances of the classes defined in interrupts can be given for more control.

  • title (str or callable) – Title text of the figure. If this is a string, it is shown with a potential placeholder named time being replaced by the current simulation time. Conversely, if title is a function, it is called with the current state and the time as arguments. This function is expected to return a string.

  • output_file (str, optional) – Specifies a single image file, which is updated periodically, so that the progress can be monitored (e.g. on a compute cluster)

  • movie (str or Movie) – Create a movie. If a filename is given, all frames are written to this file in the format deduced from the extension after the simulation ran. If a Movie is supplied, frames are appended to the instance.

  • show (bool, optional) – Determines whether the plot is shown while the simulation is running. If False, the files are created in the background. This option can slow down a simulation severely. For the default value of None, the images are only shown if neither output_file nor movie is set.

  • max_fps (float) – Determines the maximal rate (frames per second) at which the plots are updated in real time during the simulation. Some plots are skipped if the tracker receives data at a higher rate. A larger value (e.g., math.inf) can be used to ensure every frame is drawn, which might penalizes the overall performance.

  • plot_args (dict) – Extra arguments supplied to the plot call. For example, this can be used to specify axes ranges when a single panel is shown. For instance, the value {‘ax_style’: {‘ylim’: (0, 1)}} enforces the y-axis to lie between 0 and 1.

Note

If an instance of Movie is given as the movie argument, it can happen that the movie is not written to the file when the simulation ends. This is because, the movie could still be extended by appending frames. To write the movie to a file call its save() method. Beside adding frames before and after the simulation, an explicit movie object can also be used to adjust the output, e.g., by setting the dpi argument or the frame_rate.

finalize(info: Optional[Dict[str, Any]] = None) None[source]

finalize the tracker, supplying additional information

Parameters

info (dict) – Extra information from the simulation

handle(state: FieldBase, t: float) None[source]

handle data supplied to this tracker

Parameters
  • state (FieldBase) – The current state of the simulation

  • t (float) – The associated time

initialize(state: FieldBase, info: Optional[Dict[str, Any]] = None) float[source]

initialize the tracker with information about the simulation

Parameters
  • state (FieldBase) – An example of the data that will be analyzed by the tracker

  • info (dict) – Extra information from the simulation

Returns

The first time the tracker needs to handle data

Return type

float

class PrintTracker(interval: ~Union[~InterruptsBase, float, str, ~Sequence[float], ~numpy.ndarray] = 1, stream: ~IO[str] = <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[source]

Bases: TrackerBase

Tracker printing data to a stream (default: stdout)

Parameters
  • interval – Determines how often the tracker interrupts the simulation. Simple numbers are interpreted as durations measured in the simulation time variable. Alternatively, a string using the format ‘hh:mm:ss’ can be used to give durations in real time. Finally, instances of the classes defined in interrupts can be given for more control.

  • stream – The stream used for printing

handle(field: FieldBase, t: float) None[source]

handle data supplied to this tracker

Parameters
  • field (FieldBase) – The current state of the simulation

  • t (float) – The associated time

name = 'print'
class ProgressTracker(interval: Optional[Union[InterruptsBase, float, str, Sequence[float], ndarray]] = None, ndigits: int = 5, leave: bool = True)[source]

Bases: TrackerBase

Tracker showing the progress of the simulation

Parameters
  • interval – Determines how often the tracker interrupts the simulation. Simple numbers are interpreted as durations measured in the simulation time variable. Alternatively, a string using the format ‘hh:mm:ss’ can be used to give durations in real time. Finally, instances of the classes defined in interrupts can be given for more control. The default value None updates the progress bar approximately every (real) second.

  • ndigits (int) – The number of digits after the decimal point that are shown maximally.

  • leave (bool) – Whether to leave the progress bar after the simulation has finished (default: True)

finalize(info: Optional[Dict[str, Any]] = None) None[source]

finalize the tracker, supplying additional information

Parameters

info (dict) – Extra information from the simulation

handle(field: FieldBase, t: float) None[source]

handle data supplied to this tracker

Parameters
  • field (FieldBase) – The current state of the simulation

  • t (float) – The associated time

initialize(field: FieldBase, info: Optional[Dict[str, Any]] = None) float[source]

initialize the tracker with information about the simulation

Parameters
  • field (FieldBase) – An example of the data that will be analyzed by the tracker

  • info (dict) – Extra information from the simulation

Returns

The first time the tracker needs to handle data

Return type

float

name = 'progress'
class RuntimeTracker(max_runtime: Union[int, float, str], interval: Union[InterruptsBase, float, str, Sequence[float], ndarray] = 1)[source]

Bases: TrackerBase

Tracker interrupting the simulation once a duration has passed

Parameters
  • max_runtime (float or str) – The maximal runtime of the simulation. If the runtime is exceeded, the simulation is interrupted. Values can be either given as a number (interpreted as seconds) or as a string, which is then parsed using the function parse_duration().

  • interval – Determines how often the tracker interrupts the simulation. Simple numbers are interpreted as durations measured in the simulation time variable. Alternatively, a string using the format ‘hh:mm:ss’ can be used to give durations in real time. Finally, instances of the classes defined in interrupts can be given for more control.

handle(field: FieldBase, t: float) None[source]

handle data supplied to this tracker

Parameters
  • field (FieldBase) – The current state of the simulation

  • t (float) – The associated time

initialize(field: FieldBase, info: Optional[Dict[str, Any]] = None) float[source]
Parameters
  • field (FieldBase) – An example of the data that will be analyzed by the tracker

  • info (dict) – Extra information from the simulation

Returns

The first time the tracker needs to handle data

Return type

float

class SteadyStateTracker(interval: Optional[Union[InterruptsBase, float, str, Sequence[float], ndarray]] = None, atol: float = 1e-08, rtol: float = 1e-05, progress: bool = False)[source]

Bases: TrackerBase

Tracker aborting the simulation once steady state is reached

Steady state is obtained when the state does not change anymore. This is the case when the derivative is close to zero. Concretely, the current state cur is compared to the state prev at the previous time step. Convergence is assumed when abs(prev - cur) <= dt * (atol + rtol * cur) for all points in the state. Here, dt denotes the time that elapsed between the two states that are compared.

Parameters
  • interval – Determines how often the tracker interrupts the simulation. Simple numbers are interpreted as durations measured in the simulation time variable. Alternatively, a string using the format ‘hh:mm:ss’ can be used to give durations in real time. Finally, instances of the classes defined in interrupts can be given for more control. The default value None checks for the steady state approximately every (real) second.

  • atol (float) – Absolute tolerance that must be reached to abort the simulation

  • rtol (float) – Relative tolerance that must be reached to abort the simulation

  • progress (bool) – Flag indicating whether the progress towards convergence is shown graphically during the simulation

handle(field: FieldBase, t: float) None[source]

handle data supplied to this tracker

Parameters
  • field (FieldBase) – The current state of the simulation

  • t (float) – The associated time

name = 'steady_state'
progress_bar_format = 'Convergence: {percentage:3.0f}%|{bar}| [{elapsed}<{remaining}]'

determines the format of the progress bar shown when progress = True