pygsti.report

pyGSTi Reporting Python Package

Subpackages

Submodules

Package Contents

Classes

Notebook

Python representation of an IPython notebook

Report

The internal model of a report.

_ReportableQty

A computed quantity and possibly its error bars, primarily for use in reports.

_Basis

An ordered set of labeled matrices/vectors.

_DirectSumBasis

A basis that is the direct sum of one or more "component" bases.

_Lbl

A label used to identify a gate, circuit layer, or (sub-)circuit.

GateEigenvalues

Gate eigenvalues

CircuitEigenvalues

Circuit eigenvalues

CircuitHalfDiamondNorm

1/2 diamond norm of difference between productA(circuit) and productB(circuit)

HalfDiamondNorm

Half the diamond distance bewteen model_a.operations[op_label] and model_b.operations[op_label]

Workspace

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

_ExplicitOpModel

Encapsulates a set of gate, state preparation, and POVM effect operations.

_StateSpace

Base class for defining a state space (Hilbert or Hilbert-Schmidt space).

_Circuit

A quantum circuit.

_CircuitList

A unmutable list (a tuple) of Circuit objects and associated metadata.

_PlaquetteGridCircuitStructure

Encapsulates a set of circuits, along with an associated structure.

_Lbl

A label used to identify a gate, circuit layer, or (sub-)circuit.

_VerbosityPrinter

Class responsible for logging things to stdout or a file.

Functions

_null_fn(*arg)

_project_to_valid_prob(p, tol=1e-09)

_make_reportable_qty_or_dict(f0, df=None, non_markovian_ebs=False)

Just adds special processing with f0 is a dict, where we

evaluate(model_fn, cri=None, verbosity=0)

Evaluate a ModelFunction object using confidence region information

spam_dotprods(rho_vecs, povms)

SPAM dot products (concatenates POVMS)

choi_matrix(gate, mx_basis)

Choi matrix

choi_eigenvalues(gate, mx_basis)

Choi matrix eigenvalues

choi_trace(gate, mx_basis)

Trace of the Choi matrix

rel_circuit_eigenvalues(model_a, model_b, circuit)

Eigenvalues of dot(productB(circuit)^-1, productA(circuit))

circuit_frobenius_diff(model_a, model_b, circuit)

Frobenius distance btwn productA(circuit) and productB(circuit)

circuit_entanglement_infidelity(model_a, model_b, circuit)

Entanglement infidelity btwn productA(circuit) and productB(circuit)

circuit_avg_gate_infidelity(model_a, model_b, circuit)

Average gate infidelity between productA(circuit) and productB(circuit).

circuit_jtrace_diff(model_a, model_b, circuit)

Jamiolkowski trace distance between productA(circuit) and productB(circuit)

circuit_nonunitary_entanglement_infidelity(model_a, model_b, circuit)

Nonunitary entanglement infidelity between productA(circuit) and productB(circuit)

circuit_nonunitary_avg_gate_infidelity(model_a, model_b, circuit)

Nonunitary average gate infidelity between productA(circuit) and productB(circuit).

circuit_eigenvalue_entanglement_infidelity(model_a, model_b, circuit)

Eigenvalue entanglement infidelity between productA(circuit) and productB(circuit).

circuit_eigenvalue_avg_gate_infidelity(model_a, model_b, circuit)

Eigenvalue average gate infidelity between productA(circuit) and productB(circuit).

circuit_eigenvalue_nonunitary_entanglement_infidelity(model_a, model_b, circuit)

Eigenvalue nonunitary entanglement infidelity between productA(circuit) and productB(circuit).

circuit_eigenvalue_nonunitary_avg_gate_infidelity(model_a, model_b, circuit)

Eigenvalue nonunitary average gate infidelity between productA(circuit) and productB(circuit).

circuit_eigenvalue_diamondnorm(model_a, model_b, circuit)

Eigenvalue diamond distance between productA(circuit) and productB(circuit).

circuit_eigenvalue_nonunitary_diamondnorm(model_a, model_b, circuit)

Eigenvalue nonunitary diamond distance between productA(circuit) and productB(circuit).

povm_entanglement_infidelity(model_a, model_b, povmlbl)

POVM entanglement infidelity between model_a and model_b.

povm_jtrace_diff(model_a, model_b, povmlbl)

POVM Jamiolkowski trace distance between model_a and model_b

povm_half_diamond_norm(model_a, model_b, povmlbl)

Half the POVM diamond distance between model_a and model_b.

decomposition(gate)

DEPRECATED: Decompose a 1Q gate into rotations about axes.

upper_bound_fidelity(gate, mx_basis)

Upper bound on entanglement fidelity

closest_ujmx(gate, mx_basis)

Jamiolkowski state of closest unitary to gate

maximum_fidelity(gate, mx_basis)

Fidelity between gate and its closest unitary

maximum_trace_dist(gate, mx_basis)

Jamiolkowski trace distance between gate and its closest unitary

angles_btwn_rotn_axes(model)

Array of angles between the rotation axes of the gates of model.

entanglement_fidelity(a, b, mx_basis)

Entanglement fidelity between a and b

entanglement_infidelity(a, b, mx_basis)

Entanglement infidelity between a and b

closest_unitary_fidelity(a, b, mx_basis)

Entanglement infidelity between closest unitaries to a and b

frobenius_diff(a, b, mx_basis)

Frobenius distance between a and b

jtrace_diff(a, b, mx_basis)

Jamiolkowski trace distance between a and b

std_unitarity(a, b, mx_basis)

a gauge-invariant quantity that behaves like the unitarity

eigenvalue_unitarity(a, b)

a gauge-invariant quantity that behaves like the unitarity

nonunitary_entanglement_infidelity(a, b, mx_basis)

Returns (d^2 - 1)/d^2 * (1 - sqrt(U)), where U is the unitarity of a*b^{-1}

nonunitary_avg_gate_infidelity(a, b, mx_basis)

Returns (d - 1)/d * (1 - sqrt(U)), where U is the unitarity of a*b^{-1}

eigenvalue_nonunitary_entanglement_infidelity(a, b, mx_basis)

Returns (d^2 - 1)/d^2 * (1 - sqrt(U)), where U is the eigenvalue-unitarity of a*b^{-1}

eigenvalue_nonunitary_avg_gate_infidelity(a, b, mx_basis)

Returns (d - 1)/d * (1 - sqrt(U)), where U is the eigenvalue-unitarity of a*b^{-1}

eigenvalue_entanglement_infidelity(a, b, mx_basis)

Eigenvalue entanglement infidelity between a and b

eigenvalue_avg_gate_infidelity(a, b, mx_basis)

Eigenvalue average gate infidelity between a and b

eigenvalue_diamondnorm(a, b, mx_basis)

Eigenvalue diamond distance between a and b

eigenvalue_nonunitary_diamondnorm(a, b, mx_basis)

Eigenvalue nonunitary diamond distance between a and b

avg_gate_infidelity(a, b, mx_basis)

Returns the average gate infidelity between a and b, where b is the "target" operation.

model_model_angles_btwn_axes(a, b, mx_basis)

Angle between the rotation axes of a and b (1-qubit gates)

rel_eigenvalues(a, b, mx_basis)

Eigenvalues of b^{-1} * a

rel_log_tig_eigenvalues(a, b, mx_basis)

Eigenvalues of log(b^{-1} * a)

rel_log_gti_eigenvalues(a, b, mx_basis)

Eigenvalues of log(a * b^{-1})

rel_log_diff_eigenvalues(a, b, mx_basis)

Eigenvalues of log(a) - log(b)

rel_gate_eigenvalues(a, b, mx_basis)

Eigenvalues of b^{-1} * a

errorgen_and_projections(errgen, mx_basis)

Project errgen on all of the standard sets of error generators.

log_tig_and_projections(a, b, mx_basis)

Projections of log(b^{-1}*a).

log_gti_and_projections(a, b, mx_basis)

Projections of log(a*b^{-1}).

log_diff_and_projections(a, b, mx_basis)

Projections of log(a)-log(b).

robust_log_gti_and_projections(model_a, model_b, synthetic_idle_circuits)

Projections of log(A*B^{-1}) using a gauge-robust technique.

general_decomposition(model_a, model_b)

Decomposition of gates in model_a using those in model_b as their targets.

average_gateset_infidelity(model_a, model_b)

Average model infidelity

predicted_rb_number(model_a, model_b)

Prediction of RB number based on estimated (A) and target (B) models

vec_fidelity(a, b, mx_basis)

State fidelity between state vectors a and b

vec_infidelity(a, b, mx_basis)

State infidelity fidelity between state vectors a and b

vec_trace_diff(a, b, mx_basis)

Trace distance between state vectors a and b

vec_as_stdmx(vec, mx_basis)

State vector as a standard density matrix

vec_as_stdmx_eigenvalues(vec, mx_basis)

Eigenvalues of the density matrix corresponding to a state vector

info_of_opfn_by_name(name)

Returns a nice human-readable name and tooltip for a given gate-function abbreviation.

evaluate_opfn_by_name(name, model, target_model, op_label_or_string, confidence_region_info)

Evaluates that gate-function named by the abbreviation name.

instrument_infidelity(a, b, mx_basis)

Infidelity between instruments a and b

instrument_half_diamond_norm(a, b, mx_basis)

The diamond norm distance between instruments a and b.

evaluate_instrumentfn_by_name(name, model, target_model, inst_label, confidence_region_info)

Evaluates that instrument-function named by the abbreviation name.

_deprecated_fn(replacement=None)

Decorator for deprecating a function.

_add_new_labels(running_lbls, current_lbls)

Simple routine to add current-labels to a list of

_add_new_estimate_labels(running_lbls, estimates, combine_robust)

Like _add_new_labels but perform robust-suffix processing.

_get_viewable_crf(est, est_lbl, mdl_lbl, verbosity=0)

create_offline_zip(output_dir='.')

Creates a zip file containing the a directory ("offline") of files need to display "offline" reports.

_set_toggles(results_dict, brevity, combine_robust)

_create_master_switchboard(ws, results_dict, confidence_level, nmthreshold, printer, fmt, combine_robust, idt_results_dict=None, embed_figures=True)

Creates the "master switchboard" used by several of the reports

_construct_idtresults(idt_idle_op, idt_pauli_dicts, gst_results_dict, printer)

Constructs a dictionary of idle tomography results, parallel

_create_single_metric_switchboard(ws, results_dict, b_gauge_inv, dataset_labels, est_labels=None, embed_figures=True)

create_general_report(results, filename, title='auto', confidence_level=None, linlog_percentile=5, errgen_type='logGTi', nmthreshold=50, precision=None, comm=None, ws=None, auto_open=False, cachefile=None, brief=False, connected=False, link_to=None, resizable=True, autosize='initial', verbosity=1)

DEPRECATED: use pygsti.report.create_standard_report(...)

create_standard_report(results, filename, title='auto', confidence_level=None, comm=None, ws=None, auto_open=False, link_to=None, brevity=0, advanced_options=None, verbosity=1)

Create a "standard" GST report, containing details about each estimate in results individually.

create_nqnoise_report(results, filename, title='auto', confidence_level=None, comm=None, ws=None, auto_open=False, link_to=None, brevity=0, advanced_options=None, verbosity=1)

Creates a report designed to display results containing for n-qubit noisy model estimates.

create_report_notebook(results, filename, title='auto', confidence_level=None, auto_open=False, connected=False, verbosity=0)

Create a "report notebook".

find_std_clifford_compilation(model, verbosity=0)

Returns the standard Clifford compilation for model, if one exists. Otherwise returns None.

construct_standard_report(results, title='auto', confidence_level=None, comm=None, ws=None, advanced_options=None, verbosity=1)

Create a "standard" GST report, containing details about each estimate in results individually.

construct_nqnoise_report(results, title='auto', confidence_level=None, comm=None, ws=None, advanced_options=None, verbosity=1)

Creates a report designed to display results containing for n-qubit noisy model estimates.

create_drift_report(results, title='auto', ws=None, verbosity=1)

Creates a Drift report.

empty_volumetric_plot(figsize=None, y_values=None, x_values=None, title=None, xlabel='Depth', ylabel='Width')

Creates an empty volumetric plot with just the axes set.

_get_xy(data, y_values=None, x_values=None)

volumetric_plot(data, y_values=None, x_values=None, title=None, fig=None, ax=None, cmap=my_cmap, color=None, flagQV=False, qv_threshold=None, figsize=(10, 10), scale=1.0, centerscale=1.0, linescale=1.0, pass_threshold=0, show_threshold=0)

Creates a volumetric benchmarking plot.

volumetric_boundary_plot(data, y_values=None, x_values=None, boundary=None, threshold=0.5, missing_data_action='continue', monotonic=True, color='k', linewidth=4, linestyle='-', dashing=None, fig=None, ax=None, figsize=None, title=None, label=None)

Creates a volumetric benchmarking boundary plot, that displays boundary at which the given data

capability_region_plot(vbdataframe, metric='polarization', threshold=1 / _np.e, significance=0.05, figsize=(10, 10), scale=1.0, title=None, colors=None)

Creates a capability regions plot from a VBDataFrame. Default options creates plots like those shown

volumetric_distribution_plot(vbdataframe, metric='polarization', threshold=1 / _np.e, hypothesis_test='standard', significance=0.05, figsize=(10, 10), scale={'min': 1.95, 'mean': 1, 'max': 0.13}, title=None, cmap=my_cmap)

