Table Of Contents

modelicares.simres

Classes and functions to Load, analyze, and plot results from Modelica simulations

Classes:

  • SimRes - Class to load and analyze results from a Modelica-based simulation
  • Info - Aliases for the “get” methods in SimRes

Functions:

  • merge_times() - Merge a list of multiple time vectors into one vector
class modelicares.simres.Info

Aliases for the “get” methods in SimRes

Example:

>>> from modelicares.simres import SimRes, Info

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> Info.FV(sim, 'L.v')
-0.25352862
FV(names, f=<function <lambda> at 0x7f9da11eeed8>)

Alias for SimRes.get_FV()

IV(names, f=<function <lambda> at 0x7f9da11eede8>)

Alias for SimRes.get_IV()

description(names)

Alias for SimRes.get_description()

displayUnit(names)

Alias for SimRes.get_displayUnit()

indices_wi_times(names, t_1=None, t_2=None)

Alias for SimRes.get_indices_wi_times()

max(names, f=<function <lambda> at 0x7f9da11ef410>)

Alias for SimRes.get_max()

mean(names, f=<function <lambda> at 0x7f9da11ef500>)

Alias for SimRes.get_mean()

min(names, f=<function <lambda> at 0x7f9da11ef5f0>)

Alias for SimRes.get_min()

times(names, i=slice(0, None, None), f=<function <lambda> at 0x7f9da11ef050>)

Alias for SimRes.get_times()

tuple(names, i=slice(0, None, None))

Alias for SimRes.get_tuple()

unit(names)

Alias for SimRes.get_unit()

values(names, i=slice(0, None, None), f=<function <lambda> at 0x7f9da11ef1b8>)

Alias for SimRes.get_values()

values_at_times(names, times, f=<function <lambda> at 0x7f9da11ef2a8>)

Alias for SimRes.get_values_at_times()

class modelicares.simres.SimRes(fname='dsres.mat', constants_only=False)

Bases: object

Class to load and analyze results from a Modelica-based simulation

This class contains the following methods:

  • browse() - Launch a variable browser
  • get_description() - Return the description(s) of variable(s)
  • get_displayUnit() - Return the Modelica displayUnit attribute(s) of variable(s)
  • get_indices_wi_times() - Return the widest index pair(s) for which the time of signal(s) is within given limits
  • get_IV() - Return the initial value(s) of variable(s)
  • get_FV() - Return the final value(s) of variable(s)
  • get_max() - Return the maximum value(s) of variable(s)
  • get_mean() - Return the time-averaged value(s) of variable(s)
  • get_min() - Return the minimum value(s) of variable(s)
  • get_times() - Return vector(s) of the sample times of variable(s)
  • get_tuple() - Return tuple(s) of time and value vectors for variable(s)
  • get_unit() - Return the unit attribute(s) of variable(s)
  • get_values() - Return vector(s) of the values of the samples of variable(s)
  • get_values_at_times() - Return vector(s) of the values of the samples of variable(s)
  • names() - Return a list of variable names that match a pattern
  • nametree() - Return a tree of all variable names with respect to the path names
  • plot() - Plot data as points and/or curves in 2D Cartesian coordinates
  • sankey() - Create a figure with Sankey diagram(s)

On initialization, load Modelica simulation results from a MATLAB® file in Dymola® format.

Arguments:

  • fname: Name of the file (may include the path)

    The file extension (‘.mat’) is optional.

  • constants_only: True, if only the variables from the first data table should be loaded

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

Example:

>>> from modelicares import SimRes
>>> sim = SimRes('examples/ChuaCircuit.mat')
__call__(names, action=<function get_values at 0x7f9da11ef230>, *args, **kwargs)

Upon a call to an instance of SimRes, call a method on variable(s) given their name(s).

Arguments:

  • names: String or (possibly nested) list of strings of the variable names

  • action: Method for retrieving information about the variable(s)

    The default is get_values(). action may be a list or tuple, in which case the return value is a list or tuple.

  • *args, **kwargs: Additional arguments for action

Examples:

>>> from modelicares.simres import SimRes, Info
>>> sim = SimRes('examples/ChuaCircuit.mat')

# Values of a single variable
>>> sim('L.v') 
array([  0.00000000e+00, ... -2.53528625e-01], dtype=float32)
>>> # This is equivalent to:
>>> sim.get_values('L.v') 
array([  0.00000000e+00, ... -2.53528625e-01], dtype=float32)

