pygsti.modelmembers.states

Sub-package holding model state preparation objects.

Submodules

Package Contents

Classes

ComposedState

TODO: update docstring

ComputationalBasisState

A static state vector that is tensor product of 1-qubit Z-eigenstates.

CPTPState

TODO: update docstring

FullPureState

A "fully parameterized" state vector where each element is an independent parameter.

FullState

A "fully parameterized" state vector where each element is an independent parameter.

State

TODO: update docstring

StaticPureState

A pure state vector that is completely fixed, or "static" (i.e. that posesses no parameters).

StaticState

A state vector that is completely fixed, or "static" (i.e. that posesses no parameters).

TensorProductState

A state vector that is a tensor-product of other state vectors.

TPState

A fixed-unit-trace state vector.

Functions

create_from_pure_vector(pure_vector, state_type, basis='pp', evotype='default', state_space=None, on_construction_error='warn')

TODO: docstring -- create a State from a state vector

create_from_dmvec(superket_vector, state_type, basis='pp', evotype='default', state_space=None)

state_type_from_op_type(op_type)

Decode an op type into an appropriate state type.

convert(state, to_type, basis, extra=None)

TODO: update docstring

finite_difference_deriv_wrt_params(state, wrt_filter=None, eps=1e-07)

Computes a finite-difference Jacobian for a State object.

check_deriv_wrt_params(state, deriv_to_check=None, wrt_filter=None, eps=1e-07)

Checks the deriv_wrt_params method of a State object.

optimize_state(vec_to_optimize, target_vec)

Optimize the parameters of vec_to_optimize.

class pygsti.modelmembers.states.ComposedState(static_state, errormap)

Bases: pygsti.modelmembers.states.state.State

TODO: update docstring A Lindblad-parameterized State (that is also expandable into terms).

Parameters
  • pure_vec (numpy array or State) –

    An array or State in the full density-matrix space (this vector will have dimension 4 in the case of a single qubit) which represents a pure-state preparation or projection. This is used as the “base” preparation or projection that is followed or preceded by, respectively, the parameterized Lindblad-form error generator. (This argument is not copied if it is a State. A numpy array

    is converted to a new StaticState.)

  • errormap (MapOperator) – The error generator action and parameterization, encapsulated in a gate object. Usually a LindbladOp or ComposedOp object. (This argument is not copied, to allow ComposedStates to share error generator parameters with other gates and spam vectors.)

classmethod _from_memoized_dict(cls, mm_dict, serial_memo)

For subclasses to implement. Submember-existence checks are performed, and the gpindices of the return value is set, by the non-underscored :method:`from_memoized_dict` implemented in this class.

_update_rep(self)
submembers(self)

Get the ModelMember-derived objects contained in this one.

Returns

list

set_gpindices(self, gpindices, parent, memo=None)

Set the parent and indices into the parent’s parameter vector that are used by this ModelMember object.

Parameters
  • gpindices (slice or integer ndarray) – The indices of this objects parameters in its parent’s array.

  • parent (Model or ModelMember) – The parent whose parameter array gpindices references.

  • memo (dict, optional) – A memo dict used to avoid circular references.

Returns

None

to_dense(self, on_space='minimal', scratch=None)

Return this state vector as a (dense) numpy array.

The memory in scratch maybe used when it is not-None.

Parameters
  • on_space ({'minimal', 'Hilbert', 'HilbertSchmidt'}) – The space that the returned dense operation acts upon. For unitary matrices and bra/ket vectors, use ‘Hilbert’. For superoperator matrices and super-bra/super-ket vectors use ‘HilbertSchmidt’. ‘minimal’ means that ‘Hilbert’ is used if possible given this operator’s evolution type, and otherwise ‘HilbertSchmidt’ is used.

  • scratch (numpy.ndarray, optional) – scratch space available for use.

Returns

numpy.ndarray

taylor_order_terms(self, order, max_polynomial_vars=100, return_coeff_polys=False)

Get the order-th order Taylor-expansion terms of this state vector.

This function either constructs or returns a cached list of the terms at the given order. Each term is “rank-1”, meaning that it is a state preparation followed by or POVM effect preceded by actions on a density matrix rho of the form:

rho -> A rho B

The coefficients of these terms are typically polynomials of the State’s parameters, where the polynomial’s variable indices index the global parameters of the State’s parent (usually a Model) , not the State’s local parameter array (i.e. that returned from to_vector).

Parameters
  • order (int) – The order of terms to get.

  • max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.

  • return_coeff_polys (bool) – Whether a parallel list of locally-indexed (using variable indices corresponding to this object’s parameters rather than its parent’s) polynomial coefficients should be returned as well.

Returns

  • terms (list) – A list of RankOneTerm objects.

  • coefficients (list) – Only present when return_coeff_polys == True. A list of compact polynomial objects, meaning that each element is a (vtape,ctape) 2-tuple formed by concatenating together the output of :method:`Polynomial.compact`.

taylor_order_terms_above_mag(self, order, max_polynomial_vars, min_term_mag)

Get the order-th order Taylor-expansion terms of this state vector that have magnitude above min_term_mag.

This function constructs the terms at the given order which have a magnitude (given by the absolute value of their coefficient) that is greater than or equal to min_term_mag. It calls :method:`taylor_order_terms` internally, so that all the terms at order order are typically cached for future calls.

Parameters
  • order (int) – The order of terms to get.

  • max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.

  • min_term_mag (float) – the minimum term magnitude.

Returns

list

property total_term_magnitude(self)

Get the total (sum) of the magnitudes of all this state vector’s terms.

The magnitude of a term is the absolute value of its coefficient, so this function returns the number you’d get from summing up the absolute-coefficients of all the Taylor terms (at all orders!) you get from expanding this state vector in a Taylor series.

