pygsti.models.explicitmodel.ExplicitOpModel

Contents

pygsti.models.explicitmodel.ExplicitOpModel#

class 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: OpModel

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

An ExplicitOpModel 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 set_all_parameterizations(), which also gives a description of each parameterization type.

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

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

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

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

  • instrument_prefix (string, optional) – Key prefix for instruments, allowing the model to determining 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 probs() or 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.

Creates a new OpModel. Rarely used except from derived classes __init__ functions. :param state_space: The state space for this model. :type state_space: StateSpace :param basis: The basis used for the state space by dense operator representations. :type basis: Basis :param evotype: 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.

Parameters:
  • layer_rules (LayerRules) – The “layer rules” used for constructing operators for circuit layers. This functionality is essential to using this model to simulate circuits, and is typically supplied by derived classes.

  • simulator (ForwardSimulator or {"auto", "matrix", "map"}) – The forward simulator (or typ) that this model should use. “auto” tries to determine the best type automatically.

Methods

__init__(state_space[, basis, ...])

Creates a new OpModel. Rarely used except from derived classes __init__ functions. :param state_space: The state space for this model. :type state_space: StateSpace :param basis: The basis used for the state space by dense operator representations. :type basis: Basis :param evotype: 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. :type evotype: Evotype or str, optional :param layer_rules: The "layer rules" used for constructing operators for circuit layers. This functionality is essential to using this model to simulate circuits, and is typically supplied by derived classes. :type layer_rules: LayerRules :param simulator: The forward simulator (or typ) that this model should use. "auto" tries to determine the best type automatically. :type simulator: ForwardSimulator or {"auto", "matrix", "map"}.

add_mongodb_write_ops(write_ops, mongodb[, ...])

Accumulate write and update operations for writing this object to a MongoDB database.

all_objects()

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

bulk_circuit_outcomes(circuits[, ...])

Get all the possible outcome labels produced by simulating each of the circuits in this list of circuits.

bulk_expand_instruments_and_separate_povm(...)

Creates a list of dictionaries mapping from SeparatePOVMCircuit objects from expanding the instruments of this circuit.

bulk_probabilities(circuits[, clip_to, ...])

Construct a dictionary containing the probabilities for an entire list of circuits.

circuit_layer_operator(layerlbl[, typ])

Construct or retrieve the operation associated with a circuit layer.

circuit_operator(circuit)

Construct or retrieve the operation associated with a circuit.

circuit_outcomes(circuit)

Get all the possible outcome labels produced by simulating this circuit.

circuit_parameter_dependence(circuits[, ...])

Calculate the which model parameters each of the input circuits depends upon.

collect_parameters(params_to_collect[, ...])

Updates this model's parameters so that previously independent parameters are tied together.

complete_circuit(circuit[, ...])

Adds any implied preparation or measurement layers to circuit

complete_circuits(circuits[, ...])

Adds any implied preparation or measurement layers to list of circuits.

compute_clifford_symplectic_reps([...])

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

compute_nongauge_and_gauge_spaces([...])

TODO: docstring

compute_nongauge_projector([item_weights, ...])

Construct a projector onto the non-gauge parameter space.

compute_num_outcomes(circuit)

The number of outcomes of circuit, given by it's existing or implied POVM label.

convert_members_inplace(to_type[, ...])

Method for converting the parameterizations of modelmembers within this model to new ones in-place.

copy()

Copy this model.

create_modelmember_graph()

Generate a ModelMemberGraph for the model.

create_processor_spec([qudit_labels])

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

depolarize([op_noise, spam_noise, ...])

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

deriv_wrt_params()

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

diamonddist(other_model[, transform_mx, ...])

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

dump(f[, format])

Serializes and writes this object to a given output stream.

dumps([format])

Serializes this object and returns it as a string.

errorgen_coefficients([normalized_elem_gens])

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

expand_instruments_and_separate_povm(circuit)

Creates a dictionary of SeparatePOVMCircuit objects from expanding the instruments of this circuit.

fogi_contribution(op_label[, error_type, ...])

Computes a contribution to the FOGI error on a single gate.

fogi_errorgen_component_labels([...])

fogi_errorgen_components_array([...])

fogi_errorgen_vector([normalized_elem_gens])

Constructs a vector from all the error generator coefficients involved in the FOGI analysis of this model.

frobeniusdist(other_model[, transform_mx, ...])

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

from_mongodb(mongodb, doc_id, **kwargs)

Create and initialize an object from a MongoDB instance.

from_mongodb_doc(mongodb, collection_name, ...)

Create and initialize an object from a MongoDB instance and pre-loaded primary document.

from_nice_serialization(state)

Create and initialize an object from a "nice" serialization.

from_vector(v[, close])

Sets this Model's operations based on parameter values v.

increase_dimension(new_dimension)

Enlarge the dimension of this model.

is_equivalent(other_model[, rtol, atol])

Whether or not two Models are equivalent to each other.

is_similar(other_model[, rtol, atol])

Whether or not two Models have the same structure.

jtracedist(other_model[, transform_mx, ...])

Compute the Jamiolkowski trace distance between this model and other_model.