Creates volumetric benchmarking plots that display the maximum, mean and minimum of a given figure-of-merit (by

Attributes

_CVXPY_AVAILABLE

FINITE_DIFF_EPS

Spam_dotprods

Choi_matrix

Choi_evals

Choi_trace

Rel_circuit_eigenvalues

Circuit_fro_diff

Circuit_entanglement_infidelity

Circuit_avg_gate_infidelity

Circuit_jt_diff

Circuit_nonunitary_entanglement_infidelity

Circuit_nonunitary_avg_gate_infidelity

Circuit_eigenvalue_entanglement_infidelity

Circuit_eigenvalue_avg_gate_infidelity

Circuit_eigenvalue_nonunitary_entanglement_infidelity

Circuit_eigenvalue_nonunitary_avg_gate_infidelity

Circuit_eigenvalue_diamondnorm

Circuit_eigenvalue_nonunitary_diamondnorm

POVM_entanglement_infidelity

POVM_jt_diff

Upper_bound_fidelity

Closest_ujmx

Maximum_fidelity

Maximum_trace_dist

Angles_btwn_rotn_axes

Entanglement_fidelity

Entanglement_infidelity

Closest_unitary_fidelity

Fro_diff

Jt_diff

Nonunitary_entanglement_infidelity

Nonunitary_avg_gate_infidelity

Eigenvalue_nonunitary_entanglement_infidelity

Eigenvalue_nonunitary_avg_gate_infidelity

Eigenvalue_entanglement_infidelity

Eigenvalue_avg_gate_infidelity

Eigenvalue_diamondnorm

Eigenvalue_nonunitary_diamondnorm

Avg_gate_infidelity

Model_model_angles_btwn_axes

Rel_eigvals

Rel_logTiG_eigvals

Rel_logGTi_eigvals

Rel_logGmlogT_eigvals

Rel_gate_eigenvalues

LogTiG_and_projections

LogGTi_and_projections

LogGmlogT_and_projections

Robust_LogGTi_and_projections

General_decomposition

Average_gateset_infidelity

Predicted_rb_number

Vec_fidelity

Vec_infidelity

Vec_tr_diff

Vec_as_stdmx

Vec_as_stdmx_eigenvalues

Instrument_infidelity

Instrument_half_diamond_norm

_pygsti_version

ROBUST_SUFFIX_LIST

DEFAULT_BAD_FIT_THRESHOLD

blues

class pygsti.report.Notebook(cells=None, notebook_text_files=None)

Bases: object

Python representation of an IPython notebook

Parameters
  • cells (list, optional) – List of NotebookCell objects.

  • notebook_text_files (list, optional) – List of filenames (text files with ‘@@markdown’ or ‘@@code’ designating cells).

DefaultTemplate

The default template notebook to use (a .ipynb file).

Type

str

DefaultTemplate = Empty.ipynb
to_json_dict(self, template_filename=DefaultTemplate)

Using an existing (usually empty) notebook as a template, generate the json for a new notebook.

Parameters

template_filename (str, optional) – Name of an existing notebook file to build from

Returns

dict

save_to(self, output_filename, template_filename=DefaultTemplate)

Save this class to a file as a jupyter notebook

Parameters
  • output_filename (str) – File to save the output jupyter notebook to

  • template_filename (str, optional) – Name of an existing notebook file to build from

Returns

None

add(self, cell)

Add a cell to the notebook

Parameters

cell (NotebookCell object) – Cell to add.

Returns

None

add_block(self, block, cell_type)

Add a block to the notebook

Parameters
  • block (str) – block of either code or markdown

  • cell_type (str) – tag for the cell. Either ‘code’ or ‘markdown’

Returns

None

add_file(self, filename, cell_type)

Read in a cell block from a file

Parameters
  • filename (str) – filename containing either code or markdown

  • cell_type (str) – tag for the cell. Either ‘code’ or ‘markdown’

Returns

None

add_code(self, block)

Add code to notebook

Parameters

block (str) – Block of python code

Returns

None

add_markdown(self, block)

Add markdown to notebook

Parameters

block (str) – Block of markdown (or HTML)

Returns

None

add_code_file(self, filename)

Add a code file to the notebook

Parameters

filename (str) – name of file containing python code

Returns

None

add_markdown_file(self, filename)

Add a markdown file to the notebook

Parameters

filename (str) – name of file containing markdown

Returns

None

add_notebook_text(self, text)

Add custom formatted text to the notebook.

Text contains both python and markdown, with cells differentiated by @@code and @@markdown tags. At least one cell tag must be present for the file to be correctly parsed

Parameters

text (str) – notebook formatted text

Returns

None

add_notebook_text_file(self, filename)

Add a custom formatted text file to the notebook.

Text file contains both python and markdown, with cells differentiated by @@code and @@markdown tags. At least one cell tag must be present for the file to be correctly parsed

Parameters

filename (str) – name of file containing notebook formatted text

Returns

None

add_notebook_text_files(self, filenames)

Add multiple notebook text files to the notebook, in order

Parameters

filenames (list(str)) – names of file containing notebook formatted text

Returns

None

add_notebook_file(self, filename)

Append an .ipynb file to this notebook

Parameters

filename (str) – ipynb file to append

Returns

None

add_notebook_files(self, filenames)

Add multiple notebook files to the notebook, in order

Parameters

filenames (list(str)) – names of file containing ipynb json

Returns

None

launch_new(self, output_filename, template_filename=DefaultTemplate)

Save and then launch this notebook with a new Jupyter server.

Note that this function waits to return until the notebook server exists, and so is difficult to work with.

Parameters
  • output_filename (str) – filename to save this notebook to

  • template_filename (str, optional) – filename to build this notebook from (see save_to)

Returns

None

launch(self, output_filename, template_filename=DefaultTemplate, port='auto')

Save and then launch this notebook

Parameters
  • output_filename (str) – filename to save this notebook to

  • template_filename (str, optional) – filename to build this notebook from (see save_to)

  • port (int, optional) – Port to launch server on.

Returns

None

class pygsti.report.Report(templates, results, sections, flags, global_qtys, report_params, build_defaults=None, pdf_available=True, workspace=None)

The internal model of a report.

This class should never be instantiated directly. Instead, users should use the appropriate factory method in pygsti.report.factory.

Parameters
  • templates (dict (str -> Path-like)) – A map of the available report generation types (html, pdf, notebook) to template paths.

  • results (Results or similar) – The underlying Results-like object used to generate this report.

  • sections (iterable of Section) – Collection of sections to be built into the generated report.

  • flags (set of str) – Set of flags controlling aspects of report generation.

  • global_qtys (dict (str -> any)) – Key-value map of report quantities not tied to any specific section.

  • report_params (dict (str -> any)) – Key-value map of report quantities used when building sections.

  • build_defaults (dict (str -> any), optional) – Default values for the build_options parameter of this instance’s build methods. Defaults to an empty dict.

  • pdf_available (bool, optional) – True if the underlying results can be represented as a static PDF. If this report cannot be represented statically, write_pdf will raise. Defaults to True.

  • workspace (Workspace, optional) – A Workspace used for caching figure computation. By default, a new workspace will be used.

_build(self, build_options=None)

Render all sections to a map of report elements for templating

write_html(self, path, auto_open=False, link_to=None, connected=False, build_options=None, brevity=0, precision=None, resizable=True, autosize='initial', single_file=False, verbosity=0)

Write this report to the disk as a collection of HTML documents.

Parameters
  • path (str or path-like object) – The filesystem path of a directory to write the report to. If the specified directory does not exist, it will be created automatically

  • auto_open (bool, optional) – Whether the output file should be automatically opened in a web browser.

  • 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 create and include links to Latex, PDF, and Python pickle files, respectively.

  • connected (bool, optional) – Whether output HTML should assume an active internet connection. If True, then the resulting HTML file size will be reduced because it will link to web resources (e.g. CDN libraries) instead of embedding them.

  • build_options (dict) – Dict of options for building plots. Expected values are defined during construction of this report object.

  • brevity (int, optional) –

    Amount of detail to include in the report. Larger values mean smaller “more briefr” reports, which reduce generation time, load time, and disk space consumption. In particular:

    • 1: Plots showing per-sequences quantities disappear at brevity=1

    • 2: Reference sections disappear at brevity=2

    • 3: Germ-level estimate tables disappear at brevity=3

    • 4: Everything but summary figures disappears at brevity=4

  • 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.

  • resizable (bool, optional) – Whether plots and tables are made with resize handles and can be resized within the report.

  • autosize ({'none', 'initial', 'continual'}) – Whether tables and plots should be resized, either initially – i.e. just upon first rendering (“initial”) – or whenever the browser window is resized (“continual”).

  • single_file (bool, optional) – If true, the report will be written to a single HTML document, with external dependencies baked-in. This mode is not recommended for large reports, because this file can grow large enough that major web browsers may struggle to render it.

  • verbosity (int, optional) – Amount of detail to print to stdout.

write_notebook(self, path, auto_open=False, connected=False, verbosity=0)

Write this report to the disk as an IPython notebook

A notebook report allows the user to interact more flexibly with the data underlying the figures, and to easily generate customized variants on the figures. As such, this type of report will be most useful for experts who want to tinker with the standard analysis presented in the static HTML or LaTeX format reports.

Parameters
  • path (str or path-like object) – The filesystem path to write the report to. By convention, this should use the .ipynb file extension.

  • auto_open (bool, optional) – If True, automatically open the report in a web browser after it has been generated.

  • connected (bool, optional) – Whether output notebook should assume an active internet connection. If True, then the resulting file size will be reduced because it will link to web resources (e.g. CDN libraries) instead of embedding them.

  • verbosity (int, optional) – How much detail to send to stdout.

write_pdf(self, path, latex_cmd='pdflatex', latex_flags=None, build_options=None, brevity=0, precision=None, auto_open=False, comm=None, verbosity=0)

Write this report to the disk as a PDF document.

Parameters
  • path (str or path-like object) – The filesystem path to write the report to. By convention, this should use the .pdf file extension.

  • latex_cmd (str, optional) – Shell command to run to compile a PDF document from the generated LaTeX source.

  • latex_flags ([str], optional) – List of flags to pass when calling latex_cmd.

  • build_options (dict) – Dict of options for building plots. Expected values are defined during construction of this report object.

  • brevity (int, optional) –

    Amount of detail to include in the report. Larger values mean smaller “more briefr” reports, which reduce generation time, load time, and disk space consumption. In particular:

    • 1: Plots showing per-sequences quantities disappear at brevity=1

    • 2: Reference sections disappear at brevity=2

    • 3: Germ-level estimate tables disappear at brevity=3

    • 4: Everything but summary figures disappears at brevity=4

  • 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.

  • auto_open (bool, optional) – Whether the output file should be automatically opened in a web browser.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.

  • verbosity (int, optional) – Amount of detail to print to stdout.

class pygsti.report._ReportableQty(value, errbar=None, non_markovian_ebs=False)

Bases: object

A computed quantity and possibly its error bars, primarily for use in reports.

Parameters
  • value (object) – The value, usually a float or numpy array.

  • errbar (object, optional) – The (symmetric) error bar on value. If value is an array, errbar has the same shape. None is used to signify “no error bars”.

  • non_markovian_ebs (bool, optional) – Whether these error bars are “non-markovian”-type error bars (it can be useful to keep track of this for formatting).

size

Returns the size of this ReportableQty’s value.

Type

int

__str__(self)

Return str(self).

__repr__(self)

Return repr(self).

__add__(self, x)
__mul__(self, x)
__truediv__(self, x)
__getstate__(self)
__setstate__(self, d)
__copy__(self)
__deepcopy__(self, memo)
log(self)

Returns a ReportableQty that is the logarithm of this one.

Returns

ReportableQty

real(self)

Returns a ReportableQty that is the real part of this one.

Returns

ReportableQty

imag(self)

Returns a ReportableQty that is the imaginary part of this one.

Returns

ReportableQty

absdiff(self, constant_value, separate_re_im=False)

Create a ReportableQty that is the difference between constant_value and this one.

The returned quantity’s value is given by (element-wise in the vector case):

abs(self - constant_value).

Parameters
  • constant_value (float or numpy.ndarray) – The constant value to use.

  • separate_re_im (bool, optional) – When True, two separate real- and imaginary-part ReportableQty objects are returned (applicable to complex-valued quantities).

Returns

ReportableQty or tuple – The output ReportableQty`(s). If `separate_re_im=True then a 2-tuple of (real-part, imaginary-part) quantities is returned. Otherwise a single quantity is returned.

infidelity_diff(self, constant_value)

Creates a ReportableQty that is the difference between constant_value and this one.

The returned quantity’s value is given by (element-wise in the vector case):

1.0 - Re(conjugate(constant_value) * self )

Parameters

constant_value (float or numpy.ndarray) – The constant value to use.

Returns

ReportableQty

mod(self, x)

Creates a ReportableQty that holds this_qty mod x.

That is, the value and error bar (if present) are modulus-divided by x.

Parameters

x (int) – Value to modulus-divide by.

Returns

ReportableQty

hermitian_to_real(self)

Creates a ReportableQty that holds a real “version” of a Hermitian matrix.

Specifically, the returned quantity’s value is the real matrix whose upper/lower triangle contains the real/imaginary parts of the corresponding off-diagonal matrix elements of the Hermitian matrix stored in this ReportableQty.

This is used for display purposes. If this object doesn’t contain a Hermitian matrix, ValueError is raised.

Returns

ReportableQty

reshape(self, *args)

Returns a ReportableQty whose underlying values are reshaped.

Returns

ReportableQty

property size(self)

Returns the size of this ReportableQty’s value.

Returns

int

static from_val(value, non_markovian_ebs=False)

Convert Table values into ReportableQtys or leave them be if they are well-formed types.

Well-formed types include: - strings - figures - :class:`ReportableQty`s

A tuple will be converted to a ReportableQty holding the first field as a value and second field as an error bar. Anything else will be converted to a ReportableQty with no error bars.

Parameters
  • value (object) – The value to convert.

  • non_markovian_ebs (bool, optional) – Whether the error bars are of the “non-markovian”-type.

Returns

ReportableQty

property has_errorbar(self)

Return whether this quantity is storing an error bar (bool).

Returns

bool

scale_inplace(self, factor)

Scale the value and error bar (if present) by factor.

Parameters

factor (float) – The scaling factor.

Returns

None

property value(self)

Returns the quantity’s value

Returns

object – Usually a float or numpy array.

property errorbar(self)

Returns the quantity’s error bar(s)

Returns

object – Usually a float or numpy array.

property value_and_errorbar(self)

Returns the quantity’s value and error bar(s)

Returns

  • value (object) – This object’s value (usually a float or numpy array).

  • error_bar (object) – This object’s value (usually a float or numpy array).

render_with(self, f, specs=None, ebstring='%s +/- %s', nmebstring=None)

Render this ReportableQty using the function f.

Parameters
  • f (function) – The formatter function which separately converts the stored value and error bar (if present) to string quantities that are then formatted using ebstring, nmebstring or just “%s” (if there’s no error bar). This function must have the signature f(val, specs) where val is either the value or error bar and specs is a dictionary given by the next argument.

  • specs (dict, optional) – Additional parameters to pass to the formatter function f.

  • ebstring (str, optional) – format string that describes how to display the value and error bar after they are rendered as string (ebstring should have two `%s`s in it).

  • nmebstring (str, optional) – format string, similar to ebstring, for displaying non-Markovian error bars (if None then ebstring is used).

Returns

str

class pygsti.report._Basis(name, longname, real, sparse)

Bases: pygsti.baseobjs.nicelyserializable.NicelySerializable

An ordered set of labeled matrices/vectors.

The base class for basis objects. A basis in pyGSTi is an abstract notion of a set of labeled elements, or “vectors”. Each basis has a certain size, and has .elements, .labels, and .ellookup members, the latter being a dictionary mapping of labels to elements.

An important point to note that isn’t immediately intuitive is that while Basis object holds elements (in its .elements property) these are not the same as its vectors (given by the object’s vector_elements property). Often times, in what we term a “simple” basis, the you just flatten an element to get the corresponding vector-element. This works for bases where the elements are either vectors (where flattening does nothing) and matrices. By storing elements as distinct from vector_elements, the Basis can capture additional structure of the elements (such as viewing them as matrices) that can be helpful for their display and interpretation. The elements are also sometimes referred to as the “natural elements” because they represent how to display the element in a natrual way. A non-simple basis occurs when vector_elements need to be stored as elements in a larger “embedded” way so that these elements can be displayed and interpeted naturally.

A second important note is that there is assumed to be some underlying “standard” basis underneath all the bases in pyGSTi. The elements in a Basis are always written in this standard basis. In the case of the “std”-named basis in pyGSTi, these elements are just the trivial vector or matrix units, so one can rightly view the “std” pyGSTi basis as the “standard” basis for a that particular dimension.

The arguments below describe the basic properties of all basis objects in pyGSTi. It is important to remember that the vector_elements of a basis are different from its elements (see the Basis docstring), and that dim refers to the vector elements whereas elshape refers to the elements.

For example, consider a 2-element Basis containing the I and X Pauli matrices. The size of this basis is 2, as there are two elements (and two vector elements). Since vector elements are the length-4 flattened Pauli matrices, the dimension (dim) is 4. Since the elements are 2x2 Pauli matrices, the elshape is (2,2).

As another example consider a basis which spans all the diagonal 2x2 matrices. The elements of this basis are the two matrix units with a 1 in the (0,0) or (1,1) location. The vector elements, however, are the length-2 [1,0] and [0,1] vectors obtained by extracting just the diagonal entries from each basis element. Thus, for this basis, size=2, dim=2, and elshape=(2,2) - so the dimension is not just the product of elshape entries (equivalently, elsize).

Parameters
  • name (string) – The name of the basis. This can be anything, but is usually short and abbreviated. There are several types of bases built into pyGSTi that can be constructed by this name.

  • longname (string) – A more descriptive name for the basis.

  • real (bool) – Elements and vector elements are always allowed to have complex entries. This argument indicates whether the coefficients in the expression of an arbitrary vector in this basis must be real. For example, if real=True, then when pyGSTi transforms a vector in some other basis to a vector in this basis, it will demand that the values of that vector (i.e. the coefficients which multiply this basis’s elements to obtain a vector in the “standard” basis) are real.

  • sparse (bool) – Whether the elements of .elements for this Basis are stored (when they are stored at all) as sparse matrices or vectors.

dim

The dimension of the vector space this basis fully or partially spans. Equivalently, the length of the vector_elements of the basis.

Type

int

size

The number of elements (or vector-elements) in the basis.

Type

int

elshape

The shape of each element. Typically either a length-1 or length-2 tuple, corresponding to vector or matrix elements, respectively. Note that vector elements always have shape (dim,) (or (dim,1) in the sparse case).

Type

int

elndim

The number of element dimensions, i.e. len(self.elshape)

Type

int

elsize

The total element size, i.e. product(self.elshape)

Type

int

vector_elements

The “vectors” of this basis, always 1D (sparse or dense) arrays.

Type

list

classmethod cast(cls, name_or_basis_or_matrices, dim=None, sparse=None, classical_name='cl')

Convert various things that can describe a basis into a Basis object.

Parameters
  • name_or_basis_or_matrices (various) –

    Can take on a variety of values to produce different types of bases:

    • None: an empty ExpicitBasis

    • Basis: checked with dim and sparse and passed through.

    • str: BuiltinBasis or DirectSumBasis with the given name.

    • list: an ExplicitBasis if given matrices/vectors or a

      DirectSumBasis if given a (name, dim) pairs.

  • dim (int or StateSpace, optional) – The dimension of the basis to create. Sometimes this can be inferred based on name_or_basis_or_matrices, other times it must be supplied. This is the dimension of the space that this basis fully or partially spans. This is equal to the number of basis elements in a “full” (ordinary) basis. When a StateSpace object is given, a more detailed direct-sum-of-tensor-product-blocks structure for the state space (rather than a single dimension) is described, and a basis is produced for this space. For instance, a DirectSumBasis basis of TensorProdBasis components can result when there are multiple tensor-product blocks and these blocks consist of multiple factors.

  • sparse (bool, optional) – Whether the resulting basis should be “sparse”, meaning that its elements will be sparse rather than dense matrices.

  • classical_name (str, optional) – An alternate builtin basis name that should be used when constructing the bases for the classical sectors of dim, when dim is a StateSpace object.

Returns

Basis

property dim(self)

The dimension of the vector space this basis fully or partially spans. Equivalently, the length of the vector_elements of the basis.

property size(self)

The number of elements (or vector-elements) in the basis.

property elshape(self)

The shape of each element. Typically either a length-1 or length-2 tuple, corresponding to vector or matrix elements, respectively. Note that vector elements always have shape (dim,) (or (dim,1) in the sparse case).

property elndim(self)

The number of element dimensions, i.e. len(self.elshape)

Returns

int

property elsize(self)

The total element size, i.e. product(self.elshape)

Returns

int

is_simple(self)

Whether the flattened-element vector space is the same space as the space this basis’s vectors belong to.

Returns

bool

is_complete(self)

Whether this is a complete basis, i.e. this basis’s vectors span the entire space that they live in.

Returns

bool

is_partial(self)

The negative of :method:`is_complete`, effectively “is_incomplete”.

Returns

bool

property vector_elements(self)

The “vectors” of this basis, always 1D (sparse or dense) arrays.

Returns

list – A list of 1D arrays.

copy(self)

Make a copy of this Basis object.

Returns

Basis

with_sparsity(self, desired_sparsity)

Returns either this basis or a copy of it with the desired sparsity.

If this basis has the desired sparsity it is simply returned. If not, this basis is copied to one that does.

Parameters

desired_sparsity (bool) – The sparsity (True for sparse elements, False for dense elements) that is desired.

Returns

Basis

abstract _copy_with_toggled_sparsity(self)
__str__(self)

Return str(self).

__getitem__(self, index)
__len__(self)
__eq__(self, other)

Return self==value.

create_transform_matrix(self, to_basis)

Get the matrix that transforms a vector from this basis to to_basis.

Parameters

to_basis (Basis or string) – The basis to transform to or a built-in basis name. In the latter case, a basis to transform to is built with the same structure as this basis but with all components constructed from the given name.

Returns

numpy.ndarray (even if basis is sparse)

reverse_transform_matrix(self, from_basis)

Get the matrix that transforms a vector from from_basis to this basis.

The reverse of :method:`create_transform_matrix`.

Parameters

from_basis (Basis or string) – The basis to transform from or a built-in basis name. In the latter case, a basis to transform from is built with the same structure as this basis but with all components constructed from the given name.

Returns

numpy.ndarray (even if basis is sparse)

is_normalized(self)

Check if a basis is normalized, meaning that Tr(Bi Bi) = 1.0.

Available only to bases whose elements are matrices for now.

Returns

bool

property to_std_transform_matrix(self)

Retrieve the matrix that transforms a vector from this basis to the standard basis of this basis’s dimension.

Returns

numpy array or scipy.sparse.lil_matrix – An array of shape (dim, size) where dim is the dimension of this basis (the length of its vectors) and size is the size of this basis (its number of vectors).

property from_std_transform_matrix(self)

Retrieve the matrix that transforms vectors from the standard basis to this basis.

Returns

numpy array or scipy sparse matrix – An array of shape (size, dim) where dim is the dimension of this basis (the length of its vectors) and size is the size of this basis (its number of vectors).

property to_elementstd_transform_matrix(self)

Get transformation matrix from this basis to the “element space”.

Get the matrix that transforms vectors in this basis (with length equal to the dim of this basis) to vectors in the “element space” - that is, vectors in the same standard basis that the elements of this basis are expressed in.

Returns

numpy array – An array of shape (element_dim, size) where element_dim is the dimension, i.e. size, of the elements of this basis (e.g. 16 if the elements are 4x4 matrices) and size is the size of this basis (its number of vectors).

property from_elementstd_transform_matrix(self)

Get transformation matrix from “element space” to this basis.

Get the matrix that transforms vectors in the “element space” - that is, vectors in the same standard basis that the elements of this basis are expressed in - to vectors in this basis (with length equal to the dim of this basis).

Returns

numpy array – An array of shape (size, element_dim) where element_dim is the dimension, i.e. size, of the elements of this basis (e.g. 16 if the elements are 4x4 matrices) and size is the size of this basis (its number of vectors).

create_equivalent(self, builtin_basis_name)

Create an equivalent basis with components of type builtin_basis_name.

Create a Basis that is equivalent in structure & dimension to this basis but whose simple components (perhaps just this basis itself) is of the builtin basis type given by builtin_basis_name.

Parameters

builtin_basis_name (str) – The name of a builtin basis, e.g. “pp”, “gm”, or “std”. Used to construct the simple components of the returned basis.

Returns

Basis

create_simple_equivalent(self, builtin_basis_name=None)

Create a basis of type builtin_basis_name whose elements are compatible with this basis.

Create a simple basis and one without components (e.g. a TensorProdBasis, is a simple basis w/components) of the builtin type specified whose dimension is compatible with the elements of this basis. This function might also be named “element_equivalent”, as it returns the builtin_basis_name-analogue of the standard basis that this basis’s elements are expressed in.

Parameters

builtin_basis_name (str, optional) – The name of the built-in basis to use. If None, then a copy of this basis is returned (if it’s simple) or this basis’s name is used to try to construct a simple and component-free version of the same builtin-basis type.

Returns

Basis

is_compatible_with_state_space(self, state_space)

Checks whether this basis is compatible with a given state space.

Parameters

state_space (StateSpace) – the state space to check.

Returns

bool

class pygsti.report._DirectSumBasis(component_bases, name=None, longname=None)

Bases: LazyBasis

A basis that is the direct sum of one or more “component” bases.

Elements of this basis are the union of the basis elements on each component, each embedded into a common block-diagonal structure where each component occupies its own block. Thus, when there is more than one component, a DirectSumBasis is not a simple basis because the size of its elements is larger than the size of its vector space (which corresponds to just the diagonal blocks of its elements).

Parameters
  • component_bases (iterable) – A list of the component bases. Each list elements may be either a Basis object or a tuple of arguments to :function:`Basis.cast`, e.g. (‘pp’,4).

  • name (str, optional) – The name of this basis. If None, the names of the component bases joined with “+” is used.

  • longname (str, optional) – A longer description of this basis. If None, then a long name is automatically generated.

vector_elements

The “vectors” of this basis, always 1D (sparse or dense) arrays.

Type

list

_to_nice_serialization(self)
classmethod _from_nice_serialization(cls, state)
property dim(self)

The dimension of the vector space this basis fully or partially spans. Equivalently, the length of the vector_elements of the basis.

property size(self)

The number of elements (or vector-elements) in the basis.

property elshape(self)

The shape of each element. Typically either a length-1 or length-2 tuple, corresponding to vector or matrix elements, respectively. Note that vector elements always have shape (dim,) (or (dim,1) in the sparse case).

__hash__(self)

Return hash(self).

_lazy_build_vector_elements(self)
_lazy_build_elements(self)
_lazy_build_labels(self)
_copy_with_toggled_sparsity(self)
__eq__(self, other)

Return self==value.

property vector_elements(self)

The “vectors” of this basis, always 1D (sparse or dense) arrays.

Returns

list

property to_std_transform_matrix(self)

Retrieve the matrix that transforms a vector from this basis to the standard basis of this basis’s dimension.

Returns

numpy array or scipy.sparse.lil_matrix – An array of shape (dim, size) where dim is the dimension of this basis (the length of its vectors) and size is the size of this basis (its number of vectors).

property to_elementstd_transform_matrix(self)

Get transformation matrix from this basis to the “element space”.

Get the matrix that transforms vectors in this basis (with length equal to the dim of this basis) to vectors in the “element space” - that is, vectors in the same standard basis that the elements of this basis are expressed in.

Returns

numpy array – An array of shape (element_dim, size) where element_dim is the dimension, i.e. size, of the elements of this basis (e.g. 16 if the elements are 4x4 matrices) and size is the size of this basis (its number of vectors).

create_equivalent(self, builtin_basis_name)

Create an equivalent basis with components of type builtin_basis_name.

Create a Basis that is equivalent in structure & dimension to this basis but whose simple components (perhaps just this basis itself) is of the builtin basis type given by builtin_basis_name.

Parameters

builtin_basis_name (str) – The name of a builtin basis, e.g. “pp”, “gm”, or “std”. Used to construct the simple components of the returned basis.

Returns

DirectSumBasis

create_simple_equivalent(self, builtin_basis_name=None)

Create a basis of type builtin_basis_name whose elements are compatible with this basis.

Create a simple basis and one without components (e.g. a TensorProdBasis, is a simple basis w/components) of the builtin type specified whose dimension is compatible with the elements of this basis. This function might also be named “element_equivalent”, as it returns the builtin_basis_name-analogue of the standard basis that this basis’s elements are expressed in.

Parameters

builtin_basis_name (str, optional) – The name of the built-in basis to use. If None, then a copy of this basis is returned (if it’s simple) or this basis’s name is used to try to construct a simple and component-free version of the same builtin-basis type.

Returns

Basis

class pygsti.report._Lbl

Bases: object

A label used to identify a gate, circuit layer, or (sub-)circuit.

A label consisting of a string along with a tuple of integers or sector-names specifying which qubits, or more generally, parts of the Hilbert space that is acted upon by an object so-labeled.

property depth(self)

The depth of this label, viewed as a sub-circuit.

property reps(self)

Number of repetitions (of this label’s components) that this label represents.

property has_nontrivial_components(self)
collect_args(self)
strip_args(self)
expand_subcircuits(self)

Expand any sub-circuits within this label.

Returns a list of component labels which doesn’t include any CircuitLabel labels. This effectively expands any “boxes” or “exponentiation” within this label.

Returns

tuple – A tuple of component Labels (none of which should be :class:`CircuitLabel`s).

pygsti.report._CVXPY_AVAILABLE
pygsti.report.FINITE_DIFF_EPS = 1e-07
pygsti.report._null_fn(*arg)
pygsti.report._project_to_valid_prob(p, tol=1e-09)
pygsti.report._make_reportable_qty_or_dict(f0, df=None, non_markovian_ebs=False)

Just adds special processing with f0 is a dict, where we return a dict or ReportableQtys rather than a single ReportableQty of the dict.

pygsti.report.evaluate(model_fn, cri=None, verbosity=0)

Evaluate a ModelFunction object using confidence region information

Parameters
  • model_fn (ModelFunction) – The function to evaluate

  • cri (ConfidenceRegionFactoryView, optional) – View for computing confidence intervals.

  • verbosity (int, optional) – Amount of detail to print to stdout.

Returns

ReportableQty or dict – If model_fn does returns a dict of ReportableQty objects, otherwise a single ReportableQty.

pygsti.report.spam_dotprods(rho_vecs, povms)

SPAM dot products (concatenates POVMS)

Parameters
  • rho_vecs (list) – A list of State objects.

  • povms (list) – A list of POVM objects.

Returns

numpy.ndarray – A 2D array of shape (len(rho_vecs), num_evecs) where num_evecs is the total number of effect vectors in all of povms.

pygsti.report.Spam_dotprods
pygsti.report.choi_matrix(gate, mx_basis)

Choi matrix

Parameters
  • gate (numpy.ndarray) – the transfer-matrix specifying a gate’s action.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that gate is in.

Returns

numpy.ndarray

pygsti.report.Choi_matrix
pygsti.report.choi_eigenvalues(gate, mx_basis)

Choi matrix eigenvalues

Parameters
  • gate (numpy.ndarray) – the transfer-matrix specifying a gate’s action.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that gate is in.

Returns

numpy.ndarray

pygsti.report.Choi_evals
pygsti.report.choi_trace(gate, mx_basis)

Trace of the Choi matrix

Parameters
  • gate (numpy.ndarray) – the transfer-matrix specifying a gate’s action.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that gate is in.

Returns

float

pygsti.report.Choi_trace
class pygsti.report.GateEigenvalues(model, oplabel)

Bases: pygsti.report.modelfunction.ModelFunction

Gate eigenvalues

Parameters
  • model (Model) – Model gate is contained within.

  • oplabel (Label) – The gate’s label within model.

evaluate(self, model)

Evaluate at model

Parameters

model (Model) – A model nearby in parameter space.

Returns

numpy.ndarray

evaluate_nearby(self, nearby_model)

Evaluate at a nearby model

Parameters

nearby_model (Model) – A model nearby in parameter space.

Returns

numpy.ndarray

class pygsti.report.CircuitEigenvalues(model, circuit)

Bases: pygsti.report.modelfunction.ModelFunction

Circuit eigenvalues

Parameters
  • model (Model) – Model used to evaluate circuit.

  • circuit (Circuit) – The circuit whose process matrix we want the eigenvalues of.

evaluate(self, model)

Evaluate at model

Parameters

model (Model) – Model to evaluate at.

Returns

numpy.ndarray

evaluate_nearby(self, nearby_model)

Evaluate at nearby model

Parameters

nearby_model (Model) – A model nearby in parameter space.

Returns

numpy.ndarray

pygsti.report.rel_circuit_eigenvalues(model_a, model_b, circuit)

Eigenvalues of dot(productB(circuit)^-1, productA(circuit))

Parameters
  • model_a (Model) – The first model (to evaluate productA)

  • model_b (Model) – The second model (to evaluate productB)

  • circuit (Circuit) – The circuit.

Returns

numpy.ndarray

pygsti.report.Rel_circuit_eigenvalues
pygsti.report.circuit_frobenius_diff(model_a, model_b, circuit)

Frobenius distance btwn productA(circuit) and productB(circuit)

Parameters
  • model_a (Model) – The first model (to evaluate productA)

  • model_b (Model) – The second model (to evaluate productB)

  • circuit (Circuit) – The circuit.

Returns

float

pygsti.report.Circuit_fro_diff
pygsti.report.circuit_entanglement_infidelity(model_a, model_b, circuit)

Entanglement infidelity btwn productA(circuit) and productB(circuit)

Parameters
  • model_a (Model) – The first model (to evaluate productA)

  • model_b (Model) – The second model (to evaluate productB)

  • circuit (Circuit) – The circuit.

Returns

float

pygsti.report.Circuit_entanglement_infidelity
pygsti.report.circuit_avg_gate_infidelity(model_a, model_b, circuit)

Average gate infidelity between productA(circuit) and productB(circuit).

Parameters
  • model_a (Model) – The first model (to evaluate productA)

  • model_b (Model) – The second model (to evaluate productB)

  • circuit (Circuit) – The circuit.

Returns

float

pygsti.report.Circuit_avg_gate_infidelity
pygsti.report.circuit_jtrace_diff(model_a, model_b, circuit)

Jamiolkowski trace distance between productA(circuit) and productB(circuit)

Parameters
  • model_a (Model) – The first model (to evaluate productA)

  • model_b (Model) – The second model (to evaluate productB)

  • circuit (Circuit) – The circuit.

Returns

float

pygsti.report.Circuit_jt_diff
class pygsti.report.CircuitHalfDiamondNorm(model_a, model_b, circuit)

Bases: pygsti.report.modelfunction.ModelFunction

1/2 diamond norm of difference between productA(circuit) and productB(circuit)

Parameters
  • model_a (Model) – The first model (to evaluate productA)

  • model_b (Model) – The second model (to evaluate productB)

  • circuit (Circuit) – The circuit.

evaluate(self, model)

Evaluate this function at model

Parameters

model (Model) – Model to evaluate at.

Returns

float

evaluate_nearby(self, nearby_model)

Evaluate at a nearby model

Parameters

nearby_model (Model) – A model nearby in parameter space.

Returns

float

pygsti.report.circuit_nonunitary_entanglement_infidelity(model_a, model_b, circuit)

Nonunitary entanglement infidelity between productA(circuit) and productB(circuit)

Parameters
  • model_a (Model) – The first model (to evaluate productA)

  • model_b (Model) – The second model (to evaluate productB)

  • circuit (Circuit) – The circuit.

Returns

float

pygsti.report.Circuit_nonunitary_entanglement_infidelity
pygsti.report.circuit_nonunitary_avg_gate_infidelity(model_a, model_b, circuit)

Nonunitary average gate infidelity between productA(circuit) and productB(circuit).

Parameters
  • model_a (Model) – The first model (to evaluate productA)

  • model_b (Model) – The second model (to evaluate productB)

  • circuit (Circuit) – The circuit.

Returns

float

pygsti.report.Circuit_nonunitary_avg_gate_infidelity
pygsti.report.circuit_eigenvalue_entanglement_infidelity(model_a, model_b, circuit)

Eigenvalue entanglement infidelity between productA(circuit) and productB(circuit).

Parameters
  • model_a (Model) – The first model (to evaluate productA)

  • model_b (Model) – The second model (to evaluate productB)

  • circuit (Circuit) – The circuit.

Returns

float

pygsti.report.Circuit_eigenvalue_entanglement_infidelity
pygsti.report.circuit_eigenvalue_avg_gate_infidelity(model_a, model_b, circuit)

Eigenvalue average gate infidelity between productA(circuit) and productB(circuit).

Parameters
  • model_a (Model) – The first model (to evaluate productA)

  • model_b (Model) – The second model (to evaluate productB)

  • circuit (Circuit) – The circuit.

Returns

float

pygsti.report.Circuit_eigenvalue_avg_gate_infidelity
pygsti.report.circuit_eigenvalue_nonunitary_entanglement_infidelity(model_a, model_b, circuit)

Eigenvalue nonunitary entanglement infidelity between productA(circuit) and productB(circuit).

Parameters
  • model_a (Model) – The first model (to evaluate productA)

  • model_b (Model) – The second model (to evaluate productB)

  • circuit (Circuit) – The circuit.

Returns

float

pygsti.report.Circuit_eigenvalue_nonunitary_entanglement_infidelity
pygsti.report.circuit_eigenvalue_nonunitary_avg_gate_infidelity(model_a, model_b, circuit)

Eigenvalue nonunitary average gate infidelity between productA(circuit) and productB(circuit).

Parameters
  • model_a (Model) – The first model (to evaluate productA)

  • model_b (Model) – The second model (to evaluate productB)

  • circuit (Circuit) – The circuit.

Returns

float

pygsti.report.Circuit_eigenvalue_nonunitary_avg_gate_infidelity
pygsti.report.circuit_eigenvalue_diamondnorm(model_a, model_b, circuit)

Eigenvalue diamond distance between productA(circuit) and productB(circuit).

Parameters
  • model_a (Model) – The first model (to evaluate productA)

  • model_b (Model) – The second model (to evaluate productB)

  • circuit (Circuit) – The circuit.

Returns

float

pygsti.report.Circuit_eigenvalue_diamondnorm
pygsti.report.circuit_eigenvalue_nonunitary_diamondnorm(model_a, model_b, circuit)

Eigenvalue nonunitary diamond distance between productA(circuit) and productB(circuit).

Parameters
  • model_a (Model) – The first model (to evaluate productA)

  • model_b (Model) – The second model (to evaluate productB)

  • circuit (Circuit) – The circuit.

Returns

float

pygsti.report.Circuit_eigenvalue_nonunitary_diamondnorm
pygsti.report.povm_entanglement_infidelity(model_a, model_b, povmlbl)

POVM entanglement infidelity between model_a and model_b.

Equal to 1 - entanglement_fidelity(POVM_MAP) where POVM_MAP is the extension of the POVM from the classical space of k-outcomes to the space of (diagonal) k by k density matrices.

Parameters
  • model_a (Model) – The first model.

  • model_b (Model) – The second model.

  • povmlbl (Label) – The POVM label (must be present in both models).

Returns

float

pygsti.report.POVM_entanglement_infidelity
pygsti.report.povm_jtrace_diff(model_a, model_b, povmlbl)

POVM Jamiolkowski trace distance between model_a and model_b

Equal to Jamiolkowski_trace_distance(POVM_MAP) where POVM_MAP is the extension of the POVM from the classical space of k-outcomes to the space of (diagonal) k by k density matrices.

Parameters
  • model_a (Model) – The first model.

  • model_b (Model) – The second model.

  • povmlbl (Label) – The POVM label (must be present in both models).

Returns

float

pygsti.report.POVM_jt_diff
pygsti.report.povm_half_diamond_norm(model_a, model_b, povmlbl)

Half the POVM diamond distance between model_a and model_b.

Equal to half_diamond_dist(POVM_MAP) where POVM_MAP is the extension of the POVM from the classical space of k-outcomes to the space of (diagonal) k by k density matrices.

Parameters
  • model_a (Model) – The first model.

  • model_b (Model) – The second model.

  • povmlbl (Label) – The POVM label (must be present in both models).

Returns

float

pygsti.report.decomposition(gate)

DEPRECATED: Decompose a 1Q gate into rotations about axes.

Parameters

gate (numpy.ndarray) – the transfer-matrix specifying a gate’s action.

Returns

ReportableQty

pygsti.report.upper_bound_fidelity(gate, mx_basis)

Upper bound on entanglement fidelity

Parameters
  • gate (numpy.ndarray) – the transfer-matrix specifying a gate’s action.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that gate is in.

Returns

float

pygsti.report.Upper_bound_fidelity
pygsti.report.closest_ujmx(gate, mx_basis)

Jamiolkowski state of closest unitary to gate

Parameters
  • gate (numpy.ndarray) – the transfer-matrix specifying a gate’s action.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that gate is in.

Returns

float

pygsti.report.Closest_ujmx
pygsti.report.maximum_fidelity(gate, mx_basis)

Fidelity between gate and its closest unitary

Parameters
  • gate (numpy.ndarray) – the transfer-matrix specifying a gate’s action.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that gate is in.

Returns

float

pygsti.report.Maximum_fidelity
pygsti.report.maximum_trace_dist(gate, mx_basis)

Jamiolkowski trace distance between gate and its closest unitary

Parameters
  • gate (numpy.ndarray) – the transfer-matrix specifying a gate’s action.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that gate is in.

Returns

float

pygsti.report.Maximum_trace_dist
pygsti.report.angles_btwn_rotn_axes(model)

Array of angles between the rotation axes of the gates of model.

Parameters

model (Model) – The model to process.

Returns

numpy.ndarray – Of size (nOperations,nGate) where nOperations=len(model.operations)

pygsti.report.Angles_btwn_rotn_axes
pygsti.report.entanglement_fidelity(a, b, mx_basis)

Entanglement fidelity between a and b

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

float

pygsti.report.Entanglement_fidelity
pygsti.report.entanglement_infidelity(a, b, mx_basis)

Entanglement infidelity between a and b

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

float

pygsti.report.Entanglement_infidelity
pygsti.report.closest_unitary_fidelity(a, b, mx_basis)

Entanglement infidelity between closest unitaries to a and b

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

float

pygsti.report.Closest_unitary_fidelity
pygsti.report.frobenius_diff(a, b, mx_basis)

Frobenius distance between a and b

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

float

pygsti.report.Fro_diff
pygsti.report.jtrace_diff(a, b, mx_basis)

Jamiolkowski trace distance between a and b

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

float

pygsti.report.Jt_diff
class pygsti.report.HalfDiamondNorm(model_a, model_b, oplabel)

Bases: pygsti.report.modelfunction.ModelFunction

Half the diamond distance bewteen model_a.operations[op_label] and model_b.operations[op_label]

Parameters
  • model_a (Model) – The first model.

  • model_b (Model) – The second model.

  • oplabel (Label) – The operation (gate) label to compare.

evaluate(self, model)

Evaluate at model_a = model

Parameters

model (Model) – Model to evaluate at.

Returns

float

evaluate_nearby(self, nearby_model)

Evaluates at a nearby model

Parameters

nearby_model (Model) – A model nearby in parameter space.

Returns

float

pygsti.report.std_unitarity(a, b, mx_basis)

a gauge-invariant quantity that behaves like the unitarity

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

float

pygsti.report.eigenvalue_unitarity(a, b)

a gauge-invariant quantity that behaves like the unitarity

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

Returns

float

pygsti.report.nonunitary_entanglement_infidelity(a, b, mx_basis)

Returns (d^2 - 1)/d^2 * (1 - sqrt(U)), where U is the unitarity of a*b^{-1}

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

float

pygsti.report.Nonunitary_entanglement_infidelity
pygsti.report.nonunitary_avg_gate_infidelity(a, b, mx_basis)

Returns (d - 1)/d * (1 - sqrt(U)), where U is the unitarity of a*b^{-1}

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

float

pygsti.report.Nonunitary_avg_gate_infidelity
pygsti.report.eigenvalue_nonunitary_entanglement_infidelity(a, b, mx_basis)

Returns (d^2 - 1)/d^2 * (1 - sqrt(U)), where U is the eigenvalue-unitarity of a*b^{-1}

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

float

pygsti.report.Eigenvalue_nonunitary_entanglement_infidelity
pygsti.report.eigenvalue_nonunitary_avg_gate_infidelity(a, b, mx_basis)

Returns (d - 1)/d * (1 - sqrt(U)), where U is the eigenvalue-unitarity of a*b^{-1}

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

float

pygsti.report.Eigenvalue_nonunitary_avg_gate_infidelity
pygsti.report.eigenvalue_entanglement_infidelity(a, b, mx_basis)

Eigenvalue entanglement infidelity between a and b

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

float

pygsti.report.Eigenvalue_entanglement_infidelity
pygsti.report.eigenvalue_avg_gate_infidelity(a, b, mx_basis)

Eigenvalue average gate infidelity between a and b

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

float

pygsti.report.Eigenvalue_avg_gate_infidelity
pygsti.report.eigenvalue_diamondnorm(a, b, mx_basis)

Eigenvalue diamond distance between a and b

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

float

pygsti.report.Eigenvalue_diamondnorm
pygsti.report.eigenvalue_nonunitary_diamondnorm(a, b, mx_basis)

Eigenvalue nonunitary diamond distance between a and b

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

float

pygsti.report.Eigenvalue_nonunitary_diamondnorm
pygsti.report.avg_gate_infidelity(a, b, mx_basis)

Returns the average gate infidelity between a and b, where b is the “target” operation.

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

float

pygsti.report.Avg_gate_infidelity
pygsti.report.model_model_angles_btwn_axes(a, b, mx_basis)

Angle between the rotation axes of a and b (1-qubit gates)

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

float

pygsti.report.Model_model_angles_btwn_axes
pygsti.report.rel_eigenvalues(a, b, mx_basis)

Eigenvalues of b^{-1} * a

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

numpy.ndarray

pygsti.report.Rel_eigvals
pygsti.report.rel_log_tig_eigenvalues(a, b, mx_basis)

Eigenvalues of log(b^{-1} * a)

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

numpy.ndarray

pygsti.report.Rel_logTiG_eigvals
pygsti.report.rel_log_gti_eigenvalues(a, b, mx_basis)

Eigenvalues of log(a * b^{-1})

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

numpy.ndarray

pygsti.report.Rel_logGTi_eigvals
pygsti.report.rel_log_diff_eigenvalues(a, b, mx_basis)

Eigenvalues of log(a) - log(b)

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

numpy.ndarray

pygsti.report.Rel_logGmlogT_eigvals
pygsti.report.rel_gate_eigenvalues(a, b, mx_basis)

Eigenvalues of b^{-1} * a

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

numpy.ndarray

pygsti.report.Rel_gate_eigenvalues
pygsti.report.errorgen_and_projections(errgen, mx_basis)

Project errgen on all of the standard sets of error generators.

Parameters
  • errgen (numpy.ndarray) – The error generator.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that errgen is in.

Returns

dict – Dictionary of ‘error generator’, ‘X projections’, and ‘X projection power’ keys, where X is ‘hamiltonian’, ‘stochastic’, and ‘affine’.

pygsti.report.log_tig_and_projections(a, b, mx_basis)

Projections of log(b^{-1}*a).

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

dict – A dictionary of quantities with keys ‘error generator’, ‘X projections’, and ‘X projection power’, where X is ‘hamiltonian’, ‘stochastic’, and ‘affine’.

pygsti.report.LogTiG_and_projections
pygsti.report.log_gti_and_projections(a, b, mx_basis)

Projections of log(a*b^{-1}).

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

dict – A dictionary of quantities with keys ‘error generator’, ‘X projections’, and ‘X projection power’, where X is ‘hamiltonian’, ‘stochastic’, and ‘affine’.

pygsti.report.LogGTi_and_projections
pygsti.report.log_diff_and_projections(a, b, mx_basis)

Projections of log(a)-log(b).

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

dict – A dictionary of quantities with keys ‘error generator’, ‘X projections’, and ‘X projection power’, where X is ‘hamiltonian’, ‘stochastic’, and ‘affine’.

pygsti.report.LogGmlogT_and_projections
pygsti.report.robust_log_gti_and_projections(model_a, model_b, synthetic_idle_circuits)

Projections of log(A*B^{-1}) using a gauge-robust technique.

Parameters
  • model_a (Model) – The first model (A gates).

  • model_b (Model) – The second model (B gates).

  • synthetic_idle_circuits (list) – Circuits that encode synthetic idles.

Returns

dict – A dictionary of quantities with keys ‘G error generator’, ‘G X projections’, and ‘G X projection power’, where G is a operation label and X is ‘hamiltonian’, ‘stochastic’, and ‘affine’.

pygsti.report.Robust_LogGTi_and_projections
pygsti.report.general_decomposition(model_a, model_b)

Decomposition of gates in model_a using those in model_b as their targets.

This function uses a generalized decomposition algorithm that can gates acting on a Hilbert space of any dimension.

Parameters
  • model_a (Model) – The model.

  • model_b (Model) – The target model.

Returns

dict

pygsti.report.General_decomposition
pygsti.report.average_gateset_infidelity(model_a, model_b)

Average model infidelity

Parameters
  • model_a (Model) – The first model.

  • model_b (Model) – The second model.

Returns

float

pygsti.report.Average_gateset_infidelity
pygsti.report.predicted_rb_number(model_a, model_b)

Prediction of RB number based on estimated (A) and target (B) models

Parameters
  • model_a (Model) – The first model.

  • model_b (Model) – The second model.

Returns

float

pygsti.report.Predicted_rb_number
pygsti.report.vec_fidelity(a, b, mx_basis)

State fidelity between state vectors a and b

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

float

pygsti.report.Vec_fidelity
pygsti.report.vec_infidelity(a, b, mx_basis)

State infidelity fidelity between state vectors a and b

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

float

pygsti.report.Vec_infidelity
pygsti.report.vec_trace_diff(a, b, mx_basis)

Trace distance between state vectors a and b

Parameters
  • a (numpy.ndarray) – The first process (transfer) matrix.

  • b (numpy.ndarray) – The second process (transfer) matrix.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

float

pygsti.report.Vec_tr_diff
pygsti.report.vec_as_stdmx(vec, mx_basis)

State vector as a standard density matrix

Parameters
  • vec (numpy.ndarray) – state vector as a 1D dense array.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that vec is in.

Returns

numpy.ndarray – A 2D array (matrix) that is vec in the standard basis.

pygsti.report.Vec_as_stdmx
pygsti.report.vec_as_stdmx_eigenvalues(vec, mx_basis)

Eigenvalues of the density matrix corresponding to a state vector

Parameters
  • vec (numpy.ndarray) – state vector as a 1D dense array.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that vec is in.

Returns

numpy.ndarray

pygsti.report.Vec_as_stdmx_eigenvalues
pygsti.report.info_of_opfn_by_name(name)

Returns a nice human-readable name and tooltip for a given gate-function abbreviation.

Parameters

name (str) –

An appreviation for a gate-function name. Allowed values are:

  • ”inf” : entanglement infidelity

  • ”agi” : average gate infidelity

  • ”trace” : 1/2 trace distance

  • ”diamond” : 1/2 diamond norm distance

  • ”nuinf” : non-unitary entanglement infidelity

  • ”nuagi” : non-unitary entanglement infidelity

  • ”evinf” : eigenvalue entanglement infidelity

  • ”evagi” : eigenvalue average gate infidelity

  • ”evnuinf” : eigenvalue non-unitary entanglement infidelity

  • ”evnuagi” : eigenvalue non-unitary entanglement infidelity

  • ”evdiamond” : eigenvalue 1/2 diamond norm distance

  • ”evnudiamond” : eigenvalue non-unitary 1/2 diamond norm distance

  • ”frob” : frobenius distance

  • ”unmodeled” : unmodeled “wildcard” budget

Returns

  • nicename (str)

  • tooltip (str)

pygsti.report.evaluate_opfn_by_name(name, model, target_model, op_label_or_string, confidence_region_info)

Evaluates that gate-function named by the abbreviation name.

Parameters
  • name (str) – An appreviation for a operation-function name. Allowed values are the same as those of info_of_opfn_by_name().

  • model (Model) – The model used by the operation-function.

  • target_model (Model) – The target model.

  • op_label_or_string (str or Circuit or tuple) – The operation label or sequence of labels to compare. If a sequence of labels is given, then the “virtual gate” computed by taking the product of the specified gate matrices is compared.

  • confidence_region_info (ConfidenceRegion, optional) – If not None, specifies a confidence-region used to compute error intervals.

Returns

ReportableQty

pygsti.report.instrument_infidelity(a, b, mx_basis)

Infidelity between instruments a and b

Parameters
  • a (Instrument) – The first instrument.

  • b (Instrument) – The second instrument.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

float

pygsti.report.Instrument_infidelity
pygsti.report.instrument_half_diamond_norm(a, b, mx_basis)

The diamond norm distance between instruments a and b.

Parameters
  • a (Instrument) – The first instrument.

  • b (Instrument) – The second instrument.

  • mx_basis (Basis or {'pp', 'gm', 'std'}) – the basis that a and b are in.

Returns

float

pygsti.report.Instrument_half_diamond_norm
pygsti.report.evaluate_instrumentfn_by_name(name, model, target_model, inst_label, confidence_region_info)

Evaluates that instrument-function named by the abbreviation name.

Parameters
  • name (str) – An appreviation for a operation-function name. Allowed values are the same as those of info_of_opfn_by_name().

  • model (Model) – The model used by the operation-function.

  • target_model (Model) – The target model.

  • inst_label (Label) – The instrument label to compare.

  • confidence_region_info (ConfidenceRegion, optional) – If not None, specifies a confidence-region used to compute error intervals.

Returns

ReportableQty

class pygsti.report.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.

pygsti.report._pygsti_version = 0.9.10.post64
class pygsti.report._ExplicitOpModel(state_space, basis='pp', default_gate_type='full', default_prep_type='auto', default_povm_type='auto', default_instrument_type='auto', prep_prefix='rho', effect_prefix='E', gate_prefix='G', povm_prefix='M', instrument_prefix='I', simulator='auto', evotype='default')

Bases: pygsti.models.model.OpModel

Encapsulates a set of gate, state preparation, and POVM effect operations.

An ExplictOpModel stores a set of labeled LinearOperator objects and provides dictionary-like access to their matrices. State preparation and POVM effect operations are represented as column vectors.

Parameters
  • state_space (StateSpace) – The state space for this model.

  • basis ({"pp","gm","qt","std","sv"} or Basis, optional) – The basis used for the state space by dense superoperator representations.

  • default_param ({"full", "TP", "CPTP", etc.}, optional) – Specifies the default gate and SPAM vector parameterization type. Can be any value allowed by :method:`set_all_parameterizations`, which also gives a description of each parameterization type.

  • prep_prefix (string, optional) – Key prefixe for state preparations, allowing the model to determing what type of object a key corresponds to.

  • effect_prefix (string, optional) – Key prefix for POVM effects, allowing the model to determing what type of object a key corresponds to.

  • gate_prefix (string, optional) – Key prefix for gates, allowing the model to determing what type of object a key corresponds to.

  • povm_prefix (string, optional) – Key prefix for POVMs, allowing the model to determing what type of object a key corresponds to.

  • instrument_prefix (string, optional) – Key prefix for instruments, allowing the model to determing what type of object a key corresponds to.

  • simulator (ForwardSimulator or {"auto", "matrix", "map"}) –

    The circuit simulator used to compute any requested probabilities, e.g. from :method:`probs` or :method:`bulk_probs`. The default value of “auto” automatically selects the simulation type, and is usually what you want. Other special allowed values are:

    • ”matrix” : op_matrix-op_matrix products are computed and cached to get composite gates which can then quickly simulate a circuit for any preparation and outcome. High memory demand; best for a small number of (1 or 2) qubits.

    • ”map” : op_matrix-state_vector products are repeatedly computed to simulate circuits. Slower for a small number of qubits, but faster and more memory efficient for higher numbers of qubits (3+).

  • evotype (Evotype or str, optional) – The evolution type of this model, describing how states are represented. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.

_strict = False
property _primitive_prep_label_dict(self)
property _primitive_povm_label_dict(self)
property _primitive_op_label_dict(self)
property _primitive_instrument_label_dict(self)
_iter_parameterized_objs(self)
_excalc(self)

Create & return a special explicit-model calculator for this model

_embed_operation(self, op_target_labels, op_val, force=False)

Called by OrderedMemberDict._auto_embed to create an embedded-gate object that embeds op_val into the sub-space of self.state_space given by op_target_labels.

Parameters
  • op_target_labels (list) – A list of op_val’s target state space labels.

  • op_val (LinearOperator) – The gate object to embed. Note this should be a legitimate LinearOperator-derived object and not just a numpy array.

  • force (bool, optional) – Always wrap with an embedded LinearOperator, even if the dimension of op_val is the full model dimension.

Returns

LinearOperator – A gate of the full model dimension.

property default_gauge_group(self)

Gets the default gauge group for performing gauge transformations on this Model.

Returns

GaugeGroup

property prep(self)

The unique state preparation in this model, if one exists.

If not, a ValueError is raised.

Returns

State

property effects(self)

The effect vectors from the unique POVM in this model, if one exists.

If not, a ValueError is raised.

Returns

list of POVMEffects

__setitem__(self, label, value)

Set an operator, state, or POVM associated with a given label.

Parameters
  • label (string) – the gate or SPAM vector label.

  • value (numpy array or LinearOperator or State or POVM) – a operation matrix, state vector, or POVM, which must have the appropriate state space for the Model and appropriate type given the prefix of the label.

__getitem__(self, label)

Get an operation, state, or POVM associated with a given label.

Parameters

label (string) – the gate, state vector, or POVM label.

set_all_parameterizations(self, gate_type, prep_type='auto', povm_type='auto', instrument_type='auto', extra=None)

Convert all gates, states, and POVMs to a specific parameterization type.

Parameters
  • parameterization_type (string) –

    The gate, state, and POVM parameterization type. Allowed values are (where ‘*’ means ” terms” and ” clifford terms” evolution-type suffixes are allowed):

    • ”full” : each gate / state / POVM effect element is an independent parameter

    • ”TP” : Trace-Preserving gates and state preps

    • ”static” : no parameters

    • ”static unitary” : no parameters; convert superops to unitaries

    • ”clifford” : no parameters; convert unitaries to Clifford symplecitics.

    • ”GLND*” : General unconstrained Lindbladian

    • ”CPTP*” : Completely-Positive-Trace-Preserving

    • ”H+S+A*” : Hamiltoian, Pauli-Stochastic, and Affine errors

    • ”H+S*” : Hamiltonian and Pauli-Stochastic errors

    • ”S+A*” : Pauli-Stochastic and Affine errors

    • ”S*” : Pauli-Stochastic errors

    • ”H+D+A*” : Hamiltoian, Depolarization, and Affine errors

    • ”H+D*” : Hamiltonian and Depolarization errors

    • ”D+A*” : Depolarization and Affine errors

    • ”D*” : Depolarization errors

    • Any of the above with “S” replaced with “s” or “D” replaced with “d”. This removes the CPTP constraint on the gates and SPAM operations (and as such is seldom used).

  • extra (dict, optional) – For “H+S terms” type, this may specify a dictionary of unitary gates and pure state vectors to be used as the ideal operation of each gate/SPAM operation.

Returns

None

__setstate__(self, state_dict)
property num_elements(self)

Return the number of total operation matrix and spam vector elements in this model.

This is in general different from the number of parameters in the model, which are the number of free variables used to generate all of the matrix and vector elements.

Returns

int – the number of model elements.

property num_nongauge_params(self)

Return the number of non-gauge parameters in this model.

Returns

int – the number of non-gauge model parameters.

property num_gauge_params(self)

Return the number of gauge parameters in this model.

Returns

int – the number of gauge model parameters.

deriv_wrt_params(self)

The element-wise derivative of all this models’ operations.

Constructs a matrix whose columns are the vectorized derivatives of all the model’s raw matrix and vector elements (placed in a vector) with respect to each single model parameter.

Thus, each column has length equal to the number of elements in the model, and there are num_params() columns. In the case of a “fully parameterized model” (i.e. all operation matrices and SPAM vectors are fully parameterized) then the resulting matrix will be the (square) identity matrix.

Returns

numpy array – 2D array of derivatives.

compute_nongauge_projector(self, item_weights=None, non_gauge_mix_mx=None)

Construct a projector onto the non-gauge parameter space.

Useful for isolating the gauge degrees of freedom from the non-gauge degrees of freedom.

Parameters
  • item_weights (dict, optional) – Dictionary of weighting factors for individual gates and spam operators. Keys can be gate, state preparation, POVM effect, spam labels, or the special strings “gates” or “spam” whic represent the entire set of gate or SPAM operators, respectively. Values are floating point numbers. These weights define the metric used to compute the non-gauge space, orthogonal the gauge space, that is projected onto.

  • non_gauge_mix_mx (numpy array, optional) – An array of shape (n_non_gauge_params,n_gauge_params) specifying how to mix the non-gauge degrees of freedom into the gauge degrees of freedom that are projected out by the returned object. This argument essentially sets the off-diagonal block of the metric used for orthogonality in the “gauge + non-gauge” space. It is for advanced usage and typically left as None (the default).

Returns

numpy array – The projection operator as a N x N matrix, where N is the number of parameters (obtained via num_params()). This projector acts on parameter-space, and has rank equal to the number of non-gauge degrees of freedom.

transform_inplace(self, s)

Gauge transform this model.

Update each of the operation matrices G in this model with inv(s) * G * s, each rhoVec with inv(s) * rhoVec, and each EVec with EVec * s

Parameters

s (GaugeGroupElement) – A gauge group element which specifies the “s” matrix (and it’s inverse) used in the above similarity transform.

Returns

None

frobeniusdist(self, other_model, transform_mx=None, item_weights=None, normalize=True)

Compute the weighted frobenius norm of the difference between this model and other_model.

Differences in each corresponding gate matrix and spam vector element are squared, weighted (using item_weights as applicable), then summed. The value returned is the square root of this sum, or the square root of this sum divided by the number of summands if normalize == True.

Parameters
  • other_model (Model) – the other model to difference against.

  • transform_mx (numpy array, optional) – if not None, transform this model by G => inv(transform_mx) * G * transform_mx, for each operation matrix G (and similar for rho and E vectors) before taking the difference. This transformation is applied only for the difference and does not alter the values stored in this model.

  • item_weights (dict, optional) – Dictionary of weighting factors for individual gates and spam operators. Weights are applied multiplicatively to the squared differences, i.e., (before the final square root is taken). Keys can be gate, state preparation, POVM effect, or spam labels, as well as the two special labels “gates” and “spam” which apply to all of the gate or SPAM elements, respectively (but are overridden by specific element values). Values are floating point numbers. By default, all weights are 1.0.

  • normalize (bool, optional) – if True (the default), the sum of weighted squared-differences is divided by the weighted number of differences before the final square root is taken. If False, the division is not performed.

Returns

float

residuals(self, other_model, transform_mx=None, item_weights=None)

Compute the weighted residuals between two models.

Residuals are the differences in corresponding operation matrix and spam vector elements.

Parameters
  • other_model (Model) – the other model to difference against.

  • transform_mx (numpy array, optional) – if not None, transform this model by G => inv(transform_mx) * G * transform_mx, for each operation matrix G (and similar for rho and E vectors) before taking the difference. This transformation is applied only for the difference and does not alter the values stored in this model.

  • item_weights (dict, optional) – Dictionary of weighting factors for individual gates and spam operators. Weights applied such that they act multiplicatively on the squared differences, so that the residuals themselves are scaled by the square roots of these weights. Keys can be gate, state preparation, POVM effect, or spam labels, as well as the two special labels “gates” and “spam” which apply to all of the gate or SPAM elements, respectively (but are overridden by specific element values). Values are floating point numbers. By default, all weights are 1.0.

Returns

  • residuals (numpy.ndarray) – A 1D array of residuals (differences w.r.t. other)

  • nSummands (int) – The (weighted) number of elements accounted for by the residuals.

jtracedist(self, other_model, transform_mx=None, include_spam=True)

Compute the Jamiolkowski trace distance between this model and other_model.

This is defined as the maximum of the trace distances between each corresponding gate, including spam gates.

Parameters
  • other_model (Model) – the other model to difference against.

  • transform_mx (numpy array, optional) – if not None, transform this model by G => inv(transform_mx) * G * transform_mx, for each operation matrix G (and similar for rho and E vectors) before taking the difference. This transformation is applied only for the difference and does not alter the values stored in this model.

  • include_spam (bool, optional) – Whether to add to the max-trace-distance the frobenius distances between corresponding SPAM operations.

Returns

float

diamonddist(self, other_model, transform_mx=None, include_spam=True)

Compute the diamond-norm distance between this model and other_model.

This is defined as the maximum of the diamond-norm distances between each corresponding gate, including spam gates.

Parameters
  • other_model (Model) – the other model to difference against.

  • transform_mx (numpy array, optional) – if not None, transform this model by G => inv(transform_mx) * G * transform_mx, for each operation matrix G (and similar for rho and E vectors) before taking the difference. This transformation is applied only for the difference and does not alter the values stored in this model.

  • include_spam (bool, optional) – Whether to add to the max-diamond-distance the frobenius distances between corresponding SPAM operations.

Returns

float

_tpdist(self)

Compute the “distance” between this model and the space of trace-preserving (TP) maps.

This is defined as the square root of the sum-of-squared deviations among the first row of all operation matrices and the first element of all state preparations.

Returns

float

strdiff(self, other_model, metric='frobenius')

Return a string describing the distances between this model and other_model.

The returned string displays differences between each corresponding gate, state prep, and POVM effect.

Parameters
  • other_model (Model) – the other model to difference against.

  • metric ({'frobenius', 'infidelity', 'diamond'}) – Which distance metric to use.

Returns

str

_init_copy(self, copy_into, memo)

Copies any “tricky” member of this model into copy_into, before deep copying everything else within a .copy() operation.

__str__(self)

Return str(self).

all_objects(self)

Iterate over all of the (label, operator object) entities in this model.

This iterator runs over all state preparations, POVMS, operations, and instruments.

depolarize(self, op_noise=None, spam_noise=None, max_op_noise=None, max_spam_noise=None, seed=None)

Apply depolarization uniformly or randomly to this model’s gate and/or SPAM elements.

The result is returned without modifying the original (this) model. You must specify either op_noise or max_op_noise (for the amount of gate depolarization), and either spam_noise or max_spam_noise (for spam depolarization).

Parameters
  • op_noise (float, optional) –

    apply depolarizing noise of strength 1-op_noise to all gates in

    the model. (Multiplies each assumed-Pauli-basis operation matrix by the diagonal matrix with (1.0-op_noise) along all the diagonal elements except the first (the identity).

  • spam_noise (float, optional) – apply depolarizing noise of strength 1-spam_noise to all SPAM opeations (state and POVM effects) in the model. (Multiplies the non-identity part of each assumed-Pauli-basis state preparation vector and measurement vector by (1.0-spam_noise)).

  • max_op_noise (float, optional) – specified instead of op_noise; apply a random depolarization with maximum strength 1-max_op_noise to each gate in the model.

  • max_spam_noise (float, optional) – specified instead of spam_noise; apply a random depolarization with maximum strength 1-max_spam_noise to each state preparation and POVM in the model.

  • seed (int, optional) – if not None, seed numpy’s random number generator with this value before generating random depolarizations.

Returns

Model – the depolarized Model

rotate(self, rotate=None, max_rotate=None, seed=None)

Apply a rotation uniformly or randomly to this model.

Uniformly means the same rotation applied to each gate and randomly means different random rotations are applied to each gate of this model. The result is returned without modifying the original (this) model.

You must specify either rotate or max_rotate. This method currently only works on n-qubit models.

Parameters
  • rotate (tuple of floats, optional) – If you specify the rotate argument, then the same rotation operation is applied to each gate. That is, each gate’s matrix G is composed with a rotation operation R (so G -> dot(R, G) ) where R is the unitary superoperator corresponding to the unitary operator U = exp( sum_k( i * rotate[k] / 2.0 * Pauli_k ) ). Here Pauli_k ranges over all of the non-identity un-normalized Pauli operators (e.g. {X,Y,Z} for 1 qubit, {IX, IY, IZ, XI, XX, XY, XZ, YI, YX, YY, YZ, ZI, ZX, ZY, ZZ} for 2 qubits).

  • max_rotate (float, optional) – If max_rotate is specified (instead of rotate), then pyGSTi randomly generates a different rotate tuple, and applies the corresponding rotation, to each gate in this Model. Each component of each tuple is drawn uniformly from [0, max_rotate).

  • seed (int, optional) – if not None, seed numpy’s random number generator with this value before generating random depolarizations.

Returns

Model – the rotated Model

randomize_with_unitary(self, scale, seed=None, rand_state=None)

Create a new model with random unitary perturbations.

Apply a random unitary to each element of a model, and return the result, without modifying the original (this) model. This method works on Model as long as the dimension is a perfect square.

Parameters
  • scale (float) – maximum element magnitude in the generator of each random unitary transform.

  • seed (int, optional) – if not None, seed numpy’s random number generator with this value before generating random depolarizations.

  • rand_state (numpy.random.RandomState) – A RandomState object to generate samples from. Can be useful to set instead of seed if you want reproducible distribution samples across multiple random function calls but you don’t want to bother with manually incrementing seeds between those calls.

Returns

Model – the randomized Model

increase_dimension(self, new_dimension)

Enlarge the dimension of this model.

Enlarge the spam vectors and operation matrices of model to a specified dimension, and return the resulting inflated model. Spam vectors are zero-padded and operation matrices are padded with 1’s on the diagonal and zeros on the off-diagonal (effectively padded by identity operation).

Parameters

new_dimension (int) – the dimension of the returned model. That is, the returned model will have rho and E vectors that have shape (new_dimension,1) and operation matrices with shape (new_dimension,new_dimension)

Returns

Model – the increased-dimension Model

_decrease_dimension(self, new_dimension)

Decrease the dimension of this model.

Shrink the spam vectors and operation matrices of model to a specified dimension, and return the resulting model.

Parameters

new_dimension (int) – the dimension of the returned model. That is, the returned model will have rho and E vectors that have shape (new_dimension,1) and operation matrices with shape (new_dimension,new_dimension)

Returns

Model – the decreased-dimension Model

kick(self, absmag=1.0, bias=0, seed=None)

“Kick” this model by adding to each gate a random matrix.

The random matrices have values uniformly distributed in the interval [bias-absmag,bias+absmag].

Parameters
  • absmag (float, optional) – The maximum magnitude of the entries in the “kick” matrix relative to bias.

  • bias (float, optional) – The bias of the entries in the “kick” matrix.

  • seed (int, optional) – if not None, seed numpy’s random number generator with this value before generating random depolarizations.

Returns

Model – the kicked model.

compute_clifford_symplectic_reps(self, oplabel_filter=None)

Constructs a dictionary of the symplectic representations for all the Clifford gates in this model.

Non-StaticCliffordOp gates will be ignored and their entries omitted from the returned dictionary.

Parameters

oplabel_filter (iterable, optional) – A list, tuple, or set of operation labels whose symplectic representations should be returned (if they exist).

Returns

dict – keys are operation labels and/or just the root names of gates (without any state space indices/labels). Values are (symplectic_matrix, phase_vector) tuples.

print_info(self)

Print to stdout relevant information about this model.

This information includes the Choi matrices and their eigenvalues.

Returns

None

_effect_labels_for_povm(self, povm_lbl)

Gets the effect labels corresponding to the possible outcomes of POVM label povm_lbl.

Parameters

povm_lbl (Label) – POVM label.

Returns

list – A list of strings which label the POVM outcomes.

_member_labels_for_instrument(self, inst_lbl)

Gets the member labels corresponding to the possible outcomes of the instrument labeled by inst_lbl.

Parameters

inst_lbl (Label) – Instrument label.

Returns

list – A list of strings which label the instrument members.

_reinit_opcaches(self)

Called when parameter vector structure changes and self._opcaches should be cleared & re-initialized

create_processor_spec(self, qubit_labels='auto')

Create a processor specification from this model with the given qubit labels.

Currently this only works for models on qubits.

Parameters

qubit_labels (tuple or “auto”, optional) – A tuple of qubit labels, e.g. (‘Q0’, ‘Q1’) or (0, 1). “auto” uses the labels in this model’s state space labels.

Returns

QubitProcessorSpec

create_modelmember_graph(self)

Generate a ModelMemberGraph for the model.

Returns

ModelMemberGraph – A directed graph capturing dependencies among model members

_to_nice_serialization(self)
classmethod _from_nice_serialization(cls, state)
errorgen_coefficients(self, normalized_elem_gens=True)

TODO: docstring - returns a nested dict containing all the error generator coefficients for all the operations in this model.

_add_reparameterization(self, primitive_op_labels, fogi_dirs, errgenset_space_labels)
_format_gauge_action_matrix(self, mx, op, reduce_to_model_space, row_basis, op_gauge_basis, create_complete_basis_fn)
setup_fogi(self, initial_gauge_basis, create_complete_basis_fn=None, op_label_abbrevs=None, reparameterize=False, reduce_to_model_space=True, dependent_fogi_action='drop')
fogi_errorgen_component_labels(self, include_fogv=False, typ='normal')
fogi_errorgen_components_array(self, include_fogv=False, normalized_elem_gens=True)
set_fogi_errorgen_components_array(self, components, include_fogv=False, normalized_elem_gens=True, truncate=False)
class pygsti.report._StateSpace

Bases: pygsti.baseobjs.nicelyserializable.NicelySerializable

Base class for defining a state space (Hilbert or Hilbert-Schmidt space).

This base class just sets the API for a “state space” in pyGSTi, accessed as the direct sum of one or more tensor products of Hilbert spaces.

classmethod cast(cls, obj)

Casts obj into a StateSpace object if possible.

If obj is already of this type, it is simply returned without modification.

Parameters

obj (StateSpace or int or list) – Either an already-built state space object or an integer specifying the number of qubits, or a list of labels as would be provided to the first argument of :method:`ExplicitStateSpace.__init__`.

Returns

StateSpace

property udim(self)

Integer Hilbert (unitary operator) space dimension of this quantum state space.

Raises an error if this space is not a quantum state space.

property dim(self)

Integer Hilbert-Schmidt (super-operator) or classical dimension of this state space.

property num_qubits(self)

The number of qubits in this quantum state space.

Raises a ValueError if this state space doesn’t consist entirely of qubits.

property num_tensor_product_blocks(self)

The number of tensor-product blocks which are direct-summed to get the final state space.

Returns

int

property tensor_product_blocks_labels(self)

The labels for all the tensor-product blocks.

Returns

tuple of tuples

property tensor_product_blocks_dimensions(self)

The superoperator dimensions for all the tensor-product blocks.

Returns

tuple of tuples

property tensor_product_blocks_udimensions(self)

The unitary operator dimensions for all the tensor-product blocks.

Returns

tuple of tuples

property tensor_product_blocks_types(self)

The type (quantum vs classical) of all the tensor-product blocks.

Returns

tuple of tuples

abstract label_dimension(self, label)

The superoperator dimension of the given label (from any tensor product block)

Parameters

label (str or int) – The label whose dimension should be retrieved.

Returns

int

abstract label_udimension(self, label)

The unitary operator dimension of the given label (from any tensor product block)

Parameters

label (str or int) – The label whose dimension should be retrieved.

Returns

int

abstract label_tensor_product_block_index(self, label)

The index of the tensor product block containing the given label.

Parameters

label (str or int) – The label whose index should be retrieved.

Returns

int

abstract label_type(self, label)

The type (quantum or classical) of the given label (from any tensor product block).

Parameters

label (str or int) – The label whose type should be retrieved.

Returns

str

tensor_product_block_labels(self, i_tpb)

The labels for the iTBP-th tensor-product block.

Parameters

i_tpb (int) – Tensor-product block index.

Returns

tuple

tensor_product_block_dimensions(self, i_tpb)

The superoperator dimensions for the factors in the iTBP-th tensor-product block.

Parameters

i_tpb (int) – Tensor-product block index.

Returns

tuple

tensor_product_block_udimensions(self, i_tpb)

The unitary-operator dimensions for the factors in the iTBP-th tensor-product block.

Parameters

i_tpb (int) – Tensor-product block index.

Returns

tuple

copy(self)

Return a copy of this StateSpace.

Returns

StateSpace

is_compatible_with(self, other_state_space)

Whether another state space is compatible with this one.

Two state spaces are considered “compatible” when their overall dimensions agree (even if their tensor product block structure and labels do not). (This checks whether the Hilbert spaces are isomorphic.)

Parameters

other_state_space (StateSpace) – The state space to check compatibility with.

Returns

bool

property is_entirely_qubits(self)

Whether this state space is just the tensor product of qubit subspaces.

Returns

bool

is_entire_space(self, labels)

True if this state space is a single tensor product block with (exactly, in order) the given set of labels.

Parameters

labels (iterable) – the labels to test.

Returns

bool

contains_labels(self, labels)

True if this state space contains all of a given set of labels.

Parameters

labels (iterable) – the labels to test.

Returns

bool

contains_label(self, label)

True if this state space contains a given label.

Parameters

label (str or int) – the label to test for.

Returns

bool

property common_dimension(self)

Returns the common super-op dimension of all the labels in this space.

If not all the labels in this space have the same dimension, then None is returned to indicate this.

This property is useful when working with stencils, where operations are created for a “stencil space” that is not exactly a subspace of a StateSpace space but will be mapped to one in the future.

Returns

int or None

property common_udimension(self)

Returns the common unitary-op dimension of all the labels in this space.

If not all the labels in this space have the same dimension, then None is returned to indicate this.

This property is useful when working with stencils, where operations are created for a “stencil space” that is not exactly a subspace of a StateSpace space but will be mapped to one in the future.

Returns

int or None

create_subspace(self, labels)

Create a sub-StateSpace object from a set of existing labels.

Parameters

labels (iterable) – The labels to include in the returned state space.

Returns

StateSpace

intersection(self, other_state_space)

Create a state space whose labels are the intersection of the labels of this space and one other.

Dimensions associated with the labels are preserved, as is the ordering of tensor product blocks. If the two spaces have the same label, but their dimensions or indices do not agree, an error is raised.

Parameters

other_state_space (StateSpace) – The other state space.

Returns

StateSpace

union(self, other_state_space)

Create a state space whose labels are the union of the labels of this space and one other.

Dimensions associated with the labels are preserved, as is the tensor product block index. If the two spaces have the same label, but their dimensions or indices do not agree, an error is raised.

Parameters

other_state_space (StateSpace) – The other state space.

Returns

StateSpace

create_stencil_subspace(self, labels)

Create a template sub-StateSpace object from a set of potentially stencil-type labels.

That is, the elements of labels don’t need to actually exist within this state space – they may be stencil labels that will resolve to a label in this state space later on.

Parameters

labels (iterable) – The labels to include in the returned state space.

Returns

StateSpace

__repr__(self)

Return repr(self).

__hash__(self)

Return hash(self).

__eq__(self, other_statespace)

Return self==value.

class pygsti.report._Circuit(layer_labels=(), line_labels='auto', num_lines=None, editable=False, stringrep=None, name='', check=True, expand_subcircuits='default', occurrence=None, compilable_layer_indices=None)

Bases: object

A quantum circuit.

A Circuit represents a quantum circuit, consisting of state preparation, gates, and measurement operations. It is composed of some number of “lines”, typically one per qubit, and stores the operations on these lines as a sequence of Label objects, one per circuit layer, whose .sslbls members indicate which line(s) the label belongs on. When a circuit is created with ‘editable=True’, a rich set of operations may be used to construct the circuit in place, after which done_editing() should be called so that the Circuit can be properly hashed as needed.

Parameters
  • layer_labels (iterable of Labels or str) –

    This argument provides a list of the layer labels specifying the state preparations, gates, and measurements for the circuit. This argument can also be a Circuit or a string, in which case it is parsed as a text-formatted circuit. Internally this will eventually be converted to a list of Label objects, one per layer, but it may be specified using anything that can be readily converted to a Label objects. For example, any of the following are allowed:

    • [‘Gx’,’Gx’] : X gate on each of 2 layers

    • `[Label(‘Gx’),Label(‘Gx’)] : same as above

    • [(‘Gx’,0),(‘Gy’,0)] : X then Y on qubit 0 (2 layers)

    • [[(‘Gx’,0),(‘Gx’,1)],[(‘Gy’,0),(‘Gy’,1)]] : parallel X then Y on qubits 0 & 1

  • line_labels (iterable, optional) – The (string valued) label for each circuit line. If ‘auto’, then line_labels is taken to be the list of all state-space labels present within layer_labels. If there are no such labels (e.g. if layer_labels contains just gate names like (‘Gx’,’Gy’)), then the special value ‘*’ is used as a single line label.

  • num_lines (int, optional) – Specify this instead of line_labels to set the latter to the integers between 0 and num_lines-1.

  • editable (bool, optional) – Whether the created Circuit is created in able to be modified. If True, then you should call done_editing() once the circuit is completely assembled, as this makes the circuit read-only and allows it to be hashed.

  • stringrep (string, optional) – A string representation for the circuit. If None (the default), then this will be generated automatically when needed. One reason you’d want to specify this is if you know of a nice compact string representation that you’d rather use, e.g. “Gx^4” instead of the automatically generated “GxGxGxGx”. If you want to initialize a Circuit entirely from a string representation you can either specify the string in as layer_labels or set layer_labels to None and stringrep to any valid (one-line) circuit string.

  • name (str, optional) – A name for this circuit (useful if/when used as a block within larger circuits).

  • check (bool, optional) – Whether stringrep should be checked against layer_labels to ensure they are consistent, and whether the labels in layer_labels are a subset of line_labels. The only reason you’d want to set this to False is if you’re absolutely sure stringrep and line_labels are consistent and want to save computation time.

  • expand_subcircuits (bool or "default") – If “default”, then the value of Circuit.default_expand_subcircuits is used. If True, then any sub-circuits (e.g. anything exponentiated like “(GxGy)^4”) will be expanded when it is stored within the created Circuit. If False, then such sub-circuits will be left as-is. It’s typically more robust to expand sub-circuits as this facilitates comparison (e.g. so “GxGx” == “Gx^2”), but in cases when you have massive exponents (e.g. “Gx^8192”) it may improve performance to set expand_subcircuits=False.

  • occurrence (hashable, optional) – A value to set as the “occurrence id” for this circuit. This value doesn’t affect the circuit an any way except by affecting it’s hashing and equivalence testing. Circuits with different occurrence ids are not equivalent. Occurrence values effectively allow multiple copies of the same ciruit to be stored in a dictionary or DataSet.

  • compilable_layer_indices (tuple, optional) – The circuit-layer indices that may be internally altered (but retaining the same target operation) and/or combined with the following circuit layer by a hardware compiler.when executing this circuit. Layers that are not “compilable” are effectively followed by a barrier which prevents the hardward compiler from restructuring the circuit across the layer boundary.

default_expand_subcircuits

By default, expand sub-circuit labels.

Type

bool

line_labels

The line labels (often qubit labels) of this circuit.

Type

tuple

layertup

This Circuit’s layers as a standard Python tuple of layer Labels.

Type

tuple

tup

This Circuit as a standard Python tuple of layer Labels and line labels.

Type

tuple

str

The Python string representation of this Circuit.

Type

str

default_expand_subcircuits = True
classmethod cast(cls, obj)

Convert obj into a Circuit.

Parameters

obj (object) – Object to convert

Returns

Circuit

classmethod from_tuple(cls, tup)

Creates a Circuit from a tuple

Parameters

tup (tuple) – The tuple to convert.

Returns

Circuit

classmethod _fastinit(cls, labels, line_labels, editable, name='', stringrep=None, occurrence=None, compilable_layer_indices=None)
_bare_init(self, labels, line_labels, editable, name='', stringrep=None, occurrence=None, compilable_layer_indices=None)
to_label(self, nreps=1)

Construct and return this entire circuit as a CircuitLabel.

Note: occurrence-id information is not stored in a circuit label, so circuits that differ only in their occurence_id will return circuit labels that are equal.

Parameters

nreps (int, optional) – The number of times this circuit will be repeated (CircuitLabels support exponentiation and you can specify this here).

Returns

CircuitLabel

property line_labels(self)

The line labels (often qubit labels) of this circuit.

property name(self)

The name of this circuit.

Note: the name is not a part of the hashed value. The name is used to name the CircuitLabel returned from :method:`to_label`.

property occurrence(self)

The occurrence id of this circuit.

property layertup(self)

This Circuit’s layers as a standard Python tuple of layer Labels.

Returns

tuple

property tup(self)

This Circuit as a standard Python tuple of layer Labels and line labels.

Returns

tuple

property compilable_layer_indices(self)

Tuple of the layer indices corresponding to “compilable” layers.

property compilable_by_layer(self)

Boolean array indicating whether each layer is “compilable” or not.

property str(self)

The Python string representation of this Circuit.

Returns

str

property layerstr(self)

Just the string representation of the circuit layers (no ‘@<line_labels>’ suffix)

property linesstr(self)

Just the string representation of the circuit’s line labels (the ‘@<line_labels>’ suffix)

_labels_lines_str(self)

Split the string representation up into layer-labels & line-labels parts

__hash__(self)

Return hash(self).

__len__(self)
__iter__(self)
__contains__(self, x)

Note: this is not covered by __iter__ for case of contained CircuitLabels

__radd__(self, x)
__add__(self, x)
repeat(self, ntimes, expand='default')

Repeat this circuit ntimes times.

Parameters
  • ntimes (int) – Number of repetitions.

  • expand (bool or "default", optional) – When False, the returned circuit will contain a CircuitLabel encapsulating the repetitions without explicitly storing them. When True, the returned circuit will be expanded into the ntimes repetitions. “default” means to use the value in the class variable Circuit.default_expand_subcircuits.

__mul__(self, x)
__pow__(self, x)
__eq__(self, x)

Return self==value.

__lt__(self, x)

Return self<value.

__gt__(self, x)

Return self>value.

property num_lines(self)

The number of lines in this circuit.

Returns

int

copy(self, editable='auto')

Returns a copy of the circuit.

Parameters

editable ({True,False,"auto"}) – Whether returned copy is editable. If “auto” is given, then the copy is editable if and only if this Circuit is.

Returns

Circuit

clear(self)

Removes all the gates in a circuit (preserving the number of lines).

Returns

None

_proc_layers_arg(self, layers)

Pre-process the layers argument used by many methods

_proc_lines_arg(self, lines)

Pre-process the lines argument used by many methods

_proc_key_arg(self, key)

Pre-process the key argument used by many methods

_layer_components(self, ilayer)

Get the components of the ilayer-th layer as a list/tuple.

_remove_layer_component(self, ilayer, indx)

Removes the indx-th component from the ilayer-th layer

_append_layer_component(self, ilayer, val)

Add val to the ilayer-th layer

_replace_layer_component(self, ilayer, indx, val)
extract_labels(self, layers=None, lines=None, strict=True)

Get a subregion - a “rectangle” - of this Circuit.

This can be used to select multiple layers and/or lines of this Circuit. The strict argument controls whether gates need to be entirely within the given rectangle or can be intersecting it. If layers is a single integer then a Label is returned (representing a layer or a part of a layer), otherwise a Circuit is returned.

Parameters
  • layers (int, slice, or list/tuple of ints) – Which layers to select (the horizontal dimension of the selection rectangle). Layers are always selected by index, and this argument can be a single (integer) index - in which case a Label is returned - or multiple indices as given by a slice or list - in which case a Circuit is returned. Note that, even though we speak of a “rectangle”, layer indices do not need to be contiguous. The special value None selects all layers.

  • lines (str/int, slice, or list/tuple of strs/ints) – Which lines to select (the vertical dimension of the selection rectangle). Lines are selected by their line-labels (elements of the circuit’s .line_labels property), which can be strings and/or integers. A single or multiple line-labels can be specified. If the line labels are integers a slice can be used, otherwise a list or tuple of labels is the only way to select multiple of them. Note that line-labels do not need to be contiguous. The special value None selects all lines.

  • strict (bool, optional) – When True, only gates lying completely within the selected region are included in the return value. If a gate straddles the region boundary (e.g. if we select just line 1 and the circuit contains “Gcnot:1:2”) then it is silently not-included in the returned label or circuit. If False, then gates which straddle the region boundary are included. Note that this may result in a Label or Circuit containing more line labels than where requested in the call to extract_labels(…)..

Returns

Label or Circuit – The requested portion of this circuit, given as a Label if layers is a single integer and as a Circuit otherwise. Note: if you want a Circuit when only selecting one layer, set layers to a slice or tuple containing just a single index.

set_labels(self, lbls, layers=None, lines=None)

Write lbls to the block defined by the layers and lines arguments.

Note that lbls can be anything interpretable as a Label or list of labels.

Parameters
  • lbls (Label, list/tuple of Labels, or Circuit) – When layers is a single integer, lbls should be a single “layer label” of type Label. Otherwise, lbls should be a list or tuple of Label objects with length equal to the number of layers being set. A Circuit may also be used in this case.

  • layers (int, slice, or list/tuple of ints) – Which layers to set (the horizontal dimension of the destination rectangle). Layers are always selected by index, and this argument can be a single (integer) index or multiple indices as given by a slice or list. Note that these indices do not need to be contiguous. The special value None stands for all layers.

  • lines (str/int, slice, or list/tuple of strs/ints) – Which lines to set (the vertical dimension of the destination rectangle). Lines are selected by their line-labels, which can be strings and/or integers. A single or multiple line-labels can be specified. If the line labels are integers a slice can be used, otherwise a list or tuple of labels is the only way to specify multiple of them. The line-labels do not need to be contiguous. The special value None stands for all lines, and in this case new lines will be created if there are new state-space labels in lbls (when lines is not None an error is raised instead).

Returns

None

insert_idling_layers(self, insert_before, num_to_insert, lines=None)

Inserts into this circuit one or more idling (blank) layers.

By default, complete layer(s) are inserted. The lines argument allows you to insert partial layers (on only a subset of the lines).

Parameters
  • insert_before (int) – The layer index to insert the new layers before. Can be from 0 (insert at the beginning) to len(self)-1 (insert at end), and negative indexing can be used to insert relative to the last layer. The special value None inserts at the end.

  • num_to_insert (int) – The number of new layers to insert.

  • lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have new layers (blank circuit space) inserted into them. A single or multiple line-labels can be specified, similarly as in :method:`extract_labels`. The default value None stands for all lines.

Returns

Circuit

insert_idling_layers_inplace(self, insert_before, num_to_insert, lines=None)

Inserts into this circuit one or more idling (blank) layers.

By default, complete layer(s) are inserted. The lines argument allows you to insert partial layers (on only a subset of the lines).

Parameters
  • insert_before (int) – The layer index to insert the new layers before. Can be from 0 (insert at the beginning) to len(self)-1 (insert at end), and negative indexing can be used to insert relative to the last layer. The special value None inserts at the end.

  • num_to_insert (int) – The number of new layers to insert.

  • lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have new layers (blank circuit space) inserted into them. A single or multiple line-labels can be specified, similarly as in :method:`extract_labels`. The default value None stands for all lines.

Returns

None

_append_idling_layers_inplace(self, num_to_insert, lines=None)

Adds one or more idling (blank) layers to the end of this circuit.

By default, complete layer(s) are appended. The lines argument allows you to add partial layers (on only a subset of the lines).

Parameters
  • num_to_insert (int) – The number of new layers to append.

  • lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have new layers (blank circuit space) inserted into them. A single or multiple line-labels can be specified, similarly as in :method:`extract_labels`. The default value None stands for all lines.

Returns

None

insert_labels_into_layers(self, lbls, layer_to_insert_before, lines=None)

Inserts into this circuit the contents of lbls into new full or partial layers.

By default, complete layer(s) are inserted. The lines argument allows you to insert partial layers (on only a subset of the lines).

Parameters
  • lbls (list/tuple of Labels, or Circuit) – The full or partial layer labels to insert. The length of this list, tuple, or circuit determines the number of layers which are inserted.

  • layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)-1 (insert at end), and negative indexing can be used to insert relative to the last layer. The special value None inserts at the end.

  • lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have lbls inserted into them. Currently this can only be a larger set than the set of line labels present in lbls (in future versions this may allow filtering of lbls). value None stands for all lines.

Returns

Circuit

insert_labels_into_layers_inplace(self, lbls, layer_to_insert_before, lines=None)

Inserts into this circuit the contents of lbls into new full or partial layers.

By default, complete layer(s) are inserted. The lines argument allows you to insert partial layers (on only a subset of the lines).

Parameters
  • lbls (list/tuple of Labels, or Circuit) – The full or partial layer labels to insert. The length of this list, tuple, or circuit determines the number of layers which are inserted.

  • layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)-1 (insert at end), and negative indexing can be used to insert relative to the last layer. The special value None inserts at the end.

  • lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have lbls inserted into them. Currently this can only be a larger set than the set of line labels present in lbls (in future versions this may allow filtering of lbls). value None stands for all lines.

Returns

None

insert_idling_lines(self, insert_before, line_labels)

Insert one or more idling (blank) lines into this circuit.

Parameters
  • insert_before (str or int) – The line label to insert new lines before. The special value None inserts lines at the bottom of this circuit.

  • line_labels (list or tuple) – A list or tuple of the new line labels to insert (can be integers and/or strings).

Returns

Circuit

insert_idling_lines_inplace(self, insert_before, line_labels)

Insert one or more idling (blank) lines into this circuit.

Parameters
  • insert_before (str or int) – The line label to insert new lines before. The special value None inserts lines at the bottom of this circuit.

  • line_labels (list or tuple) – A list or tuple of the new line labels to insert (can be integers and/or strings).

Returns

None

_append_idling_lines(self, line_labels)

Add one or more idling (blank) lines onto the bottom of this circuit.

Parameters

line_labels (list or tuple) – A list or tuple of the new line labels to insert (can be integers and/or strings).

Returns

None

insert_labels_as_lines_inplace(self, lbls, layer_to_insert_before=None, line_to_insert_before=None, line_labels='auto')

Inserts into this circuit the contents of lbls into new lines.

By default, lbls is inserted at the beginning of the new lines(s). The layer_to_insert_before argument allows you to insert lbls beginning at a layer of your choice.

Parameters
  • lbls (list/tuple of Labels, or Circuit) – A list of layer labels to insert as new lines. The state-space (line) labels within lbls must not overlap with that of this circuit or an error is raised. If lbls contains more layers than this circuit currently has, new layers are added automatically.

  • layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)-1 (insert at end), and negative indexing can be used to insert relative to the last layer. The default value of None inserts at the beginning.

  • line_to_insert_before (str or int) – The line label to insert the new lines before. The default value of None inserts lines at the bottom of the circuit.

  • line_labels (list, tuple, or "auto") – The labels of the new lines being inserted. If “auto”, then these are inferred from lbls.

Returns

None

insert_labels_as_lines(self, lbls, layer_to_insert_before=None, line_to_insert_before=None, line_labels='auto')

Inserts into this circuit the contents of lbls into new lines.

By default, lbls is inserted at the beginning of the new lines(s). The layer_to_insert_before argument allows you to insert lbls beginning at a layer of your choice.

Parameters
  • lbls (list/tuple of Labels, or Circuit) – A list of layer labels to insert as new lines. The state-space (line) labels within lbls must not overlap with that of this circuit or an error is raised. If lbls contains more layers than this circuit currently has, new layers are added automatically.

  • layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)-1 (insert at end), and negative indexing can be used to insert relative to the last layer. The default value of None inserts at the beginning.

  • line_to_insert_before (str or int) – The line label to insert the new lines before. The default value of None inserts lines at the bottom of the circuit.

  • line_labels (list, tuple, or "auto") – The labels of the new lines being inserted. If “auto”, then these are inferred from lbls.

Returns

None

_append_labels_as_lines(self, lbls, layer_to_insert_before=None, line_labels='auto')

Adds the contents of lbls as new lines at the bottom of this circuit.

By default, lbls is inserted at the beginning of the new lines(s). The layer_to_insert_before argument allows you to insert lbls beginning at a layer of your choice.

Parameters
  • lbls (list/tuple of Labels, or Circuit) – A list of layer labels to append as new lines. The state-space (line) labels within lbls must not overlap with that of this circuit or an error is raised. If lbls contains more layers than this circuit currently has, new layers are added automatically.

  • layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)-1 (insert at end), and negative indexing can be used to insert relative to the last layer. The default value of None inserts at the beginning.

  • line_labels (list, tuple, or "auto") – The labels of the new lines being added. If “auto”, then these are inferred from lbls.

Returns

None

_clear_labels(self, layers, lines, clear_straddlers=False)

remove all labels in a block given by layers and lines Note: layers & lines must be lists/tuples of values; they can’t be slices or single vals

clear_labels(self, layers=None, lines=None, clear_straddlers=False)

Removes all the gates within the given circuit region. Does not reduce the number of layers or lines.

Parameters
  • layers (int, slice, or list/tuple of ints) – Defines the horizontal dimension of the region to clear. See :method:`extract_labels` for details.

  • lines (str/int, slice, or list/tuple of strs/ints) – Defines the vertical dimension of the region to clear. See :method:`extract_labels` for details.

  • clear_straddlers (bool, optional) – Whether or not gates which straddle cleared and non-cleared lines should be cleared. If False and straddling gates exist, an error will be raised.

Returns

None

delete_layers(self, layers=None)

Deletes one or more layers from the circuit.

Parameters

layers (int, slice, or list/tuple of ints) – The layer index or indices to delete. See :method:`extract_labels` for details.

Returns

None

delete_lines(self, lines, delete_straddlers=False)

Deletes one or more lines from the circuit.

Parameters
  • lines (str/int, slice, or list/tuple of strs/ints) – The line label(s) to delete. See :method:`extract_labels` for details.

  • delete_straddlers (bool, optional) – Whether or not gates which straddle deleted and non-deleted lines should be removed. If False and straddling gates exist, an error will be raised.

Returns

None

__getitem__(self, key)
__setitem__(self, key, val)
__delitem__(self, key)
to_pythonstr(self, op_labels)

Convert this circuit to an “encoded” python string.

In the returned string each operation label is represented as a single character, starting with ‘A’ and continuing down the alphabet. This can be useful for processing operation sequences using python’s string tools (regex in particular).

Parameters

op_labels (tuple) – An iterable containing at least all the layer-Labels that appear in this Circuit, and which will be mapped to alphabet characters, beginning with ‘A’.

Returns

string – The converted operation sequence.

Examples

(‘Gx’,’Gx’,’Gy’,’Gx’) => “AABA”

classmethod from_pythonstr(cls, python_string, op_labels)

Decode an “encoded string” into a Circuit.

Create a Circuit from a python string where each operation label is represented as a single character, starting with ‘A’ and continuing down the alphabet. This performs the inverse of :method:`to_pythonstr`.

Parameters
  • python_string (string) – string whose individual characters correspond to the operation labels of a operation sequence.

  • op_labels (tuple) – tuple containing all the operation labels that will be mapped from alphabet characters, beginning with ‘A’.

Returns

Circuit

Examples

“AABA” => (‘Gx’,’Gx’,’Gy’,’Gx’)

serialize(self)

Serialize the parallel gate operations of this Circuit.

Construct a new Circuit whereby all layers containing multiple gates are converted to separate single-gate layers, effectively putting each elementary gate operation into its own layer. Ordering is dictated by the ordering of the compound layer labels.

Returns

Circuit

parallelize(self, can_break_labels=True, adjacent_only=False)

Compress a circuit’s gates by performing them in parallel.

Construct a circuit with the same underlying labels as this one, but with as many gates performed in parallel as possible (with some restrictions - see the Parameters section below). Generally, gates are moved as far left (toward the start) of the circuit as possible.

Parameters
  • can_break_labels (bool, optional) – Whether compound (parallel-gate) labels in this Circuit can be separated during the parallelization process. For example, if can_break_labels=True then “Gx:0[Gy:0Gy:1]” => “[Gx:0Gy:1]Gy:0” whereas if can_break_labels=False the result would remain “Gx:0[Gy:0Gy:1]” because [Gy:0Gy:1] cannot be separated.

  • adjacent_only (bool, optional) – It True, then operation labels are only allowed to move into an adjacent label, that is, they cannot move “through” other operation labels. For example, if adjacent_only=True then “Gx:0Gy:0Gy:1” => “Gx:0[Gy:0Gy:1]” whereas if adjacent_only=False the result would be “[Gx:0Gy:1]Gy:0. Setting this to True is sometimes useful if you want to parallelize a serial string in such a way that subsequently calling .serialize() will give you back the original string.

Returns

Circuit

expand_subcircuits_inplace(self)

Expands all CircuitLabel labels within this circuit.

This operation is done in place and so can only be performed on an editable Circuit.

Returns

None

expand_subcircuits(self)

Returns a new circuit with CircuitLabel labels expanded.

Returns

Circuit

factorize_repetitions_inplace(self)

Attempt to replace repeated sub-circuits with CircuitLabel objects.

More or less the reverse of :method:`expand_subcircuits`, this method attempts to collapse repetitions of the same labels into single CircuitLabel labels within this circuit.

This operation is done in place and so can only be performed on an editable Circuit.

Returns

None

insert_layer(self, circuit_layer, j)

Inserts a single layer into a circuit.

The input layer does not need to contain a gate that acts on every qubit, but it should not contain more than one gate on a qubit.

Parameters
  • circuit_layer (Label) – The layer to insert. A (possibly compound) Label object or something that can be converted into one, e.g. ((‘Gx’,0),(‘Gcnot’,1,2)) or just ‘Gx’.

  • j (int) – The layer index (depth) at which to insert the circuit_layer.

Returns

Circuit

insert_layer_inplace(self, circuit_layer, j)

Inserts a single layer into a circuit.

The input layer does not need to contain a gate that acts on every qubit, but it should not contain more than one gate on a qubit.

Parameters
  • circuit_layer (Label) – The layer to insert. A (possibly compound) Label object or something that can be converted into one, e.g. ((‘Gx’,0),(‘Gcnot’,1,2)) or just ‘Gx’.

  • j (int) – The layer index (depth) at which to insert the circuit_layer.

Returns

None

insert_circuit(self, circuit, j)

Inserts a circuit into this circuit.

The circuit to insert can be over more qubits than this circuit, as long as all qubits that are not part of this circuit are idling. In this case, the idling qubits are all discarded. The circuit to insert can also be on less qubits than this circuit: all other qubits are set to idling. So, the labels of the circuit to insert for all non-idling qubits must be a subset of the labels of this circuit.

Parameters
  • circuit (Circuit) – The circuit to be inserted.

  • j (int) – The layer index (depth) at which to insert the circuit.

Returns

Circuit

insert_circuit_inplace(self, circuit, j)

Inserts a circuit into this circuit.

The circuit to insert can be over more qubits than this circuit, as long as all qubits that are not part of this circuit are idling. In this case, the idling qubits are all discarded. The circuit to insert can also be on less qubits than this circuit: all other qubits are set to idling. So, the labels of the circuit to insert for all non-idling qubits must be a subset of the labels of this circuit.

Parameters
  • circuit (Circuit) – The circuit to be inserted.

  • j (int) – The layer index (depth) at which to insert the circuit.

Returns

None

append_circuit(self, circuit)

Append a circuit to the end of this circuit.

This circuit must satisfy the requirements of :method:`insert_circuit()`. See that method for more details.

Parameters

circuit (A Circuit object) – The circuit to be appended.

Returns

Circuit

append_circuit_inplace(self, circuit)

Append a circuit to the end of this circuit.

This circuit must satisfy the requirements of :method:`insert_circuit()`. See that method for more details.

Parameters

circuit (A Circuit object) – The circuit to be appended.

Returns

None

prefix_circuit(self, circuit)

Prefix a circuit to the beginning of this circuit.

This circuit must satisfy the requirements of the :method:`insert_circuit()`. See that method for more details.

Parameters

circuit (A Circuit object) – The circuit to be prefixed.

Returns

Circuit

prefix_circuit_inplace(self, circuit)

Prefix a circuit to the beginning of this circuit.

This circuit must satisfy the requirements of the :method:`insert_circuit()`. See that method for more details.

Parameters

circuit (A Circuit object) – The circuit to be prefixed.

Returns

None

tensor_circuit_inplace(self, circuit, line_order=None)

The tensor product of this circuit and circuit.

That is, it adds circuit to this circuit as new lines. The line labels of circuit must be disjoint from the line labels of this circuit, as otherwise applying the circuits in parallel does not make sense.

Parameters
  • circuit (A Circuit object) – The circuit to be tensored.

  • line_order (List, optional) – A list of all the line labels specifying the order of the circuit in the updated circuit. If None, the lines of circuit are added below the lines of this circuit. Note that, for many purposes, the ordering of lines of the circuit is irrelevant.

Returns

None

tensor_circuit(self, circuit, line_order=None)

The tensor product of this circuit and circuit.

That is, it adds circuit to this circuit as new lines. The line labels of circuit must be disjoint from the line labels of this circuit, as otherwise applying the circuits in parallel does not make sense.

Parameters
  • circuit (A Circuit object) – The circuit to be tensored.

  • line_order (List, optional) – A list of all the line labels specifying the order of the circuit in the updated circuit. If None, the lines of circuit are added below the lines of this circuit. Note that, for many purposes, the ordering of lines of the circuit is irrelevant.

Returns

Circuit

replace_layer_with_circuit_inplace(self, circuit, j)

Replaces the j-th layer of this circuit with circuit.

Parameters
  • circuit (Circuit) – The circuit to insert

  • j (int) – The layer index to replace.

Returns

None

replace_layer_with_circuit(self, circuit, j)

Replaces the j-th layer of this circuit with circuit.

Parameters
  • circuit (Circuit) – The circuit to insert

  • j (int) – The layer index to replace.

Returns

Circuit

replace_gatename_inplace(self, old_gatename, new_gatename)

Changes the name of a gate throughout this Circuit.

Note that the name is only a part of the label identifying each gate, and doesn’t include the lines (qubits) a gate acts upon. For example, the “Gx:0” and “Gx:1” labels both have the same name but act on different qubits.

Parameters
  • old_gatename (str) – The gate name to replace.

  • new_gatename (str) – The name to replace old_gatename with.

Returns

None

replace_gatename(self, old_gatename, new_gatename)

Returns a copy of this Circuit except that old_gatename is changed to new_gatename.

Note that the “name” is only a part of the “label” identifying each gate, and doesn’t include the lines (qubits) a gate acts upon. For example, the “Gx:0” and “Gx:1” labels both have the same name but act on different qubits.

Parameters
  • old_gatename (str) – The gate name to replace.

  • new_gatename (str) – The name to replace old_gatename with.

Returns

Circuit

replace_gatename_with_idle_inplace(self, gatename)

Treats a given gatename as an idle gate throughout this Circuit.

This effectively removes this gate name from the circuit, and replaces a layer containing only this gate name with an idle layer.

Parameters

gatename (str) – The gate name to replace.

Returns

None

replace_gatename_with_idle(self, gatename)

Returns a copy of this Circuit with a given gatename treated as an idle gate.

This effectively removes this gate name from the circuit, and replaces a layer containing only this gate name with an idle layer.

Parameters

gatename (str) – The gate name to replace.

Returns

Circuit

replace_layer(self, old_layer, new_layer)

Returns a copy of this Circuit except that old_layer is changed to new_layer.

Parameters
  • old_layer (str or Label) – The layer to find.

  • new_layer (str or Label) – The layer to replace found layers with.

Returns

Circuit

replace_layers_with_aliases(self, alias_dict)

Performs a find and replace using layer aliases.

Returns a copy of this Circuit except that it’s layers that match keys of alias_dict are replaced with the corresponding values.

Parameters

alias_dict (dict) – A dictionary whose keys are layer Labels (or equivalent tuples or strings), and whose values are Circuits.

Returns

Circuit

change_gate_library(self, compilation, allowed_filter=None, allow_unchanged_gates=False, depth_compression=True, one_q_gate_relations=None)

Re-express a circuit over a different model.

Parameters
  • compilation (dict or CompilationLibrary.) –

    If a dictionary, the keys are some or all of the gates that appear in the circuit, and the values are replacement circuits that are normally compilations for each of these gates (if they are not, the action of the circuit will be changed). The circuits need not be on all of the qubits, and need only satisfy the requirements of the insert_circuit method. There must be a key for every gate except the self.identity gate, unless allow_unchanged_gates is False. In that case, gate that aren’t a key in this dictionary are left unchanged.

    If a CompilationLibrary, this will be queried via the retrieve_compilation_of() method to find compilations for all of the gates in the circuit. So this CompilationLibrary must contain or be able to auto-generate compilations for the requested gates, except when allow_unchanged_gates is True. In that case, gates that a compilation is not returned for are left unchanged.

  • allowed_filter (dict or set, optional) – Specifies which gates are allowed to be used when generating compilations from compilation. Can only be not None if compilation is a CompilationLibrary. If a dict, keys must be gate names (like “Gcnot”) and values QubitGraph objects indicating where that gate (if it’s present in the library) may be used. If a set, then it specifies a set of qubits and any gate in the current library that is confined within that set is allowed. If None, then all gates within the library are allowed.

  • allow_unchanged_gates (bool, optional) – Whether to allow some gates to remain unchanged, and therefore to be absent from compilation. When True such gates are left alone; when False an error is raised if any such gates are encountered.

  • depth_compression (bool, optional) – Whether to perform depth compression after changing the gate library. If one_q_gate_relations is None this will only remove idle layers and compress the circuit by moving everything as far forward as is possible without knowledge of the action of any gates other than self.identity. See the depth_compression method for more details. Under most circumstances this should be true; if it is False changing gate library will often result in a massive increase in circuit depth.

  • one_q_gate_relations (dict, optional) – Gate relations for the one-qubit gates in the new gate library, that are used in the depth compression, to cancel / combine gates. E.g., one key-value pair might be (‘Gh’,’Gh’) : ‘I’, to signify that two Hadamards c ompose to the idle gate ‘Gi’. See the depth_compression() method for more details.

Returns

None

map_names_inplace(self, mapper)

The names of all of the simple labels are updated in-place according to the mapping function mapper.

Parameters

mapper (dict or function) – A dictionary whose keys are the existing gate name values and whose values are the new names (strings) or a function which takes a single (existing name) argument and returns a new name.

Returns

None

map_state_space_labels_inplace(self, mapper)

The labels of all of the lines (wires/qubits) are updated according to the mapping function mapper.

Parameters

mapper (dict or function) – A dictionary whose keys are the existing self.line_labels values and whose value are the new labels, or a function which takes a single (existing line-label) argument and returns a new line-label.

Returns

None

map_state_space_labels(self, mapper)

Creates a new Circuit whose line labels are updated according to the mapping function mapper.

Parameters

mapper (dict or function) – A dictionary whose keys are the existing self.line_labels values and whose value are the new labels, or a function which takes a single (existing line-label) argument and returns a new line-label.

Returns

Circuit

reorder_lines_inplace(self, order)

Reorders the lines (wires/qubits) of the circuit.

Note that the ordering of the lines is unimportant for most purposes.

Parameters

order (list) – A list containing all of the circuit line labels (self.line_labels) in the order that the should be converted to.

Returns

None

reorder_lines(self, order)

Reorders the lines (wires/qubits) of the circuit.

Note that the ordering of the lines is unimportant for most purposes.

Parameters

order (list) – A list containing all of the circuit line labels (self.line_labels) in the order that the should be converted to.

Returns

Circuit

_is_line_idling(self, line_label, idle_layer_labels=None)

Whether the line in question is idling in every circuit layer.

Parameters
  • line_label (str or int) – The label of the line (i.e., “wire” or qubit).

  • idle_layer_labels (iterable, optional) – A list or tuple of layer-labels that should be treated as idle operations, so their presence will not disqualify a line from being “idle”. E.g. [“Gi”] will cause “Gi” layers to be considered idle layers.

Returns

bool – True if the line is idling. False otherwise.

idling_lines(self, idle_layer_labels=None)

Returns the line labels corresponding to idling lines.

Parameters

idle_layer_labels (iterable, optional) – A list or tuple of layer-labels that should be treated as idle operations, so their presence will not disqualify a line from being “idle”. E.g. [“Gi”] will cause “Gi” layers to be considered idle layers.

Returns

tuple

delete_idling_lines_inplace(self, idle_layer_labels=None)

Removes from this circuit all lines that are idling at every layer.

Parameters

idle_layer_labels (iterable, optional) – A list or tuple of layer-labels that should be treated as idle operations, so their presence will not disqualify a line from being “idle”. E.g. [“Gi”] will cause “Gi” layers to be considered idle layers.

Returns

None

delete_idling_lines(self, idle_layer_labels=None)

Removes from this circuit all lines that are idling at every layer.

Parameters

idle_layer_labels (iterable, optional) – A list or tuple of layer-labels that should be treated as idle operations, so their presence will not disqualify a line from being “idle”. E.g. [“Gi”] will cause “Gi” layers to be considered idle layers.

Returns

Circuit

replace_with_idling_line_inplace(self, line_label, clear_straddlers=True)

Converts the specified line to an idling line, by removing all its gates.

If there are any multi-qubit gates acting on this line, this function will raise an error when clear_straddlers=False.

Parameters
  • line_label (str or int) – The label of the line to convert to an idling line.

  • clear_straddlers (bool, optional) – Whether or not gates which straddle the line_label should also be cleared. If False and straddling gates exist, an error will be raised.

Returns

None

reverse_inplace(self)

Reverses the order of the circuit.

Returns

None

_combine_one_q_gates_inplace(self, one_q_gate_relations)

Compresses sequences of 1-qubit gates in the circuit, using the provided gate relations.

One of the steps of the depth_compression() method, and in most cases that method will be more useful.

Parameters

one_q_gate_relations (dict) –

Keys that are pairs of strings, corresponding to 1-qubit gate names, with values that are a single string, also corresponding to a 1-qubit gate name. Whenever a 1-qubit gate with name name1 is followed in the circuit by a 1-qubit gate with name2 then, if one_q_gate_relations[name1,name2] = name3, name1 -> name3 and name2 -> self.identity, the identity name in the circuit. Moreover, this is still implemented when there are self.identity gates between these 1-qubit gates, and it is implemented iteratively in the sense that if there is a sequence of 1-qubit gates with names name1, name2, name3, … and there are relations for all of (name1,name2) -> name12, (name12,name3) -> name123 etc then the entire sequence of 1-qubit gates will be compressed into a single possibly non-idle 1-qubit gate followed by idle gates in place of the previous 1-qubit gates. Note that None can be used as name3 to signify that the result is the identity (no gate labels).

If a QubitProcessorSpec object has been created for the gates/device in question, the QubitProcessorSpec.oneQgate_relations is the appropriate (and auto-generated) one_q_gate_relations.

Note that this function will not compress sequences of 1-qubit gates that cannot be compressed by independently inspecting sequential non-idle pairs (as would be the case with, for example, Gxpi Gzpi Gxpi Gzpi, if the relation did not know that (Gxpi,Gzpi) -> Gypi, even though the sequence is the identity).

Returns

bool – False if the circuit is unchanged, and True otherwise.

_shift_gates_forward_inplace(self)

Shift all gates forward (left) as far as is possible.

This operation is performed without any knowledge of what any of the gates are. One of the steps of :method:`depth_compression()`.

Returns

bool – False if the circuit is unchanged, and True otherwise.

delete_idle_layers_inplace(self)

Deletes all layers in this circuit that contain no gate operations.

One of the steps of the depth_compression() method.

Returns

bool – False if the circuit is unchanged, and True otherwise.

compress_depth_inplace(self, one_q_gate_relations=None, verbosity=0)

Compresses the depth of this circuit using very simple re-write rules.

  1. If one_q_gate_relations is provided, all sequences of 1-qubit gates in the circuit are compressed as far as is possible using only the pair-wise combination rules provided by this dict (see below).

  2. All gates are shifted forwarded as far as is possible without any knowledge of what any of the gates are.

  3. All idle-only layers are deleted.

Parameters
  • one_q_gate_relations (dict) –

    Keys that are pairs of strings, corresponding to 1-qubit gate names, with values that are a single string, also corresponding to a 1-qubit gate name. Whenever a 1-qubit gate with name name1 is followed in the circuit by a 1-qubit gate with name2 then, if one_q_gate_relations[name1,name2] = name3, name1 -> name3 and name2 -> self.identity, the identity name in the circuit. Moreover, this is still implemented when there are self.identity gates between these 1-qubit gates, and it is implemented iteratively in the sense that if there is a sequence of 1-qubit gates with names name1, name2, name3, … and there are relations for all of (name1,name2) -> name12, (name12,name3) -> name123 etc then the entire sequence of 1-qubit gates will be compressed into a single possibly non-idle 1-qubit gate followed by idle gates in place of the previous 1-qubit gates.

    If a QubitProcessorSpec object has been created for the gates/device in question, the QubitProcessorSpec.oneQgate_relations is the appropriate (and auto-generated) one_q_gate_relations.

    Note that this function will not compress sequences of 1-qubit gates that cannot be compressed by independently inspecting sequential non-idle pairs (as would be the case with, for example, Gxpi Gzpi Gxpi Gzpi, if the relation did not know that (Gxpi,Gzpi) -> Gypi, even though the sequence is the identity).

  • verbosity (int, optional) – If > 0, information about the depth compression is printed to screen.

Returns

None

layer(self, j)

Returns a tuple of the components, i.e. the (non-identity) gates, in the layer at depth j.

These are the .components of the Label returned by indexing this Circuit (using square brackets) with j, i.e. this returns this_circuit[j].components.

Parameters

j (int) – The index (depth) of the layer to be returned

Returns

tuple

layer_label(self, j)

Returns the layer, as a Label, at depth j.

This label contains as components all the (non-identity) gates in the layer..

Parameters

j (int) – The index (depth) of the layer to be returned

Returns

Label

layer_with_idles(self, j, idle_gate_name='I')

Returns a tuple of the components of the layer at depth j, with idle_gate_name at empty circuit locations.

This effectively places an explicit idle_gate_name gates wherever there is an implied identity operation in the circuit.

Parameters
  • j (int) – The index (depth) of the layer to be returned

  • idle_gate_name (str, optional) – The idle gate name to use. Note that state space (qubit) labels will be added to this name to form a Label.

Returns

tuple

layer_label_with_idles(self, j, idle_gate_name='I')

Returns the layer, as a Label, at depth j, with idle_gate_name at empty circuit locations.

This effectively places an explicit idle_gate_name gates wherever there is an implied identity operation in the circuit.

Parameters
  • j (int) – The index (depth) of the layer to be returned

  • idle_gate_name (str, optional) – The idle gate name to use. Note that state space (qubit) labels will be added to this name to form a Label.

Returns

Label

property num_layers(self)

The number of circuit layers.

In simple circuits, this is the same as the depth (given by :method:`depth`). For circuits containing sub-circuit blocks, this gives the number of top-level layers in this circuit.

Returns

int

property depth(self)

The circuit depth.

This is the number of layers in simple circuits. For circuits containing sub-circuit blocks, this includes the full depth of these blocks. If you just want the number of top-level layers, use :method:`num_layers`.

Returns

int

property width(self)

The circuit width.

This is the number of qubits on which the circuit acts. This includes qubits that only idle, but are included as part of the circuit according to self.line_labels.

Returns

int

property size(self)

Returns the circuit size.

This is the sum of the sizes of all the gates in the circuit. A gate that acts on n-qubits has a size of n, with the exception of the idle which has a size of 0. Hence, the circuit is given by: size = depth * num_lines - num_1Q_idles.

Returns

int

property duration(self)
two_q_gate_count(self)

The number of two-qubit gates in the circuit.

(Note that this cannot distinguish between “true” 2-qubit gates and gate that have been defined to act on two qubits but that represent some tensor-product gate.)

Returns

int

num_nq_gates(self, nq)

The number of nq-qubit gates in the circuit.

(Note that this cannot distinguish between “true” nq-qubit gates and gate that have been defined to act on nq qubits but that represent some tensor-product gate.)

Parameters

nq (int) – The qubit-count of the gates to count. For example, if nq == 3, this function returns the number of 3-qubit gates.

Returns

int

property num_multiq_gates(self)

The number of multi-qubit (2+ qubits) gates in the circuit.

(Note that this cannot distinguish between “true” multi-qubit gates and gate that have been defined to act on more than one qubit but that represent some tensor-product gate.)

Returns

int

_togrid(self, identity_name)

return a list-of-lists rep?

__str__(self)

A text rendering of the circuit.

__repr__(self)

Return repr(self).

format_display_str(self, width=80)

Formats a string for displaying this circuit suject to a maximum width.

Parameters

width (int, optional) – The maximum width in characters. If the circuit is longer than this width it is wrapped using multiple lines (like a musical score).

Returns

str

_print_labelinfo(self)

A useful debug routine for printing the internal label structure of a circuit

abstract _write_q_circuit_tex(self, filename)

Writes a LaTeX file for rendering this circuit nicely.

Creates a file containing LaTex that will display this circuit using the Qcircuit.tex LaTex import (compiling the LaTex requires that you have the Qcircuit.tex file).

Parameters

filename (str) – The file to write the LaTex into. Should end with ‘.tex’

Returns

None

convert_to_cirq(self, qubit_conversion, wait_duration=None, gatename_conversion=None, idle_gate_name='Gi')

Converts this circuit to a Cirq circuit.

Parameters
  • qubit_conversion (dict) – Mapping from qubit labels (e.g. integers) to Cirq qubit objects.

  • wait_duration (cirq.Duration, optional) – If no gatename_conversion dict is given, the idle operation is not converted to a gate. If wait_diration is specified and gatename_conversion is not specified, then the idle operation will be converted to a cirq.WaitGate with the specified duration.

  • gatename_conversion (dict, optional) – If not None, a dictionary that converts the gatenames in the circuit to the Cirq gates that will appear in the Cirq circuit. If only standard pyGSTi names are used (e.g., ‘Gh’, ‘Gp’, ‘Gcnot’, ‘Gcphase’, etc) this dictionary need not be specified, and an automatic conversion to the standard Cirq names will be implemented.

  • idle_gate_name (str, optional) – Name to use for idle gates. Defaults to ‘Gi’

Returns

A Cirq Circuit object.

convert_to_quil(self, num_qubits=None, gatename_conversion=None, qubit_conversion=None, readout_conversion=None, block_between_layers=True, block_idles=True, gate_declarations=None)

Converts this circuit to a quil string.

Parameters
  • num_qubits (int, optional) – The number of qubits for the quil file. If None, then this is assumed to equal the number of line labels in this circuit.

  • gatename_conversion (dict, optional) – A dictionary mapping gate names contained in this circuit to the corresponding gate names used in the rendered quil. If None, a standard set of conversions is used (see :function:`standard_gatenames_quil_conversions`).

  • qubit_conversion (dict, optional) – If not None, a dictionary converting the qubit labels in the circuit to the desired qubit labels in the quil output. Can be left as None if the qubit labels are either (1) integers, or (2) of the form ‘Qi’ for integer i. In this case they are converted to integers (i.e., for (1) the mapping is trivial, for (2) the mapping strips the ‘Q’).

  • readout_conversion (dict, optional) – If not None, a dictionary converting the qubit labels mapped through qubit_conversion to the bit labels for readot. E.g. Suppose only qubit 2 (on Rigetti hardware) is in use. Then the pyGSTi string will have only one qubit (labeled 0); it will get remapped to 2 via qubit_conversion={0:2}. At the end of the quil circuit, readout should go recorded in bit 0, so readout_conversion = {0:0}. (That is, qubit with pyGSTi label 0 gets read to Rigetti bit 0, even though that qubit has Rigetti label 2.)

  • block_between_layers (bool, optional) – When True, add in a barrier after every circuit layer. Including such “pragma” blocks can be important for QCVV testing, as this can help reduce the “behind-the-scenes” compilation (beyond necessary conversion to native instructions) experience by the circuit.

  • block_idles (bool, optional) – In the special case of global idle gates, pragma-block barriers are inserted even when block_between_layers=False. Set block_idles=False to disable this behavior, whcih typically results in global idle gates being removed by the compiler.

  • gate_declarations (dict, optional) – If not None, a dictionary that provides unitary maps for particular gates that are not already in the quil syntax.

Returns

str – A quil string.

convert_to_openqasm(self, num_qubits=None, standard_gates_version='u3', gatename_conversion=None, qubit_conversion=None, block_between_layers=True, block_between_gates=False, gateargs_map=None)

Converts this circuit to an openqasm string.

Parameters
  • num_qubits (int, optional) – The number of qubits for the openqasm file. If None, then this is assumed to equal the number of line labels in this circuit.

  • version (string, optional) – Either ‘u3’ or ‘x-sx-rz’. Specifies the naming convention for the QASM gates. With ‘u3’, all single-qubit gates are specified in terms of the ‘u3’ gate, used by IBM and QisKit until ~2021 (see the qasm_u3 function). With ‘x-sx-rz’, all single-gates are specified in terms of ‘x’ (an x pi rotation), ‘sx’ (an x pi/2 rotation) and ‘rz’ (a parameterized rotation around z by an angle theta).

  • gatename_conversion (dict, optional) – If not None, a dictionary that converts the gatenames in the circuit to the gatenames that will appear in the openqasm output. If only standard pyGSTi names are used (e.g., ‘Gh’, ‘Gp’, ‘Gcnot’, ‘Gcphase’, etc) this dictionary need not be specified, and an automatic conversion to the standard openqasm names will be implemented.

  • qubit_conversion (dict, optional) – If not None, a dictionary converting the qubit labels in the circuit to the desired qubit labels in the openqasm output. Can be left as None if the qubit labels are either (1) integers, or (2) of the form ‘Qi’ for integer i. In this case they are converted to integers (i.e., for (1) the mapping is trivial, for (2) the mapping strips the ‘Q’).

  • block_between_layers (bool, optional) – When True, add in a barrier after every circuit layer. Including such barriers can be important for QCVV testing, as this can help reduce the “behind-the-scenes” compilation (beyond necessary conversion to native instructions) experience by the circuit.

  • gateargs_map (dict, optional) – If not None, a dict that maps strings (representing pyGSTi standard gate names) to functions that map the parameters of a pyGSTi gate to a string to be combined with the QASM name to specify the specific gate, in QASM. If only standard pyGSTi names are used (e.g., ‘Gh’, ‘Gzr’, ‘Gczr, etc) or none of the gates are parameterized, this dictionary need not be specified, and an automatic conversion to the standard openqasm format will be implemented.

Returns

str – An openqasm string.

simulate(self, model, return_all_outcomes=False)

Compute the outcome probabilities of this Circuit using model as a model for the gates.

The order of the outcome strings (e.g., ‘0100’) is w.r.t. to the ordering of the qubits in the circuit. That is, the ith element of the outcome string corresponds to the qubit with label self.line_labels[i].

Parameters
  • model (Model) – A description of the gate and SPAM operations corresponding to the labels stored in this Circuit. If this model is over more qubits than the circuit, the output will be the probabilities for the qubits in the circuit marginalized, if possible over the other qubits. But, the simulation is over the full set of qubits in the model, and so the time taken for the simulation scales with the number of qubits in the model. For models where “spectator” qubits do not affect the qubits in this circuit (such as with perfect gates), more efficient simulations will be obtained by first creating a model only over the qubits in this circuit.

  • return_all_outcomes (bool, optional) – Whether to include outcomes in the returned dictionary that have zero probability. When False, the threshold for discarding an outcome as z ero probability is 10^-12.

Returns

probs (dictionary) – A dictionary with keys equal to all (return_all_outcomes is True) or possibly only some (return_all_outcomes is False) of the possible outcomes, and values that are float probabilities.

done_editing(self)

Make this circuit read-only, so that it can be hashed (e.g. used as a dictionary key).

This is done automatically when attempting to hash a Circuit for the first time, so there’s calling this function can usually be skipped (but it’s good for code clarity).

Returns

None

expand_instruments_and_separate_povm(self, model, observed_outcomes=None)

Creates a dictionary of SeparatePOVMCircuit objects from expanding the instruments of this circuit.

Each key of the returned dictionary replaces the instruments in this circuit with a selection of their members. (The size of the resulting dictionary is the product of the sizes of each instrument appearing in this circuit when observed_outcomes is None). Keys are stored as SeparatePOVMCircuit objects so it’s easy to keep track of which POVM outcomes (effects) correspond to observed data. This function is, for the most part, used internally to process a circuit before computing its outcome probabilities.

Parameters

model (Model) –

The model used to provide necessary details regarding the expansion, including:

  • default SPAM layers

  • definitions of instrument-containing layers

  • expansions of individual instruments and POVMs

Returns

OrderedDict – A dict whose keys are SeparatePOVMCircuit objects and whose values are tuples of the outcome labels corresponding to this circuit, one per POVM effect held in the key.

class pygsti.report._CircuitList(circuits, op_label_aliases=None, circuit_rules=None, circuit_weights=None, name=None)

Bases: pygsti.baseobjs.nicelyserializable.NicelySerializable

A unmutable list (a tuple) of Circuit objects and associated metadata.

Parameters
  • circuits (list) – The list of circuits that constitutes the primary data held by this object.

  • op_label_aliases (dict, optional) – Dictionary of circuit meta-data whose keys are operation label “aliases” and whose values are circuits corresponding to what that operation label should be expanded into before querying the dataset. Defaults to the empty dictionary (no aliases defined). e.g. op_label_aliases[‘Gx^3’] = pygsti.obj.Circuit([‘Gx’,’Gx’,’Gx’])

  • circuit_weights (numpy.ndarray, optional) – If not None, an array of per-circuit weights (of length equal to the number of circuits) that are typically used to multiply the counts extracted for each circuit.

  • name (str, optional) – An optional name for this list, used for status messages.

classmethod cast(cls, circuits)

Convert (if needed) an object into a CircuitList.

Parameters

circuits (list or CircuitList) – The object to convert.

Returns

CircuitList

_to_nice_serialization(self)
classmethod _from_nice_serialization(cls, state)
__len__(self)
__getitem__(self, index)
__iter__(self)
apply_aliases(self)

Applies any operation-label aliases to this circuit list.

Returns

list – A list of :class:`Circuit`s.

truncate(self, circuits_to_keep)

Builds a new circuit list containing only a given subset.

This can be safer then just creating a new CircuitList because it preserves the aliases, etc., of this list.

Parameters

circuits_to_keep (list or set) – The circuits to retain in the returned circuit list.

Returns

CircuitList

truncate_to_dataset(self, dataset)

Builds a new circuit list containing only those elements in dataset.

Parameters

dataset (DataSet) – The dataset to check. Aliases are applied to the circuits in this circuit list before they are tested.

Returns

CircuitList

__hash__(self)

Return hash(self).

__eq__(self, other)

Return self==value.

__setstate__(self, state_dict)
class pygsti.report._PlaquetteGridCircuitStructure(plaquettes, x_values, y_values, xlabel, ylabel, additional_circuits=None, op_label_aliases=None, circuit_rules=None, circuit_weights_dict=None, additional_circuits_location='start', name=None)

Bases: pygsti.circuits.circuitlist.CircuitList

Encapsulates a set of circuits, along with an associated structure.

By “structure”, we mean the ability to index the circuits by a 4-tuple (x, y, minor_x, minor_y) for displaying in nested color box plots, along with any aliases.

classmethod cast(cls, circuits_or_structure)

Convert (if needed) an object into a circuit structure.

Parameters

circuits_or_structure (list or CircuitList) – The object to convert. If a PlaquetteGridCircuitStructure, then the object is simply returned. Lists of circuits (including :class:`CircuitList`s are converted to structures having no plaquettes.

Returns

PlaquetteGridCircuitStructure

_to_nice_serialization(self)
classmethod _from_nice_serialization(cls, state)
property plaquettes(self)
iter_plaquettes(self)
plaquette(self, x, y, empty_if_missing=False)

The plaquette at (x,y).

Parameters
  • x (various) – x-value (not index)

  • y (various) – y-value (not index)

  • empty_if_missing (bool, optional) – Whether an empty (0-element) plaquette should be returned when the requested (x,y) is missing.

Returns

CircuitPlaquette

property used_xs(self)

The x-values which have at least one non-empty plaquette

Returns

list

property used_ys(self)

The y-values which have at least one non-empty plaquette

Returns

list

truncate(self, circuits_to_keep=None, xs_to_keep=None, ys_to_keep=None, keep_rows_cols=True)

Truncate this circuit structure to a subset of its current circuits.

Parameters
  • circuits_to_keep (list) – Keep only the circuits present in this list (of Circuit objects).

  • xs_to_keep (list, optional) – The x-values to keep. If None, then all are kept.

  • ys_to_keep (list, optional) – The y-values to keep. If None, then all are kept.

  • keep_rows_cols (bool) – Whether to retain the same number of rows as columns (even if entire rows and/or columns are empty). By default, this is True because we usually want all the plaquettes of a PlaquetteGridCircuitStructure to have the same number of rows and columns.

Returns

PlaquetteGridCircuitStructure

nested_truncations(self, axis='x', keep_rows_cols=False)

Get the nested truncations of this circuit structure along an axis.

When axis == ‘x’, a list of truncations (of this structure) that keep an incrementally larger set of all the x-values. E.g., if the x-values are [1,2,4], truncations to [1], [1,2], and [1,2,4] (no truncation) would be returned.

Setting axis ==’y’ gives the same behavior except using the y-values.

Parameters
  • axis ({'x', 'y'}) – Which axis to truncate along (see above).

  • keep_rows_cols (bool) – Whether to retain the same number of rows as columns (even if entire rows and/or columns are empty).

Returns

list – A list of PlaquetteGridCircuitStructure objects (truncations of this object).

process_circuits(self, processor_fn, updated_aliases=None)

Create a new plaquette with circuits manipulated according to processor_fn.

Parameters
  • processor_fn (function) – A function which takes a single Circuit argument and returns another (or the same) Circuit.

  • updated_aliases (dict, optional) – Because the Label keys of an alias dictionary (maps Label -> Circuit) cannot be processed as a Circuit, one must supply a manualy processed alias dictionary. If you don’t use alias dictionaries just leave this set to None.

Returns

PlaquetteGridCircuitStructure

copy(self)

Returns a copy of this circuit structure.

Returns

PlaquetteGridCircuitStructure

class pygsti.report._Lbl

Bases: object

A label used to identify a gate, circuit layer, or (sub-)circuit.

A label consisting of a string along with a tuple of integers or sector-names specifying which qubits, or more generally, parts of the Hilbert space that is acted upon by an object so-labeled.

property depth(self)

The depth of this label, viewed as a sub-circuit.

property reps(self)

Number of repetitions (of this label’s components) that this label represents.

property has_nontrivial_components(self)
collect_args(self)
strip_args(self)
expand_subcircuits(self)

Expand any sub-circuits within this label.

Returns a list of component labels which doesn’t include any CircuitLabel labels. This effectively expands any “boxes” or “exponentiation” within this label.

Returns

tuple – A tuple of component Labels (none of which should be :class:`CircuitLabel`s).

class pygsti.report._VerbosityPrinter(verbosity=1, filename=None, comm=None, warnings=True, split=False, clear_file=True)

Bases: object

Class responsible for logging things to stdout or a file.

Controls verbosity and can print progress bars. ex:

>>> VerbosityPrinter(1)

would construct a printer that printed out messages of level one or higher to the screen.

>>> VerbosityPrinter(3, 'output.txt')

would construct a printer that sends verbose output to a text file

The static function create_printer() will construct a printer from either an integer or an already existing printer. it is a static method of the VerbosityPrinter class, so it is called like so:

>>> VerbosityPrinter.create_printer(2)

or

>>> VerbostityPrinter.create_printer(VerbosityPrinter(3, 'output.txt'))

printer.log('status') would log ‘status’ if the printers verbosity was one or higher. printer.log('status2', 2) would log ‘status2’ if the printer’s verbosity was two or higher

printer.error('something terrible happened') would ALWAYS log ‘something terrible happened’. printer.warning('something worrisome happened') would log if verbosity was one or higher - the same as a normal status.

Both printer.error and printer.warning will prepend ‘ERROR: ‘ or ‘WARNING: ‘ to the message they are given. Optionally, printer.log() can also prepend ‘Status_n’ to the message, where n is the message level.

Logging of progress bars/iterations:

>>> with printer_instance.progress_logging(verbosity):
>>>     for i, item in enumerate(data):
>>>         printer.show_progress(i, len(data))
>>>         printer.log(...)

will output either a progress bar or iteration statuses depending on the printer’s verbosity

Parameters
  • verbosity (int) – How verbose the printer should be.

  • filename (str, optional) – Where to put output (If none, output goes to screen)

  • comm (mpi4py.MPI.Comm or ResourceAllocation, optional) – Restricts output if the program is running in parallel (By default, if the rank is 0, output is sent to screen, and otherwise sent to commfiles 1, 2, …

  • warnings (bool, optional) – Whether or not to print warnings

  • split (bool, optional) – Whether to split output between stdout and stderr as appropriate, or to combine the streams so everything is sent to stdout.

  • clear_file (bool, optional) – Whether or not filename should be cleared (overwritten) or simply appended to.

_comm_path

relative path where comm files (outputs of non-root ranks) are stored.

Type

str

_comm_file_name

root filename for comm files (outputs of non-root ranks).

Type

str

_comm_file_ext

filename extension for comm files (outputs of non-root ranks).

Type

str

_comm_path =
_comm_file_name =
_comm_file_ext = .txt
_create_file(self, filename)
_get_comm_file(self, comm_id)
clone(self)

Instead of deepcopy, initialize a new printer object and feed it some select deepcopied members

Returns

VerbosityPrinter

static create_printer(verbosity, comm=None)

Function for converting between interfaces

Parameters
  • verbosity (int or VerbosityPrinter object, required:) – object to build a printer from

  • comm (mpi4py.MPI.Comm object, optional) – Comm object to build printers with. !Will override!

Returns

VerbosityPrinter – The printer object, constructed from either an integer or another printer

__add__(self, other)

Increase the verbosity of a VerbosityPrinter

__sub__(self, other)

Decrease the verbosity of a VerbosityPrinter

__getstate__(self)
__setstate__(self, state_dict)
_append_to(self, filename, message)
_put(self, message, flush=True, stderr=False)
_record(self, typ, level, message)
error(self, message)

Log an error to the screen/file

Parameters

message (str) – the error message

Returns

None

warning(self, message)

Log a warning to the screen/file if verbosity > 1

Parameters

message (str) – the warning message

Returns

None

log(self, message, message_level=None, indent_char='  ', show_statustype=False, do_indent=True, indent_offset=0, end='\n', flush=True)

Log a status message to screen/file.

Determines whether the message should be printed based on current verbosity setting, then sends the message to the appropriate output

Parameters
  • message (str) – the message to print (or log)

  • message_level (int, optional) – the minimum verbosity level at which this level is printed.

  • indent_char (str, optional) – what constitutes an “indent” (messages at higher levels are indented more when do_indent=True).

  • show_statustype (bool, optional) – if True, prepend lines with “Status Level X” indicating the message_level.

  • do_indent (bool, optional) – whether messages at higher message levels should be indented. Note that if this is False it may be helpful to set show_statustype=True.

  • indent_offset (int, optional) – an additional number of indentations to add, on top of any due to the message level.

  • end (str, optional) – the character (or string) to end message lines with.

  • flush (bool, optional) – whether stdout should be flushed right after this message is printed (this avoids delays in on-screen output due to buffering).

Returns

None

_progress_bar(self, iteration, total, bar_length, num_decimals, fill_char, empty_char, prefix, suffix, indent)
_verbose_iteration(self, iteration, total, prefix, suffix, verbose_messages, indent, end)
__str__(self)

Return str(self).

verbosity_env(self, level)

Create a temporary environment with a different verbosity level.

This is context manager, controlled using Python’s with statement:

>>> with printer.verbosity_env(2):
        printer.log('Message1') # printed at verbosity level 2
        printer.log('Message2') # printed at verbosity level 2
Parameters

level (int) – the verbosity level of the environment.

progress_logging(self, message_level=1)

Context manager for logging progress bars/iterations.

(The printer will return to its normal, unrestricted state when the progress logging has finished)

Parameters

message_level (int, optional) – progress messages will not be shown until the verbosity level reaches message_level.

show_progress(self, iteration, total, bar_length=50, num_decimals=2, fill_char='#', empty_char='-', prefix='Progress:', suffix='', verbose_messages=[], indent_char='  ', end='\n')

Displays a progress message (to be used within a progress_logging block).

Parameters
  • iteration (int) – the 0-based current iteration – the interation number this message is for.

  • total (int) – the total number of iterations expected.

  • bar_length (int, optional) – the length, in characters, of a text-format progress bar (only used when the verbosity level is exactly equal to the progress_logging message level.

  • num_decimals (int, optional) – number of places after the decimal point that are displayed in progress bar’s percentage complete.

  • fill_char (str, optional) – replaces ‘#’ as the bar-filling character

  • empty_char (str, optional) – replaces ‘-’ as the empty-bar character

  • prefix (str, optional) – message in front of the bar

  • suffix (str, optional) – message after the bar

  • verbose_messages (list, optional) – A list of strings to display after an initial “Iter X of Y” line when the verbosity level is higher than the progress_logging message level and so more verbose messages are shown (and a progress bar is not). The elements of verbose_messages will occur, one per line, after the initial “Iter X of Y” line.

  • indent_char (str, optional) – what constitutes an “indentation”.

  • end (str, optional) – the character (or string) to end message lines with.

Returns

None

_end_progress(self)
start_recording(self)

Begins recording the output (to memory).

Begins recording (in memory) a list of (type, verbosityLevel, message) tuples that is returned by the next call to :method:`stop_recording`.

Returns

None

is_recording(self)

Returns whether this VerbosityPrinter is currently recording.

Returns

bool

stop_recording(self)

Stops recording and returns recorded output.

Stops a “recording” started by :method:`start_recording` and returns the list of (type, verbosityLevel, message) tuples that have been recorded since then.

Returns

list

pygsti.report._deprecated_fn(replacement=None)

Decorator for deprecating a function.

Parameters

replacement (str, optional) – the name of the function that should replace it.

Returns

function

pygsti.report.ROBUST_SUFFIX_LIST = ['.robust', '.Robust', '.robust+', '.Robust+']
pygsti.report.DEFAULT_BAD_FIT_THRESHOLD = 2.0
pygsti.report._add_new_labels(running_lbls, current_lbls)

Simple routine to add current-labels to a list of running-labels without introducing duplicates and preserving order as best we can.

pygsti.report._add_new_estimate_labels(running_lbls, estimates, combine_robust)

Like _add_new_labels but perform robust-suffix processing.

In particular, if combine_robust == True then do not add labels which have a “.robust” counterpart.

pygsti.report._get_viewable_crf(est, est_lbl, mdl_lbl, verbosity=0)
pygsti.report.create_offline_zip(output_dir='.')

Creates a zip file containing the a directory (“offline”) of files need to display “offline” reports.

This offline directory is often generated by reports when connected=False is specified..

For offline reports to display, the “offline” folder must be placed in the same directory as the report’s HTML file. This function can be used to easily obtain a copy of the offline folder for the purpose of sharing offline reports with other people. If you’re just creating your own offline reports using pyGSTi, the offline folder is automatically copied into it’s proper position - so you don’t need to call this function.

Parameters

output_dir (str, optional) – The directory in which “offline.zip” should be place.

Returns

None

pygsti.report._set_toggles(results_dict, brevity, combine_robust)
pygsti.report._create_master_switchboard(ws, results_dict, confidence_level, nmthreshold, printer, fmt, combine_robust, idt_results_dict=None, embed_figures=True)

Creates the “master switchboard” used by several of the reports

pygsti.report._construct_idtresults(idt_idle_op, idt_pauli_dicts, gst_results_dict, printer)

Constructs a dictionary of idle tomography results, parallel to the GST results in gst_results_dict, where possible.

pygsti.report._create_single_metric_switchboard(ws, results_dict, b_gauge_inv, dataset_labels, est_labels=None, embed_figures=True)
pygsti.report.create_general_report(results, filename, title='auto', confidence_level=None, linlog_percentile=5, errgen_type='logGTi', nmthreshold=50, precision=None, comm=None, ws=None, auto_open=False, cachefile=None, brief=False, connected=False, link_to=None, resizable=True, autosize='initial', verbosity=1)

DEPRECATED: use pygsti.report.create_standard_report(…)

Deprecated since version v0.9.9: create_general_report will be removed in the next major release of pyGSTi. It is replaced by construct_standard_report, which returns a Report object.

pygsti.report.create_standard_report(results, filename, title='auto', confidence_level=None, comm=None, ws=None, auto_open=False, link_to=None, brevity=0, advanced_options=None, verbosity=1)

Create a “standard” GST report, containing details about each estimate in results individually.

Either a PDF or HTML report is generated, based on whether filename ends in “.pdf” or not. In the richer HTML-mode, switches (drop-down boxes, buttons, etc.) allow the viewer to choose which estimate is displayed. The estimates in multiple Results objects can be viewed by providing a dictionary of Results objects as the results argument. Note that when comparing many estimates it is often more convenient to view the report generated by create_comparison_report(), which is organized for this purpose.

In PDF-mode this interactivity is not possible and so results may contain just a single estimate. The chief advantage of this more limited mode is that is produces a highly-portable and self-contained PDF file.

Deprecated since version v0.9.9: create_standard_report will be removed in the next major release of pyGSTi. It is replaced by construct_standard_report, which returns a Report object.

Parameters
  • results (Results) – An object which represents the set of results from one or more GST estimation runs, typically obtained from running run_long_sequence_gst() or run_stdpractice_gst(), OR a dictionary of such objects, representing multiple GST runs to be compared (typically all with different data sets). The keys of this dictionary are used to label different data sets that are selectable in the report.

  • filename (string, optional) – The output filename where the report file(s) will be saved. If None, then no output file is produced (but returned Workspace still caches all intermediate results).

  • title (string, optional) – The title of the report. “auto” causes a random title to be generated (which you may or may not like).

  • confidence_level (int, optional) – If not None, then the confidence level (between 0 and 100) used in the computation of confidence regions/intervals. If None, no confidence regions or intervals are computed.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.

  • ws (Workspace, optional) – The workspace used as a scratch space for performing the calculations and visualizations required for this report. If you’re creating multiple reports with similar tables, plots, etc., it may boost performance to use a single Workspace for all the report generation.

  • auto_open (bool, optional) – If True, automatically open the report in a web browser after it has been generated.

  • 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 create and include links to Latex, PDF, and Python pickle files, respectively. “tex” creates latex source files for tables; “pdf” renders PDFs of tables and plots ; “pkl” creates Python versions of plots (pickled python data) and tables (pickled pandas DataFrams).

  • brevity (int, optional) –

    Amount of detail to include in the report. Larger values mean smaller “more briefr” reports, which reduce generation time, load time, and disk space consumption. In particular:

    • 1: Plots showing per-sequences quantities disappear at brevity=1

    • 2: Reference sections disappear at brevity=2

    • 3: Germ-level estimate tables disappear at brevity=3

    • 4: Everything but summary figures disappears at brevity=4

  • advanced_options (dict, optional) –

    A dictionary of advanced options for which the default values are usually are fine. Here are the possible keys of advanced_options:

    • connectedbool, optional

      Whether output HTML should assume an active internet connection. If True, then the resulting HTML file size will be reduced because it will link to web resources (e.g. CDN libraries) instead of embedding them.

    • cachefilestr, optional

      filename with cached workspace results

    • linlogPercentilefloat, optional

      Specifies the colorscale transition point for any logL or chi2 color box plots. The lower (100 - linlogPercentile) percentile of the expected chi2 distribution is shown in a linear grayscale, and the top linlogPercentile is shown on a logarithmic colored scale.

    • errgen_type: {“logG-logT”, “logTiG”, “logGTi”}

      The type of error generator to compute. Allowed values are:

      • ”logG-logT” : errgen = log(gate) - log(target_op)

      • ”logTiG” : errgen = log( dot(inv(target_op), gate) )

      • ”logGTi” : errgen = log( dot(gate, inv(target_op)) )

    • nmthresholdfloat, optional

      The threshold, in units of standard deviations, that triggers the usage of non-Markovian error bars. If None, then non-Markovian error bars are never computed.

    • 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.

    • resizablebool, optional

      Whether plots and tables are made with resize handles and can be resized within the report.

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

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

    • embed_figures: bool, optional

      Whether figures should be embedded in the generated report.

    • combine_robustbool, optional

      Whether robust estimates should automatically be combined with their non-robust counterpart when displayed in reports. (default is True).

    • confidence_interval_brevityint, optional

      Roughly specifies how many figures will have confidence intervals (when applicable). Defaults to ‘1’. Smaller values mean more tables will get confidence intervals (and reports will take longer to generate).

    • idt_basis_dictstuple, optional

      Tuple of (prepDict,measDict) pauli-basis dictionaries, which map between 1-qubit Pauli basis strings (e.g. ‘-X’ or ‘Y’) and tuples of gate names (e.g. (‘Gx’,’Gx’)). If given, idle tomography will be performed on the ‘Gi’ gate and included in the report.

    • idt_idle_oplabelLabel, optional

      The label identifying the idle gate (for use with idle tomography).

    • colorboxplot_bgcolorstr, optional

      Background color for the color box plots in this report. Can be common color names, e.g. “black”, or string RGB values, e.g. “rgb(255,128,0)”.

  • verbosity (int, optional) – How much detail to send to stdout.

Returns

Workspace – The workspace object used to create the report

pygsti.report.create_nqnoise_report(results, filename, title='auto', confidence_level=None, comm=None, ws=None, auto_open=False, link_to=None, brevity=0, advanced_options=None, verbosity=1)

Creates a report designed to display results containing for n-qubit noisy model estimates.

Such models are characterized by the fact that gates and SPAM objects may not have dense representations (or it may be very expensive to compute them) , and that these models are likely CloudNoiseModel objects or have similar structure.

Deprecated since version v0.9.9: create_nqnoise_report will be removed in the next major release of pyGSTi. It is replaced by construct_standard_report, which returns a Report object.

Parameters
  • results (Results) – An object which represents the set of results from one or more GST estimation runs, typically obtained from running run_long_sequence_gst() or run_stdpractice_gst(), OR a dictionary of such objects, representing multiple GST runs to be compared (typically all with different data sets). The keys of this dictionary are used to label different data sets that are selectable in the report.

  • filename (string, optional) – The output filename where the report file(s) will be saved. If None, then no output file is produced (but returned Workspace still caches all intermediate results).

  • title (string, optional) – The title of the report. “auto” causes a random title to be generated (which you may or may not like).

  • confidence_level (int, optional) – If not None, then the confidence level (between 0 and 100) used in the computation of confidence regions/intervals. If None, no confidence regions or intervals are computed.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.

  • ws (Workspace, optional) – The workspace used as a scratch space for performing the calculations and visualizations required for this report. If you’re creating multiple reports with similar tables, plots, etc., it may boost performance to use a single Workspace for all the report generation.

  • auto_open (bool, optional) – If True, automatically open the report in a web browser after it has been generated.

  • 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 create and include links to Latex, PDF, and Python pickle files, respectively. “tex” creates latex source files for tables; “pdf” renders PDFs of tables and plots ; “pkl” creates Python versions of plots (pickled python data) and tables (pickled pandas DataFrams).

  • brevity (int, optional) –

    Amount of detail to include in the report. Larger values mean smaller “more briefr” reports, which reduce generation time, load time, and disk space consumption. In particular:

    • 1: Plots showing per-sequences quantities disappear at brevity=1

    • 2: Reference sections disappear at brevity=2

    • 3: Germ-level estimate tables disappear at brevity=3

    • 4: Everything but summary figures disappears at brevity=4

  • advanced_options (dict, optional) –

    A dictionary of advanced options for which the default values are usually are fine. Here are the possible keys of advanced_options:

    • connectedbool, optional

      Whether output HTML should assume an active internet connection. If True, then the resulting HTML file size will be reduced because it will link to web resources (e.g. CDN libraries) instead of embedding them.

    • cachefilestr, optional

      filename with cached workspace results

    • linlogPercentilefloat, optional

      Specifies the colorscale transition point for any logL or chi2 color box plots. The lower (100 - linlogPercentile) percentile of the expected chi2 distribution is shown in a linear grayscale, and the top linlogPercentile is shown on a logarithmic colored scale.

    • nmthresholdfloat, optional

      The threshold, in units of standard deviations, that triggers the usage of non-Markovian error bars. If None, then non-Markovian error bars are never computed.

    • 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.

    • resizablebool, optional

      Whether plots and tables are made with resize handles and can be resized within the report.

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

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

    • combine_robustbool, optional

      Whether robust estimates should automatically be combined with their non-robust counterpart when displayed in reports. (default is True).

    • confidence_interval_brevityint, optional

      Roughly specifies how many figures will have confidence intervals (when applicable). Defaults to ‘1’. Smaller values mean more tables will get confidence intervals (and reports will take longer to generate).

    • colorboxplot_bgcolorstr, optional

      Background color for the color box plots in this report. Can be common color names, e.g. “black”, or string RGB values, e.g. “rgb(255,128,0)”.

  • verbosity (int, optional) – How much detail to send to stdout.

Returns

Workspace – The workspace object used to create the report

pygsti.report.create_report_notebook(results, filename, title='auto', confidence_level=None, auto_open=False, connected=False, verbosity=0)

Create a “report notebook”.

A Jupyter ipython notebook file which, when its cells are executed, will generate similar figures to those contained in an html report (via create_standard_report()).

A notebook report allows the user to interact more flexibly with the data underlying the figures, and to easily generate customized variants on the figures. As such, this type of report will be most useful for experts who want to tinker with the standard analysis presented in the static HTML or LaTeX format reports.

Deprecated since version v0.9.9: create_report_notebook will be removed in the next major release of pyGSTi. It is replaced by the Report.write_notebook

Parameters
  • results (Results) – An object which represents the set of results from one or more GST estimation runs, typically obtained from running run_long_sequence_gst() or run_stdpractice_gst(), OR a dictionary of such objects, representing multiple GST runs to be compared (typically all with different data sets). The keys of this dictionary are used to label different data sets that are selectable (via setting Python variables) in the report.

  • filename (string, optional) – The output filename where the report file(s) will be saved. Must end in “.ipynb”.

  • title (string, optional) – The title of the report. “auto” causes a random title to be generated (which you may or may not like).

  • confidence_level (int, optional) – If not None, then the confidence level (between 0 and 100) used in the computation of confidence regions/intervals. If None, no confidence regions or intervals are computed.

  • auto_open (bool, optional) – If True, automatically open the report in a web browser after it has been generated.

  • connected (bool, optional) – Whether output notebook should assume an active internet connection. If True, then the resulting file size will be reduced because it will link to web resources (e.g. CDN libraries) instead of embedding them.

  • verbosity (int, optional) – How much detail to send to stdout.

Returns

None

pygsti.report.find_std_clifford_compilation(model, verbosity=0)

Returns the standard Clifford compilation for model, if one exists. Otherwise returns None.

Parameters
  • model (Model) – The ideal (target) model of primitive gates.

  • verbosity (int, optional) – How much detail to send to stdout.

Returns

dict or None – The Clifford compilation dictionary (if one can be found).

pygsti.report.construct_standard_report(results, title='auto', confidence_level=None, comm=None, ws=None, advanced_options=None, verbosity=1)

Create a “standard” GST report, containing details about each estimate in results individually.

Parameters
  • results (Results) – An object which represents the set of results from one or more GST estimation runs, typically obtained from running run_long_sequence_gst() or run_stdpractice_gst(), OR a dictionary of such objects, representing multiple GST runs to be compared (typically all with different data sets). The keys of this dictionary are used to label different data sets that are selectable in the report.

  • title (string, optional) – The title of the report. “auto” causes a random title to be generated (which you may or may not like).

  • confidence_level (int, optional) – If not None, then the confidence level (between 0 and 100) used in the computation of confidence regions/intervals. If None, no confidence regions or intervals are computed.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.

  • ws (Workspace, optional) – The workspace used as a scratch space for performing the calculations and visualizations required for this report. If you’re creating multiple reports with similar tables, plots, etc., it may boost performance to use a single Workspace for all the report generation.

  • advanced_options (dict, optional) –

    A dictionary of advanced options for which the default values are usually are fine. Here are the possible keys of advanced_options:

    • linlogPercentilefloat, optional

      Specifies the colorscale transition point for any logL or chi2 color box plots. The lower (100 - linlogPercentile) percentile of the expected chi2 distribution is shown in a linear grayscale, and the top linlogPercentile is shown on a logarithmic colored scale.

    • nmthresholdfloat, optional

      The threshold, in units of standard deviations, that triggers the usage of non-Markovian error bars. If None, then non-Markovian error bars are never computed.

    • embed_figures: bool, optional

      Whether figures should be embedded in the generated report.

    • combine_robustbool, optional

      Whether robust estimates should automatically be combined with their non-robust counterpart when displayed in reports. (default is True).

    • idt_basis_dictstuple, optional

      Tuple of (prepDict,measDict) pauli-basis dictionaries, which map between 1-qubit Pauli basis strings (e.g. ‘-X’ or ‘Y’) and tuples of gate names (e.g. (‘Gx’,’Gx’)). If given, idle tomography will be performed on the ‘Gi’ gate and included in the report.

    • idt_idle_oplabelLabel, optional

      The label identifying the idle gate (for use with idle tomography).

  • verbosity (int, optional) – How much detail to send to stdout.

Returns

Workspace – The workspace object used to create the report

pygsti.report.construct_nqnoise_report(results, title='auto', confidence_level=None, comm=None, ws=None, advanced_options=None, verbosity=1)

Creates a report designed to display results containing for n-qubit noisy model estimates.

Such models are characterized by the fact that gates and SPAM objects may not have dense representations (or it may be very expensive to compute them) , and that these models are likely CloudNoiseModel objects or have similar structure.

Parameters
  • results (Results) – An object which represents the set of results from one or more GST estimation runs, typically obtained from running run_long_sequence_gst() or run_stdpractice_gst(), OR a dictionary of such objects, representing multiple GST runs to be compared (typically all with different data sets). The keys of this dictionary are used to label different data sets that are selectable in the report.

  • title (string, optional) – The title of the report. “auto” causes a random title to be generated (which you may or may not like).

  • confidence_level (int, optional) – If not None, then the confidence level (between 0 and 100) used in the computation of confidence regions/intervals. If None, no confidence regions or intervals are computed.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors.

  • ws (Workspace, optional) – The workspace used as a scratch space for performing the calculations and visualizations required for this report. If you’re creating multiple reports with similar tables, plots, etc., it may boost performance to use a single Workspace for all the report generation.

  • advanced_options (dict, optional) –

    A dictionary of advanced options for which the default values are usually are fine. Here are the possible keys of advanced_options:

    • linlogPercentilefloat, optional

      Specifies the colorscale transition point for any logL or chi2 color box plots. The lower (100 - linlogPercentile) percentile of the expected chi2 distribution is shown in a linear grayscale, and the top linlogPercentile is shown on a logarithmic colored scale.

    • nmthresholdfloat, optional

      The threshold, in units of standard deviations, that triggers the usage of non-Markovian error bars. If None, then non-Markovian error bars are never computed.

    • combine_robustbool, optional

      Whether robust estimates should automatically be combined with their non-robust counterpart when displayed in reports. (default is True).

    • confidence_interval_brevityint, optional

      Roughly specifies how many figures will have confidence intervals (when applicable). Defaults to ‘1’. Smaller values mean more tables will get confidence intervals (and reports will take longer to generate).

    • embed_figures: bool, optional

      Whether figures should be embedded in the generated report.

  • verbosity (int, optional) – How much detail to send to stdout.

Returns

class:Report : A constructed report object

pygsti.report.create_drift_report(results, title='auto', ws=None, verbosity=1)

Creates a Drift report.

Parameters
  • results (StabilityAnalysisResults) – The drift-analysis results to create the report from.

  • title (string, optional) – The title of the report. “auto” causes a random title to be generated (which you may or may not like).

  • ws (Workspace, optional) – The workspace used as a scratch space for performing the calculations and visualizations required for this report. If you’re creating multiple reports with similar tables, plots, etc., it may boost performance to use a single Workspace for all the report generation.

  • verbosity (int, optional) – How much detail to send to stdout.

Returns

Report (A constructed report object)

pygsti.report.blues
pygsti.report.empty_volumetric_plot(figsize=None, y_values=None, x_values=None, title=None, xlabel='Depth', ylabel='Width')

Creates an empty volumetric plot with just the axes set.

Parameters
  • figsize (tuple or None, optional) – The figure size.

  • y_values (list or None, optional) – The y-axis values, typically corresponding to circuit widths.

  • x_values (list or None, optional) – The x-axis values, typically corresponding to circuit depths.

  • title (string or None, optional) – Plot title

  • xlabel (string, optional) – x-axis label

  • ylabel (string, optional) – y-axis label.

Returns

fig, ax (matplolib fig and ax.)

pygsti.report._get_xy(data, y_values=None, x_values=None)
pygsti.report.volumetric_plot(data, y_values=None, x_values=None, title=None, fig=None, ax=None, cmap=my_cmap, color=None, flagQV=False, qv_threshold=None, figsize=(10, 10), scale=1.0, centerscale=1.0, linescale=1.0, pass_threshold=0, show_threshold=0)

Creates a volumetric benchmarking plot.

pygsti.report.volumetric_boundary_plot(data, y_values=None, x_values=None, boundary=None, threshold=0.5, missing_data_action='continue', monotonic=True, color='k', linewidth=4, linestyle='-', dashing=None, fig=None, ax=None, figsize=None, title=None, label=None)

Creates a volumetric benchmarking boundary plot, that displays boundary at which the given data drops below the specified threshold

pygsti.report.capability_region_plot(vbdataframe, metric='polarization', threshold=1 / _np.e, significance=0.05, figsize=(10, 10), scale=1.0, title=None, colors=None)

Creates a capability regions plot from a VBDataFrame. Default options creates plots like those shown in Fig. 3 of “Measuring the Capabilities of Quantum Computers” arXiv:2008.11294.

pygsti.report.volumetric_distribution_plot(vbdataframe, metric='polarization', threshold=1 / _np.e, hypothesis_test='standard', significance=0.05, figsize=(10, 10), scale={'min': 1.95, 'mean': 1, 'max': 0.13}, title=None, cmap=my_cmap)

Creates volumetric benchmarking plots that display the maximum, mean and minimum of a given figure-of-merit (by default, circuit polarization) as a function of circuit shape. This function can be used to create figures like those shown in Fig. 1 of “Measuring the Capabilities of Quantum Computers” arXiv:2008.11294.

Parameters
  • vbdataframe (VBDataFrame) – A VBDataFrame object containing the data to be plotted in a VB plot.

  • metric (string, optional) – The quantity to plot. Default is ‘polarization’ as used and defined in arXiv:2008.11294. The plot will show the maximum, mean, and minimum of this metric at each circuit shape.

  • threshold (float, optional) – The threshold for “success” for the figure-of-merit defined by metric. This threshold is used to compute the three “success” boundaries that are shown in the plot.

  • hypothesis_test (string, optional) –

    The type of statistical significance adjustment to apply to the boundaries. The options are - ‘standard’: this reproduces the method used and described in arXiv:2008.11294 (see the

    appendices for details). With this option, there will be a difference between the boundary for the minimum and maximum polarization only if there is statistically significant evidence in the data for this.

    • ’none’: no statistical significance adjustment: all three boundaries show the point at which

      relevant statistic (maximum, mean, minimum) drops below the threshold.

  • significance (float, optional) – The statistical significance in the hypothesis tests. Only used in hypothesis_test is not ‘none’.

  • figsize (tuple, optional) – The figure size

  • scale (dict, optional) – The scale for the three concentric squares, showing the maximum, mean and minimum.

  • title (sting, optional) – The figure title.

  • cmap (ColorMap, optional) – A matplotlib colormap.

Returns

fig, ax (matplolib fig and ax.)