Returns

float

property total_term_magnitude_deriv(self)

The derivative of the sum of all this state vector’s terms.

Get the derivative of the total (sum) of the magnitudes of all this state vector’s terms with respect to the operators (local) parameters.

Returns

numpy array – An array of length self.num_params

deriv_wrt_params(self, wrt_filter=None)

The element-wise derivative this state vector.

Construct a matrix whose columns are the derivatives of the state vector with respect to a single param. Thus, each column is of length dimension and there is one column per state vector parameter.

Parameters

wrt_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)

Returns

numpy array – Array of derivatives, shape == (dimension, num_params)

hessian_wrt_params(self, wrt_filter1=None, wrt_filter2=None)

Construct the Hessian of this state vector with respect to its parameters.

This function returns a tensor whose first axis corresponds to the flattened operation matrix and whose 2nd and 3rd axes correspond to the parameters that are differentiated with respect to.

Parameters
  • wrt_filter1 (list or numpy.ndarray) – List of parameter indices to take 1st derivatives with respect to. (None means to use all the this operation’s parameters.)

  • wrt_filter2 (list or numpy.ndarray) – List of parameter indices to take 2nd derivatives with respect to. (None means to use all the this operation’s parameters.)

Returns

numpy array – Hessian with shape (dimension, num_params1, num_params2)

property parameter_labels(self)

An array of labels (usually strings) describing this model member’s parameters.

property num_params(self)

Get the number of independent parameters which specify this state vector.

Returns

int – the number of independent parameters.

to_vector(self)

Extract a vector of the underlying gate parameters from this gate.

Returns

numpy array – a 1D numpy array with length == num_params().

from_vector(self, v, close=False, dirty_value=True)

Initialize the state vector using a 1D array of parameters.

Parameters
  • v (numpy array) – The 1D vector of state vector parameters. Length must == num_params()

  • close (bool, optional) – Whether v is close to this state vector’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.

  • dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.

Returns

None

transform_inplace(self, s)

Update state (column) vector V as inv(s) * V or s^T * V for preparation or effect state vectors, respectively.

Note that this is equivalent to state preparation vectors getting mapped: rho -> inv(s) * rho and the transpose of effect vectors being mapped as E^T -> E^T * s.

Generally, the transform function updates the parameters of the state vector such that the resulting vector is altered as described above. If such an update cannot be done (because the gate parameters do not allow for it), ValueError is raised.

Parameters

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

Returns

None

depolarize(self, amount)

Depolarize this state vector by the given amount.

Generally, the depolarize function updates the parameters of the State such that the resulting vector is depolarized. If such an update cannot be done (because the gate parameters do not allow for it), ValueError is raised.

Parameters

amount (float or tuple) – The amount to depolarize by. If a tuple, it must have length equal to one less than the dimension of the spam vector. All but the first element of the spam vector (often corresponding to the identity element) are multiplied by amount (if a float) or the corresponding amount[i] (if a tuple).

Returns

None

errorgen_coefficient_labels(self)

The elementary error-generator labels corresponding to the elements of :method:`errorgen_coefficients_array`.

Returns

tuple – A tuple of (<type>, <basisEl1> [,<basisEl2]) elements identifying the elementary error generators of this gate.

errorgen_coefficients_array(self)

The weighted coefficients of this state prep’s error generator in terms of “standard” error generators.

Constructs a 1D array of all the coefficients returned by :method:`errorgen_coefficients`, weighted so that different error generators can be weighted differently when a errorgen_penalty_factor is used in an objective function.

Returns

numpy.ndarray – A 1D array of length equal to the number of coefficients in the linear combination of standard error generators that is this state preparation’s error generator.

errorgen_coefficients(self, return_basis=False, logscale_nonham=False)

Constructs a dictionary of the Lindblad-error-generator coefficients of this state.

Note that these are not necessarily the parameter values, as these coefficients are generally functions of the parameters (so as to keep the coefficients positive, for instance).

Parameters
  • return_basis (bool, optional) – Whether to also return a Basis containing the elements with which the error generator terms were constructed.

  • logscale_nonham (bool, optional) – Whether or not the non-hamiltonian error generator coefficients should be scaled so that the returned dict contains: (1 - exp(-d^2 * coeff)) / d^2 instead of coeff. This essentially converts the coefficient into a rate that is the contribution this term would have within a depolarizing channel where all stochastic generators had this same coefficient. This is the value returned by :method:`error_rates`.

Returns

  • lindblad_term_dict (dict) – Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2-tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify off-diagonal non-Hamiltonian Lindblad terms. Basis labels are integers starting at 0. Values are complex coefficients.

  • basis (Basis) – A Basis mapping the basis labels used in the keys of lindblad_term_dict to basis matrices.

set_errorgen_coefficients(self, lindblad_term_dict, action='update', logscale_nonham=False, truncate=True)

Sets the coefficients of terms in the error generator of this state.

The dictionary lindblad_term_dict has tuple-keys describing the type of term and the basis elements used to construct it, e.g. (‘H’,’X’).