# Values of a list of variables
>>> sim(['L.L', 'C1.C'], SimRes.get_description)
['Inductance', 'Capacitance']
>>> # This is equivalent to:
>>> sim.get_description(['L.L', 'C1.C'])
['Inductance', 'Capacitance']

# Other attributes
>>> print("The final value of %s is %.3f %s." %
...       sim('L.i', (Info.description, Info.FV, Info.unit)))
The final value of Current flowing from pin p to pin n is 2.049 A.
__contains__(name)

Test if a variable is present in the simulation results.

Arguments:

  • name: Name of variable

Example:

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

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

Upon accessing a variable name within an instance of SimRes, return its values.

Arguments:

  • names: String or (possibly nested) list of strings of the variable names

Examples:

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

>>> sim['L.v'] 
array([  0.00000000e+00, ... -2.53528625e-01], dtype=float32)
>>> # This is equivalent to:
>>> sim.get_values('L.v') 
array([  0.00000000e+00, ... -2.53528625e-01], dtype=float32)
__len__()

Return the number of variables in the simulation.

Example:

>>> from modelicares import SimRes
>>> 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.
__repr__()

Return a formal description of the SimRes instance.

Example:

>>> from modelicares import SimRes
>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> sim 
SimRes('...ChuaCircuit.mat')
__str__()

Return an informal description of the SimRes instance.

Example:

>>> from modelicares import SimRes
>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> print(sim) 
Modelica simulation results from "...ChuaCircuit.mat"
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:

>>> from modelicares import SimRes
>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> sim.browse()
variable browser
get_FV(names, f=<function <lambda> at 0x7f9da11eeed8>)

Return the final value(s) of variable(s).

Arguments:

  • names: String or (possibly nested) list of strings of variable names
  • f: Function that should be applied to the value(s) (default is identity)

If names is a string, then the output will be a single value. If names is a (optionally nested) list of strings, then the output will be a (nested) list of values.

Example:

>>> from modelicares import SimRes

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> sim.get_FV('L.v')
-0.25352862
get_IV(names, f=<function <lambda> at 0x7f9da11eede8>)

Return the initial value(s) of variable(s).

Arguments:

  • names: String or (possibly nested) list of strings of the variable names
  • f: Function that should be applied to the value(s) (default is identity)

If names is a string, then the output will be a single value. If names is a (optionally nested) list of strings, then the output will be a (nested) list of values.

Example:

>>> from modelicares import SimRes

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> sim.get_IV('L.v')
0.0
get_description(names)

Return the description(s) of variable(s).

Arguments:

  • names: Name(s) of the variable(s) from which to get the description(s)

    This may be a string or (possibly nested) list of strings representing the names of the variables.

If names is a string, then the output will be a single description. If names is a (optionally nested) list of strings, then the output will be a (nested) list of descriptions.

Example:

>>> from modelicares import SimRes

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> sim.get_description('L.v')
'Voltage drop between the two pins (= p.v - n.v)'
get_displayUnit(names)

Return the Modelica displayUnit attribute(s) of variable(s).

Arguments:

  • names: Name(s) of the variable(s) from which to get the display unit(s)

    This may be a string or (possibly nested) list of strings representing the names of the variables.

If names is a string, then the output will be a single display unit. If names is a (optionally nested) list of strings, then the output will be a (nested) list of display units.

Example:

>>> from modelicares import SimRes

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> sim.get_displayUnit('G.T_heatPort')
'degC'
get_indices_wi_times(names, t_1=None, t_2=None)

Return the widest index pair(s) for which the time of signal(s) is within given limits.

Arguments:

  • names: String or (possibly nested) list of strings of the variable names
  • t_1: Lower bound of time
  • t_2: Upper bound of time

If names is a string, then the output will be an array of values. If names is a (optionally nested) list of strings, then the output will be a (nested) list of arrays.

Example:

>>> from modelicares import SimRes

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> sim.get_indices_wi_times('L.v', t_1=500, t_2=2000)
(104, 412)
get_max(names, f=<function <lambda> at 0x7f9da11ef410>)

Return the maximum value(s) of variable(s).

Arguments:

  • names: String or (possibly nested) list of strings of variable names
  • f: Function that should be applied before taking the maximum (default is identity)

If names is a string, then the output will be a single value. If names is a (optionally nested) list of strings, then the output will be a (nested) list of values.

Example:

>>> from modelicares import SimRes

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> sim.get_max('L.v')
0.77344114
get_mean(names, f=<function <lambda> at 0x7f9da11ef500>)

Return the time-averaged value(s) of variable(s).

Arguments:

  • names: String or (possibly nested) list of strings of variable names
  • f: Function that should be applied before taking the mean (default is identity)

If names is a string, then the output will be a single value. If names is a (optionally nested) list of strings, then the output will be a (nested) list of values.

Example:

>>> from modelicares import SimRes

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> sim.get_mean('L.v')
0.014733823
get_min(names, f=<function <lambda> at 0x7f9da11ef5f0>)

Return the minimum value(s) of variable(s).

Arguments:

  • names: String or (possibly nested) list of strings of variable names
  • f: Function that should be applied before taking the minimum (default is identity)

If names is a string, then the output will be a single value. If names is a (optionally nested) list of strings, then the output will be a (nested) list of values.

Example:

>>> from modelicares import SimRes

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> sim.get_min('L.v')
-0.9450165
get_times(names, i=slice(0, None, None), f=<function <lambda> at 0x7f9da11ef050>)

Return vector(s) of the sample times of variable(s).

Arguments:

  • names: String or (possibly nested) list of strings of the variable names

  • i: Index (-1 for last), list of indices, or slice of the time(s) to return

    By default, all times are returned.

  • f: Function that should be applied to all times (default is identity)

If names is a string, then the output will be an array of times. If names is a (optionally nested) list of strings, then the output will be a (nested) list of arrays.

Example:

>>> from modelicares import SimRes

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> sim.get_times('L.v') 
array([    0.        , ...  2500.        ], dtype=float32)
get_tuple(names, i=slice(0, None, None))

Return tuple(s) of time and value vectors for variable(s).

Each tuple contains two vectors: one for times and one for values.

Arguments:

  • names: String or (possibly nested) list of strings of the variable names

  • i: Index (-1 for last), list of indices, or slice of the values(s) to return

    By default, all values are returned.

If names is a string, then the output will be a tuple. If names is a (optionally nested) list of strings, then the output will be a (nested) list of tuples.

Example:

>>> from modelicares import SimRes

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> sim.get_tuple('L.v') 
(array([    0.        , ... ,  2500.        ], dtype=float32), array([  0.00000000e+00, ... -2.53528625e-01], dtype=float32))

Note that this is a tuple of vectors, not a vector of tuples.

get_unit(names)

Return the unit attribute(s) of variable(s).

Arguments:

  • names: Name(s) of the variable(s) from which to get the unit(s)

    This may be a string or (possibly nested) list of strings representing the names of the variables.

If names is a string, then the output will be a single unit. If names is a (optionally nested) list of strings, then the output will be a (nested) list of units.

Example:

>>> from modelicares import SimRes

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> sim.get_unit('L.v')
'V'
get_values(names, i=slice(0, None, None), f=<function <lambda> at 0x7f9da11ef1b8>)

Return vector(s) of the values of the samples of variable(s).

Arguments:

  • names: String or (possibly nested) list of strings of the variable names

  • i: Index (-1 for last), list of indices, or slice of the values(s) to return

    By default, all values are returned.

  • f: Function that should be applied to all values (default is identity)

If names is a string, then the output will be an array of values. If names is a (optionally nested) list of strings, then the output will be a (nested) list of arrays.

Example:

>>> from modelicares import SimRes

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> sim.get_values('L.v') 
array([  0.00000000e+00, ... -2.53528625e-01], dtype=float32)

If the variable cannot be found, then possible matches are listed:

>>> sim.get_values(['L.vv']) 
L.vv is not a valid variable name.

Did you mean one of these?
       L.v
       L.p.v
       L.n.v

The other get_* methods also give this message when a variable cannot be found.

get_values_at_times(names, times, f=<function <lambda> at 0x7f9da11ef2a8>)

Return vector(s) of the values of the samples of variable(s) at given times.

Arguments:

  • names: String or (possibly nested) list of strings of the variable names
  • times: Scalar, numeric list, or a numeric array of the times from which to pull samples
  • f: Function that should be applied to all values (default is identity)

If names is a string, then the output will be an array of values. If names is a (optionally nested) list of strings, then the output will be a (nested) list of arrays.

If times is not provided, all of the samples will be returned. If necessary, the values will be interpolated over time. The function f is applied before interpolation.

Example:

>>> from modelicares import SimRes

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> sim.get_values_at_times('L.v', [0, 2000])
array([ 0.        ,  0.15459341])
names(pattern=None, re=False)