kick([absmag, bias, seed])

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

load(f[, format])

Load an object of this type, or a subclass of this type, from an input stream.

loads(s[, format])

Load an object of this type, or a subclass of this type, from a string.

print_info()

print_modelmembers()

Print a summary of all the members within this model.

print_parameters_by_op([max_depth])

probabilities(circuit[, outcomes, time])

Construct a dictionary containing the outcome probabilities of circuit.

randomize_with_unitary(scale[, seed, ...])

Create a new model with random unitary perturbations.

read(path[, format])

Read an object of this type, or a subclass of this type, from a file.

remove_from_mongodb(mongodb, doc_id[, ...])

Remove the documents corresponding to an instance of this class from a MongoDB database.

remove_me_from_mongodb(mongodb[, session, ...])

residuals(other_model[, transform_mx, ...])

Compute the weighted residuals between two models.

rotate([rotate, max_rotate, seed])

Apply a rotation uniformly or randomly to this model.

set_all_parameterizations(gate_type[, ...])

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

set_default_gauge_group_for_member_type(...)

Updates the default gauge group to the default value for the specified modelmember type.

set_fogi_errorgen_components_array(components)

set_parameter_bounds(index[, lower_bound, ...])

Set the bounds for a single model parameter.

set_parameter_label(index, label)

Set the label of a single model parameter.

set_parameter_value(index, val[, close])

This method allows for updating the value of a single model parameter at the specified parameter index.

set_parameter_values(indices, values[, close])

This method allows for updating the values of multiple model parameter at the specified parameter indices.

setup_fogi(initial_gauge_basis[, ...])

split_circuit(circuit[, erroron, ...])

Splits a circuit into prep_layer + op_layers + povm_layer components.

split_circuits(circuits[, erroron, ...])

Splits a circuit into prep_layer + op_layers + povm_layer components.

strdiff(other_model[, metric])

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

to_nice_serialization()

Serialize this object in a way that adheres to "niceness" rules of common text file formats.

to_vector()

Returns the model vectorized according to the optional parameters.

transform_inplace(s)

Gauge transform this model.

uncollect_parameters(param_to_uncollect)

Updates this model's parameters so that a common parameter becomes independent parameters.

write(path, **format_kwargs)

Writes this object to a file.

write_to_mongodb(mongodb[, session, ...])

Write this object to a MongoDB database.

Attributes

basis

The basis used to represent dense (super)operators of this model

collection_name

default_gauge_group

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

dim

The dimension of the model.

effects

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

evotype

Evolution type

hyperparams

Dictionary of hyperparameters associated with this model

num_elements

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

num_gauge_params

Return the number of gauge parameters in this model.

num_modeltest_params

The parameter count to use when testing this model against data.

num_nongauge_params

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

num_params

The number of free parameters when vectorizing this model.

param_interposer

parameter_bounds

Upper and lower bounds on the values of each parameter, utilized by optimization routines

parameter_labels

A list of labels, usually of the form (op_label, string_description) describing this model's parameters.

parameter_labels_pretty

The list of parameter labels but formatted in a nice way.

prep

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

primitive_instrument_labels

primitive_op_labels

primitive_povm_labels

primitive_prep_labels

sim

Forward simulator for this model

state_space

State space labels

add_mongodb_write_ops(write_ops, mongodb, overwrite_existing=False, **kwargs)#

Accumulate write and update operations for writing this object to a MongoDB database.

Similar to write_to_mongodb() but collects write operations instead of actually executing any write operations on the database. This function may be preferred to write_to_mongodb() when this object is being written as a part of a larger entity and executing write operations is saved until the end.

As in write_to_mongodb(), self.collection_name is the collection name and _id is either: 1) the ID used by a previous write or initial read-in, if one exists, OR 2) a new random bson.objectid.ObjectId

Parameters:
  • write_ops (WriteOpsByCollection) – An object that keeps track of pymongo write operations on a per-collection basis. This object accumulates write operations to be performed at some point in the future.

  • mongodb (pymongo.database.Database) – The MongoDB instance to write data to.

  • overwrite_existing (bool, optional) – Whether existing documents should be overwritten. The default of False causes a ValueError to be raised if a document with the given _id already exists and is different from what is being written.

  • **kwargs (dict) – Additional keyword arguments potentially used by subclass implementations. Any arguments allowed by a subclass’s _add_auxiliary_write_ops_and_update_doc method is allowed here.

Returns:

The identifier (_id value) of the main document that was written.

Return type:

bson.objectid.ObjectId

all_objects()#

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

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

bulk_circuit_outcomes(circuits, split_circuits=None, completed_circuits=None)#

Get all the possible outcome labels produced by simulating each of the circuits in this list of circuits.

Parameters:
  • circuits (list of Circuits) – list of Circuits to get outcomes of.

  • split_circuits (list of tuples, optional (default None)) – If specified, this is a list of tuples for each circuit corresponding to the splitting of the circuit into the prep label, spam-free circuit, and povm label. This is the same format produced by the :meth:split_circuit(s) method, and so this option can allow for accelerating this method when that has previously been run. When using this kwarg only one of this or the complete_circuits kwargs should be used.

  • completed_circuits (list of Circuits, optional (default None)) – If specified, this is a list of completed circuits with prep and povm labels included. This is the format produced by the :meth:complete_circuit(s) method, and this can be used to accelerate this method call when that has been previously run. Should not be used in conjunction with split_circuits.