Parameters
  • lindblad_term_dict (dict) – Keys are (termType, basisLabel1, <basisLabel2>) tuples, where termType is “H” (Hamiltonian), “S” (Stochastic), or “A” (Affine). Hamiltonian and Affine terms always have a single basis label (so key is a 2-tuple) whereas Stochastic tuples have 1 basis label to indicate a diagonal term and otherwise have 2 basis labels to specify off-diagonal non-Hamiltonian Lindblad terms. Values are the coefficients of these error generators, and should be real except for the 2-basis-label case.

  • action ({"update","add","reset"}) – How the values in lindblad_term_dict should be combined with existing error-generator coefficients.

  • logscale_nonham (bool, optional) – Whether or not the values in lindblad_term_dict for non-hamiltonian error generators should be interpreted as error rates (of an “equivalent” depolarizing channel, see :method:`errorgen_coefficients`) instead of raw coefficients. If True, then the non-hamiltonian coefficients are set to -log(1 - d^2*rate)/d^2, where rate is the corresponding value given in lindblad_term_dict. This is what is performed by the function :method:`set_error_rates`.

  • truncate (bool, optional) – Whether to allow adjustment of the errogen coefficients in order to meet constraints (e.g. to preserve CPTP) when necessary. If False, then an error is thrown when the given coefficients cannot be set as specified.

Returns

None

errorgen_coefficients_array_deriv_wrt_params(self)

The jacobian of :method:`errogen_coefficients_array` with respect to this state’s parameters.

Returns

numpy.ndarray – A 2D array of shape (num_coeffs, num_params) where num_coeffs is the number of coefficients of this operation’s error generator and num_params is this operation’s number of parameters.

class pygsti.modelmembers.states.ComputationalBasisState(zvals, basis='pp', evotype='default', state_space=None)

Bases: pygsti.modelmembers.states.state.State

A static state vector that is tensor product of 1-qubit Z-eigenstates.

This is called a “computational basis state” in many contexts.

Parameters
  • zvals (iterable) – A list or other iterable of integer 0 or 1 outcomes specifying which computational basis element this object represents. The length of zvals gives the total number of qubits.

  • basis (Basis or {'pp','gm','std'}, optional) – The basis used to construct the Hilbert-Schmidt space representation of this state as a super-ket.

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

  • state_space (StateSpace, optional) – The state space for this operation. If None a default state space with the appropriate number of qubits is used.

classmethod from_state_vector(cls, vec, basis='pp', evotype='default', state_space=None)

Create a new ComputationalBasisState from a dense vector.

Parameters
  • vec (numpy.ndarray) – A state vector specifying a computational basis state in the standard basis. This vector has length 4^n for n qubits.

  • basis (Basis or {'pp','gm','std'}, optional) – The basis of vec as a super-ket.

  • evotype (Evotype or str) – The evolution type. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.

  • state_space (StateSpace, optional) – The state space for this operation. If None a default state space with the appropriate number of qubits is used.

Returns

ComputationalBasisState

classmethod from_pure_vector(cls, purevec, basis='pp', evotype='default', state_space=None)

Create a new ComputationalBasisState from a pure-state vector.

Currently, purevec must be a single computational basis state (it cannot be a superpostion of multiple of them).

Parameters
  • purevec (numpy.ndarray) – A complex-valued state vector specifying a pure state in the standard computational basis. This vector has length 2^n for n qubits.

  • basis (Basis or {'pp','gm','std'}, optional) – The basis of vec as a super-ket.

  • evotype (Evotype or str, optional) – The evolution type of the resulting effect vector. The special value “default” is equivalent to specifying the value of pygsti.evotypes.Evotype.default_evotype.

  • state_space (StateSpace, optional) – The state space for this operation. If None a default state space with the appropriate number of qubits is used.

Returns

ComputationalBasisState

to_dense(self, on_space='minimal', scratch=None)

Return this state vector as a (dense) numpy array.

The memory in scratch maybe used when it is not-None.

Parameters
  • on_space ({'minimal', 'Hilbert', 'HilbertSchmidt'}) – The space that the returned dense operation acts upon. For unitary matrices and bra/ket vectors, use ‘Hilbert’. For superoperator matrices and super-bra/super-ket vectors use ‘HilbertSchmidt’. ‘minimal’ means that ‘Hilbert’ is used if possible given this operator’s evolution type, and otherwise ‘HilbertSchmidt’ is used.

  • scratch (numpy.ndarray, optional) – scratch space available for use.

Returns

numpy.ndarray

taylor_order_terms(self, order, max_polynomial_vars=100, return_coeff_polys=False)

Get the order-th order Taylor-expansion terms of this state vector.

This function either constructs or returns a cached list of the terms at the given order. Each term is “rank-1”, meaning that it is a state preparation followed by or POVM effect preceded by actions on a density matrix rho of the form:

rho -> A rho B

The coefficients of these terms are typically polynomials of the State’s parameters, where the polynomial’s variable indices index the global parameters of the State’s parent (usually a Model) , not the State’s local parameter array (i.e. that returned from to_vector).

Parameters
  • order (int) – The order of terms to get.

  • max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.

  • return_coeff_polys (bool) – Whether a parallel list of locally-indexed (using variable indices corresponding to this object’s parameters rather than its parent’s) polynomial coefficients should be returned as well.

Returns

  • terms (list) – A list of RankOneTerm objects.

  • coefficients (list) – Only present when return_coeff_polys == True. A list of compact polynomial objects, meaning that each element is a (vtape,ctape) 2-tuple formed by concatenating together the output of :method:`Polynomial.compact`.

property num_params(self)

Get the number of independent parameters which specify this state vector.

Returns

int – the number of independent parameters.

to_vector(self)

Get the state vector parameters as an array of values.

Returns

numpy array – The parameters as a 1D array with length num_params().

from_vector(self, v, close=False, dirty_value=True)

Initialize the state vector using a 1D array of parameters.

Parameters
  • v (numpy array) – The 1D vector of state vector parameters. Length must == num_params()

  • close (bool, optional) – Whether v is close to this state vector’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.

  • dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.

Returns

None

to_memoized_dict(self, mmg_memo)

Create a serializable dict with references to other objects in the memo.

Parameters

