Table Of Contents

modelicares.aux

Auxiliary methods to help plot and interpret experimental data

class modelicares.aux.Quantity

Named tuple class for a constant physical quantity

The factor and then the offset are applied to the number to arrive at the quantity expressed in terms of the unit.

__repr__()

Return a nicely formatted representation string

factor

Alias for field number 1

number

Alias for field number 0

offset

Alias for field number 2

unit

Alias for field number 3

modelicares.aux.add_arrows(p, x_locs=[0], xstar_offset=0, ystar_offset=0, lstar=0.05, label='', orientation='tangent', color='r')

Overlay arrows with annotations on top of a pre-plotted line.

Arguments:

  • p: A plot instance (matplotlib.lines.Line2D object)
  • x_locs: x-axis locations of the arrows
  • xstar_offset: Normalized x-axis offset from the middle of the arrow to the text
  • ystar_offset: Normalized y-axis offset from the middle of the arrow to the text
  • lstar: Length of each arrow in normalized xy axes
  • label: Annotation text
  • orientation: ‘tangent’, ‘horizontal’, or ‘vertical’
  • color: Color of the arrows (from matplotlib.colors)

Example:

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from modelicares import *

>>> # Create a plot.
>>> figure('examples/add_arrows') 
<matplotlib.figure.Figure object at 0x...>
>>> x = np.arange(100)
>>> p = plt.plot(x, np.sin(x/4.0))

>>> # Add arrows and annotations.
>>> add_arrows(p[0], x_locs=x.take(np.arange(20,100,20)),
...            label="Incr. time", xstar_offset=-0.15)
>>> saveall()
Saved examples/add_arrows.pdf
Saved examples/add_arrows.png
>>> plt.show()
example of add_arrows()
modelicares.aux.add_hlines(ax=None, positions=[0], labels=[], **kwargs)

Add horizontal lines to a set of axes with optional labels.

Arguments:

  • ax: Axes (matplotlib.axes object)

  • positions: Positions (along the x axis)

  • labels: List of labels for the lines

  • **kwargs: Line properties (propagated to matplotlib.pyplot.axhline())

    E.g., color='k', linestyle='--', linewidth=0.5

Example:

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from modelicares import *

>>> # Create a plot.
>>> figure('examples/add_hlines') 
<matplotlib.figure.Figure object at 0x...>
>>> x = np.arange(100)
>>> y = np.sin(x/4.0)
>>> plt.plot(x, y) 
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.ylim([-1.2, 1.2])
(-1.2, 1.2)

>>> # Add horizontal lines and labels.
>>> add_hlines(positions=[min(y), max(y)], labels=["min", "max"],
...            color='r', ls='--')
>>> saveall()
Saved examples/add_hlines.pdf
Saved examples/add_hlines.png
>>> plt.show()
example of add_hlines()
modelicares.aux.add_vlines(ax=None, positions=[0], labels=[], **kwargs)

Add vertical lines to a set of axes with optional labels.

Arguments:

  • ax: Axes (matplotlib.axes object)

  • positions: Positions (along the x axis)

  • labels: List of labels for the lines

  • **kwargs: Line properties (propagated to matplotlib.pyplot.axvline())

    E.g., color='k', linestyle='--', linewidth=0.5

Example:

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from modelicares import *

>>> # Create a plot.
>>> figure('examples/add_vlines') 
<matplotlib.figure.Figure object at 0x...>
>>> x = np.arange(100)
>>> y = np.sin(x/4.0)
>>> plt.plot(x, y) 
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.ylim([-1.2, 1.2])
(-1.2, 1.2)

>>> # Add horizontal lines and labels.
>>> add_vlines(positions=[25, 50, 75], labels=["A", "B", "C"],
...            color='k', ls='--')
>>> saveall()
Saved examples/add_vlines.pdf
Saved examples/add_vlines.png
>>> plt.show()
example of add_vlines()
modelicares.aux.animate(imagebase='_tmp', fname='animation', fps=10, clean=False)

Encode a series of PNG images as a MPG movie.

Arguments:

  • imagebase: Base filename for the PNG images

    The images should be located in the current directory as an “imagebase**xx.png” sequence, where xx is a frame index.

  • fname: Filename for the movie

    ”.mpg” will be appended if necessary.

  • fps: Number of frames per second

  • clean: True, if the PNG images should be deleted afterward

