pygsti.report.workspace

Defines the Workspace class and supporting functionality.

Module Contents

Classes

Workspace

Central to data analysis, Workspace objects facilitate the building of reports and dashboards.

Switchboard

Encapsulates a render-able set of user-interactive switches for controlling visualized output.

SwitchboardView

A duplicate or "view" of an existing switchboard.

SwitchValue

A value that is controlled by the switches of a single Switchboard.

WorkspaceOutput

Base class for all forms of data-visualization within a Workspace context.

NotApplicable

Class signifying that an given set of arguments is not applicable to a function being evaluated.

WorkspaceTable

Encapsulates a table within a Workspace context.

WorkspacePlot

Encapsulates a plot within a Workspace context.

WorkspaceText

Encapsulates a block of text within a Workspace context.

Functions

in_ipython_notebook()

Returns true if called from within an IPython/jupyter notebook

display_ipynb(content)

Render HTML content to an IPython notebook cell display

enable_plotly_pickling()

Hacks the plotly python library so that figures may be pickled and un-pickled.

disable_plotly_pickling()

Reverses the effect of enable_plotly_pickling()

ws_custom_digest(md5, v)

A "digest" function for hashing several special types

random_id()

Returns a random document-objet-model (DOM) ID

Attributes

VALIDATE_PLOTLY

pygsti.report.workspace.VALIDATE_PLOTLY = False
pygsti.report.workspace.in_ipython_notebook()

Returns true if called from within an IPython/jupyter notebook

Returns

bool

pygsti.report.workspace.display_ipynb(content)

Render HTML content to an IPython notebook cell display

Parameters

contentstr

HTML content to insert.

Returns

None

pygsti.report.workspace.enable_plotly_pickling()

Hacks the plotly python library so that figures may be pickled and un-pickled.

This hack should be used only temporarily - so all pickling and un-pickling should be done between calls to enable_plotly_pickling() and disable_plotly_pickling().

Returns

None

pygsti.report.workspace.disable_plotly_pickling()

Reverses the effect of enable_plotly_pickling()

Returns

None

pygsti.report.workspace.ws_custom_digest(md5, v)

A “digest” function for hashing several special types

Parameters

md5hashlib.HASH

The MD5 hash object.

vobject

the value to add to md5 (using md5.update(…)).

Returns

None

pygsti.report.workspace.random_id()

Returns a random document-objet-model (DOM) ID

Returns

str

class pygsti.report.workspace.Workspace(cachefile=None)

Bases: object

Central to data analysis, Workspace objects facilitate the building of reports and dashboards.

In particular, they serve as a:

  • factory for tables, plots, and other types of output

  • cache manager to optimize the construction of such output

  • serialization manager for saving and loading analysis variables

Workspace objects are typically used either 1) within an ipython notebook to interactively build a report/dashboard, or 2) within a script to build a hardcoded (“fixed”) report/dashboard.

Parameters

cachefilestr, optional

filename with cached workspace results

Initialize a Workspace object.

Parameters

cachefilestr, optional

filename with cached workspace results

save_cache(cachefile, show_unpickled=False)

Save this Workspace’s cache to a file.

Parameters
cachefilestr

The filename to save the cache to.

show_unpickledbool, optional

Whether to print quantities (keys) of cache that could not be saved because they were not pickle-able.

Returns

None

load_cache(cachefile)

Load this Workspace’s cache from cachefile.

Parameters
cachefilestr

The filename to load the cache from.

Returns

None

init_notebook_mode(connected=False, autodisplay=False)

Initialize this Workspace for use in an iPython notebook environment.

This function should be called prior to using the Workspace when working within an iPython notebook.

Parameters
connectedbool , optional

Whether to assume you are connected to the internet. If you are, then setting this to True allows initialization to rely on web- hosted resources which will reduce the overall size of your notebook.

autodisplaybool , optional

Whether to automatically display workspace objects after they are created.

Returns

None

switched_compute(fn, *args)

Calls a compute function with special handling of SwitchedValue arguments.

This is similar to calling fn, given its name and arguments, when some or all of those arguments are SwitchedValue objects.

