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, interrupts=1, *, interval=None)[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 (Callable) – 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.

  • interrupts (InterruptData) – Determines when the tracker interrupts the simulation. A single numbers determines an interval (measured in the simulation time unit) of regular interruption. A string is interpreted as a duration in real time assuming the format ‘hh:mm:ss’. A list of numbers is taken as explicit simulation time points. More fine- grained contol is possible by passing an instance of classes defined in interrupts.

handle(field, t)[source]

handle data supplied to this tracker

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

  • t (float) – The associated time

Return type:

None

class ConsistencyTracker(interrupts=None, *, interval=None)[source]

Bases: TrackerBase

Tracker interrupting the simulation when the state is not finite

Parameters:

interrupts (InterruptData | None) – Determines when the tracker interrupts the simulation. A single numbers determines an interval (measured in the simulation time unit) of regular interruption. A string is interpreted as a duration in real time assuming the format ‘hh:mm:ss’. A list of numbers is taken as explicit simulation time points. More fine- grained contol is possible by passing an instance of classes defined in interrupts. The default value None checks for consistency approximately every (real) second.

handle(field, t)[source]

handle data supplied to this tracker

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

  • t (float) – The associated time

Return type:

None

name = 'consistency'
class DataTracker(func, interrupts=1, *, filename=None, interval=None)[source]

Bases: CallbackTracker

Tracker storing custom data obtained by calling a function

Example

The data tracker can be used to gather statistics during the run

def get_statistics(state, time):
    return {"mean": state.data.mean(), "variance": state.data.var()}

data_tracker = DataTracker(get_statistics, interval=10)

Adding data_tracker to the simulation will gather the statistics every 10 time units. After the simulation, the final result will be accessable via the data attribute or conveniently as a pandas from the dataframe attribute.

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 (Callable) – 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.

  • interrupts (InterruptData) – Determines when the tracker interrupts the simulation. A single numbers determines an interval (measured in the simulation time unit) of regular interruption. A string is interpreted as a duration in real time assuming the format ‘hh:mm:ss’. A list of numbers is taken as explicit simulation time points. More fine- grained contol is possible by passing an instance of classes defined in interrupts.

  • 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=None)[source]

finalize the tracker, supplying additional information

Parameters:

info (dict) – Extra information from the simulation

Return type:

None

handle(field, t)[source]

handle data supplied to this tracker

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

  • t (float) – The associated time

Return type:

None