Note

This method requires mencoder. On Linux, install it with the following command: sudo apt-get install mencoder.

Example:

import matplotlib.pyplot as plt
from numpy.random import rand
from modelicares import *

# Create the frames.
fig = plt.figure(figsize=(5,5))
ax = fig.add_subplot(111)
for i in range(50):  # 50 frames
    ax.cla()
    ax.imshow(rand(5,5), interpolation='nearest')
    fname = '_tmp%02d.png' % i
    print 'Saving frame', fname
    fig.savefig(fname) # doctest: +ELLIPSIS

# Assemble the frames into a movie.
animate(clean=True)
modelicares.aux.closeall()

Close all open figures.

This is a shortcut for the following:

>>> from matplotlib._pylab_helpers import Gcf
>>> Gcf.destroy_all()
modelicares.aux.color(ax, c, *args, **kwargs)

Plot 2D scalar data on a color axis in 2D Cartesian coordinates.

This uses a uniform grid.

Arguments:

  • ax: Axis onto which the data should be plotted
  • c: color- or c-axis data (2D array)
  • *args, **kwargs: Propagated to matplotlib.pyplot.imshow()

Example:

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from modelicares import *

>>> figure('examples/color') 
<matplotlib.figure.Figure object at 0x...>
>>> x, y = np.meshgrid(np.arange(0, 2*np.pi, 0.2),
...                    np.arange(0, 2*np.pi, 0.2))
>>> c = np.cos(x) + np.sin(y)
>>> ax = plt.subplot(111)
>>> color(ax, c) 
<matplotlib.image.AxesImage object at 0x...>
>>> saveall()
Saved examples/color.pdf
Saved examples/color.png
>>> plt.show()
example of color()
modelicares.aux.convert(quantity)

Convert the expression of a physical quantity between units.

Arguments:

Example:

>>> from modelicares import *

>>> T = 293.15 # Temperature in K
>>> T_degC = convert(Quantity(T, factor=1, offset=-273.15, unit='C'))
>>> print(str(T) + " K is " + str(T_degC) + " degC.")
293.15 K is 20.0 degC.
modelicares.aux.expand_path(path)

Expand a file path by replacing ‘~’ with the user directory and making the path absolute.

Example:

>>> from modelicares import *

>>> expand_path('~/Documents') 
'/home/.../Documents'
>>> # on Linux or 'C:\Users\...\Documents' on Windows, where "..."
>>> # is the user id.
modelicares.aux.figure(label, *args, **kwargs)

Create a figure and set its label.

Arguments:

  • label: String to apply to the figure’s label property
  • *args, **kwargs: Propagated to matplotlib.pyplot.figure()

Example:

>>> fig = figure("velocity_vs_time") 
>>> plt.getp(fig, 'label')
'velocity_vs_time'

Note

The label property is used as the base filename in the saveall() method.

modelicares.aux.flatten_dict(d, parent_key='', separator='.')

Flatten a nested dictionary.

Arguments:

  • d: Dictionary (may be nested to an arbitrary depth)
  • parent_key: Key of the parent dictionary, if any
  • separator: String or character that joins elements of the keys or path names

Example:

>>> from modelicares import *
>>> flatten_dict(dict(a=1, b=dict(c=2, d='hello')))
{'a': 1, 'b.c': 2, 'b.d': 'hello'}
modelicares.aux.flatten_list(l, ltypes=(<type 'list'>, <type 'tuple'>))

Flatten a nested list.

Arguments:

  • l: List (may be nested to an arbitrary depth)

    If the type of l is not in ltypes, then it is placed in a list.

  • ltypes: Tuple (not list) of accepted indexable types

Example:

>>> from modelicares import *
>>> flatten_list([1, [2, 3, [4]]])
[1, 2, 3, 4]
modelicares.aux.get_indices(x, target)

Return the the pair of indices that bound a target value in a monotonically increasing vector.

Arguments:

  • x: Vector
  • target: Target value

Example:

>>> from modelicares import *
>>> get_indices([0,1,2],1.6)
(1, 2)
modelicares.aux.get_pow10(num)