Caching is employed to avoid duplicating function evaluations which have the same arguments. Note that the function itself doesn’t need to deal with SwitchValue objects, as this routine resolves such objects into a series of function evaluations using the underlying value(s) within the SwitchValue. This routine is primarily used internally for the computation of tables and plots.

if any of the arguments is an instance of NotApplicable then fn is not evaluated and the instance is returned as the evaluation result. If multiple arguments are NotApplicable instances, the first is used as the result.

Parameters
fnfunction

The function to evaluate

Returns
fn_valueslist

The function return values for all relevant sets of arguments. Denote the length of this list by N.

switchboardslist

A list of all the relevant Switchboards used during the function evaluation. Denote the length of this list by M.

switchboard_switch_indiceslist

A list of length M whose elements are tuples containing the 0-based indices of the relevant switches (i.e. those used by any of the arguments) for each switchboard (element of switchboards).

switchpos_mapdict

A dictionary whose keys are switch positions, and whose values are integers between 0 and N which index the element of fn_values corresponding to the given switch positions. Each “switch positions” key is a tuple of length M whose elements (one per switchboard) are tuples of 0-based switch-position indices indicating the position of the relevant switches of that switchboard. Thus, len(key[i]) = len(switchboard_switch_indices[i]), where key is a dictionary key.

class pygsti.report.workspace.Switchboard(ws, switches, positions, types, initial_pos=None, descriptions=None, show='all', id=None, use_loadable_items=False)

Bases: collections.OrderedDict

Encapsulates a render-able set of user-interactive switches for controlling visualized output.

Outwardly a Switchboard looks like a dictionary of SwitchValue objects, which in turn look like appropriately sized numpy arrays of values for some quantity. Different switch positions select different values and thereby what data is visualized in various outputs (e.g. tables and plots).

Parameters

wsWorkspace

The containing (parent) workspace.

switcheslist

A list of switch names. The length of this list is the number of switches.

positionslist

Elements are lists of position labels, one per switch. Length must be equal to len(switches).

typeslist of {‘buttons’,’dropdown’,’slider’,’numslider’}

A list of switch-type strings specifying what type of switch each switch is.

  • ‘buttons’: a set of toggle buttons

  • ‘dropdown’: a drop-down (or combo-box)

  • ‘slider’: a horizontal slider (equally spaced items)

  • ‘numslider’: a horizontal slider (spaced by numeric value)

initial_poslist or None (optional)

A list of 0-based integer indices giving the initial position of each of the len(switches) switches. None defaults to the first (0-th) position for each switch.

descriptionslist (optional)

A string description for each of the len(switches) switches.

showlist (optional)

A list of boolean (one for each of the len(switches) switches) indicating whether or not that switch should be rendered. The special values “all” and “none” show all or none of the switches, respectively.

idstr (optional)

A DOM identifier to use when rendering this Switchboard to HTML. Usually leaving this value as None is best, in which case a random identifier is created.

use_loadable_itemsbool, optional

Whether “loadable” items are being used. When using loadable items, elements of a web page are explicitly told when to initialize themselves by a “load_loadable_item” signal instead of loading as soon as the DOM is ready (a traditional on-ready handler). Using this option increases the performance of large/complex web pages.

Create a new Switchboard.

Parameters

switcheslist

A list of switch names. The length of this list is the number of switches.

positionslist

Elements are lists of position labels, one per switch. Length must be equal to len(switches).

typeslist of {‘buttons’,’dropdown’,’slider’,’numslider’}

A list of switch-type strings specifying what type of switch each switch is.

  • ‘buttons’: a set of toggle buttons

  • ‘dropdown’: a drop-down (or combo-box)

  • ‘slider’: a horizontal slider (equally spaced items)

  • ‘numslider’: a horizontal slider (spaced by numeric value)

initial_poslist or None (optional)

A list of 0-based integer indices giving the initial position of each of the len(switches) switches. None defaults to the first (0-th) position for each switch.

descriptionslist (optional)

A string description for each of the len(switches) switches.

