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

_PYGSTI_WORKSPACE_INITIALIZED

VALIDATE_PLOTLY

pygsti.report.workspace._PYGSTI_WORKSPACE_INITIALIZED = False
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

content (str) – 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
  • md5 (hashlib.HASH) – The MD5 hash object.

  • v (object) – 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

cachefile (str, optional) – filename with cached workspace results

save_cache(self, cachefile, show_unpickled=False)

Save this Workspace’s cache to a file.

Parameters
  • cachefile (str) – The filename to save the cache to.

  • show_unpickled (bool, optional) – Whether to print quantities (keys) of cache that could not be saved because they were not pickle-able.

Returns

None

load_cache(self, cachefile)

Load this Workspace’s cache from cachefile.

Parameters

cachefile (str) – The filename to load the cache from.

Returns

None

__getstate__(self)
__setstate__(self, state_dict)
_makefactory(self, cls, autodisplay)
_register_components(self, autodisplay)
init_notebook_mode(self, 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
  • connected (bool , 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.

  • autodisplay (bool , optional) – Whether to automatically display workspace objects after they are created.

Returns

None

switched_compute(self, 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

fn (function) – The function to evaluate

Returns

  • fn_values (list) – The function return values for all relevant sets of arguments. Denote the length of this list by N.

  • switchboards (list) – A list of all the relevant Switchboards used during the function evaluation. Denote the length of this list by M.

  • switchboard_switch_indices (list) – 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_map (dict) – 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
  • ws (Workspace) – The containing (parent) workspace.

  • switches (list) – A list of switch names. The length of this list is the number of switches.

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

  • types (list 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_pos (list 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.

  • descriptions (list (optional)) – A string description for each of the len(switches) switches.

  • show (list (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.

  • id (str (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_items (bool, 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(self, varname, dependencies)

Adds a new switched-value to this Switchboard.

Parameters
  • varname (str) – 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).

  • dependencies (list 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(self, 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
  • varname (str) – 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).

  • value (object) – The un-switched value to associate with varname.

Returns

None

__setitem__(self, key, val)

Set self[key] to value.

render(self, 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.

_render_base(self, typ, view_suffix, show)

Break off this implementation so SwitchboardViews can use.

create_switch_change_handlerjs(self, switch_index)

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

Parameters

switch_index (int) – The 0-based index of which switch to get handler JS for.

Returns

str

create_switch_valuejs(self, switch_index)

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

Parameters

switch_index (int) – The 0-based index of which switch to get value-extracting JS for.

Returns

str

display(self)

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(self, switches='all', idsuffix='auto')

Return a view of this Switchboard.

Parameters
  • switches (list, 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.

  • idsuffix (str, 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

__getattr__(self, attr)
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
  • switchboard (Switchboard) – The base switch board.

  • idsuffix (str, optional) – A suffix to append to the DOM ID of this switchboard when rendering the view. If “auto”, a random suffix is used.

  • show (list (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(self, 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(self)

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_switchboard (Switchboard) – The switch board this value is associated with.

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

  • dependencies (iterable) – 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.

__getitem__(self, key)
__getslice__(self, i, j)
__setitem__(self, key, val)
__getattr__(self, attr)
__len__(self)
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

ws (Workspace) – The workspace containing the new object.

default_render_options

Class attribute giving default rendering options.

Type

dict

default_render_options
set_render_options(self, **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_dir (str 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.

  • precision (int 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_overrides (dict, 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_requirejs (bool, 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_display (bool, 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.

  • resizable (bool, 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_to (tuple 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_cmd (str, optional) – The system command or executable used to compile LaTeX documents. Usually “pdflatex”.

  • latex_flags (list, 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_size (tuple) – 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_includes (bool, 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_src (bool, optional) – When LaTeX compilation is done, should the source “.tex” files be removed? If `False`, then they *are removed.

Returns

None

__getstate__(self)
__setstate__(self, d)
abstract render(self, typ='html')

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

Parameters

typ (str) – 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(self)

Display this object within an iPython notebook.

Returns

None

abstract saveas(self, 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
  • filename (str) – The destination filename. Its extension determines what type of file is saved.

  • index (int, 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.

  • verbosity (int, optional) – Controls the level of detail printed to stdout.

Returns

None

_ccompute(self, fn, *args, **kwargs)

Cached-computation using self.ws’s smart cache

_create_onready_handler(self, content, id)
_render_html(self, id, div_htmls, div_jss, div_ids, switchpos_map, switchboards, switch_indices, div_css_classes=None, link_to=None, link_to_files_dir=None, embed_figures=True)

Helper rendering function, which takes care of the (complex) common logic which take a series of HTML div blocks corresponding to the results of a Workspace.switched_compute(…) call and builds the HTML and JS necessary for toggling the visibility of these divs in response to changes in switch position(s).

Parameters
  • id (str) – The identifier to use when constructing DOM ids.

  • div_htmls (list) – The html content for each switched block (typically a elements are “<div>…</div>” blocks themselves). This is the content that is switched between.

  • div_jss (list) – Javascript content to accompany each switched block.

  • div_ids (list) – A list giving the DOM ids for the div blocks given by div_html.

  • switchpos_map (dict) – A dictionary mapping switch positions to div-index. Keys are switch tuples of per-switchboard positions (i.e. a tuple of tuples), giving the positions of each switch specified in switch_indices. Values are integer indices into html_divs.

  • switchboards (list) – A list of relevant SwitchBoard objects.

  • switch_indices (list) – A list of tuples, one per Switchboard object, giving the relevant switch indices (integers) within that Switchboard.

  • div_css_classes (list, optional) – A list of (string) CSS classes to add to the div elements created by this function.

  • link_to (list, optional) – If not None, a list of one or more items from the set {“tex”, “pdf”, “pkl”} indicating whether or not to include links to Latex, PDF, and Python pickle files, respectively.

  • link_to_files_dir (str, optional) – The directory to place linked-to files in. Only used when link_to is not None.

  • embed_figures (bool, optional) – If True (default), figures will be embedded directly into the report HTML. Otherwise, figures will be written to link_to_files_dir and dynamically loaded into the report with AJAX requests.

Returns

dict – A dictionary of strings whose keys indicate which portion of the embeddable output the value is. Keys are “html” and “js”.

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

ws (Workspace) – The containing (parent) workspace.

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

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

Parameters
  • typ (str) – The format to render as. Allowed options are “html”, “latex”, and “python”.

  • id (str, 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
  • ws (Workspace) – The workspace containing the new object.

  • fn (function) – A table-creating function.

  • args (various) – The arguments to fn.

render(self, typ)

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

Parameters

typ (str) – 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(self, 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
  • filename (str) – The destination filename. Its extension determines what type of file is saved.

  • index (int, 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.

  • verbosity (int, optional) – Controls the level of detail printed to stdout.

Returns

None

_form_table_js(self, table_id, table_html, table_plot_handlers, switchboard_init_js)
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
  • ws (Workspace) – The workspace containing the new object.

  • fn (function) – A table-creating function.

  • args (various) – The arguments to fn.

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

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

Parameters
  • typ (str) – The format to render as. Currently “html”, “latex” and “python” are supported.

  • id (str, 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(self, 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
  • filename (str) – The destination filename. Its extension determines what type of file is saved.

  • index (int, 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.

  • verbosity (int, optional) – Controls the level of detail printed to stdout.

Returns

None

_form_plot_js(self, plot_id, plot_handlers, switchboard_init_js)
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
  • ws (Workspace) – The workspace containing the new object.

  • fn (function) – A text-creating function.

  • args (various) – The arguments to fn.

render(self, typ)

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

Parameters

typ (str) – 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(self, 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
  • filename (str) – The destination filename. Its extension determines what type of file is saved.

  • index (int, 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.

  • verbosity (int, optional) – Controls the level of detail printed to stdout.

Returns

None

_form_text_js(self, text_id, text_html, switchboard_init_js)