Return type:

list of tuples corresponding to the possible outcomes for each circuit.

bulk_expand_instruments_and_separate_povm(circuits, observed_outcomes_list=None, split_circuits=None, completed_circuits=None)#

Creates a list of dictionaries mapping from 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.

This function works similarly to expand_instruments_and_separate_povm, except it operates on an entire list of circuits at once, and provides additional kwargs to accelerate computation.

Parameters:
  • circuit (Circuit) –

    The circuit to expand, using necessary details regarding the expansion from this model, including:

    • default SPAM layers

    • definitions of instrument-containing layers

    • expansions of individual instruments and POVMs

  • observed_outcomes_list (list of iterables, optional (default None)) – If specified a list of iterables over the subset of outcomes empirically observed for each circuit.

  • split_circuits (list of tuples, optional (default None)) – If specified, this is a list of tuples for each circuit corresponding to the splitting of the circuit into the prep label, spam-free circuit, and povm label. This is the same format produced by the :meth:split_circuit(s) method, and so this option can allow for accelerating this method when that has previously been run. When using this kwarg only one of this or the complete_circuits kwargs should be used.

  • completed_circuits (list of Circuits, optional (default None)) – If specified, this is a list of completed circuits with prep and povm labels included. This is the format produced by the :meth:complete_circuit(s) method, and this can be used to accelerate this method call when that has been previously run. Should not be used in conjunction with split_circuits.

Returns:

A list of dictionaries whose keys are SeparatePOVMCircuit objects and whose values are tuples of the outcome labels corresponding to each circuit, one per POVM effect held in the key.

Return type:

list of OrderedDicts

bulk_probabilities(circuits, clip_to=None, comm=None, mem_limit=None, smartc=None)#

Construct a dictionary containing the probabilities for an entire list of circuits.

Parameters:
  • circuits ((list of Circuits) or CircuitOutcomeProbabilityArrayLayout) – When a list, each element specifies a circuit to compute outcome probabilities for. A CircuitOutcomeProbabilityArrayLayout specifies the circuits along with an internal memory layout that reduces the time required by this function and can restrict the computed probabilities to those corresponding to only certain outcomes.

  • clip_to (2-tuple, optional) – (min,max) to clip return value if not None.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors. Distribution is performed over subtrees of evalTree (if it is split).

  • mem_limit (int, optional) – A rough memory limit in bytes which is used to determine processor allocation.

  • dataset (DataSet, optional) – If not None, restrict what is computed to only those probabilities corresponding to non-zero counts (observed outcomes) in this data set.

  • smartc (SmartCache, optional) – A cache object to cache & use previously cached values inside this function.

Returns:

probs – A dictionary such that probs[opstr] is an ordered dictionary of (outcome, p) tuples, where outcome is a tuple of labels and p is the corresponding probability.

Return type:

dictionary

circuit_layer_operator(layerlbl, typ='auto')#

Construct or retrieve the operation associated with a circuit layer.

Parameters:
  • layerlbl (Label) – The circuit-layer label to construct an operation for.

  • typ ({'op','prep','povm','auto'}) – The type of layer layerlbl refers to: ‘prep’ is for state preparation (only at the beginning of a circuit), ‘povm’ is for a measurement: a POVM or effect label (only at the end of a circuit), and ‘op’ is for all other “middle” circuit layers.

Return type:

LinearOperator or State or POVM

circuit_operator(circuit)#

Construct or retrieve the operation associated with a circuit.

Parameters:

circuit (Circuit) – The circuit to construct an operation for. This circuit should not contain any state preparation or measurement layers.

Return type:

LinearOperator

circuit_outcomes(circuit)#

Get all the possible outcome labels produced by simulating this circuit.

Parameters:

circuit (Circuit) – Circuit to get outcomes of.

Return type:

tuple corresponding to the possible outcomes for circuit.

circuit_parameter_dependence(circuits, return_param_circ_map=False)#

Calculate the which model parameters each of the input circuits depends upon. Return this result in the the form of a dictionary whose keys are circuits, and whose values are lists of parameters upon which that circuit depends. Optionally a reverse mapping from model parameters to the input circuits which depend on that parameter.

Note: This methods does not work with models using parameter interposers presently.

Parameters:
  • circuits (list of Circuits) – List of circuits to determine parameter dependence for.

  • return_param_circ_map (bool, optional (default False)) – A flag indicating whether to return a reverse mapping from parameters to circuits depending on those parameters.

Returns:

  • circuit_parameter_map (dict) – Dictionary with keys given by Circuits and values giving the list of model parameter indices upon which that circuit depends.

  • param_to_circuit_map (dict, optional) – Dictionary with keys given by model parameter indices, and values giving the list of input circuits dependent upon that parameter.

collect_parameters(params_to_collect, new_param_label=None)#

