modelicares.simres

This submodule contains the following classes:

  • SimRes - Class to load, analyze, and plot results from a Modelica simulation
  • SimResList - Special list of simulation results (SimRes instances)
  • Variable - Special namedtuple to represent a variable in a simulation, with methods to retrieve and perform calculations on its values
  • VarList - Special list of simulation variables (instances of Variable), with attributes to access information from all of the variables at once
class modelicares.simres.SimRes(fname='dsres.mat', constants_only=False, tool=None)

Bases: modelicares._res.Res

Class to load, analyze, and plot results from a Modelica simulation

Initialization arguments:

  • fname: Name of the file (including the directory if necessary)

  • constants_only: True to load only the variables from the first data table

    The first data table typically contains all of the constants, parameters, and variables that don’t vary. If only that information is needed, it may save resources to set constants_only to True.

  • tool: String indicating the simulation tool that created the file and thus the function to be used to load it

    By default, the available functions are tried in order until one works (or none do).

Methods using built-in Python operators and syntax:

  • __call__() - Access a list of variables by their names (invoked as sim(<list of variable names>)).

    The return value has attributes to retrieve information about all of the variables in the list at once (values, units, etc.).

  • __contains__() - Return True if a variable is present in the simulation results (invoked as <variable name> in sim).

  • __getitem__() - Access a variable by name (invoked as sim[<variable name>]).

    The return value has attributes to retrieve information about the variable (values, unit, etc.).

  • __len__() - Return the number of variables in the simulation (invoked as len(sim)).

Other methods:

  • browse() - Launch a variable browser.
  • find() - Find variable names that match a pattern.
  • plot() - Plot data as points and/or curves in 2D Cartesian coordinates.
  • sankey() - Create a figure with one or more Sankey diagrams.
  • to_pandas() - Return a pandas DataFrame with selected variables.

Properties:

  • dirname - Directory from which the variables were loaded
  • fbase - Base filename from which the results were loaded, without the directory or file extension.
  • fname - Filename from which the variables were loaded, with absolute path
  • n_constants - Number of variables that do not change over time
  • names - List of all the variable names
  • nametree - Tree of variable names that reflects the model hierarchy
  • tool - String indicating the function used to load the results (named after the corresponding Modelica tool)

Example:

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> print(sim) 
Modelica simulation results from .../examples/ChuaCircuit.mat
__call__(names)

Access a list of variables by their names.

This method returns VarList, give access to retrieve properties and call methods on all of the variables at once. Please see Variable or __getitem__() for more information about the the accessible attributes.

Arguments:

  • names: List of variable names

    The list can be nested, and the results will retain the hierarchy. If names is a single variable name, then the result is the same as from __getitem__().

Example:

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> sim(['L.v', 'L.i']).unit
['V', 'A']
__contains__(name)

Return True if a variable is present in the simulation results.

Arguments:

  • name: Name of variable

Example:

>>> sim = SimRes('examples/ChuaCircuit.mat')

>>> # 'L.v' is a valid variable name:
>>> 'L.v' in sim
True
>>> # but 'x' is not:
>>> 'x' in sim
False
__getitem__(name)

Access a variable by name.

This method returns a Variable instance, which has the following methods to retrieve information about the variable:

  • array() - Return an array of times and values for the variable.
  • FV() - Return the final value of the variable.
  • IV() - Return the final value of the variable.
  • max() - Return the maximum value of the variable.
  • mean() - Return the time-averaged value of the variable.
  • mean_rectified() - Return the time-averaged absolute value of the variable.
  • min() - Return the minimum value of the variable.
  • RMS() - Return the time-averaged root mean square value of the variable.
  • RMS_AC() - Return the time-averaged AC-coupled root mean square value of the variable.
  • times() - Return the sample times of the variable.
  • value() - Return the value of the variable if it is a constant (otherwise, error).
  • values() - Return the values of the variable.

and these properties:

  • description - The Modelica variable’s description string
  • unit - The Modelica variable’s unit attribute
  • displayUnit - The Modelica variable’s displayUnit attribute
  • is_constant - True, if the variable does not change over time

Examples:

>>> sim = SimRes('examples/ChuaCircuit.mat')

>>> sim['L.v'].unit
'V'