to_file(filename, **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(interrupts='0:03', *, show=True, max_fps=2, interval=None, **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:
  • interrupts (InterruptData) – Determines when the tracker interrupts the simulation. A single numbers determines an interval (measured in the simulation time unit) of regular interruption. A string is interpreted as a duration in real time assuming the format ‘hh:mm:ss’. A list of numbers is taken as explicit simulation time points. More fine- grained contol is possible by passing an instance of classes defined in interrupts.

  • 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(interrupts=1, atol=0.0001, rtol=0.0001, *, interval=None)[source]

Bases: TrackerBase

Tracking interrupting the simulation when material conservation is broken

Parameters:
  • interrupts (InterruptData) – Determines when the tracker interrupts the simulation. A single numbers determines an interval (measured in the simulation time unit) of regular interruption. A string is interpreted as a duration in real time assuming the format ‘hh:mm:ss’. A list of numbers is taken as explicit simulation time points. More fine- grained contol is possible by passing an instance of classes defined in interrupts.

  • atol (float) – Absolute tolerance for amount deviations

  • rtol (float) – Relative tolerance for amount deviations

handle(field, t)[source]

handle data supplied to this tracker

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

  • t (float) – The associated time

Return type:

None

initialize(field, info=None)[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(interrupts=1, *, title='Time: {time:g}', output_file=None, movie=None, show=None, tight_layout=False, max_fps=inf, plot_args=None, interval=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.

Example

To create a movie while running the simulation, you can use

movie_tracker = PlotTracker(interval=10, movie="my_movie.mp4")
eq.solve(..., tracker=movie_tracker)

This will create the file my_movie.mp4 during the simulation. Note that you can display the frames interactively by setting show=True.

Parameters:
  • interrupts (InterruptData) – Determines when the tracker interrupts the simulation. A single numbers determines an interval (measured in the simulation time unit) of regular interruption. A string is interpreted as a duration in real time assuming the format ‘hh:mm:ss’. A list of numbers is taken as explicit simulation time points. More fine- grained contol is possible by passing an instance of classes defined in interrupts.

  • 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 set to None, the images are only shown if neither output_file nor movie is set, otherwise they are kept hidden. Note that showing the plot can slow down a simulation severely.

  • tight_layout (bool) – Determines whether tight_layout() is used.

  • 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. For instance, the following example code creates a movie with a framerate of 15, a resolution of 200 dpi, and a bitrate of 6000 kilobits per second:

movie = Movie("movie.mp4", framerate=15, dpi=200, bitrate=6000)
eq.solve(..., tracker=PlotTracker(1, movie=movie))
movie.save()
finalize(info=None)[source]

finalize the tracker, supplying additional information

Parameters:

info (dict) – Extra information from the simulation

Return type:

None

handle(state, t)[source]

handle data supplied to this tracker

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

  • t (float) – The associated time

Return type:

None

initialize(state, info=None)[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(interrupts=1, stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, *, interval=None)[source]

Bases: TrackerBase

Tracker printing data to a stream (default: stdout)

Parameters:
  • interrupts (InterruptData) – Determines when the tracker interrupts the simulation. A single numbers determines an interval (measured in the simulation time unit) of regular interruption. A string is interpreted as a duration in real time assuming the format ‘hh:mm:ss’. A list of numbers is taken as explicit simulation time points. More fine- grained contol is possible by passing an instance of classes defined in interrupts.

  • stream (IO[str]) – The stream used for printing

handle(field, t)[source]

handle data supplied to this tracker

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

  • t (float) – The associated time

Return type:

None

name = 'print'
class ProgressTracker(interrupts=None, *, fancy=True, ndigits=5, leave=True, interval=None)[source]

Bases: TrackerBase

Tracker showing the progress of the simulation

Parameters:
  • interrupts (InterruptData | None) – Determines when the tracker interrupts the simulation. A single numbers determines an interval (measured in the simulation time unit) of regular interruption. A string is interpreted as a duration in real time assuming the format ‘hh:mm:ss’. A list of numbers is taken as explicit simulation time points. More fine- grained contol is possible by passing an instance of classes defined in interrupts. The default value None updates the progress bar approximately every (real) second.

  • fancy (bool) – Flag determining whether a fancy progress bar should be used in jupyter notebooks (if ipywidgets is installed)

  • 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=None)[source]

finalize the tracker, supplying additional information

Parameters:

info (dict) – Extra information from the simulation

Return type:

None

handle(field, t)[source]

handle data supplied to this tracker

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

  • t (float) – The associated time

Return type:

None

initialize(field, info=None)[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, interrupts=1, *, interval=None)[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().

  • interrupts (InterruptData) – Determines when the tracker interrupts the simulation. A single numbers determines an interval (measured in the simulation time unit) of regular interruption. A string is interpreted as a duration in real time assuming the format ‘hh:mm:ss’. A list of numbers is taken as explicit simulation time points. More fine- grained contol is possible by passing an instance of classes defined in interrupts.

handle(field, t)[source]

handle data supplied to this tracker

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

  • t (float) – The associated time

Return type:

None

initialize(field, info=None)[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(interrupts=None, atol=1e-08, rtol=1e-05, *, progress=False, evolution_rate=None, interval=None)[source]

Bases: TrackerBase

Tracker aborting the simulation once steady state is reached

Steady state is obtained when the state does not change anymore, i.e., when the evolution rate is close to zero. If the argument evolution_rate is specified, it is used to calculate the evolution rate directly. If it is omitted, the evolution rate is estaimted by comparing the current state cur to the state prev at the previous time step. In both cases, convergence is assumed when the absolute value of the evolution rate falls below atol + rtol * cur for all points. Here, atol and rtol denote absolute and relative tolerances, respectively.

Parameters:
  • interrupts (InterruptData | None) – Determines when the tracker interrupts the simulation. A single numbers determines an interval (measured in the simulation time unit) of regular interruption. A string is interpreted as a duration in real time assuming the format ‘hh:mm:ss’. A list of numbers is taken as explicit simulation time points. More fine- grained contol is possible by passing an instance of classes defined in interrupts. 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

  • evolution_rate (callable) – Function to evaluate the current evolution rate. If omitted, the evolution rate is estimate from the change in the state variable, which can be less accurate. A suitable form of the function is returned by eq.make_pde_rhs(state) when eq is the PDE class.

handle(field, t)[source]

handle data supplied to this tracker

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

  • t (float) – The associated time

Return type:

None

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

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