FigureManager

class myplotspec.FigureManager.FigureManager(*args, **kwargs)

Bases: object

Manages the generation of figures.

defaults

str, dict

Default arguments to draw_report(), draw_figure(), draw_subplot(), and draw_dataset() functions, in yaml format. Outer level (of indentation or keys) provides function names, and inner level provides default arguments to each function:

defaults = """
    method_1:
      method_1_arg_1: 1000
      method_1_arg_2: abcd
    method_2
      method_2_arg_1: 2000
      method_2_arg_2: efgh
    ...
"""
available_presets

str, dict

Available sets of preset arguments to draw_report(), draw_figure(), draw_subplot(), and draw_dataset() functions, in yaml format. Outer level (of indentation or keys) provides preset names, middle level provides function names, and inner level provides arguments to pass to each function when preset is active:

available_presets = """
  preset_1:
    method_1:
      method_1_arg_1: 1001
      method_1_arg_2: abcde
    method_2
      method_2_arg_1: 2001
      method_2_arg_2: efghi
  preset_2:
    method_1:
      method_1_arg_1: 1002
      method_1_arg_2: abcdef
    method_2
      method_2_arg_1: 2002
      method_2_arg_2: efghij
"""

Each preset may additionally contain the keys ‘help’, ‘class’, ‘extends’ and ‘inherits’. ‘help’ may contain a short help message displayed with the help text of the script, while ‘class’ is the name of the category in which the preset is classified; built-in categories include ‘content’, for presets related to the type of data being used, ‘appearance’, for presets related to modifications to formatting, and ‘target’, for presets specifying the target destination of the figure, such as ‘notebook’ or ‘presentation’. ‘extends’ may contain the name of another preset within the class from which the preset will inherit (and optionally override) all arguments. Subclasses of this base FigureManager class may also include the keyword ‘inherits’ which may contain the name of a preset of FigureManager (listed below) from which it will inherit (and optionally override) all arguments.

dataset_cache

dict

Cache of previously-loaded datasets. Keys are the return values of the method ‘get_cache_key’ from the class of each dataset, and values are the datasets themselves. This may be passed on from draw_dataset() to the dataset classes’ __init__ methods, which may in turn add their own datasets to it.

Initializes.

Parameters:
  • defaults (string, dict, optional) – Default arguments; may be a yaml string, path to a yaml file, or a dictionary; if not provided pulled from self.defaults
  • args (tuple) – Additional positional arguments
  • kwargs (dict) – Additional keyword arguments
initialize_presets(*args, **kwargs)

Initializes presets.

Parameters:
  • available_presets (string, dict) – Available presets; may be a yaml string, path to a yaml file, or a dictionary; if not provided pulled from available_presets
  • args (tuple) – Additional positional arguments
  • kwargs (dict) – Additional keyword arguments
__call__(*args, **kwargs)

When called as a function, calls draw_report().

Parameters:
  • args (tuple) – Passed to draw_report()
  • kwargs (dict) – Passed to draw_report()
draw_report(*in_args, **in_kwargs)

Draws one or more figures based on provided specifications.

Figure specs are provided in a dict structured as follows:

figures = {
    'all': {
        'shared_xlabel': 'Time',
        'shared_ylabel': 'Measurement',
        'shared_legend': True,
        ...
    },
    '0': {
        'title': 'Trial 1',
        'subplots': {
            ...
        },
        ...
    },
    '1': {
        'title': 'Trial 2',
        'subplots': {
            ...
        },
        ...
    },
    '2': {
        'title': 'Trial 3',
        'subplots': {
            ...
        },
        ...
    },
    ...
}

The values stored at each (0-indexed) integer key provide the arguments to be passed to draw_figure() for each of a series of figures. Values stored at ‘all’ are passed to each figure, but overridden by values specific to that figure.

Parameters:
  • figure[s] (dict) – Figure specifications
  • preset[s] (str, list, optional) – Selected preset(s); presets loaded from figure specification will take precedence over those passed as arguments
  • yaml_spec (str, dict, optional) – Argument data structure; may be string path to yaml file, yaml-format string, or dictionary
  • verbose (int) – Level of verbose output
  • debug (int) – Level of debug output
  • kwargs (dict) – Additional keyword arguments

Note

This function is one of two responsible for managing the output of figures to pdf files, if specified. While other output formats are single-page, pdf files may be multi-page. In order to allow multiple figures to be output to multiple pdfs, this function maintains a dict outfiles containing references to a PdfPages object for each specified pdf outfile. draw_figure()‘s decorator manage_output adds new PdfPages objects as requested, or adds pages to existing ones. Once all figures have been drawn, this function closes each PdfPages.

draw_figure(*in_args, **in_kwargs)

Draws a figure.

Figure will typically contain one or more subplots, whose specifications are provided in a dict structured as follows:

subplots = {
    'all': {
        'legend': True,
        ...
    },
    '0': {
        'title':    'Subplot 1',
        'datasets': {
            ...
        },
        ...
    },
    '1': {
        'title':    'Subplot 2',
        'datasets': {
            ...
        },
        ...
    },
    '2': {
        'title':    'Subplot 3',
        'datasets': {
            ...
        },
        ...
    },
    ...
}

The values stored at each integer key (0-indexed) provide the arguments to be passed to draw_subplot() for each of a series of subplots. Values stored at ‘all’ are passed to each subplot, but overridden by values specific to that subplot.

Figure may be annotated by drawing a title, shared x axis label, shared y axis label, or shared legend. Title and shared axis labels are (by default) centered on all subplots present on the figure, Shared legend is drawn on an additional subplot created after those specified in subplots, using the arguments provided in ‘shared_legend’.

Parameters:
  • outfile (str) – Output filename
  • subplot[s] (dict) – Subplot specifications
  • preset[s] (str, list, optional) – Selected preset(s); presets loaded from figure specification will take precedence over those passed as arguments
  • nrows (int, optional) – Number of rows of subplots
  • ncols (int, optional) – Number of columns of subplots
  • nsubplots (int, optional) – Number of subplots
  • title (str, optional) – Figure title
  • [shared][x]label (str, optional) – X label to be shared among subplots
  • [shared][y]label (str, optional) – Y label to be shared among subplots
  • shared_legend (bool, optional) – Generate a legend shared between subplots
  • multiplot (bool, optional) – Subplots in specification are a small multiple set; x and y labels and ticklabels are omitted for plots other than those along the left side and bottom
  • multi_xticklabels (list, optional) – x tick labels to be assigned to subplots along bottom; only necessary with multiplot
  • multi_yticklabels (list, optional) – y tick labels to be assigned to subplots along left side; only necessary with multiplot
  • multi_tick_kw (dict, optional) – tick params to be assigned to multiple subplots
  • verbose (int) – Level of verbose output
  • debug (int) – Level of debug output
  • kwargs (dict) – Additional keyword arguments
Returns:

(figure) – Figure

draw_subplot(*in_args, **in_kwargs)

Draws a subplot.

Subplot will typically plot one or more datasets, whose specifications are provided in a dict structured as follows:

datasets = {
    'all': {
        'lw': 2,
        ...
    },
    '0': {
        'label':  'Dataset 1',
        'infile': '/path/to/dataset_1.txt',
        'color':  'red',
        ...
    },
    '1': {
        'label':  'Dataset 2',
        'infile': '/path/to/dataset_2.txt',
        'color':  'green',
        ...
    },
    '2': {
        'label':  'Dataset 3',
        'infile': '/path/to/dataset_3.txt',
        'color':  'blue',
        ...
    },
    ...
}

The values stored at each integer key (0-indexed) provide the arguments to be passed to draw_dataset() for each of a series of datasets. Values stored at ‘all’ are passed to each dataset, but overridden by values specific to that dataset.

Subplot may be formatted by adjusting or labeling the x and y axes, or drawing a title or a legend.

Parameters:
  • subplot (Axes) – Axes on which to act
  • dataset[s] (dict) – Dataset specifications
  • preset[s] (str, list, optional) – Selected preset(s); presets loaded from figure specification will take precedence over those passed as arguments
  • title (str, optional) – Subplot title
  • legend (bool, optional) – Draw legend on subplot
  • partner_subplot (bool, optional) – Add a parter subplot
  • handles (OrderedDict, optional) – Nascent OrderedDict of [labels]:handles shared among subplots of host figure; used to draw shared legend on figure
  • visible (bool, optional) – Subplot visibility
  • verbose (int) – Level of verbose output
  • debug (int) – Level of debug output
  • kwargs (dict) – Additional keyword arguments
draw_dataset(*in_args, **in_kwargs)

Draws a dataset on a subplot.

Parameters:
  • subplot (Axes) – Axes on which to draw
  • infile (str) – Path to input text file; first column is x, second is y
  • label (str, optional) – Dataset label
  • color (str, list, ndarray, float, optional) – Dataset color
  • plot_kw (dict, optional) – Additional keyword arguments passed to subplot.plot()
  • handles (OrderedDict, optional) – Nascent OrderedDict of [labels]: handles on subplot
  • verbose (int) – Level of verbose output
  • debug (int) – Level of debug output
  • kwargs (dict) – Additional keyword arguments
class manage_defaults_presets(verbose=1, debug=0)

Bases: object

Decorator to manage the passage of defaults and available presets to a method.

This decorator is a partner to manage_kwargs, desiged to allows its use for methods of objects containg central defaults and available_presets attributes. It obtains available defaults and presets for the wrapped method from their central location in the host object, and passes on those applicable to the wrapped method. manage_kwargs then selects arguments to pass from among the provided defaults, available and selected presets, YAML file, and arguments provided at call time.