Updates this model’s parameters so that previously independent parameters are tied together.

The model’s parameterization is modified so that all of the parameters given by params_to_collect are replaced by a single parameter. The label of this single parameter may be given if desired.

Note that after this function is called the model’s parameter vector (i.e. the result of to_vector()) should be assumed to have a new format unrelated to the parameter vector before their adjustment. For example, you should not assume that un-modified parameters will retain their old indices.

Parameters:
  • params_to_collect (iterable) – A list or tuple of parameter labels describing the parameters to collect. These should be a subset of the elements of self.parameter_labels or of self.parameter_labels_pretty, or integer indices into the model’s parameter vector. If empty, no parameter adjustment is performed.

  • new_param_label (object, optional) – The label for the new common parameter. If None, then the parameter label of the first collected parameter is used.

Return type:

None

complete_circuit(circuit, prep_lbl_to_prepend=None, povm_lbl_to_append=None)#

Adds any implied preparation or measurement layers to circuit

Converts circuit into a “complete circuit”, where the first (0-th) layer is a state preparation and the final layer is a measurement (POVM) layer.

Parameters:
  • circuit (Circuit) – Circuit to act on.

  • prep_lbl_to_prepend (Label, optional (default None)) – Optional user specified prep label to prepend. If not specified will use the default value as given by :meth:_default_primitive_prep_layer_lbl. If the circuit already has a prep label this argument will be ignored.

  • povm_lbl_to_append (Label, optional (default None)) – Optional user specified prep label to prepend. If not specified will use the default value as given by :meth:_default_primitive_prep_layer_lbl. If the circuit already has a prep label this argument will be ignored.

Returns:

Possibly the same object as circuit, if no additions are needed.

Return type:

Circuit

complete_circuits(circuits, prep_lbl_to_prepend=None, povm_lbl_to_append=None, return_split=False)#

Adds any implied preparation or measurement layers to list of circuits.

Converts circuit into a “complete circuit”, where the first (0-th) layer is a state preparation and the final layer is a measurement (POVM) layer.

Parameters:
  • circuits (list of Circuit) – List of Circuit objects to act on.

  • prep_lbl_to_prepend (Label, optional (default None)) – Optional user specified prep label to prepend. If not specified will use the default value as given by :meth:_default_primitive_prep_layer_lbl. If the circuit already has a prep label this argument will be ignored.

  • povm_lbl_to_append (Label, optional (default None)) – Optional user specified povm label to prepend. If not specified will use the default value as given by :meth:_default_primitive_prep_layer_lbl. If the circuit already has a povm label this argument will be ignored.

  • return_split (bool, optional (default False)) – If True we additionally return a list of tuples of the form: (prep_label, no_spam_circuit, povm_label) for each circuit. This is of the same format returned by :meth:split_circuits when using the kwarg combination: erroron=(‘prep’, ‘povm’), split_prep=True, split_povm=True

Returns:

Possibly the same object as circuit, if no additions are needed.

Return type:

Circuit