mmg_memo (dict) – Memo dict from a ModelMemberGraph, i.e. keys are object ids and values are ModelMemberGraphNodes (which contain the serialize_id). This is NOT the same as other memos in ModelMember (e.g. copy, allocate_gpindices, etc.).

Returns

mm_dict (dict) – A dict representation of this ModelMember ready for serialization This must have at least the following fields:

module, class, submembers, params, state_space, evotype

Additional fields may be added by derived classes.

classmethod _from_memoized_dict(cls, mm_dict, serial_memo)

For subclasses to implement. Submember-existence checks are performed, and the gpindices of the return value is set, by the non-underscored :method:`from_memoized_dict` implemented in this class.

_is_similar(self, other, rtol, atol)

Returns True if other model member (which it guaranteed to be the same type as self) has the same local structure, i.e., not considering parameter values or submembers

__str__(self)

Return str(self).

class pygsti.modelmembers.states.CPTPState(vec, basis, truncate=False, evotype='default', state_space=None)

Bases: pygsti.modelmembers.states.densestate.DenseState

TODO: update docstring A state vector constrained to correspond ot a positive density matrix.

This state vector that is parameterized through the Cholesky decomposition of it’s standard-basis representation as a density matrix (not a Liouville vector). The resulting state vector thus represents a positive density matrix, and additional constraints on the parameters also guarantee that the trace == 1. This state vector is meant for use with CPTP processes, hence the name.

Parameters
  • vec (array_like or State) – a 1D numpy array representing the state operation. The shape of this array sets the dimension of the state.

  • basis ({"std", "gm", "pp", "qt"} or Basis) – The basis vec is in. Needed because this parameterization requires we construct the density matrix corresponding to the Lioville vector vec.

  • trunctate (bool, optional) – Whether or not a non-positive, trace=1 vec should be truncated to force a successful construction.

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

  • state_space (StateSpace, optional) – The state space for this operation. If None a default state space with the appropriate number of qubits is used.

to_memoized_dict(self, mmg_memo)

Create a serializable dict with references to other objects in the memo.

Parameters

mmg_memo (dict) – Memo dict from a ModelMemberGraph, i.e. keys are object ids and values are ModelMemberGraphNodes (which contain the serialize_id). This is NOT the same as other memos in ModelMember (e.g. copy, allocate_gpindices, etc.).

Returns

mm_dict (dict) – A dict representation of this ModelMember ready for serialization This must have at least the following fields:

module, class, submembers, params, state_space, evotype

Additional fields may be added by derived classes.

classmethod _from_memoized_dict(cls, mm_dict, serial_memo)

For subclasses to implement. Submember-existence checks are performed, and the gpindices of the return value is set, by the non-underscored :method:`from_memoized_dict` implemented in this class.

_set_params_from_vector(self, vector, truncate)
_construct_vector(self)
set_dense(self, vec)

Set the dense-vector value of this state vector.

Attempts to modify this state vector’s parameters so that the raw state vector becomes vec. Will raise ValueError if this operation is not possible.

Parameters

vec (array_like or State) – A numpy array representing a state vector, or a State object.

Returns

None

property num_params(self)

Get the number of independent parameters which specify this state vector.

Returns

int – the number of independent parameters.

to_vector(self)

Get the state vector parameters as an array of values.

Returns

numpy array – The parameters as a 1D array with length num_params().

from_vector(self, v, close=False, dirty_value=True)

Initialize the state vector using a 1D array of parameters.

Parameters
  • v (numpy array) – The 1D vector of state vector parameters. Length must == num_params()

  • close (bool, optional) – Whether v is close to this state vector’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.

  • dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.

Returns

None

deriv_wrt_params(self, wrt_filter=None)

The element-wise derivative this state vector.

Construct a matrix whose columns are the derivatives of the state vector with respect to a single param. Thus, each column is of length dimension and there is one column per state vector parameter.

Parameters

wrt_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)

Returns

numpy array – Array of derivatives, shape == (dimension, num_params)

has_nonzero_hessian(self)

Whether this state vector has a non-zero Hessian with respect to its parameters.

Returns

bool

abstract hessian_wrt_params(self, wrt_filter1=None, wrt_filter2=None)

Construct the Hessian of this state vector with respect to its parameters.

This function returns a tensor whose first axis corresponds to the flattened operation matrix and whose 2nd and 3rd axes correspond to the parameters that are differentiated with respect to.

Parameters
  • wrt_filter1 (list or numpy.ndarray) – List of parameter indices to take 1st derivatives with respect to. (None means to use all the this operation’s parameters.)

  • wrt_filter2 (list or numpy.ndarray) – List of parameter indices to take 2nd derivatives with respect to. (None means to use all the this operation’s parameters.)

Returns

numpy array – Hessian with shape (dimension, num_params1, num_params2)

class pygsti.modelmembers.states.FullPureState(purevec, basis='pp', evotype='default', state_space=None)

Bases: pygsti.modelmembers.states.densestate.DensePureState

A “fully parameterized” state vector where each element is an independent parameter.

Parameters
  • vec (array_like or State) – a 1D numpy array representing the state operation. The shape of this array sets the dimension of the state op.

  • basis (Basis or {'pp','gm','std'}, optional) – The basis used to construct the Hilbert-Schmidt space representation of this state as a super-ket.

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

  • state_space (StateSpace, optional) – The state space for this operation. If None a default state space with the appropriate number of qubits is used.

property num_params(self)

Get the number of independent parameters which specify this state vector.

Returns

int – the number of independent parameters.

to_vector(self)

Get the state vector parameters as an array of values.

Returns

numpy array – The parameters as a 1D array with length num_params().

from_vector(self, v, close=False, dirty_value=True)

Initialize the state vector using a 1D array of parameters.