Return the exponent of 10 for which the significand of a number is within the range [1, 10).

Example:

>>> get_pow10(50)
1
modelicares.aux.get_pow1000(num)

Return the exponent of 1000 for which the significand of a number is within the range [1, 1000).

Example:

>>> get_pow1000(1e5)
1
modelicares.aux.load_csv(fname, header_row=0, first_data_row=None, types=None, **kwargs)

Load a CSV file into a dictionary.

The strings from the header row are used as dictionary keys.

Arguments:

  • fname: Path and name of the file

  • header_row: Row that contains the keys (uses zero-based indexing)

  • first_data_row: First row of data (uses zero-based indexing)

    If first_data_row is not provided, then it is assumed that the data starts just after the header row.

  • types: List of data types for each column

    int and float data types will be cast into a numpy.array. If types is not provided, attempts will be made to cast each column into int, float, and str (in that order).

  • **kwargs: Propagated to csv.reader()

Example:

>>> data = load_csv("examples/load_csv.csv", header_row=2)
>>> print("The keys are: %s" % data.keys())
The keys are: ['Price', 'Description', 'Make', 'Model', 'Year']
modelicares.aux.plot(y, x=None, ax=None, label=None, color=['b', 'g', 'r', 'c', 'm', 'y', 'k'], marker=None, dashes=[(1, 0), (3, 3), (1, 1), (3, 2, 1, 2)], **kwargs)

Plot 1D scalar data as points and/or line segments in 2D Cartesian coordinates.

This is similar to matplotlib.pyplot.plot() (and actually calls that method), but provides direct support for plotting an arbitrary number of curves.

Arguments:

  • y: y-axis data

    This may contain multiple series.

  • x: x-axis data

    If x is not provided, the y-axis data will be plotted versus its indices. If x is a single series, it will be used for all of the y-axis series. If it is a list of series, each x-axis series will be matched to a y-axis series.

  • ax: Axis onto which the data should be plotted.

    If ax is None (default), axes are created.

  • label: List of labels of each series (to be used later for the legend if applied)

  • color: Single entry, list, or itertools.cycle of colors that will be used sequentially

    Each entry may be a character, grayscale, or rgb value.

  • marker: Single entry, list, or itertools.cycle of markers that will be used sequentially

    Use None for no marker. A good assortment is [“o”, “v”, “^”, “<”, “>”, “s”, “p”, “*”, “h”, “H”, “D”, “d”]. All of the possible entries are listed at: http://matplotlib.sourceforge.net/api/artist_api.html#matplotlib.lines.Line2D.set_marker.

  • dashes: Single entry, list, or itertools.cycle of dash styles that will be used sequentially

    Each style is a tuple of on/off lengths representing dashes. Use (0,1) for no line and (1,0) for a solid line.

  • **kwargs: Propagated to matplotlib.pyplot.plot()

Returns: List of matplotlib.lines.Line2D objects

Example:

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from modelicares import *

>>> figure('examples/plot') 
<matplotlib.figure.Figure object at 0x...>
>>> ax = plt.subplot(111)
>>> plot([range(11), range(10, -1, -1)], ax=ax) 
[[<matplotlib.lines.Line2D object at 0x...>], [<matplotlib.lines.Line2D object at 0x...>]]
>>> saveall()
Saved examples/plot.pdf
Saved examples/plot.png
>>> plt.show()
example of plot()
modelicares.aux.quiver(ax, u, v, x=None, y=None, pad=0.05, pivot='middle', **kwargs)

Plot 2D vector data as arrows in 2D Cartesian coordinates.

Uses a uniform grid.

Arguments:

  • ax: Axis onto which the data should be plotted
  • u: x-direction values (2D array)
  • v: y-direction values (2D array)
  • pad: Amount of white space around the data (relative to the span of the field)
  • pivot: “tail” | “middle” | “tip” (see matplotlib.pyplot.quiver())
  • **kwargs: Propagated to matplotlib.pyplot.quiver()

Example:

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from modelicares import *