showlist (optional)

A list of boolean (one for each of the len(switches) switches) indicating whether or not that switch should be rendered. The special values “all” and “none” show all or none of the switches, respectively.

idstr (optional)

A DOM identifier to use when rendering this Switchboard to HTML. Usually leaving this value as None is best, in which case a random identifier is created.

use_loadable_itemsbool, optional

Whether “loadable” items are being used. When using loadable items, elements of a web page are explicitly told when to initialize themselves by a “load_loadable_item” signal instead of loading as soon as the DOM is ready (a traditional on-ready handler). Using this option increases the performance of large/complex web pages.

add(varname, dependencies)

Adds a new switched-value to this Switchboard.

Parameters
varnamestr

A name for the variable being added. This name will be used to access the new variable (as either a dictionary key or as an object member).

dependencieslist or tuple

The (0-based) switch-indices specifying which switch positions the new variable is dependent on. For example, if the Switchboard has two switches, one for “amplitude” and one for “frequency”, and this value is only dependent on frequency, then dependencies should be set to (1,) or [1].

Returns

None

add_unswitched(varname, value)

Adds a new non-switched-value to this Switchboard.

This can be convenient for attaching related non-switched data to a Switchboard.

Parameters
varnamestr

A name for the variable being added. This name will be used to access the new variable (as either a dictionary key or as an object member).

valueobject

The un-switched value to associate with varname.

Returns

None

render(typ='html')

Render this Switchboard into the requested format.

The returned string(s) are intended to be used to embedded a visualization of this object within a larger document.

Parameters
typ{“html”}

The format to render as. Currently only HTML is supported.

Returns
dict

A dictionary of strings whose keys indicate which portion of the embeddable output the value is. Keys will vary for different typ. For “html”, keys are “html” and “js” for HTML and and Javascript code, respectively.

create_switch_change_handlerjs(switch_index)

Returns the Javascript needed to begin an on-change handler for a particular switch.

Parameters
switch_indexint

The 0-based index of which switch to get handler JS for.

Returns

str

create_switch_valuejs(switch_index)

Returns the Javascript needed to get the value of a particular switch.

Parameters
switch_indexint

The 0-based index of which switch to get value-extracting JS for.

Returns

str

display()

Display this switchboard within an iPython notebook.

Calling this function requires that you are in an iPython environment, and really only makes sense within a notebook.

Returns

None

view(switches='all', idsuffix='auto')

Return a view of this Switchboard.

Parameters
switcheslist, optional

The names of the switches to include in this view. The special value “all” includes all of the switches in the view. Alternatively, this can be an array of boolean values, one for each switch.

idsuffixstr, optional

A suffix to append to the DOM ID of this switchboard when rendering the view. If “auto”, a random suffix is used.

Returns

SwitchboardView

class pygsti.report.workspace.SwitchboardView(switchboard, idsuffix='auto', show='all')

Bases: object

A duplicate or “view” of an existing switchboard.

This view is logically represents the same set of switches. Thus, when switches are moved on the duplicate board, switches will move on the original (and vice versa).

Parameters

switchboardSwitchboard

The base switch board.

idsuffixstr, optional

A suffix to append to the DOM ID of this switchboard when rendering the view. If “auto”, a random suffix is used.

showlist (optional)

A list of booleans indicating which switches should be rendered. The special values “all” and “none” show all or none of the switches, respectively.

Create a new SwitchboardView

Parameters

switchboardSwitchboard

The base switch board.

idsuffixstr, optional

A suffix to append to the DOM ID of this switchboard when rendering the view. If “auto”, a random suffix is used.

showlist (optional)

A list of booleans indicating which switches should be rendered. The special values “all” and “none” show all or none of the switches, respectively.

render(typ='html')

Render this Switchboard into the requested format.

The returned string(s) are intended to be used to embedded a visualization of this object within a larger document.

Parameters
typ{“html”}

The format to render as. Currently only HTML is supported.

Returns
dict

A dictionary of strings whose keys indicate which portion of the embeddable output the value is. Keys will vary for different typ. For “html”, keys are “html” and “js” for HTML and and Javascript code, respectively.