Parameters
  • v (numpy array) – The 1D vector of state vector parameters. Length must == num_params()

  • close (bool, optional) – Whether v is close to this state vector’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.

  • dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.

Returns

None

deriv_wrt_params(self, wrt_filter=None)

The element-wise derivative this state vector.

Construct a matrix whose columns are the derivatives of the state vector with respect to a single param. Thus, each column is of length dimension and there is one column per state vector parameter.

Parameters

wrt_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)

Returns

numpy array – Array of derivatives, shape == (dimension, num_params)

has_nonzero_hessian(self)

Whether this state vector has a non-zero Hessian with respect to its parameters.

Returns

bool

class pygsti.modelmembers.states.FullState(vec, evotype='default', state_space=None)

Bases: pygsti.modelmembers.states.densestate.DenseState

A “fully parameterized” state vector where each element is an independent parameter.

Parameters
  • vec (array_like or SPAMVec) – a 1D numpy array representing the SPAM operation. The shape of this array sets the dimension of the SPAM op.

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

  • state_space (StateSpace, optional) – The state space for this state. If None a default state space with the appropriate number of qubits is used.

set_dense(self, vec)

Set the dense-vector value of this SPAM vector.

Attempts to modify this SPAM vector’s parameters so that the raw SPAM vector becomes vec. Will raise ValueError if this operation is not possible.

Parameters

vec (array_like or SPAMVec) – A numpy array representing a SPAM vector, or a SPAMVec object.

Returns

None

property num_params(self)

Get the number of independent parameters which specify this SPAM vector.

Returns

int – the number of independent parameters.

to_vector(self)

Get the SPAM vector parameters as an array of values.

Returns

numpy array – The parameters as a 1D array with length num_params().

from_vector(self, v, close=False, dirty_value=True)

Initialize the SPAM vector using a 1D array of parameters.

Parameters
  • v (numpy array) – The 1D vector of SPAM vector parameters. Length must == num_params()

  • close (bool, optional) – Whether v is close to this SPAM vector’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.

  • dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.

Returns

None

deriv_wrt_params(self, wrt_filter=None)

The element-wise derivative this SPAM vector.

Construct a matrix whose columns are the derivatives of the SPAM vector with respect to a single param. Thus, each column is of length dimension and there is one column per SPAM vector parameter.

Parameters

wrt_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)

Returns

numpy array – Array of derivatives, shape == (dimension, num_params)

has_nonzero_hessian(self)

Whether this SPAM vector has a non-zero Hessian with respect to its parameters.

Returns

bool

class pygsti.modelmembers.states.State(rep, evotype)

Bases: pygsti.modelmembers.modelmember.ModelMember

TODO: update docstring A parameterized state preparation OR POVM effect vector (operator).

This class is the common base class for all specific parameterizations of a state vector.

Parameters
  • rep (object) – A representation object containing the core data for this spam vector.

  • evotype (Evotype) – The evolution type.

size

The number of independent elements in this state vector (when viewed as a dense array).

Type

int

property dim(self)

Return the dimension of this state (when viewed as a dense array)

Returns

int

property size(self)

Return the number of independent elements in this gate (when viewed as a dense array)

Returns

int

set_dense(self, vec)

Set the dense-vector value of this state vector.

Attempts to modify this state vector’s parameters so that the raw state vector becomes vec. Will raise ValueError if this operation is not possible.

Parameters

vec (array_like or State) – A numpy array representing a state vector, or a State object.

Returns

None

set_time(self, t)

Sets the current time for a time-dependent operator.

For time-independent operators (the default), this function does absolutely nothing.

Parameters

t (float) – The current time.

Returns

None

abstract to_dense(self, on_space='minimal', scratch=None)

Return this state vector as a (dense) numpy array.

The memory in scratch maybe used when it is not-None.

Parameters
  • on_space ({'minimal', 'Hilbert', 'HilbertSchmidt'}) – The space that the returned dense operation acts upon. For unitary matrices and bra/ket vectors, use ‘Hilbert’. For superoperator matrices and super-bra/super-ket vectors use ‘HilbertSchmidt’. ‘minimal’ means that ‘Hilbert’ is used if possible given this operator’s evolution type, and otherwise ‘HilbertSchmidt’ is used.

  • scratch (numpy.ndarray, optional) – scratch space available for use.

Returns

numpy.ndarray

abstract taylor_order_terms(self, order, max_polynomial_vars=100, return_coeff_polys=False)

Get the order-th order Taylor-expansion terms of this state vector.

This function either constructs or returns a cached list of the terms at the given order. Each term is “rank-1”, meaning that it is a state preparation followed by or POVM effect preceded by actions on a density matrix rho of the form:

rho -> A rho B

The coefficients of these terms are typically polynomials of the State’s parameters, where the polynomial’s variable indices index the global parameters of the State’s parent (usually a Model) , not the State’s local parameter array (i.e. that returned from to_vector).

Parameters
  • order (int) – The order of terms to get.

  • max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.

  • return_coeff_polys (bool) – Whether a parallel list of locally-indexed (using variable indices corresponding to this object’s parameters rather than its parent’s) polynomial coefficients should be returned as well.

Returns

  • terms (list) – A list of RankOneTerm objects.

  • coefficients (list) – Only present when return_coeff_polys == True. A list of compact polynomial objects, meaning that each element is a (vtape,ctape) 2-tuple formed by concatenating together the output of :method:`Polynomial.compact`.

highmagnitude_terms(self, min_term_mag, force_firstorder=True, max_taylor_order=3, max_polynomial_vars=100)

Get terms with magnitude above min_term_mag.

Get the terms (from a Taylor expansion of this state vector) that have magnitude above min_term_mag (the magnitude of a term is taken to be the absolute value of its coefficient), considering only those terms up to some maximum Taylor expansion order, max_taylor_order.