compute_clifford_symplectic_reps(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:

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.

Return type:

dict

compute_nongauge_and_gauge_spaces(item_weights=None, non_gauge_mix_mx=None)#

TODO: docstring

compute_nongauge_projector(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” which 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:

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.

Return type:

numpy array

compute_num_outcomes(circuit)#

The number of outcomes of circuit, given by it’s existing or implied POVM label.

Parameters:

circuit (Circuit) – The circuit to simplify

Return type:

int

convert_members_inplace(to_type, categories_to_convert='all', labels_to_convert='all', ideal_model=None, flatten_structure=False, set_default_gauge_group=False, cptp_truncation_tol=1e-07, spam_cp_penalty=1e-07)#

Method for converting the parameterizations of modelmembers within this model to new ones in-place.

Parameters:
  • to_type (str) – String specifier for the parameterization type to convert to.

  • categories_to_convert (str or list of str, optional (default 'all')) – Categories of modelmembers to perform conversion on. Allowed options are: ‘all’, ‘ops’ or ‘operations’ (these two are aliases for the same option), ‘instruments’, ‘povms’ or ‘preps’.

  • labels_to_convert (str or list of Label, optional (default ‘all’)) –

    A string specifier, or list of Label objects, specifying the set

    of objects (state preparations, operations, instruments, etc.) within the model to apply the conversion to.

    ideal_modelModel, optional (default None)

    A model containing modelmembers instantiated such that they all correspond to the ideal actions of the given gate set elements. It is recommended that this be specified when converting to an error-generator-based parameterization.

  • flatten_structure (bool, optional (default False)) – When False, the sub-members of composed and embedded operations are separately converted, leaving the original modelmember structure unchanged. When True, composed and embedded operations are “flattened” into a single modelmember parameterized according to the requested to_type.

  • set_default_gauge_group (bool, optional (default False)) – A flag specifying whether the default gauge group for the model should be updated to the default value associated with the specified value of to_type. See set_default_gauge_group_for_member_type for more on these default gauge groups.

  • cptp_truncation_tol (float, optional (default 1e-7)) – Tolerance term used to enforce the CPTP constraint on gates when moving between different parameterizations.

  • spam_cp_penalty (float, optional (default 1e-7)) – Penalty term used to enforce the CP constraint on SPAM when moving between different parameterizations.

copy()#

Copy this model.

Returns:

a (deep) copy of this model.

Return type:

Model

create_modelmember_graph()#

Generate a ModelMemberGraph for the model.

Returns:

A directed graph capturing dependencies among model members

Return type:

ModelMemberGraph

create_processor_spec(qudit_labels='auto')#

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

Currently this only works for models on qudits.

Parameters:

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

Return type:

QuditProcessorSpec or QubitProcessorSpec

depolarize(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 operations (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:

the depolarized Model

Return type:

Model

deriv_wrt_params()#

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:

2D array of derivatives.

Return type:

numpy array

diamonddist(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.

Return type:

float

dump(f, format='json', **format_kwargs)#

Serializes and writes this object to a given output stream.

Parameters:
  • f (file-like) – A writable output stream.

  • format ({'json', 'repr'}) – The format to write.

  • format_kwargs (dict, optional) – Additional arguments specific to the format being used. For example, the JSON format accepts indent as an argument because json.dump does.

Return type:

None

dumps(format='json', **format_kwargs)#

Serializes this object and returns it as a string.

Parameters:
  • format ({'json', 'repr'}) – The format to write.

  • format_kwargs (dict, optional) – Additional arguments specific to the format being used. For example, the JSON format accepts indent as an argument because json.dump does.

Return type:

str

errorgen_coefficients(normalized_elem_gens=True)#

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

expand_instruments_and_separate_povm(circuit, 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:
  • circuit (Circuit) –

    The circuit to expand, using necessary details regarding the expansion from this model, including:

    • default SPAM layers

    • definitions of instrument-containing layers

    • expansions of individual instruments and POVMs

  • observed_outcomes (iterable, optional (default None)) – If specified an iterable over the subset of outcomes empirically observed for this circuit.

Returns:

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.

Return type:

OrderedDict

fogi_contribution(op_label, error_type='H', intrinsic_or_relational='intrinsic', target='all', hessian_for_errorbars=None)#

Computes a contribution to the FOGI error on a single gate.

This method is used when partitioning the (FOGI) error on a gate in various ways, based on the error type, whether the error is intrinsic or relational, and the upon the error support.

Parameters:
  • op_label (Label) – The operation to compute a contribution for.

  • error_type ({'H', 'S', 'fogi_total_error', 'fogi_infidelity'}) – The type of errors to include in the partition. ‘H’ means Hamiltonian and ‘S’ means Pauli stochastic. There are two options for including both H and S errors: ‘fogi_total_error’ adds the Hamiltonian errors linearly with the Pauli tochastic errors, similar to the diamond distance; ‘fogi_infidelity’ adds the Hamiltonian errors in quadrature to the linear sum of Pauli stochastic errors, similar to the entanglement or average gate infidelity.

  • intrinsic_or_relational ({"intrinsic", "relational", "all"}) – Restrict to intrinsic or relational errors (or not, using “all”).

  • target (tuple or "all") – A tuple of state space (qubit) labels to restrict to, e.g., (‘Q0’,’Q1’). Note that including multiple labels selects only those quantities that target all the labels. The special “all” value includes quantities on all targets (no restriction).

  • hessian_for_errorbars (numpy.ndarray, optional) – If not None, a hessian matrix for this model (with shape (Np, Np) where Np == self.num_params, the number of model parameters) that is used to compute and return 1-sigma error bars.

Returns:

  • value (float) – The value of the requested contribution.

  • errorbar (float) – The 1-sigma error bar, returned only if hessian_for_errorbars is given.

fogi_errorgen_vector(normalized_elem_gens=False)#

Constructs a vector from all the error generator coefficients involved in the FOGI analysis of this model.

Parameters:

normalized_elem_gens (bool, optional) – Whether or not coefficients correspond to elementary error generators constructed from normalized Pauli matrices or not.

Return type:

numpy.ndarray

frobeniusdist(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.

Return type:

float

classmethod from_mongodb(mongodb, doc_id, **kwargs)#

Create and initialize an object from a MongoDB instance.

Parameters:
  • mongodb (pymongo.database.Database) – The MongoDB instance to load from.

  • doc_id (bson.objecctid.ObjectId or dict) – The object ID or filter used to find a single object ID within the database. This document is loaded from the collection given by the collection_name attribute of this class.

  • **kwargs (dict) – Additional keyword arguments potentially used by subclass implementations. Any arguments allowed by a subclass’s _create_obj_from_doc_and_mongodb method is allowed here.

Return type:

object

classmethod from_mongodb_doc(mongodb, collection_name, doc, **kwargs)#

Create and initialize an object from a MongoDB instance and pre-loaded primary document.

Parameters:
  • mongodb (pymongo.database.Database) – The MongoDB instance to load from.

  • collection_name (str) – The collection name within mongodb that doc was loaded from. This is needed for the sole purpose of setting the created (returned) object’s database “coordinates”.

  • doc (dict) – The already-retrieved main document for the object being loaded. This takes the place of giving an identifier for this object.

  • **kwargs (dict) – Additional keyword arguments potentially used by subclass implementations. Any arguments allowed by a subclass’s _create_obj_from_doc_and_mongodb method is allowed here.

Return type:

object

classmethod from_nice_serialization(state)#

Create and initialize an object from a “nice” serialization.

A “nice” serialization here means one created by a prior call to to_nice_serialization using this class or a subclass of it. Nice serializations adhere to additional rules (e.g. that dictionary keys must be strings) that make them amenable to common file formats (e.g. JSON).

The state argument is typically a dictionary containing ‘module’ and ‘state’ keys specifying the type of object that should be created. This type must be this class or a subclass of it.

Parameters:

state (object) – An object, usually a dictionary, representing the object to de-serialize.

Return type:

object

from_vector(v, close=False)#

Sets this Model’s operations based on parameter values v.

The inverse of to_vector.

Parameters:
  • v (numpy.ndarray) – A vector of parameters, with length equal to self.num_params.

  • close (bool, optional) – Set to True if v is close to the current parameter vector. This can make some operations more efficient.

Return type:

None

increase_dimension(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:

the increased-dimension Model

Return type:

Model

is_equivalent(other_model, rtol=1e-05, atol=1e-08)#

Whether or not two Models are equivalent to each other.

If True, then the two models have the same structure and the same parameters, so they are in all ways alike and will compute the same probabilities.

Parameters:
  • other_model (Model) – The model to compare against

  • rtol (float, optional) – Relative tolerance used to check if floating point (including parameter) values are “equal”, as passed to numpy.allclose.

  • atol (float, optional) – Absolute tolerance used to check if floating point (including parameter) values are “equal”, as passed to numpy.allclose.

Return type:

bool

is_similar(other_model, rtol=1e-05, atol=1e-08)#

Whether or not two Models have the same structure.

If True, then the two models are the same except for, perhaps, being at different parameter-space points (i.e. having different parameter vectors). Similar models, A and B, can be made equivalent (see is_equivalent()) by calling modelA.from_vector(modelB.to_vector()).

Parameters:
  • other_model (Model) – The model to compare against

  • rtol (float, optional) – Relative tolerance used to check if floating point values are “equal”, as passed to numpy.allclose.

  • atol (float, optional) – Absolute tolerance used to check if floating point values are “equal”, as passed to numpy.allclose.

Return type:

bool

jtracedist(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.

Return type:

float

kick(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:

the kicked model.

Return type:

Model

classmethod load(f, format='json')#

Load an object of this type, or a subclass of this type, from an input stream.

Parameters:
  • f (file-like) – An open input stream to read from.

  • format ({'json'}) – The format of the input stream data.

Return type:

NicelySerializable

classmethod loads(s, format='json')#

Load an object of this type, or a subclass of this type, from a string.

Parameters:
  • s (str) – The serialized object.

  • format ({'json'}) – The format of the string data.

Return type:

NicelySerializable

print_modelmembers()#

Print a summary of all the members within this model.

probabilities(circuit, outcomes=None, time=None)#

Construct a dictionary containing the outcome probabilities of circuit.

Parameters:
  • circuit (Circuit or tuple of operation labels) – The sequence of operation labels specifying the circuit.

  • outcomes (list or tuple) – A sequence of outcomes, which can themselves be either tuples (to include intermediate measurements) or simple strings, e.g. ‘010’.

  • time (float, optional) – The start time at which circuit is evaluated.

Returns:

probs – A dictionary with keys equal to outcome labels and values equal to probabilities.

Return type:

OutcomeLabelDict

randomize_with_unitary(scale, seed=None, rand_state=None, transform_spam=False, param_preserving=False)#

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.

  • param_preserving (bool) –

    If False, then all members of the returned model will have “full” parameterization.

    If True, then we use ComposedOp (and ComposedState and ComposedPOVM) to define a model with unitarily-transformed members while retaining the parameterization of self.

Returns:

the randomized Model

Return type:

Model

classmethod read(path, format=None)#

Read an object of this type, or a subclass of this type, from a file.

Parameters:
  • path (str or Path or file-like) – The filename to open or an already open input stream.

  • format ({'json', None}) – The format of the file. If None this is determined automatically by the filename extension of a given path.

Return type:

NicelySerializable

classmethod remove_from_mongodb(mongodb, doc_id, collection_name=None, session=None, recursive='default')#

Remove the documents corresponding to an instance of this class from a MongoDB database.

Parameters:
  • mongodb (pymongo.database.Database) – The MongoDB instance to remove documents from.

  • doc_id (bson.objectid.ObjectId) – The identifier of the root document stored in the database.

  • collection_name (str, optional) – the MongoDB collection within mongodb where the main document resides. If None, then <this_class>.collection_name is used (which is usually what you want).

  • session (pymongo.client_session.ClientSession, optional) – MongoDB session object to use when interacting with the MongoDB database. This can be used to implement transactions among other things.

  • recursive (RecursiveRemovalSpecification, optional) – An object that filters the type of documents that are removed. Used when working with inter-related experiment designs, data, and results objects to only remove the types of documents you know aren’t being shared with other documents.

Return type:

None

residuals(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.

rotate(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:

the rotated Model

Return type:

Model

set_all_parameterizations(gate_type, prep_type='auto', povm_type='auto', instrument_type='auto', ideal_model=None, cptp_truncation_tol=1e-06, spam_cp_penalty=1e-07)#

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

  • ideal_model (Model, optional) – This may specify an ideal model of unitary gates and pure state vectors to be used as the ideal operation of each gate/SPAM operation, which is particularly useful as target for CPTP-based conversions.

  • cptp_truncation_tol (float, optional (default 1e-6)) – Tolerance used for conversion to CPTP parameterizations. When converting to CPTP models negative eigenvalues of the choi matrix representation of a superoperator are truncated, which can result in a change in the PTM for that operator. This tolerance indicates the maximum amount of truncation induced deviation from the original operations (measured by frobenius distance) we’re willing to accept without marking the conversion as failed.

  • spam_cp_penalty (float, optional (default 0.5)) – Converting SPAM operations to an error generator representation may introduce trivial gauge degrees of freedom. These gauge degrees of freedom are called trivial because they quite literally do not change the dense representation (i.e. Hilbert-Schmidt vectors) at all. Despite being trivial, error generators along this trivial gauge orbit may be non-CP, so this cptp penalty is used to favor channels within this gauge orbit which are CPTP.

Return type:

None

set_default_gauge_group_for_member_type(member_type)#

Updates the default gauge group to the default value for the specified modelmember type.

Parameters:

member_type (str) –

A string specifier for the modelmember type used to select the gauge group type. Mapping is the following:

  • ’full’ -> FullGaugeGroup

  • ’full TP’, ‘TP’, TPGaugeGroup

  • ’CPTP’ or Anything that is a valid lindblad type -> UnitaryGaugeGroup

  • Otherwise -> TrivialGaugeGroup

set_parameter_bounds(index, lower_bound=-inf, upper_bound=inf)#

Set the bounds for a single model parameter.

These limit the values the parameter can have during an optimization of the model.

Parameters:
  • index (int) – The index of the parameter whose bounds should be set.

  • lower_bound (float, optional) – The lower and upper bounds for the parameter. Can be set to the special numpy.inf (or -numpy.inf) values to effectively have no bound.

  • upper_bound (float, optional) – The lower and upper bounds for the parameter. Can be set to the special numpy.inf (or -numpy.inf) values to effectively have no bound.

Return type:

None

set_parameter_label(index, label)#

Set the label of a single model parameter.

Parameters:
  • index (int) – The index of the parameter whose label should be set.

  • label (object) – An object that serves to label this parameter. Often a string.

Return type:

None

set_parameter_value(index, val, close=False)#

This method allows for updating the value of a single model parameter at the specified parameter index.

Parameters:
  • index (int or tuple) – Index of the parameter value in the model’s parameter vector to update. If a tuple this instead indexes by the corresponding parameter label.

  • val (float) – Updated parameter value.

  • close (bool, optional) – Set to True if val is close to the current parameter vector. This can make some operations more efficient.

Return type:

None

set_parameter_values(indices, values, close=False)#

This method allows for updating the values of multiple model parameter at the specified parameter indices.

Parameters:
  • indices (list of ints or tuples) – Indices of the parameter values in the model’s parameter vector to update. If tuples this instead indexes by the corresponding parameter label. Mixing integer indices and parameter label tuples is not supported. Note: In the event that the parameter labels vector for this model contains duplicates the update may only apply to the first instance.

  • values (list or tuple of floats) – Updated parameter values.

  • close (bool, optional) – Set to True if values are close to the current parameter vector. This can make some operations more efficient.

Return type:

None

split_circuit(circuit, erroron=('prep', 'povm'), split_prep=True, split_povm=True)#

Splits a circuit into prep_layer + op_layers + povm_layer components.

If circuit does not contain a prep label or a povm label a default label is returned if one exists.

Parameters:
  • circuit (Circuit) – A circuit, possibly beginning with a state preparation label and ending with a povm label.

  • erroron (tuple of {'prep','povm'}) – A ValueError is raised if a preparation or povm label cannot be resolved when ‘prep’ or ‘povm’ is included in ‘erroron’. Otherwise None is returned in place of unresolvable labels. An exception is when this model has no preps or povms, in which case None is always returned and errors are never raised, since in this case one usually doesn’t expect to use the Model to compute probabilities (e.g. in germ selection).

  • split_prep (bool, optional) – Whether to split off the state prep and return it as prep_label. If False, then the returned preparation label is always None, and is not removed from ops_only_circuit.

  • split_povm (bool, optional) – Whether to split off the POVM and return it as povm_label. If False, then the returned POVM label is always None, and is not removed from ops_only_circuit.

Returns:

  • prep_label (Label or None)

  • ops_only_circuit (Circuit)

  • povm_label (Label or None)

split_circuits(circuits, erroron=('prep', 'povm'), split_prep=True, split_povm=True)#

Splits a circuit into prep_layer + op_layers + povm_layer components.

If circuit does not contain a prep label or a povm label a default label is returned if one exists.

Parameters:
  • circuit (list of Circuit) – A list of circuits, possibly beginning with a state preparation label and ending with a povm label.

  • erroron (tuple of {'prep','povm'}) – A ValueError is raised if a preparation or povm label cannot be resolved when ‘prep’ or ‘povm’ is included in ‘erroron’. Otherwise None is returned in place of unresolvable labels. An exception is when this model has no preps or povms, in which case None is always returned and errors are never raised, since in this case one usually doesn’t expect to use the Model to compute probabilities (e.g. in germ selection).

  • split_prep (bool, optional) – Whether to split off the state prep and return it as prep_label. If False, then the returned preparation label is always None, and is not removed from ops_only_circuit.

  • split_povm (bool, optional) – Whether to split off the POVM and return it as povm_label. If False, then the returned POVM label is always None, and is not removed from ops_only_circuit.

Returns:

  • list of tuples containing

  • prep_label (Label or None)

  • ops_only_circuit (Circuit)

  • povm_label (Label or None)

strdiff(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.

Return type:

str

to_nice_serialization()#

Serialize this object in a way that adheres to “niceness” rules of common text file formats.

Returns:

Usually a dictionary representing the serialized object, but may also be another native Python type, e.g. a string or list.

Return type:

object

to_vector()#

Returns the model vectorized according to the optional parameters.

Returns:

The vectorized model parameters.

Return type:

numpy array

transform_inplace(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.

Return type:

None

uncollect_parameters(param_to_uncollect)#

Updates this model’s parameters so that a common parameter becomes independent parameters.

The model’s parameterization is modified so that each usage of the given parameter in the model’s parameterized operations is promoted to being a new independent parameter. The labels of the new parameters are set by the operations.

Note that after this function is called the model’s parameter vector (i.e. the result of to_vector()) should be assumed to have a new format unrelated to the parameter vector before their adjustment. For example, you should not assume that un-modified parameters will retain their old indices.

Parameters:

param_to_uncollect (int or object) – A parameter label specifying the parameter to “uncollect”. This should be an element of self.parameter_labels or self.parameter_labels_pretty, or it may be an integer index into the model’s parameter vector.

Return type:

None

write(path, **format_kwargs)#

Writes this object to a file.

Parameters:
  • path (str or Path) – The name of the file that is written.

  • format_kwargs (dict, optional) – Additional arguments specific to the format being used. For example, the JSON format accepts indent as an argument because json.dump does.

Return type:

None

write_to_mongodb(mongodb, session=None, overwrite_existing=False, **kwargs)#

Write this object to a MongoDB database.

The collection name used is self.collection_name, and the _id is either: 1) the ID used by a previous write or initial read-in, if one exists, OR 2) a new random bson.objectid.ObjectId

Parameters:
  • mongodb (pymongo.database.Database) – The MongoDB instance to write data to.

  • session (pymongo.client_session.ClientSession, optional) – MongoDB session object to use when interacting with the MongoDB database. This can be used to implement transactions among other things.

  • overwrite_existing (bool, optional) – Whether existing documents should be overwritten. The default of False causes a ValueError to be raised if a document with the given _id already exists and is different from what is being written.

  • **kwargs (dict) – Additional keyword arguments potentially used by subclass implementations. Any arguments allowed by a subclass’s _add_auxiliary_write_ops_and_update_doc method is allowed here.

Returns:

The identifier (_id value) of the main document that was written.

Return type:

bson.objectid.ObjectId

property basis#

The basis used to represent dense (super)operators of this model

Return type:

Basis

property default_gauge_group#

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

Return type:

GaugeGroup

property dim#

The dimension of the model.

This equals d when the gate (or, more generally, circuit-layer) matrices would have shape d x d and spam vectors would have shape d x 1 (if they were computed).

Returns:

model dimension

Return type:

int

property effects#

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

If not, a ValueError is raised.

Return type:

list of POVMEffects

property evotype#

Evolution type

Return type:

str

property hyperparams#

Dictionary of hyperparameters associated with this model

Return type:

dict

property num_elements#

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:

the number of model elements.

Return type:

int

property num_gauge_params#

Return the number of gauge parameters in this model.

Returns:

the number of gauge model parameters.

Return type:

int

property num_modeltest_params: int#

The parameter count to use when testing this model against data.

Often times, this is the same as num_params(), but there are times when it can convenient or necessary to use a parameter count different than the actual number of parameters in this model.

property num_nongauge_params#

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

Returns:

the number of non-gauge model parameters.

Return type:

int

property num_params#

The number of free parameters when vectorizing this model.

Returns:

the number of model parameters.

Return type:

int

property parameter_bounds#

Upper and lower bounds on the values of each parameter, utilized by optimization routines

property parameter_labels#

A list of labels, usually of the form (op_label, string_description) describing this model’s parameters.

property parameter_labels_pretty#

The list of parameter labels but formatted in a nice way.

In particular, tuples where the first element is an op label are made into a single string beginning with the string representation of the operation.

property prep#

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

If not, a ValueError is raised.

Return type:

State

property sim#

Forward simulator for this model

property state_space#

State space labels

Return type:

StateSpaceLabels