>>> figure('examples/quiver') 
<matplotlib.figure.Figure object at 0x...>
>>> x, y = np.meshgrid(np.arange(0, 2*np.pi, 0.2),
...                    np.arange(0, 2*np.pi, 0.2))
>>> u = np.cos(x)
>>> v = np.sin(y)
>>> ax = plt.subplot(111)
>>> quiver(ax, u, v) 
<matplotlib.quiver.Quiver object at 0x...>
>>> saveall()
Saved examples/quiver.pdf
Saved examples/quiver.png
>>> plt.show()
example of quiver()
modelicares.aux.saveall(formats=['pdf', 'png'])

Save all open figures as images in a format or list of formats.

The directory and base filenames are taken from the label property of the figures. If the label property is empty, then a directory dialog is opened to chose a directory. In that case, the figures are saved as a sequence of numbers.

Example:

>>> import matplotlib.pyplot as plt
>>> from modelicares import *

>>> figure('temp_plot') 
<matplotlib.figure.Figure object at 0x...>
>>> plt.plot(range(10)) 
[<matplotlib.lines.Line2D object at 0x...>]
>>> saveall()
Saved temp_plot.pdf
Saved temp_plot.png

Note

The figure() method can be used to directly create a figure with a label.

modelicares.aux.setup_subplots(n_plots, n_rows, title='', subtitles=None, label='multiplot', xlabel='', xticklabels=None, xticks=None, ylabel='', yticklabels=None, yticks=None, ctype=None, clabel='', margin_left=0.098, margin_right=0.08999999999999997, margin_bottom=0.1, margin_top=0.08999999999999997, margin_cbar=0.2, wspace=0.1, hspace=0.25, cbar_space=0.1, cbar_width=0.05)

Create an array of subplots and return their axes.

Arguments:

  • n_plots: Number of (sub)plots

  • n_rows: Number of rows of (sub)plots

  • title: Title for the figure

  • subtitles: List of subtitles (i.e., titles for each subplot) or None for no subtitles

  • label: Label for the figure

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

  • xlabel: Label for the x-axes (only shown for the subplots on the bottom row)

  • xticklabels: Labels for the x-axis ticks (only shown for the subplots on the bottom row)

    If None, then the default is used.

  • xticks: Positions of the x-axis ticks

    If None, then the default is used.

  • ylabel: Label for the y-axis (only shown for the subplots on the left column)

  • yticklabels: Labels for the y-axis ticks (only shown for the subplots on the left column)

    If None, then the default is used.

  • yticks: Positions of the y-axis ticks

    If None, then the default is used.

  • ctype: Type of colorbar (None, ‘vertical’, or ‘horizontal’)

  • clabel: Label for the color- or c-bar axis

  • margin_left: Left margin

  • margin_right: Right margin (ignored if cbar_orientation == 'vertical')

  • margin_bottom: Bottom margin (ignored if cbar_orientation == 'horizontal')

  • margin_top: Top margin

  • margin_cbar: Margin reserved for the colorbar (right margin if cbar_orientation == 'vertical' and bottom margin if cbar_orientation == 'horizontal')

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

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

  • cbar_space: Space between the subplot rectangles and the colorbar

    If cbar is None, then this is ignored.

  • cbar_width: Width of the colorbar if vertical (or height if horizontal)

    If cbar is None, then this is ignored.

Returns:

  1. List of subplot axes
  2. Colorbar axis (returned iff cbar != None)
  3. Number of columns of subplots

Example:

>>> import matplotlib.pyplot as plt
>>> from modelicares import *

>>> setup_subplots(4, 2, label='examples/setup_subplots') 
([<matplotlib.axes.AxesSubplot object at 0x...>, <matplotlib.axes.AxesSubplot object at 0x...>, <matplotlib.axes.AxesSubplot object at 0x...>, <matplotlib.axes.AxesSubplot object at 0x...>], 2)
>>> saveall()
Saved examples/setup_subplots.pdf
Saved examples/setup_subplots.png
>>> plt.show()
example of setup_subplots()
modelicares.aux.shift_scale_x(ax, eagerness=0.325)

Apply an offset and a factor as necessary to the x axis.

Arguments:

  • ax: matplotlib.axes object

  • eagerness: Parameter to adjust how little of an offset is required before the label will be recentered

    • 0: Offset is never applied.
    • 1: Offset is always applied if it will help.