Note that this function also sets the magnitudes of the returned terms (by calling term.set_magnitude(…)) based on the current values of this state vector’s parameters. This is an essential step to using these terms in pruned-path-integral calculations later on.

Parameters
  • min_term_mag (float) – the threshold for term magnitudes: only terms with magnitudes above this value are returned.

  • force_firstorder (bool, optional) – if True, then always return all the first-order Taylor-series terms, even if they have magnitudes smaller than min_term_mag. This behavior is needed for using GST with pruned-term calculations, as we may begin with a guess model that has no error (all terms have zero magnitude!) and still need to compute a meaningful jacobian at this point.

  • max_taylor_order (int, optional) – the maximum Taylor-order to consider when checking whether term- magnitudes exceed min_term_mag.

  • max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.

Returns

  • highmag_terms (list) – A list of the high-magnitude terms that were found. These terms are sorted in descending order by term-magnitude.

  • first_order_indices (list) – A list of the indices into highmag_terms that mark which of these terms are first-order Taylor terms (useful when we’re forcing these terms to always be present).

taylor_order_terms_above_mag(self, order, max_polynomial_vars, min_term_mag)

Get the order-th order Taylor-expansion terms of this state vector that have magnitude above min_term_mag.

This function constructs the terms at the given order which have a magnitude (given by the absolute value of their coefficient) that is greater than or equal to min_term_mag. It calls :method:`taylor_order_terms` internally, so that all the terms at order order are typically cached for future calls.

Parameters
  • order (int) – The order of terms to get.

  • max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.

  • min_term_mag (float) – the minimum term magnitude.

Returns

list

frobeniusdist_squared(self, other_spam_vec, transform=None, inv_transform=None)

Return the squared frobenius difference between this operation and other_spam_vec.

Optionally transforms this vector first using transform and inv_transform.

Parameters
  • other_spam_vec (State) – The other spam vector

  • transform (numpy.ndarray, optional) – Transformation matrix.

  • inv_transform (numpy.ndarray, optional) – Inverse of tranform.

Returns

float

residuals(self, other_spam_vec, transform=None, inv_transform=None)

Return a vector of residuals between this spam vector and other_spam_vec.

Optionally transforms this vector first using transform and inv_transform.

Parameters
  • other_spam_vec (State) – The other spam vector

  • transform (numpy.ndarray, optional) – Transformation matrix.

  • inv_transform (numpy.ndarray, optional) – Inverse of tranform.

Returns

float

transform_inplace(self, s)

Update state preparation (column) vector V as inv(s) * V.

Note that this is equivalent to state preparation vectors getting mapped: rho -> inv(s) * rho.

Generally, the transform function updates the parameters of the state vector such that the resulting vector is altered as described above. If such an update cannot be done (because the gate parameters do not allow for it), ValueError is raised.

Parameters

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

Returns

None

depolarize(self, amount)

Depolarize this state vector by the given amount.

Generally, the depolarize function updates the parameters of the State such that the resulting vector is depolarized. If such an update cannot be done (because the gate parameters do not allow for it), ValueError is raised.

Parameters

amount (float or tuple) – The amount to depolarize by. If a tuple, it must have length equal to one less than the dimension of the gate. All but the first element of the spam vector (often corresponding to the identity element) are multiplied by amount (if a float) or the corresponding amount[i] (if a tuple).

Returns

None

property num_params(self)

Get the number of independent parameters which specify this state vector.

Returns

int – the number of independent parameters.

to_vector(self)

Get the state vector parameters as an array of values.

Returns

numpy array – The parameters as a 1D array with length num_params().

from_vector(self, v, close=False, dirty_value=True)

Initialize the state vector using a 1D array of parameters.

Parameters
  • v (numpy array) – The 1D vector of state vector parameters. Length must == num_params()

  • close (bool, optional) – Whether v is close to this state vector’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.

  • dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.

Returns

None

deriv_wrt_params(self, wrt_filter=None)

The element-wise derivative this state vector.

Construct a matrix whose columns are the derivatives of the state vector with respect to a single param. Thus, each column is of length dimension and there is one column per state vector parameter.

Parameters

wrt_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)

Returns

numpy array – Array of derivatives, shape == (dimension, num_params)

has_nonzero_hessian(self)

Whether this state vector has a non-zero Hessian with respect to its parameters.

Returns

bool

hessian_wrt_params(self, wrt_filter1=None, wrt_filter2=None)

Construct the Hessian of this state vector with respect to its parameters.

This function returns a tensor whose first axis corresponds to the flattened operation matrix and whose 2nd and 3rd axes correspond to the parameters that are differentiated with respect to.

Parameters
  • wrt_filter1 (list or numpy.ndarray) – List of parameter indices to take 1st derivatives with respect to. (None means to use all the this operation’s parameters.)

  • wrt_filter2 (list or numpy.ndarray) – List of parameter indices to take 2nd derivatives with respect to. (None means to use all the this operation’s parameters.)

Returns

numpy array – Hessian with shape (dimension, num_params1, num_params2)

static _to_vector(v)

Static method that converts a vector-like object to a 2D numpy dim x 1 column array.

Parameters

v (array_like) – Array-like object to convert to a numpy array.

Returns

numpy array

class pygsti.modelmembers.states.StaticPureState(purevec, basis='pp', evotype='default', state_space=None)

Bases: pygsti.modelmembers.states.densestate.DensePureState

A pure state vector that is completely fixed, or “static” (i.e. that posesses no parameters).