Defaults are accessed from the host object’s instance (or class) variable self.defaults, and may be a dict, a path to a YAML file, or a YAML string. Outer level (of indentation or keys) provides function names, and inner level provides default arguments to each function:

defaults = """
    method_1:
        method_1_arg_1: 1000
        method_1_arg_2: abcd
    method_2
        method_2_arg_1: 2000
        method_2_arg_2: efgh
    ...
"""

Presets are accessed from the host objects’s instance (or class) variable self.available_presets, in the same formats as self.defaults. Presets contain an outer level of keys providing the names of available presets:

available_presets = """
    preset_1:
        method_1:
            method_1_arg_1: 1001
            method_1_arg_2: abcde
        method_2
            method_2_arg_1: 2001
            method_2_arg_2: efghi
    preset_2:
        method_1:
            method_1_arg_1: 1002
            method_1_arg_2: abcdef
        method_2
            method_2_arg_1: 2002
        method_2_arg_2: efghij
"""

When this decorator is used to wrap a method of a class, it adds to the arguments being passed defaults, containing the defaults specified for the method, and available_presets, containing only the presets applicable to the method:

@manage_defaults_presets()
def method_1(*args, **kwargs):
    print(kwargs)
    ...

{
    'defaults': {
        'method_1_argument_1': 1000,
        'method_1_argument_2': 'asdf'
    },
    'presets': {
        'preset_1': {
            'method_1_argument_1': 1001,
            'method_1_argument_2': 'asde'
        },
        'preset_1': {
            'method_1_argument_1': 1002,
            'method_1_argument_2': 'asdef'
        }
    },
    ...
}
verbose

int

Level of verbose output

debug

int

Level of debug output

Stores arguments provided at decoration.

Parameters:
  • verbose (int) – Level of verbose output
  • debug (int) – Level of debug output
__call__(method)

Wraps method.

Parameters:method (method) – method to wrap
Returns:(method) – Wrapped method
class FigureManager.manage_kwargs(verbose=0, debug=0)

Bases: object

Decorator to manage the passage of keyword arguments to a function or method.

Accumulates keyword arguments from several sources, in order of increasing priority:

  1. Defaults

Obtained from the argument defaults, which may be a dict, a path to a YAML file, or a YAML string:

my_function(
    defaults = {
        'fig_width':  5.0
        'fig_height': 5.0
    },
    ...
)
  1. Presets

Available presets are obtained from the argument available_presets, which may be a dict, a path to a YAML file, or a YAML string. Selected presets are obtained from the argument presets, which may be a string or list of strings in order of increasing priority:

my_function(
    presets = 'letter',
    available_presets = {
        'letter': {
            'fig_width':   8.5
            'fig_height': 11.0
        },
        'legal': {
            'fig_width':   8.5
            'fig_height': 14.0
        }
    },
    ...
)
  1. YAML file

YAML file is obtained from the keyword argument yaml_spec, which may be a dict, a path to a YAML file, or a YAML string. Selected keys within the YAML file from which to load arguments are obtained from the argument yaml_keys, which is a list of lists in order of increasing priority:

my_function(
    yaml_spec = {
        'figures': {
            'all': {
                'fig_width':  11.0,
                'fig_height': 17.0,
                'outfile':    'plot.pdf'
            },
            '0': {
                'fig_width':  12.0
            }
        }
    },
    yaml_keys = [['figures', 'all'], ['figures', '0']],
    ...
)

If yaml_keys is omitted, the complete yaml file will be used.

  1. Function call

Arguments provided at function call:

my_function(
    fig_width  = 6.0,
    fig_height = 6.0,
    ...
)

All of the above will override defaults provided in the function declaration itself.

verbose

int

Level of verbose output

debug

int

Level of debug output

Stores arguments provided at decoration.

Parameters:
  • verbose (int) – Level of verbose output
  • debug (int) – Level of debug output
__call__(function)

Wraps function or method.

Parameters:function (function) – Function or method to wrap
Returns:(function) – Wrapped function or method
class FigureManager.manage_output

Bases: object

Decorator to manage the output of matplotlib figures.

Saves figure returned by wrapped function to a file named outfile; passing additional keyword arguments savefig_kw to Figure.savefig(). For pdf output, additional argument outfiles may be provided; containing a dictionary whose keys are the paths to output pdf files, and whose values are open PdfPages objects representing those files. The purpose of this is to allow figures output from multiple calls to the wrapped function to be output to sequential pages of the same pdf file. Typically outfiles will be initialized before calling this wrapped function; and once calls to the function is complete the PdfPages.close() method of each outfile in outfiles is called.

__call__(function)

Wraps function or method.

Parameters:function (function) – Function or method to wrap
Returns:(function) – Wrapped function or method
FigureManager.load_dataset(**kwargs)

Loads a dataset, or reloads a previously-loaded dataset from cache.

FigureManager.main(parser=None)

Provides command-line functionality.

Parameters:parser (ArgumentParser, optional) – argparse argument parser; enables sublass to instantiate parser and add arguments