>>> sim['L.v'].values(t=(10,25)) 
array([ 0.2108,  0.3046,  0.3904,  0.468 ], dtype=float32)
__len__()

Return the number of variables in the simulation.

This includes the time variable.

Example:

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> print("There are %i variables in the %s simulation." %
...       (len(sim), sim.fbase))
There are 62 variables in the ChuaCircuit simulation.
browse()

Launch a variable browser.

When a variable is selected, the right panel shows its attributes and a simple plot of the variable over time. Variable names can be dragged and dropped into a text editor.

There are no arguments or return values.

Example:

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> sim.browse() 
variable browser
find(pattern=None, re=False, constants_only=False, as_tree=False)

Find variable names that match a pattern.

By default, all names are returned. The names are sorted alphabetically.

Arguments:

  • pattern: Case-sensitive string used for matching

    • If re is False (next argument), then the pattern follows the Unix shell style:

      Character(s) Role
      * Matches everything
      ? Matches any single character
      [seq] Matches any character in seq
      [!seq] Matches any char not in seq

      Wildcard characters (‘*’) are not automatically added at the beginning or the end of the pattern. For example, ‘*x*’ matches all variables that contain “x”, but ‘x*’ matches only the variables that begin with “x”.

    • If re is True, the regular expressions are used a la Python’s re module. See also http://docs.python.org/2/howto/regex.html#regex-howto.

      Since re.search() is used to produce the matches, it is as if wildcards (‘.*’) are automatically added at the beginning and the end. For example, ‘x’ matches all variables that contain “x”. Use ‘^x$’ to match only the variables that begin with “x” and ‘x$’ to match only the variables that end with “x”.

      Note that ‘.’ is a subclass separator in Modelica but a wildcard in regular expressions. Escape subclass separators as ‘\.’.

  • re: True to use regular expressions (False to use shell style)

  • constants_only: True to include only the variables that do not change over time

  • as_tree: True if the variable names should be returned as a nested dictionary representing the model hierarchy (otherwise, simple list)

    See nametree regarding the structure of the tree.

Example:

>>> sim = SimRes('examples/ChuaCircuit.mat')

>>> # Names for voltages across all of the components:
>>> sim.find('^[^.]*.v$', re=True) 
['C1.v', 'C2.v', 'G.v', 'L.v', 'Nr.v', 'Ro.v']
n_constants

Number of variables that do not change over time.

Note that this number may be greater than the number of declared constants in the Modelica model, since a variable may have a constant value even if it is not declared as a constant.

Example:

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> print("There are %i constants in the %s simulation." %
...       (sim.n_constants, sim.fbase))
There are 23 constants in the ChuaCircuit simulation.
names

List of all of the variable names

The names are sorted alphabetically.

Example:

>>> sim = SimRes('examples/ChuaCircuit.mat')

>>> # Names for voltages across all of the components:
>>> sim.names 
['C1.v', 'C2.v', 'G.v', 'L.v', 'Nr.v', 'Ro.v']
nametree

Tree of variable names based on the model hierarchy

The tree is a nested ordered dictionary. The keys are the Modelica class instances (including the index if there are arrays) and the values are the subclasses. The value at the end of each branch is the full variable name. All entries are sorted alphabetically.

To create a filtered tree, use find() with as_tree=True.