Parameters
  • vec (array_like or SPAMVec) – a 1D numpy array representing the SPAM operation. The shape of this array sets the dimension of the SPAM op.

  • basis (Basis or {'pp','gm','std'}, optional) – The basis used to construct the Hilbert-Schmidt space representation of this state as a super-ket.

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

  • state_space (StateSpace, optional) – The state space for this operation. If None a default state space with the appropriate number of qubits is used.

taylor_order_terms(self, order, max_polynomial_vars=100, return_coeff_polys=False)

Get the order-th order Taylor-expansion terms of this state vector.

This function either constructs or returns a cached list of the terms at the given order. Each term is “rank-1”, meaning that it is a state preparation followed by or POVM effect preceded by actions on a density matrix rho of the form:

rho -> A rho B

The coefficients of these terms are typically polynomials of the State’s parameters, where the polynomial’s variable indices index the global parameters of the State’s parent (usually a Model) , not the State’s local parameter array (i.e. that returned from to_vector).

Parameters
  • order (int) – The order of terms to get.

  • max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.

  • return_coeff_polys (bool) – Whether a parallel list of locally-indexed (using variable indices corresponding to this object’s parameters rather than its parent’s) polynomial coefficients should be returned as well.

Returns

  • terms (list) – A list of RankOneTerm objects.

  • coefficients (list) – Only present when return_coeff_polys == True. A list of compact polynomial objects, meaning that each element is a (vtape,ctape) 2-tuple formed by concatenating together the output of :method:`Polynomial.compact`.

_is_similar(self, other, rtol, atol)

Returns True if other model member (which it guaranteed to be the same type as self) has the same local structure, i.e., not considering parameter values or submembers

class pygsti.modelmembers.states.StaticState(vec, evotype='default', state_space=None)

Bases: pygsti.modelmembers.states.densestate.DenseState

A state vector that is completely fixed, or “static” (i.e. that posesses no parameters).

Parameters
  • vec (array_like or State) – a 1D numpy array representing the state. The shape of this array sets the dimension of the state.

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

  • state_space (StateSpace, optional) – The state space for this operation. If None a default state space with the appropriate number of qubits is used.

_is_similar(self, other, rtol, atol)

Returns True if other model member (which it guaranteed to be the same type as self) has the same local structure, i.e., not considering parameter values or submembers

class pygsti.modelmembers.states.TensorProductState(factors, state_space)

Bases: pygsti.modelmembers.states.state.State

A state vector that is a tensor-product of other state vectors.

Parameters
  • factors (list of States) – a list of the component states to take the tensor product of.

  • state_space (StateSpace, optional) – The state space for this operation.

classmethod _from_memoized_dict(cls, mm_dict, serial_memo)

For subclasses to implement. Submember-existence checks are performed, and the gpindices of the return value is set, by the non-underscored :method:`from_memoized_dict` implemented in this class.

submembers(self)

Get the ModelMember-derived objects contained in this one.

Returns

list

_update_rep(self)
property parameter_labels(self)

An array of labels (usually strings) describing this model member’s parameters.

to_dense(self, on_space='minimal', scratch=None)

Return this state vector as a (dense) numpy array.

The memory in scratch maybe used when it is not-None.

Parameters
  • on_space ({'minimal', 'Hilbert', 'HilbertSchmidt'}) – The space that the returned dense operation acts upon. For unitary matrices and bra/ket vectors, use ‘Hilbert’. For superoperator matrices and super-bra/super-ket vectors use ‘HilbertSchmidt’. ‘minimal’ means that ‘Hilbert’ is used if possible given this operator’s evolution type, and otherwise ‘HilbertSchmidt’ is used.

  • scratch (numpy.ndarray, optional) – scratch space available for use.

Returns

numpy.ndarray

taylor_order_terms(self, order, max_polynomial_vars=100, return_coeff_polys=False)

Get the order-th order Taylor-expansion terms of this state vector.

This function either constructs or returns a cached list of the terms at the given order. Each term is “rank-1”, meaning that it is a state preparation followed by or POVM effect preceded by actions on a density matrix rho of the form:

rho -> A rho B

The coefficients of these terms are typically polynomials of the State’s parameters, where the polynomial’s variable indices index the global parameters of the State’s parent (usually a Model) , not the State’s local parameter array (i.e. that returned from to_vector).

Parameters
  • order (int) – The order of terms to get.

  • max_polynomial_vars (int, optional) – maximum number of variables the created polynomials can have.

  • return_coeff_polys (bool) – Whether a parallel list of locally-indexed (using variable indices corresponding to this object’s parameters rather than its parent’s) polynomial coefficients should be returned as well.

Returns

  • terms (list) – A list of RankOneTerm objects.

  • coefficients (list) – Only present when return_coeff_polys == True. A list of compact polynomial objects, meaning that each element is a (vtape,ctape) 2-tuple formed by concatenating together the output of :method:`Polynomial.compact`.

property num_params(self)

Get the number of independent parameters which specify this state vector.

Returns

int – the number of independent parameters.

to_vector(self)

Get the state vector parameters as an array of values.

Returns

numpy array – The parameters as a 1D array with length num_params().

from_vector(self, v, close=False, dirty_value=True)

Initialize the state vector using a 1D array of parameters.

Parameters
  • v (numpy array) – The 1D vector of state vector parameters. Length must == num_params()

  • close (bool, optional) – Whether v is close to this state vector’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.

  • dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.

Returns

None

deriv_wrt_params(self, wrt_filter=None)

The element-wise derivative this state vector.

Construct a matrix whose columns are the derivatives of the state vector with respect to a single param. Thus, each column is of length dimension and there is one column per state vector parameter. An empty 2D array in the StaticState case (num_params == 0).

Parameters

wrt_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)

Returns

numpy array – Array of derivatives, shape == (dimension, num_params)