display()

Display this switchboard within an iPython notebook.

Calling this function requires that you are in an iPython environment, and really only makes sense within a notebook.

Returns

None

class pygsti.report.workspace.SwitchValue(parent_switchboard, name, dependencies)

Bases: object

A value that is controlled by the switches of a single Switchboard.

“Value” here means an arbitrary quantity, and is usually an argument to visualization functions.

The paradigm is one of a Switchboard being a collection of switches along with a dictionary of SwitchValues, whereby each SwitchValue is a mapping of switch positions to values. For efficiency, a SwitchValue need only map a “subspace” of the switch positions, that is, the position-space spanned by only a subset of the switches. Which switch-positions are mapped is given by the “dependencies” of a SwitchValue.

SwitchValue behaves much like a numpy array of values in terms of element access.

Parameters

parent_switchboardSwitchboard

The switch board this value is associated with.

namestr

The name of this value, which is also the key or member name used to access this value from its parent Switchboard.

dependenciesiterable

The 0-based indices identifying which switches this value depends upon, and correspondingly, which switch positions the different axes of the new SwitchValue correspond to.

Creates a new SwitchValue.

Parameters

parent_switchboardSwitchboard

The switch board this value is associated with.

namestr

The name of this value, which is also the key or member name used to access this value from its parent Switchboard.

dependenciesiterable

The 0-based indices identifying which switches this value depends upon, and correspondingly, which switch positions the different axes of the new SwitchValue correspond to.

class pygsti.report.workspace.WorkspaceOutput(ws)

Bases: object

Base class for all forms of data-visualization within a Workspace context.

WorkspaceOutput sets a common interface for performing data visualization using a Workspace. In particular, render is used to create embeddable output in various formats, and display is used to show the object within an iPython notebook.

Parameters

wsWorkspace

The workspace containing the new object.

Attributes

default_render_optionsdict

Class attribute giving default rendering options.

Create a new WorkspaceOutput object. Usually not called directly.

Parameters

wsWorkspace

The workspace containing the new object.

default_render_options
set_render_options(**kwargs)

Sets rendering options, which affect how render() behaves.

The reason render options are set via this function rather than passed directly as arguments to the render(…) call is twofold. First, it allows for global ‘default’ options to be set before creating WorkspaceOutput-derived objects; Secondly, it allows the user to set render options right after an object is constructed, separately from the rendering process (which is sometimes desirable).

Parameters
output_dirstr or False

The name of the output directory under which all output files should be created. The names of these files just the IDs of the items being rendered.

precisionint or dict, optional

The amount of precision to display. A dictionary with keys “polar”, “sci”, and “normal” can separately specify the precision for complex angles, numbers in scientific notation, and everything else, respectively. If an integer is given, it this same value is taken for all precision types. If None, then {‘normal’: 6, ‘polar’: 3, ‘sci’: 0} is used.

switched_item_mode{‘inline’,’separate files’}, optional

Whether switched items should be rendered inline within the ‘html’ and ‘js’ blocks of the return value of render(), or whether each switched item (corresponding to a single “switch position”) should be rendered in a separate file and loaded on-demand only when it is needed.

switched_item_id_overridesdict, optional

A dictionary of index:id pairs, where index is a 0-based index into the list of switched items (plots or tables), and id is a string ID. Since the ID is used as the filename when saving files, overriding the ID is useful when writing a single plot or table to a specific filename.

global_requirejsbool, optional

Whether the table is going to be embedded in an environment with a globally defined RequireJS library. If True, then rendered output will make use of RequireJS.

click_to_displaybool, optional

If True, table plots are not initially created but must be clicked to prompt creation. This is False by default, and can be useful to set to True for tables with especially complex plots whose creation would slow down page loading significantly.

resizablebool, optional

Whether or not to place table inside a JQueryUI resizable widget (only applies when typ == “html”).

autosize{‘none’, ‘initial’, ‘continual’}, optional

Whether tables and plots should be resized either initially, i.e. just upon first rendering (“initial”) or whenever the browser window is resized (“continual”). This option only applies for html rendering.