Example:

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from texunit import label_number
>>> from modelicares import *

>>> # Generate some random data.
>>> x = np.linspace(55478, 55486, 100) # Small range and large offset
>>> xlabel = label_number('Time', 's')
>>> y = np.cumsum(np.random.random(100) - 0.5)

>>> # Plot the data.
>>> ax = setup_subplots(2, 2, label='examples/shift_scale_x')[0]
>>> for a in ax:
...     a.plot(x, y)
...     a.set_xlabel(xlabel) 
[<matplotlib.lines.Line2D object at 0x...>]
<matplotlib.text.Text object at 0x...>
[<matplotlib.lines.Line2D object at 0x...>]
<matplotlib.text.Text object at 0x...>

>>> # Shift and scale the axes.
>>> ax[0].set_title('Original plot') 
<matplotlib.text.Text object at 0x...>
>>> ax[1].set_title('After applying offset and factor') 
<matplotlib.text.Text object at 0x...>
>>> shift_scale_x(ax[1])
>>> saveall()
Saved examples/shift_scale_x.pdf
Saved examples/shift_scale_x.png
>>> plt.show()
example of shift_scale_x()
modelicares.aux.shift_scale_y(ax, eagerness=0.325)

Apply an offset and a factor as necessary to the y axis.

Arguments:

  • ax: matplotlib.axes object

  • eagerness: Parameter to adjust how little of an offset is required before the label will be recentered

    • 0: Offset is never applied.
    • 1: Offset is always applied if it will help.

Example:

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from texunit import label_number
>>> from modelicares import *

>>> # Generate some random data.
>>> x = range(100)
>>> y = np.cumsum(np.random.random(100) - 0.5)
>>> y -= y.min()
>>> y *= 1e-3
>>> y += 1e3 # Small magnitude and large offset
>>> ylabel = label_number('Velocity', 'mm/s')

>>> # Plot the data.
>>> ax = setup_subplots(2, 2, label='examples/shift_scale_y')[0]
>>> for a in ax:
...     a.plot(x, y)
...     a.set_ylabel(ylabel) 
[<matplotlib.lines.Line2D object at 0x...>]
<matplotlib.text.Text object at 0x...>
[<matplotlib.lines.Line2D object at 0x...>]
<matplotlib.text.Text object at 0x...>

>>> # Shift and scale the axes.
>>> ax[0].set_title('Original plot') 
<matplotlib.text.Text object at 0x...>
>>> ax[1].set_title('After applying offset and factor') 
<matplotlib.text.Text object at 0x...>
>>> shift_scale_y(ax[1])
>>> saveall()
Saved examples/shift_scale_y.pdf
Saved examples/shift_scale_y.png
>>> plt.show()
example of shift_scale_y()
class modelicares.aux.ArrowLine(*args, **kwargs)

A matplotlib subclass to draw an arrowhead on a line

Initialize the line and arrow.

Arguments:

  • arrow (=None): Type of arrow (e.g., ‘>’)
  • arrowsize (=2*4): Size of arrow
  • arrowedgecolor (=’b’): Color of arrow edge
  • arrowfacecolor (=’b’): Color of arrow face
  • arrowedgewidth (=4): Width of arrow edge
  • arrowheadwidth (=arrowsize): Width of arrow head
  • arrowheadlength (=arrowsize): Length of arrow head
  • *args, **kwargs: Propagated to matplotlib.lines.Line2D

Example:

>>> import matplotlib.pyplot as plt
>>> from modelicares import *

>>> fig = figure('examples/ArrowLine') 
>>> ax = fig.add_subplot(111, autoscale_on=False)
>>> t = [-1,2]
>>> s = [0,-1]
>>> line = ArrowLine(t, s, color='b', ls='-', lw=2, arrow='>',
...                  arrowsize=20)
>>> ax.add_line(line) 
<modelicares.aux.ArrowLine object at 0x...>
>>> ax.set_xlim(-3, 3)
(-3, 3)
>>> ax.set_ylim(-3, 3)
(-3, 3)
>>> saveall()
Saved examples/ArrowLine.pdf
Saved examples/ArrowLine.png
>>> plt.show()
example of ArrowLine