Return a list of variable names that match a pattern.

By default, all names are returned.

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 variables that begin with “x”, whereas ‘*x*’ matches all variables that contain “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 the subclass separator as ‘\.’.

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

Examples:

>>> from modelicares import SimRes
>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> # Names starting with "L.p", using shell-style matching:
>>> sim.names('L.p*')
[u'L.p.i', u'L.p.v']
>>> # Names ending with "p.v", using re matching:
>>> sim.names('p\.v$', re=True)
[u'C2.p.v', u'Gnd.p.v', u'L.p.v', u'Nr.p.v', u'C1.p.v', u'Ro.p.v', u'G.p.v']
nametree()

Return a tree of all variable names with respect to the path names.

The tree represents the structure of the Modelica model. It is returned as a nested dictionary. The keys are the path elements and the values are sub-dictionaries or variable names.

There are no arguments.

Example:

>>> from modelicares import SimRes
>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> sim.nametree() 
{u'G': {u'G': u'G.G', ... u'n': {u'i': u'G.n.i', u'v': u'G.n.v'}, ...}, u'L': {...}, ...}
plot(ynames1=, []ylabel1=None, legends1=, []leg1_kwargs={'loc': 'best'}, ax1=None, ynames2=, []ylabel2=None, 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 data as points and/or curves in 2D Cartesian coordinates.

Arguments:

  • ynames1: 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 the common description will be used. Use ‘’ for no label.

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

    If legends1 is an empty list ([]), ynames1 will be used. 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, legends2, leg2_kwargs, and ax2: Similar to ynames1, ylabel1, legends1, leg1_kwargs, and ax1 but for the secondary y axis

  • xname: Name of the x-axis data

  • 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 will be used as a base filename if the figure is saved.

  • 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 base.plot() (and thus 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:

>>> from modelicares import SimRes, save

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> sim.plot(ynames1='L.i', ylabel1="Current",
...          ynames2='L.der(i)', ylabel2="Derivative of current",
...          title="Chua Circuit", label='examples/ChuaCircuit') 
(<matplotlib.axes...AxesSubplot object at 0x...>, <matplotlib.axes...AxesSubplot object at 0x...>)

>>> save()
Saved examples/ChuaCircuit.pdf
Saved examples/ChuaCircuit.png
plot of Chua circuit
sankey(names=[], times=[0], n_rows=1, title=None, subtitles=[], label='sankey', margin_left=0.05, margin_right=0.05, margin_bottom=0.05, margin_top=0.1, wspace=0.1, hspace=0.25, **kwargs)

Create a figure with Sankey diagram(s).

Arguments:

  • names: List of names of the flow variables

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

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

  • n_rows: Number of rows of (sub)plots

  • 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 subtitles (i.e., titles for each subplot)

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

  • label: Label for the figure

    This will be used as the base filename if the figure is saved.

  • margin_left: Left margin

  • margin_right: Right margin

  • margin_bottom: Bottom margin

  • margin_top: Top margin

  • wspace: The amount of width reserved for blank space between subplots

  • hspace: The amount of height reserved for white space between subplots

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

Returns:

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

Example:

>>> from modelicares import SimRes, save

>>> sim = SimRes('examples/ThreeTanks')
>>> sankeys = sim.sankey(label='examples/ThreeTanks',
...     title="Sankey Diagrams of Modelica.Fluid.Examples.Tanks.ThreeTanks",
...     times=[0, 50, 100, 150], n_rows=2, format='%.1f ',
...     names=['tank1.ports[1].m_flow', 'tank2.ports[1].m_flow',
...            'tank3.ports[1].m_flow'],
...     labels=['Tank 1', 'Tank 2', 'Tank 3'],
...     orientations=[-1, 0, 1],
...     scale=0.1, margin=6, offset=1.5,
...     pathlengths=2, trunklength=10)
>>> save()
Saved examples/ThreeTanks.pdf
Saved examples/ThreeTanks.png
Sankey digarams of three-tank model
modelicares.simres.merge_times(times_list)

Merge a list of multiple time vectors into one vector.

Example:

>>> from modelicares.simres import SimRes, merge_times

>>> sim = SimRes('examples/ChuaCircuit.mat')
>>> times_list = sim.get_times(['L.v', 'G.T_heatPort'])
>>> merge_times(times_list) 
array([    0.        , ... 2500.        ], dtype=float32)