link_totuple of {“tex”, “pdf”, “pkl”} or None, optional

If not None, a list of one or more items from the given set indicating whether or not to include links to Latex, PDF, and Python pickle files, respectively. Note that setting this render option does not automatically create/render additional formats of this output object (you need to make multiple render calls for that) - it just creates the links to these files when rendering as “html”.

valign{“top”,”bottom”}

Whether the switched items should be vertically aligned by their tops or bottoms (when they’re different heights).

latex_cmdstr, optional

The system command or executable used to compile LaTeX documents. Usually “pdflatex”.

latex_flagslist, optional

A list of (string-valued) flags to pass to latex_cmd when compiling LaTeX documents. Defaults to [“-interaction=nonstopmode”, “-halt-on-error”, “-shell-escape”]

page_sizetuple

The usable page size for LaTeX documents, as (width,*height*) where width and height are in inches. Note that this does not include margins. Defaults to (6.5,8.0).

render_includesbool, optional

When rendering as “latex”, whether included files should also be rendered (either by compiling latex to PDF or saving plots as PDFs).

leave_includes_srcbool, optional

When LaTeX compilation is done, should the source “.tex” files be removed? If `False`, then they *are removed.

Returns

None

abstract render(typ='html')

Renders this object into the specified format, specifically for embedding it within a larger document.

Parameters
typstr

The format to render as. Currently “html” is widely supported and “latex” is supported for tables.

Returns
dict

A dictionary of strings whose keys indicate which portion of the embeddable output the value is. Keys will vary for different typ. For “html”, keys are “html” and “js” for HTML and and Javascript code, respectively.

display()

Display this object within an iPython notebook.

Returns

None

abstract saveas(filename, index=None, verbosity=0)

Saves this workspace output object to a file.

The type of file that is saved is determined automatically by the extension of filename. Recognized extensions are pdf (PDF), tex (LaTeX), pkl (Python pickle) and html (HTML). Since this object may contain different instances of its data based on switch positions, when their are multiple instances the user must specify the index argument to disambiguate.

Parameters
filenamestr

The destination filename. Its extension determines what type of file is saved.

indexint, optional

An absolute index into the list of different switched “versions” of this object’s data. In most cases, the object being saved doesn’t depend on any switch boards and has only a single “version”, in which caes this can be left as the default.

verbosityint, optional

Controls the level of detail printed to stdout.

Returns

None

class pygsti.report.workspace.NotApplicable(ws)

Bases: WorkspaceOutput

Class signifying that an given set of arguments is not applicable to a function being evaluated.

Parameters

wsWorkspace

The containing (parent) workspace.

Create a new NotApplicable object.

render(typ='html', id=None)

Renders this object into the specified format, specifically for embedding it within a larger document.

Parameters
typstr

The format to render as. Allowed options are “html”, “latex”, and “python”.

idstr, optional

An DOM id used in place of the objects internal id.

Returns
dict

A dictionary of strings whose keys indicate which portion of the embeddable output the value is. Keys will vary for different typ. For “html”, keys are “html” and “js” for HTML and and Javascript code, respectively.

class pygsti.report.workspace.WorkspaceTable(ws, fn, *args)

Bases: WorkspaceOutput

Encapsulates a table within a Workspace context.

A base class which provides the logic required to take a single table-generating function and make it into a legitimate WorkspaceOutput object for using within workspaces.

Parameters

wsWorkspace

The workspace containing the new object.

fnfunction

A table-creating function.

argsvarious

The arguments to fn.

Create a new WorkspaceTable. Usually not called directly.

Parameters

wsWorkspace

The workspace containing the new object.

fnfunction

A table-creating function.

argsvarious

The arguments to fn.

render(typ)

Renders this table into the specified format, specifically for embedding it within a larger document.

Parameters
typstr

The format to render as. Currently “html”, “latex” and “python” are supported.

Returns
dict

A dictionary of strings giving the different portions of the embeddable output. For “html”, keys are “html” and “js”. For “latex”, there is a single key “latex”.