Example:

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> sim.nametree 
OrderedDict([('C1', OrderedDict([('C', 'C1.C'), ('der(v)', 'C1.der(v)'), ..., ('Time', 'Time')])
plot(ynames1=, []ylabel1=None, f1={}, legends1=, []leg1_kwargs={'loc': 'best'}, ax1=None, ynames2=, []ylabel2=None, f2={}, legends2=, []leg2_kwargs={'loc': 'best'}, ax2=None, xname='Time', xlabel=None, title=None, label='xy', incl_prefix=False, suffix=None, use_paren=True, **kwargs)

Plot variables as points and/or curves in 2D Cartesian coordinates.

The abscissa may be time or any other variable (i.e., scatterplots are possible).

Arguments:

  • ynames1: Name or list of names of variables for the primary y axis

    If any names are invalid, then they will be skipped.

  • ylabel1: Label for the primary y axis

    If ylabel1 is None (default) and all of the variables have the same Modelica description string, then it will be used as the label. Use ‘’ for no label.

  • f1: Dictionary of labels and functions for additional traces to be plotted on the primary y axis

    The functions take as the input a list of the vectors of values of the variables in ynames1, sampled at the values of the ‘Time’ variable.

  • legends1: List of legend entries for variables assigned to the primary y axis

    If legends1 is an empty list ([]), ynames1 will be used along with the keys from the f1 dictionary. If legends1 is None and all of the variables on the primary axis have the same unit, then no legend will be shown.

  • leg1_kwargs: Dictionary of keyword arguments for the primary legend

  • ax1: Primary y axes

    If ax1 is not provided, then axes will be created in a new figure.

  • ynames2, ylabel2, f2, legends2, leg2_kwargs, and ax2: Similar to ynames1, ylabel1, f1, legends1, leg1_kwargs, and ax1 but for the secondary y axis

  • xname: Name of the x-axis variable

  • xlabel: Label for the x axis

    If xlabel is None (default), the variable’s Modelica description string will be applied. Use ‘’ for no label.

  • title: Title for the figure

    If title is None (default), then the title will be the base filename. Use ‘’ for no title.

  • label: Label for the figure (ignored if ax is provided)

    This is used as the base filename if the figure is saved using save() or saveall().

  • incl_prefix: If True, prefix the legend strings with the base filename of the class.

  • suffix: String that will be added at the end of the legend entries

  • use_paren: Add parentheses around the suffix

  • **kwargs: Propagated to modelicares.util.plot() and then to matplotlib.pyplot.plot().

    If both y axes are used (primary and secondary), then the dashes argument is ignored. The curves on the primary axis will be solid and the curves on the secondary axis will be dotted.

Returns:

  1. ax1: Primary y axes
  2. ax2: Secondary y axes

Example:

(Source code, png, hires.png, pdf)

plot of Chua circuit
sankey(names=[], times=[0], n_rows=1, title=None, subtitles=[], label='sankey', left=0.05, right=0.05, bottom=0.05, top=0.1, hspace=0.1, vspace=0.25, **kwargs)

Create a figure with one or more Sankey diagrams.

Arguments:

  • names: List of names of the flow variables

  • times: List of times at which the variables should be sampled

    If multiple times are given, then subfigures will be generated, each with a Sankey diagram.

  • n_rows: Number of rows of subplots

  • title: Title for the figure

    If title is None (default), then the title will be “Sankey Diagram of fbase”, where fbase is the base filename of the data. Use ‘’ for no title.

  • subtitles: List of titles for each subplot

    If not provided, “t = x s” will be used, where x is the time of each entry. “(initial)” or “(final)” is appended if applicable.

  • label: Label for the figure

    This is used as the base filename if the figure is saved using save() or saveall().

  • left: Left margin

  • right: Right margin

  • bottom: Bottom margin

  • top: Top margin

  • hspace: Horizontal space between columns of subplots

  • vspace: Vertical space between rows of subplots

  • **kwargs: Additional arguments for matplotlib.sankey.Sankey

Returns:

  1. List of matplotlib.sankey.Sankey instances of the subplots

Example:

(Source code, png, hires.png, pdf)

Sankey diagram of three tanks
to_pandas(names=None, aliases={})

Return a pandas DataFrame with values from selected variables.

The index is time. The column headings indicate the variable names as well as the units.

The data frame has methods for further manipulation and exporting (e.g., to_clipboard(), to_csv(), to_excel(), to_hdf(), and to_html()).

Arguments:

  • names: String or list of strings of the variable names

    If names is None (default), then all variables are included.

  • aliases: Dictionary of aliases for the variable names

    The keys are the “official” variable names from the Modelica model and the values are the names as they should be included in the column headings. Any variables not in this list will not be aliased. Any unmatched aliases will not be used.

Examples:

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> voltages = sim.find('^[^.]*.v$', re=True)
>>> sim.to_pandas(voltages) 
          C1.v / V  C2.v / V   G.v / V   L.v / V  Nr.v / V  Ro.v / V
Time / s
0         4.000000  0.000000 -4.000000  0.000000  4.000000  0.000000
5         3.882738  0.109426 -3.773312  0.109235  3.882738  0.000191
...
[514 rows x 6 columns]

We can relabel columns using the aliases argument:

>>> sim = SimRes('examples/ThreeTanks.mat')
>>> aliases = {'tank1.level': "Tank 1 level",
...            'tank2.level': "Tank 2 level",
...            'tank3.level': "Tank 3 level"}
>>> sim.to_pandas(list(aliases), aliases) 
           Tank 1 level / m  Tank 2 level / m  Tank 3 level / m
Time / s
0.000000           8.000000          3.000000          3.000000
0.400000           7.974962          2.990460          3.034578
0.800000           7.950003          2.981036          3.068961
1.200000           7.925121          2.971729          3.103150
1.600000           7.900317          2.962539          3.137144
...
[502 rows x 3 columns]
class modelicares.simres.SimResList(*args)

Bases: modelicares._res.ResList

Special list of simulation results (SimRes instances)

Initialization signatures:

  • SimResList(): Returns an empty simulation list

  • SimResList(sims), where sims is a list of SimRes instances: Casts the list into a SimResList

  • SimResList(filespec), where filespec is a filename or directory, possibly with wildcards a la glob: Returns a SimResList of SimRes instances loaded from the matching or contained files

    The filename or directory must include the absolute path or be resolved to the current directory.

    An error is only raised if no files can be loaded.

  • SimResList(filespec1, filespec2, ...): Loads all files matching or contained by filespec1, filespec2, etc. as above.

    Each file will be opened once at most; duplicate filename matches are ignored.

Built-in methods

The list has all of the methods of a standard Python list (e.g., + or __add__/__radd__, clear(), del or __delitem__, += or __iadd__, *= or __imul__, iter() or __iter__, copy(), extend(), index(), insert(), len() or __len__, * or __mul__/__rmul__, pop(), remove(), reverse(), reversed() or __reversed__, = or __setitem__, __sizeof__(), and sort()). By default, the sort() method orders the list of simulations by the full path of the result files. Note that len() returns the number of simulations, not the number of variables like it does for SimRes.

Overloaded standard methods:

  • append() - Add simulation(s) to the end of the list of simulations (accepts a SimRes instance, directory, or filename).

  • __getitem__() - Retrieve a simulation using an index, simulations using a slice, or a variable across the list of simulations using a variable name.

  • __contains__() - Return True if:

    • a simulation is in the list of simulations or
    • a variable name is present in all of the simulations in the list.

Additional methods:

  • find() - Find the names of variables that are present in all of the simulations and that match a pattern.
  • plot() - Plot data from the simulations in 2D Cartesian coordinates.
  • get_unique_IVs() - Return a dictionary of initial values that are different among the variables that the simulations share.

Properties:

  • basedir - Highest common directory that the result files share
  • unique_names - Return a dictionary of variable names that are not in all of the simulations.
  • names - List of names of variables that are present in all of the simulations
  • nametree - Tree of the common variable names of the simulations based on the model hierarchy
  • Also, the properties of SimRes (dirname, fbase, fname, n_constants, and tool) can be retrieved as a list across all of the simulations; see the example below.

Example:

>>> sims = SimResList('examples/ChuaCircuit/*/')
>>> sims.dirname 
['.../examples/ChuaCircuit/1', '.../examples/ChuaCircuit/2']
__contains__(item)

Return True if a variable is present in all of the simulation results or a simulation is present in the list of simulations.

This method is overloaded—item can be a string representing a variable name or a SimRes instance.

Example:

First, load some simulations:

>>> sims = SimResList('examples/ChuaCircuit/*/')

Now check if a variable is in all of the simulations:

>>> 'L.L' in sims
True

or if a simulation in the list:

>>> sims[0] in sims
True
__getitem__(i)

Return a list of results of a variable across all of the simulations or a simulation from the list of simulations.

This method is overloaded beyond the standard indexing and slicing. If the index (i) is a variable name (string), then a VarList is returned with references to the corresponding variable in each of the simulations. That list can be used to access the attributes listed in SimRes.__getitem__() and described further in Variable.

Example:

>>> sims = SimResList('examples/ChuaCircuit/*/')
>>> sims['L.v'].mean() 
[0.0013353984, 0.023054097]
append(item)

Add simulation(s) to the end of the list of simulations.

Arguments:

  • item: SimRes instance or a file specification

    The file specification may be a filename or directory, possibly with wildcards a la glob, where simulation results can be loaded by SimRes. The filename or directory must include the absolute path or be resolved to the current directory. An error is only raised if no files can be loaded.

Unlike the append method of a standard Python list, this method may add more than one item. If item is a directory or a wildcarded filename, it may match multiple valid files.

Simulation results will be appended to the list even if they are already included.

Example:

>>> sims = SimResList('examples/ChuaCircuit/*/')
>>> sims.append('examples/ThreeTanks.mat')
>>> print(sims) 
List of simulation results (SimRes instances) from the following files
in the .../examples directory:
   ChuaCircuit/1/dsres.mat
   ChuaCircuit/2/dsres.mat
   ThreeTanks.mat
find(pattern=None, re=False, constants_only=False, as_tree=False)

Find the names of variables that are present in all of the simulations and that match a pattern.

By default, all of the common variables are returned. The names are sorted alphabetically.

Arguments:

  • pattern: Case-sensitive string used for matching

    • If re is False (next argument), then the pattern follows the Unix shell style:

      Character(s) Role
      * Matches everything
      ? Matches any single character
      [seq] Matches any character in seq
      [!seq] Matches any char not in seq

      Wildcard characters (‘*’) are not automatically added at the beginning or the end of the pattern. For example, ‘*x*’ matches all variables that contain “x”, but ‘x*’ matches only the variables that begin with “x”.

    • If re is True, regular expressions are used a la Python’s re module. See also http://docs.python.org/2/howto/regex.html#regex-howto.

      Since re.search() is used to produce the matches, it is as if wildcards (‘.*’) are automatically added at the beginning and the end. For example, ‘x’ matches all variables that contain “x”. Use ‘^x$’ to match only the variables that begin with “x” and ‘x$’ to match only the variables that end with “x”.

      Note that ‘.’ is a subclass separator in Modelica but a wildcard in regular expressions. Escape subclass separators as ‘\.’.

  • re: True to use regular expressions (False to use shell style)

  • constants_only: True to include only the variables that do not change over time

  • as_tree: True if the variable names should be returned as a nested dictionary representing the model hierarchy (otherwise, simple list)

    See nametree regarding the structure of the tree.

Example:

>>> sims = SimResList('examples/ChuaCircuit/*/')

>>> # Names for voltages across all of the components:
>>> sorted(sims.find('^[^.]*.v$', re=True))
['C1.v', 'C2.v', 'G.v', 'L.v', 'Nr.v', 'Ro.v']
get_unique_IVs(constants_only=False, tolerance=1e-10)

Return a dictionary of initial values that are different among the variables that the simulations share. Each key is a variable name and each value is a list of initial values across the simulations.

Arguments:

  • constants_only: True to include only the variables that do not change over time
  • tolerance: Maximum variation allowed for values to still be considered the same

Example:

>>> sims = SimResList('examples/ChuaCircuit/*/')
>>> print(sims) 
List of simulation results (SimRes instances) from the following files
in the .../examples/ChuaCircuit directory:
   1/dsres.mat
   2/dsres.mat
>>> sims.get_unique_IVs()['L.L'] 
[15.0, 21.0]
names

List of all of the names of variables that are present in all of the simulations

The names are sorted alphabetically.

Example:

>>> sims = SimResList('examples/ChuaCircuit/*/')
>>> sims.names 
['C1.C', 'C1.der(v)', 'C1.i', 'C1.n.i', ..., 'Time']
nametree

Tree of the common variable names in the simulations based on the model hierarchy

The tree is a nested ordered dictionary. The keys are the Modelica class instances (including the index if there are arrays) and the values are the subclasses. The value at the end of each branch is the full variable name. All entries are sorted alphabetically.

To create a filtered tree, use find() with as_tree*=*True.

Example:

>>> sims = SimResList('examples/ChuaCircuit/*/')
>>> sims.nametree 
OrderedDict([('C1', OrderedDict([('C', 'C1.C'), ('der(v)', 'C1.der(v)'), ..., ('Time', 'Time')])
plot(*args, **kwargs)

Plot data from selected variables over all of the simulations in 2D Cartesian coordinates.

This method calls plot() from the included instances of SimRes.

A new figure is created if necessary.

Arguments:

*args and **kwargs are propagated to SimRes.plot() (then to modelicares.util.plot() and finally to matplotlib.pyplot.plot()), except for the following keyword arguments:

Returns:

  1. ax1: Primary y axes
  2. ax2: Secondary y axes

Example:

(Source code, png, hires.png, pdf)

plot of a Chua circuit with different inductances
unique_names

Dictionary of variable names that are not in all of the simulations

Each key is a variable name and each value is a Boolean list indicating if the associated variable appears in each of the simulations.

Example:

>>> sims = SimResList('examples/*')
>>> print(sims) 
List of simulation results (SimRes instances) from the following files
in the .../examples directory:
   ThreeTanks.mat
   ChuaCircuit.mat
>>> sims.unique_names['L.L'] 
[False, True]
class modelicares.simres.VarList

Bases: list

Special list of simulation variables (instances of Variable), allowing access to information from all of the variables at once

The properties and methods of this class are the same as Variable, except that they return lists. Each entry in the list is the result of accessing or calling the corresponding property or method of each simulation result.

This class is typically not instantiated directly by the user, but instances are returned when indexing multiple variables from a simulation result (__call__() method of a SimRes instance) or a single variable from multiple simulations (__getitem__() method of a SimResList). In the case of indexing multiple variables from a simulation result, this list may be nested.

Examples:

Multiple variables from a simulation:

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> voltages = sim(['C1.v', 'L.v'])
>>> voltages.FV()
[2.4209836, -0.25352862]

Single variable from multiple simulations:

>>> sims = SimResList('examples/ChuaCircuit/*/')
>>> sims['C1.v'].mean() 
[-1.6083468, 0.84736514]
class modelicares.simres.Variable

Bases: modelicares.simres.VariableNamedTuple

Special namedtuple to represent a variable in a simulation, with methods to retrieve and perform calculations on its values

This class is usually not instantiated directly by the user, but instances are returned when indexing a variable name from a simulation result (SimRes instance).

Examples:

Load a simulation and retrieve a variable (instance of this class):

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> T = sim['G.T_heatPort']

Get the variable’s description:

>>> T.description 
'Temperature of HeatPort'

Get the variable’s unit:

>>> T.unit
'K'

Get the variable’s display unit:

>>> T.displayUnit
'degC'

Determine if the variable is constant:

>>> T.is_constant
True

Besides the properties in the above, there are methods to retrieve times, values, and functions of the times and values (array(), FV(), IV(), max(), mean(), mean_rectified(), min(), RMS(), RMS_AC(), times(), value(), values()). Please see the summary in SimRes.__getitem__() or the full descriptions of those methods below.

FV(f=None)

Return function f of the final value of the variable.

Example:

Load a simulation and retrieve a variable:

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> C1_v = sim['C1.v']

Get the final value:

>>> C1_v.FV()
2.4209836
IV(f=None)

Return function f of the initial value of the variable.

Example:

Load a simulation and retrieve a variable:

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> C1_v = sim['C1.v']

Get the initial value:

>>> C1_v.IV()
4.0
RMS(f=None)

Return the time-averaged root mean square value of function f of the variable.

Example:

Load a simulation and retrieve a variable:

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> C1_v = sim['C1.v']

Get the root mean square value:

>>> C1_v.RMS()
2.4569478
RMS_AC(f=None)

Return the time-averaged AC-coupled root mean square value of function f of the variable.

Example:

Load a simulation and retrieve a variable:

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> C1_v = sim['C1.v']

Get the AC-coupled root mean square value:

>>> C1_v.RMS_AC()
3.1022301
array(t=None, ft=None, fv=None)

Return an array with function ft of the times of the variable as the first column and function fv of the values of the variable as the second column.

The times and values are taken at index or slice i. If i is None, then all times and values are returned.

Arguments:

  • t: Time index

    • Default or None: All samples are included.

    • float: Interpolate (linearly) to a single time.

    • list: Interpolate (linearly) to a list of times.

    • tuple: Extract samples from a range of times. The structure is similar to the arguments of Python’s slice function, except that the start and stop values can be floating point numbers. The samples within and up to the limits are included. Interpolation is not used.

      • (stop,): All samples up to stop are included.

        Be sure to include the comma to distinguish this tuple from a float.

      • (start, stop): All samples between start and stop are included.

      • (start, stop, skip): Every skipth sample is included between start and stop.

  • ft: Function that operates on the vector of times (default or None is identity)

  • fv: Function that operates on the vector of values (default or None is identity)

Example:

Load a simulation and retrieve a variable:

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> C1_v = sim['C1.v']

Get the recorded times and values between 0 and 10 s as an array:

>>> C1_v.array(t=(0, 10)) 
array([[  0.    ,   4.    ],
       [  5.    ,   3.8827],
       [ 10.    ,   3.8029]], dtype=float32)
is_constant

True if the variable does not change over time

Example:

Load a simulation and retrieve a variable:

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> C1_v = sim['C1.v']

Determine if the variable is constant:

>>> C1_v.is_constant
False
max(f=None)

Return the maximum value of function f of the variable.

Example:

Load a simulation and retrieve a variable:

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> C1_v = sim['C1.v']

Get the maximum value:

>>> C1_v.max()
4.5046349
mean(f=None)

Return the time-averaged arithmetic mean value of function f of the variable.

Example:

Load a simulation and retrieve a variable:

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> C1_v = sim['C1.v']

Get the mean value:

>>> C1_v.mean()
0.76859528
mean_rectified(f=None)

Return the time-averaged rectified arithmetic mean value of function f of the variable.

Example:

Load a simulation and retrieve a variable:

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> C1_v = sim['C1.v']

Get the rectified mean value:

>>> C1_v.mean_rectified()
2.2870927
min(f=None)

Return the minimum value of function f of the variable.

Example:

Load a simulation and retrieve a variable:

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> C1_v = sim['C1.v']

Get the minimum value:

>>> C1_v.min()
-3.8189442
times(t=None, f=None)

Return function f of the recorded times of the variable.

Arguments:

  • t: Time index

    This may have any of the forms listed in values(), but the useful ones are:

    • Default or None: All times are included.

    • tuple: Extract recorded times from a range of times. The structure is similar to the arguments of Python’s slice function, except that the start and stop values can be floating point numbers. The times within and up to the limits are included. Interpolation is not used.

      • (stop,): All times up to stop are included.

        Be sure to include the comma to distinguish this tuple from a float.

      • (start, stop): All recorded times between start and stop are included.

      • (start, stop, skip): Every skip*th recorded time is included between *start and stop.

  • f: Function that operates on the vector of recorded times (default or None is identity)

Example:

Load a simulation and retrieve a variable:

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> C1_v = sim['C1.v']

Get the recorded times between 0 and 20 s:

>>> C1_v.times(t=(0, 20))
array([  0.,   5.,  10.,  15.,  20.], dtype=float32)
value(f=None)

Return function f of the value of a constant variable.

This method raises a ValueError if the variable is time-varying.

Arguments:

  • f: Function that operates on the value (default or None is identity)

Example:

Load a simulation and retrieve a constant variable:

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> Ro_R = sim['Ro.R']

Get the value of the variable:

>>> Ro_R.value()
0.0125
values(t=None, f=None)

Return function f of the values of the variable.

Arguments:

  • t: Time index

    • Default or None: All samples are included.

    • float: Interpolate (linearly) to a single time.

    • list: Interpolate (linearly) to a list of times.

    • tuple: Extract samples from a range of times. The structure is similar to the arguments of Python’s slice function, except that the start and stop values can be floating point numbers. The samples within and up to the limits are included. Interpolation is not used.

      • (stop,): All samples up to stop are included.

        Be sure to include the comma to distinguish this tuple from a float.

      • (start, stop): All samples between start and stop are included.

      • (start, stop, skip): Every skipth sample is included between start and stop.

  • f: Function that operates on the vector of values (default or None is identity)

Examples:

Load a simulation and retrieve a variable.

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> C1_v = sim['C1.v']

Get the recorded values between 0 and 20 s:

>>> C1_v.values(t=(0, 20)) 
array([ 4.    ,  3.8827,  3.8029,  3.756 ,  3.7374], dtype=float32)

Get the interpolated values at 2.5 and 17.5 s:

>>> C1_v.values(t=[2.5, 17.5])
[3.941368936561048, 3.7467045785160735]