has_nonzero_hessian(self)

Whether this state vector has a non-zero Hessian with respect to its parameters.

Returns

bool

__str__(self)

Return str(self).

class pygsti.modelmembers.states.TPState(vec, evotype='default', state_space=None)

Bases: pygsti.modelmembers.states.densestate.DenseState

A fixed-unit-trace state vector.

This state vector is fully parameterized except for the first element, which is frozen to be 1/(d**0.25). This is so that, when the state vector is interpreted in the Pauli or Gell-Mann basis, the represented density matrix has trace == 1. This restriction is frequently used in conjuction with trace-preserving (TP) gates, hence its name.

Parameters
  • vec (array_like or State) – a 1D numpy array representing the state. The shape of this array sets the dimension of the state.

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

  • state_space (StateSpace, optional) – The state space for this operation. If None a default state space with the appropriate number of qubits is used.

property columnvec(self)

Direct access the the underlying data as column vector, i.e, a (dim,1)-shaped array.

set_dense(self, vec)

Set the dense-vector value of this state vector.

Attempts to modify this state vector’s parameters so that the raw state vector becomes vec. Will raise ValueError if this operation is not possible.

Parameters

vec (array_like or State) – A numpy array representing a state vector, or a State object.

Returns

None

property num_params(self)

Get the number of independent parameters which specify this state vector.

Returns

int – the number of independent parameters.

to_vector(self)

Get the state vector parameters as an array of values.

Returns

numpy array – The parameters as a 1D array with length num_params().

from_vector(self, v, close=False, dirty_value=True)

Initialize the state vector using a 1D array of parameters.

Parameters
  • v (numpy array) – The 1D vector of state vector parameters. Length must == num_params()

  • close (bool, optional) – Whether v is close to this state vector’s current set of parameters. Under some circumstances, when this is true this call can be completed more quickly.

  • dirty_value (bool, optional) – The value to set this object’s “dirty flag” to before exiting this call. This is passed as an argument so it can be updated recursively. Leave this set to True unless you know what you’re doing.

Returns

None

deriv_wrt_params(self, wrt_filter=None)

The element-wise derivative this state vector.

Construct a matrix whose columns are the derivatives of the state vector with respect to a single param. Thus, each column is of length dimension and there is one column per state vector parameter.

Parameters

wrt_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)

Returns

numpy array – Array of derivatives, shape == (dimension, num_params)

has_nonzero_hessian(self)

Whether this state vector has a non-zero Hessian with respect to its parameters.

Returns

bool

pygsti.modelmembers.states.create_from_pure_vector(pure_vector, state_type, basis='pp', evotype='default', state_space=None, on_construction_error='warn')

TODO: docstring – create a State from a state vector

pygsti.modelmembers.states.create_from_dmvec(superket_vector, state_type, basis='pp', evotype='default', state_space=None)
pygsti.modelmembers.states.state_type_from_op_type(op_type)

Decode an op type into an appropriate state type.

pygsti.modelmembers.states.convert(state, to_type, basis, extra=None)

TODO: update docstring Convert SPAM vector to a new type of parameterization.

This potentially creates a new State object. Raises ValueError for invalid conversions.

Parameters
  • state (State) – State vector to convert

  • to_type ({"full","full TP","static","static unitary","clifford",LINDBLAD}) – The type of parameterizaton to convert to. “LINDBLAD” is a placeholder for the various Lindblad parameterization types. See :method:`Model.set_all_parameterizations` for more details.

  • basis ({'std', 'gm', 'pp', 'qt'} or Basis object) – The basis for state. Allowed values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt) (or a custom basis object).

  • extra (object, optional) – Additional information for conversion.

Returns

State – The converted State vector, usually a distinct object from the object passed as input.

pygsti.modelmembers.states.finite_difference_deriv_wrt_params(state, wrt_filter=None, eps=1e-07)

Computes a finite-difference Jacobian for a State object.

The returned value is a matrix whose columns are the vectorized derivatives of the spam vector with respect to a single parameter, matching the format expected from the spam vectors’s deriv_wrt_params method.

Parameters
  • state (State) – The spam vector object to compute a Jacobian for.

  • wrt_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)

  • eps (float, optional) – The finite difference step to use.

Returns

numpy.ndarray – An M by N matrix where M is the number of gate elements and N is the number of gate parameters.

pygsti.modelmembers.states.check_deriv_wrt_params(state, deriv_to_check=None, wrt_filter=None, eps=1e-07)

Checks the deriv_wrt_params method of a State object.

This routine is meant to be used as an aid in testing and debugging State classes by comparing the finite-difference Jacobian that should be returned by state.deriv_wrt_params with the one that actually is. A ValueError is raised if the two do not match.

Parameters
  • state (State) – The gate object to test.

  • deriv_to_check (numpy.ndarray or None, optional) – If not None, the Jacobian to compare against the finite difference result. If None, state.deriv_wrt_parms() is used. Setting this argument can be useful when the function is called within a LinearOperator class’s deriv_wrt_params() method itself as a part of testing.

  • wrt_filter (list or numpy.ndarray) – List of parameter indices to take derivative with respect to. (None means to use all the this operation’s parameters.)

  • eps (float, optional) – The finite difference step to use.

Returns

None

pygsti.modelmembers.states.optimize_state(vec_to_optimize, target_vec)

Optimize the parameters of vec_to_optimize.

The optimization is performed so that the the resulting State vector is as close as possible to target_vec.

This is trivial for the case of FullState instances, but for other types of parameterization this involves an iterative optimization over all the parameters of vec_to_optimize.

Parameters
  • vec_to_optimize (State) – The state vector to optimize. This object gets altered.

  • target_vec (State) – The state vector used as the target.

Returns

None