saveas(filename, index=None, verbosity=0)

Saves this workspace table object to a file.

The type of file that is saved is determined automatically by the extension of filename. Recognized extensions are pdf (PDF), tex (LaTeX), pkl (Python pickle) and html (HTML). Since this object may contain different instances of its data based on switch positions, when their are multiple instances the user must specify the index argument to disambiguate.

Parameters
filenamestr

The destination filename. Its extension determines what type of file is saved.

indexint, optional

An absolute index into the list of different switched “versions” of this object’s data. In most cases, the object being saved doesn’t depend on any switch boards and has only a single “version”, in which caes this can be left as the default.

verbosityint, optional

Controls the level of detail printed to stdout.

Returns

None

class pygsti.report.workspace.WorkspacePlot(ws, fn, *args)

Bases: WorkspaceOutput

Encapsulates a plot within a Workspace context.

A base class which provides the logic required to take a single plot.ly figure-generating function and make it into a legitimate WorkspaceOutput object for using within workspaces.

Parameters

wsWorkspace

The workspace containing the new object.

fnfunction

A table-creating function.

argsvarious

The arguments to fn.

Create a new WorkspaceTable. Usually not called directly.

Parameters

wsWorkspace

The workspace containing the new object.

fnfunction

A table-creating function.

argsvarious

The arguments to fn.

render(typ='html', id=None)

Renders this plot into the specified format, specifically for embedding it within a larger document.

Parameters
typstr

The format to render as. Currently “html”, “latex” and “python” are supported.

idstr, optional

A base id to use when rendering. If None, the object’s persistent id is used, which usually what you want.

Returns
dict

A dictionary of strings giving the HTML and Javascript portions of the embeddable output. Keys are “html” and “js”.

saveas(filename, index=None, verbosity=0)

Saves this workspace plot object to a file.

The type of file that is saved is determined automatically by the extension of filename. Recognized extensions are pdf (PDF), pkl (Python pickle) and html (HTML). Since this object may contain different instances of its data based on switch positions, when their are multiple instances the user must specify the index argument to disambiguate.

Parameters
filenamestr

The destination filename. Its extension determines what type of file is saved.

indexint, optional

An absolute index into the list of different switched “versions” of this object’s data. In most cases, the object being saved doesn’t depend on any switch boards and has only a single “version”, in which caes this can be left as the default.

verbosityint, optional

Controls the level of detail printed to stdout.

Returns

None

class pygsti.report.workspace.WorkspaceText(ws, fn, *args)

Bases: WorkspaceOutput

Encapsulates a block of text within a Workspace context.

A base class which provides the logic required to take a single text-generating function and make it into a legitimate WorkspaceOutput object for using within workspaces.

Parameters

wsWorkspace

The workspace containing the new object.

fnfunction

A text-creating function.

argsvarious

The arguments to fn.

Create a new WorkspaceText object. Usually not called directly.

Parameters

wsWorkspace

The workspace containing the new object.

fnfunction

A text-creating function.

argsvarious

The arguments to fn.

render(typ)

Renders this text block into the specified format, specifically for embedding it within a larger document.

Parameters
typstr

The format to render as. Currently “html”, “latex” and “python” are supported.

Returns
dict

A dictionary of strings giving the different portions of the embeddable output. For “html”, keys are “html” and “js”. For “latex”, there is a single key “latex”.

saveas(filename, index=None, verbosity=0)

Saves this workspace text block object to a file.

The type of file that is saved is determined automatically by the extension of filename. Recognized extensions are pdf (PDF), tex (LaTeX), pkl (Python pickle) and html (HTML). Since this object may contain different instances of its data based on switch positions, when their are multiple instances the user must specify the index argument to disambiguate.

Parameters
filenamestr

The destination filename. Its extension determines what type of file is saved.

indexint, optional

An absolute index into the list of different switched “versions” of this object’s data. In most cases, the object being saved doesn’t depend on any switch boards and has only a single “version”, in which caes this can be left as the default.

verbosityint, optional

Controls the level of detail printed to stdout.

Returns

None