inquanto.states

InQuanto representation of quantum states.

class FermionState(data=None, coeff=1.0)

Bases: State

Represents a state in a fermionic Fock space as a linear combination of basis states.

The state is stored as a dict, with the keys being FermionStateString objects (configurations) and values being the corresponding configuration coefficients. The FermionState is initialised from a FermionStateString and a coefficient, a tuple of tuple elements, each containing a coefficient and a FermionStateString object, or a dict, with FermionStateString objects as keys and coefficients as values. For a single basis state, it can also be initialised with a list of integers, wherein a default set of modes (indexed from 0 upwards) will be assumed. See below for examples.

Parameters:

Examples

>>> fs0 = FermionState([1, 1, 0, 0], 1)
>>> print(fs0)
(1, {0: 1, 1: 1, 2: 0, 3: 0})
>>> fss = FermionStateString({0:1, 1:1, 2:0, 3:0})
>>> fs1 = FermionState(fss, 1)
>>> print(fs1)
(1, {0: 1, 1: 1, 2: 0, 3: 0})
>>> fss0 = FermionStateString({0:1, 1:1, 2:0, 5:0})
>>> fss1 = FermionStateString({0:1, 1:0, 2:1, 5:0})
>>> fs2 = FermionState(((0.9, fss0), (0.1, fss1)))
>>> print(fs2)
(0.9, {0: 1, 1: 1, 2: 0, 5: 0}), (0.1, {0: 1, 1: 0, 2: 1, 5: 0})
>>> fss0 = FermionStateString({0:1, 1:1, 2:0, 5:0})
>>> fss1 = FermionStateString({0:1, 1:0, 2:1, 5:0})
>>> fs3 = FermionState({fss0: 0.9, fss1: 0.1})
>>> print(fs3)
(0.9, {0: 1, 1: 1, 2: 0, 5: 0}), (0.1, {0: 1, 1: 0, 2: 1, 5: 0})
approx_equal_to(other, abs_tol=1e-10)

Checks if object’s dictionary values are numerically identical to the other object values.

Parameters:
  • other (LinearDictCombiner) – Object to compare to.

  • abs_tol (float, default: 1e-10) – Threshold of comparing numeric values.

Raises:

TypeError – Comparison of two values can’t be done due to types mismatch.

Return type:

bool

approx_equal_to_by_random_subs(other, order=1, abs_tol=1e-10)

Checks if object’s dictionary values are numerically identical to the other object values.

Symbols contained in the difference of the two objects, if any, are substituted by random numeric values prior to norm check.

Parameters:
  • other (LinearDictCombiner) – Object to compare to.

  • order (int, default: 1) – Parameter specifying the norm formula (see numpy.linalg.norm() documentation).

  • abs_tol (float, default: 1e-10) – Threshold against which the norm of the difference is checked.

Return type:

bool

property basis_states: List[StateStringT]

Returns the basis states with nonzero coefficient as a list.

clone()

Performs shallow copy of the object.

Return type:

TypeVar(SYMBOLICTYPE, bound= Symbolic)

property coefficients: List[int | float | complex | Expr]

Returns the scalar coefficients of individual basis vectors as a list.

compress(abs_tol=1e-10, symbol_sub_type=CompressSymbolSubType.NONE)

Combines duplicate terms, removing those with negligible coefficient.

Parameters:
  • abs_tol (float, default: 1e-10) – Tolerance for comparing values to zero.

  • symbol_sub_type (Union[CompressSymbolSubType, str], default: CompressSymbolSubType.NONE) – Defines the behaviour for dealing with symbolic expressions in coefficients. If “none”, symbolic expressions are left intact. If “unity”, substitutes all free symbols with 1, and removes all imaginary and real components below tolerance. If “random”, substitutes all free symbols with a random number between 0 and 1, and removes imaginary and real components below tolerance.

Warning

When symbol_sub_type != "none", this method assumes significant expression structure is known a priori, and is best suited to operators which have simple product expressions, such as excitation operators for VQE ansatzes and digital quantum simulation. Otherwise, it may remove terms relevant to computation. Each expression is of the form \(f(a_1,a_2,\ldots,a_n)\) for some symbols \(a_i\). \(|f(a_1,a_2,\ldots,a_n)|\) is assumed to monotonically increase in both real and imaginary components for all \(a_i \in [0, 1]\).

Returns:

LinearDictCombiner – Updated instance of LinearDictCombiner.

copy()

Performs deep copy of the object.

Return type:

TypeVar(SYMBOLICTYPE, bound= Symbolic)

df()

Returns a Pandas DataFrame object of the dictionary.

Return type:

DataFrame

empty()

Checks if dictionary is empty.

Return type:

bool

evalf(*args, **kwargs)

Evaluates symbolic expressions stored in dict values and replaces them with the results.

Parameters:
  • args (Any) – Args to be passed to sympy.evalf().

  • kwargs (Any) – Kwargs to be passed to sympy.evalf().

Returns:

LinearDictCombiner – Updated instance of LinearDictCombiner.

free_symbols()

Returns the free symbols in the coefficient values.

free_symbols_ordered()

Returns the free symbols in the dict, ordered alphabetically.

Returns:

SymbolSet – Ordered set of symbols.

classmethod from_ndarray(state_vector, modes=None, reverse=False)

Returns an instance representing the provided ndarray state vector.

This method will take a state vector as a ndarray column vector and convert it to a State object. Modes - and the bit position in the state index to which each corresponds - can be defined with the modes parameter. In the absence of this parameter, a default register of the appropriate size is implicit, with the index being assumed to correspond to an ILO-BE ordering of the default register.

In keeping with numpy convention, 1-D arrays and 2-D arrays with shape (\(N\),1) are treated as column vectors. The length \(N\) of the vector must be either 0 or a power of 2. Differently shaped arrays are not accepted.

Parameters:
  • state_vector (ndarray) – The state vector representing the state to be created.

  • modes (Optional[Iterable[TypeVar(ModeT)]], default: None) – An ordering of modes used for defining indices, from most significant to least significant. Default behaviour as above.

  • reverse (default: False) – If True, reverse bit order of state vector indices (e.g. for changing endianness).

Returns:

An instance of this class representing the provided ndarray state vector.

Raises:

ValueError – If the input state vector has invalid shape.

classmethod from_sparray(state_vector, modes=None, reverse=False)

Returns an instance representing the provided scipy sparse array state_vector.

This method will take a state vector as a scipy sparse array and convert it to a State object. Modes - and the bit position in the state index to which each corresponds - can be defined with the modes parameter. In the absence of this parameter, a default register of the appropriate size is implicit, with the index being assumed to correspond to an ILO-BE ordering of the default register.

The shape of the array must be (\(N\), 1) where \(N\) is either 0 or a power of 2. Differently shaped arrays are not accepted.

Parameters:
  • state_vector (spmatrix) – The state vector representing the state to be created.

  • modes (Optional[Iterable[TypeVar(ModeT)]], default: None) – An ordering of modes used for defining indices, from most significant to least significant. Default behaviour as above.

  • reverse (default: False) – If True, reverse bit order of state vector indices (e.g. for changing endianness).

Returns:

An instance of this class representing state_vector.

classmethod from_string(input_string)

Constructs a child class instance from a string.

Parameters:

input_string (str) – String in the format coeff1 [(coeff1_1, term1_1), ..., (coeff1_n, term1_n)], ..., coeffn [(coeffn_1, termn_1), ...].

Returns:

TypeVar(StateT, bound= State) – Child class object.

get_numeric_representation()

Placeholder, unimplemented method.

get_symbolic_representation()

Placeholder, unimplemented method.

is_all_coeff_complex()

Check if all coefficients have complex values.

Returns:

boolFalse if a non-complex value occurs before any free symbols in the dict values, or True if no non-complex values occur.

Warning

Returns None if a free symbol occurs before any non-complex values in the coefficients.

is_all_coeff_imag()

Check if all coefficients have purely imaginary values.

Returns:

boolFalse if a non-complex value occurs before any free symbols in the dict values, or True if no non-complex values occur.

Warning

Returns None if a free symbol occurs before any non-imaginary values in the coefficients.

is_all_coeff_real()

Check if all coefficients have real values.

Returns:

boolFalse if a non-real value occurs before any free symbols in the dict values, or True if no non-real values occur.

Warning

Returns None if a free symbol occurs before any non-real values in the dict coefficients.

is_all_coeff_symbolic()

Check if all coefficients contain free symbols.

Returns:

bool – Whether all coefficients contain free symbols.

is_any_coeff_complex()

Check if any coefficients have complex values.

Returns:

boolTrue if a complex value occurs before any free symbols in the dict values, or False if no complex values occur.

Warning

Returns None if a free symbol occurs before any complex values in the coefficients.

is_any_coeff_imag()

Check if any coefficients have imaginary values.

Returns:

boolTrue if an imaginary value occurs before any free symbols in the dict values, or False if no imaginary values occur.

Warning

Returns None if a free symbol occurs before any imaginary values in the coefficients.

is_any_coeff_real()

Check if any coefficients have real values.

Returns:

boolTrue if a real value occurs before any free symbols in the dict values, or False if no real values occur.

Warning

Returns None if a free symbol occurs before any real values in the coefficients.

is_any_coeff_symbolic()

Check if any coefficients contain free symbols.

Returns:

bool – Whether any coefficients contain free symbols.

is_basis_state()

Checks this object represents a scalar multiple of a single basis state.

Return type:

bool

is_normalized(order=2, abs_tol=1e-10)

Returns True if operator has unit p-norm, else False.

Parameters:
  • order (int, default: 2) – Norm order.

  • abs_tol (float, default: 1e-10) – Tolerance threshold for comparison with unity.

Raises:

ValueError – Coefficients contain free symbols.

Return type:

bool

is_parallel_with(other, abs_tol=1e-10)

Returns True if other is parallel with this (i.e. a scalar multiple of this), otherwise False.

Parameters:
  • other (LinearDictCombiner) – The other object to compare against

  • abs_tol (Optional[float], default: 1e-10) – Tolerance threshold for comparison. Set to None to test for exact equivalence.

Returns:

boolTrue if other is parallel with this, otherwise False.

is_unit_1norm(abs_tol=1e-10)

Returns True if operator has unit 1-norm, else False.

Parameters:

abs_tol (float, default: 1e-10) – Tolerance threshold for comparison with unity.

Return type:

bool

is_unit_2norm(abs_tol=1e-10)

Returns True if operator has unit 1-norm, else False.

Parameters:

abs_tol (float, default: 1e-10) – Tolerance threshold for comparison with unity.

Return type:

bool

is_unit_norm(order=2, abs_tol=1e-10)

Returns True if operator has unit p-norm, else False.

Parameters:
  • order (int, default: 2) – Norm order.

  • abs_tol (float, default: 1e-10) – Tolerance threshold for comparison with unity.

Raises:

ValueError – Coefficients contain free symbols.

Return type:

bool

items()

Returns dictionary items.

Return type:

ItemsView[Any, Union[int, float, complex, Expr]]

classmethod key_from_str(key_str)

Converts a string to an instance of this class’s basis state type.

Parameters:

key_str (str) –

Return type:

TypeVar(StateStringT, bound= StateString)

classmethod load_h5(name)

Loads a state object from .h5 file.

Parameters:

name (Union[str, Group]) – Name of .h5 file to be loaded.

Returns:

TypeVar(StateT, bound= State) – Loaded integral operator object.

make_hashable()

Return a hashable representation of the object.

Returns:

str – A string representation of this instance.

map(mapping)

Updates dictionary values, using a mapping function provided.

Parameters:

mapping (Callable[[Union[int, float, complex, Expr]], Union[int, float, complex, Expr]]) – Mapping function to update the dict.

Returns:

LinearDictCombiner – This instance.

property n_symbols: int

Returns the number of free symbols in the object.

norm_coefficients(order=2)

Returns the p-norm of the coefficients.

Parameters:

order (int, default: 2) – Norm order.

Return type:

Union[complex, float]

normalized(norm_value=1.0, norm_order=2)

Returns a copy of this object with normalised coefficients.

Parameters:
  • norm_value (float, default: 1.0) – The desired norm of the returned operator.

  • norm_order (int, default: 2) – The order of the norm to be used.

Returns:

LinearDictCombiner – A copy of the object with coefficients normalised to the desired value.

property num_modes: int

Returns the number of modes.

print_table()

Print dictionary formatted as a table.

Return type:

NoReturn

qubit_encode(mapping=None, qubits=None)

Performs qubit encoding (mapping), using provided mapping function, of the current FermionState.

Terms are treated and mapped independently.

Parameters:
  • mapping (Optional[QubitMapping], default: None) – Mapping class. Default mapping procedure is the Jordan-Wigner transformation.

  • qubits (Union[list[Qubit], int, None], default: None) – The qubit register. If left as None, a default register will be assumed if possible. See the mapping class documentation for further details.

Returns:

QubitState – Mapped QubitState.

remove_global_phase()

Returns a copy with a global phase applied such that the first element has a real coefficient.

This is an alias for set_global_phase() - see this method for greater control over the phase to be applied.

Returns:

LinearDictCombiner – A copy of the object with a global phase applied such that the first element has a real coefficient.

reversed_order()

Reverses the order of terms and returns it as a new object.

Return type:

LinearDictCombiner

save_h5(name)

Dumps state object to .h5 file.

Parameters:

name (Union[str, Group]) – Destination filename of .h5 file.

Return type:

None

set_global_phase(phase=0.0)

Returns a copy with a global phase applied such that the first element has the desired phase.

Parameters:
  • phase (Union[int, float, complex, Expr], default: 0.0) – The phase to yield on the first element, in half-turns (i.e. multiples of pi).

  • phase. (A symbolic expression can be assigned to) –

Returns:

LinearDictCombiner – A copy of the object with the desired global phase applied.

simplify(*args, **kwargs)

Simplifies expressions stored in dictionary values.

Parameters:
  • args (Any) – Args to be passed to sympy.simplify().

  • kwargs (Any) – Kwargs to be passed to sympy.simplify().

Returns:

LinearDictCombiner – Updated instance of LinearDictCombiner.

property single_term: StateStringT

Returns the stored configuration as a StateString, if only a single configuration is stored.

Raises:

RuntimeError – if more or less than one configuration is stored

Returns:

The single configuration occupation vector.

split()

Generates State objects containing only single configurations, preserving coefficients.

Return type:

Generator[TypeVar(StateT, bound= State), None, None]

string_class

alias of FermionStateString

subs(symbol_map)

Returns a new objects with symbols substituted.

Parameters:

symbol_map (Union[SymbolDict, Dict[Symbol, Expr], Dict[Symbol, float], Dict[Symbol, Union[float, complex, Expr]], Callable[[Symbol], Expr], str]) – A mapping for substitution of free symbols.

Returns:

TypeVar(SYMBOLICTYPE, bound= Symbolic) – A copy of self with symbols substituted according to the provided map.

symbol_substitution(symbol_map=None)

Substitutes free symbols for numerical values according to a map.

Parameters:

symbol_map (Union[SymbolDict, Dict[Symbol, Expr], Dict[Symbol, float], Dict[Symbol, Union[float, complex, Expr]], Callable[[Symbol], Expr], str, None], default: None) –

Return type:

LinearDictCombiner

sympify(*args, **kwargs)

Sympifies dictionary values.

Replaces values with their corresponding symbolic expressions.

Parameters:
  • args (Any) – Args to be passed to sympy.sympify().

  • kwargs (Any) – Kwargs to be passed to sympy.sympify().

Returns:

LinearDictCombiner – Updated instance of LinearDictCombiner.

Raises:

RuntimeError – Sympification fails.

property terms: List[Any]

Returns dictionary keys.

to_ndarray(modes=None, dtype=complex, reverse=False)

Returns a state vector representation of this state.

Modes - and the bit position in the state index to which each corresponds - can be defined with the modes parameter. In the absence of this parameter, a default register of the appropriate size is implicit, with the index being assumed to correspond to an ILO-BE ordering of the default register. See below for examples.

Parameters:
  • modes (Optional[List[TypeVar(ModeT)]], default: None) – An ordering of modes used for defining indices, from most significant to least significant. Default behaviour as above.

  • dtype (default: complex) – The numpy dtype to be used for the returned vector.

  • reverse (bool, default: False) – If True, reverse bit order of state vector indices (e.g. for changing endianness).

Returns:

ndarray – A dense numpy ndarray representation of the state.

Examples

>>> qss0 = StateString({0:1,1:1,2:0,3:0})
>>> qss1 = StateString({0:1,1:0,2:1,3:0})
>>> qs = State({qss0: 0.9, qss1: 0.1})
>>> state_vector = qs.to_ndarray()
>>> print(state_vector)
[[0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0.1+0.j]
 [0. +0.j]
 [0.9+0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]]
>>> state_vector = qs.to_ndarray([0,2,3,1])
>>> print(state_vector)
[[0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0.9+0.j]
 [0. +0.j]
 [0. +0.j]
 [0.1+0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]]
to_sparray(modes=None, matrix_type=scipy.sparse.csr_array, dtype=complex, reverse=False)

Returns a scipy sparse array state vector representation of this state.

Modes - and the bit position in the state index to which each corresponds - can be defined with the modes parameter. In the absence of this parameter, a default register of the appropriate size is implicit, with the index being assumed to correspond to an ILO-BE ordering of the default register. See to_ndarray() for examples.

Parameters:
  • modes (Optional[List[TypeVar(ModeT)]], default: None) – An ordering of modes used for defining indices, from most significant to least significant. Default behaviour as above.

  • matrix_type (default: scipy.sparse.csr_array) – The type of the sparse matrix to be generated.

  • dtype (default: complex) – The numpy dtype to be used for the returned vector.

  • reverse (bool, default: False) – If True, reverse bit order of state vector indices (e.g. for changing endianness).

Returns:

A scipy sparse array representation of the state.

unsympify(precision=15, partial=False)

Unsympifies dictionary values.

Replaces symbolic expressions with their corresponding numeric values.

Parameters:
  • precision (int, default: 15) – The number of decimal digits of precision used for evaluation.

  • partial (bool, default: False) – Set to True to allow partial unsympification where terms containing free symbols are present. By default, free symbols in any coefficient will cause an exception.

Returns:

LinearDictCombiner – Updated instance of LinearDictCombiner.

Raises:

TypeError – Unsympification fails.

vdot(other)

Calculates the inner product with another State object.

The other State is treated as the ket, this one is treated as the bra - i.e. the coefficient

Parameters:

other (TypeVar(StateT, bound= State)) – Another State forming the ket of the inner product.

Returns:

Union[int, float, complex, Expr] – The inner product between self and other.

classmethod zero()

Return object with a zero dict entry.

Examples

>>> print(LinearDictCombiner.zero())
(0)
class FermionStateString(data)

Bases: StateString[int]

Represents a single basis state of a fermionic Fock space.

Fermionic modes are represented as integers, which serve as a numerical label for each mode/spin-orbital. This class does not contain capacity for storing a scalar coefficient associated with the basis state (i.e. it represents a ray, not a vector) – see FermionState for an arbitrary state in the fermionic state space. Note that instances of this class are immutable after creation.

Parameters:

data (Union[Dict[TypeVar(ModeT), Union[int, bool]], List[Union[int, bool]], Tuple[Union[int, bool]]]) – The basis state to be represented. Generally this will be in the form of a dictionary mapping mode indices to occupation numbers, as per the example below. For backwards compatibility, this can additionally be instantiated using a list of integer occupation numbers, for which a default set of modes will be assumed.

Raises:

ValueError – If provided occupation numbers are not 0 or 1.

Examples

>>> fss = FermionStateString({0:1, 1:1, 2:0, 5:0})
>>> print(fss)
{0: 1, 1: 1, 2: 0, 5: 0}
property all_modes: FrozenSet

Returns all mode objects in the space of which this StateString is a basis state.

classmethod from_index(state_index, modes=None, reverse=False)

Creates an instance from the index of a state vector corresponding to a single basis state.

Modes - and the bit position in the state index to which each corresponds - can be defined with the modes parameter. In the absence of this parameter, a default register of the appropriate size is implicit, with the index being assumed to correspond to an ILO-BE ordering of the default register. See below for examples.

Parameters:
  • state_index (int) – The index of a state vector corresponding to the basis state to which the created object will correspond.

  • modes (Optional[Iterable[TypeVar(ModeT)]], default: None) – A collection of modes, the state values of which are represented by the state vector, in the appropriate ordering.

  • reverse (default: False) – If True, reverse the bits of the index.

Returns:

TypeVar(StateStringT, bound= StateString) – An instance of this class corresponding to the basis state to which the provided index corresponds.

Examples

>>> index = 12
>>> statestring = StateString.from_index(index)
>>> print(statestring)
{0: 1, 1: 1, 2: 0, 3: 0}
>>> statestring = StateString.from_index(index,modes=[3,0,1,2])
>>> print(statestring)
{3: 1, 0: 1, 1: 0, 2: 0}
classmethod from_list_int(data)

Construct a StateString from a list of integers or booleans.

The integers within the list should correspond to the states of individual modes. Modes will be assumed to be indexed in the [0, len(data)) range in ascending order.

Parameters:

data (List[Union[int, bool]]) – State values to assign for the default mode set.

Returns:

TypeVar(StateStringT, bound= StateString) – An instance of this class representing the basis state with provided state values, using a default set of modes.

classmethod from_string(data)

Generate a class instance from a string.

This method will make a best effort to interpret a string as an instance of this class. It is provided largely for backwards compatibility. Caution is advised.

Parameters:

data (str) – A string from which to attempt to generate an instance of this class.

Returns:

TypeVar(StateStringT, bound= StateString) – A class instance generated from the input string.

property hamming_weight: int

Returns the Hamming weight of the basis state.

classmethod load_h5(name)

Loads a state string object from .h5 file.

Parameters:

name (Union[str, Group]) – Name of .h5 file to be loaded.

Returns:

TypeVar(StateStringT, bound= StateString) – Loaded integral operator object.

mode_class

alias of int

property num_modes: int

Returns the number of modes in the space of which this StateString is a basis state.

occupations_ordered()

Returns a list of integer or boolean occupation numbers corresponding to modes ordered in increasing lexicographic order.

Return type:

List[Union[int, bool]]

qubit_encode(mapping=None, qubits=None)

Performs qubit encoding (mapping), using provided mapping function, of the current FermionStateString.

Terms are treated and mapped independently.

Parameters:
  • mapping (Optional[QubitMapping], default: None) – Mapping class. Default mapping procedure is the Jordan-Wigner transformation.

  • qubits (Union[list[Qubit], int, None], default: None) – The qubit register. If left as None, a default register will be assumed if possible. See the mapping class documentation for further details.

Returns:

QubitStateString – Mapped QubitStateString.

save_h5(name)

Dumps state string object to .h5 file.

Parameters:

name (Union[str, Group]) – Destination filename of .h5 file.

Return type:

None

to_index(modes=None, reverse=False)

Returns the index of the state vector to which this basis state corresponds.

The ordering of modes when defining indexing into the state vector can be controlled with the modes parameter. By default, modes will be ordered following an ILO-BE convention - see examples.

Parameters:
  • modes (Optional[Iterable[TypeVar(ModeT)]], default: None) – An ordering of modes used for defining state vector indices, from most significant to least significant.

  • reverse (default: False) – If True, reverse the order of bits in the state vector index.

Returns:

int – A state vector index corresponding to this basis state.

Raises:

ValueError – If provided modes are not the same as those of the state.

Examples

>>> statestring = StateString({0:1,1:1,2:0,3:0})
>>> index = statestring.to_index()
>>> print(index)
12
>>> index = statestring.to_index([0,2,3,1])
>>> print(index)
9
class QubitState(data=None, coeff=1.0)

Bases: State, Representable

Represents the state of a register of qubits as a linear combination of computational basis states.

The state is stored as a dictionary, with the keys being QubitStateString objects and values being the corresponding configuration coefficients. The QubitState may be initialised from a QubitStateString and a coefficient, a tuple of tuple elements, each containing a coefficient and a QubitStateString object, or a dict, with QubitStateString objects as keys and coefficients as values. For a single basis state, it can also be initialised with a list of integers, wherein a default set of qubits (indexed from 0 upwards) will be assumed. See below for examples.

Parameters:

Examples

>>> qs0 = QubitState([1, 1, 0, 0], 1)
>>> print(qs0)
(1, {q[0]: 1, q[1]: 1, q[2]: 0, q[3]: 0})
>>> qss = QubitStateString({Qubit(0):1,Qubit(1):1,Qubit(2):0,Qubit(5):0})
>>> qs1 = QubitState(qss, 1)
>>> print(qs1)
(1, {q[0]: 1, q[1]: 1, q[2]: 0, q[5]: 0})
>>> qss0 = QubitStateString({Qubit(0):1,Qubit(1):1,Qubit(2):0,Qubit(5):0})
>>> qss1 = QubitStateString({Qubit(0):1,Qubit(1):0,Qubit(2):1,Qubit(5):0})
>>> qs2 = QubitState(((0.9, qss0), (0.1, qss1)))
>>> print(qs2)
(0.9, {q[0]: 1, q[1]: 1, q[2]: 0, q[5]: 0}), (0.1, {q[0]: 1, q[1]: 0, q[2]: 1, q[5]: 0})
>>> qss0 = QubitStateString({Qubit(0):1,Qubit(1):1,Qubit(2):0,Qubit(5):0})
>>> qss1 = QubitStateString({Qubit(0):1,Qubit(1):0,Qubit(2):1,Qubit(5):0})
>>> qs3 = QubitState({qss0: 0.9, qss1: 0.1})
>>> print(qs3)
(0.9, {q[0]: 1, q[1]: 1, q[2]: 0, q[5]: 0}), (0.1, {q[0]: 1, q[1]: 0, q[2]: 1, q[5]: 0})
approx_equal_to(other, abs_tol=1e-10)

Checks if object’s dictionary values are numerically identical to the other object values.

Parameters:
  • other (LinearDictCombiner) – Object to compare to.

  • abs_tol (float, default: 1e-10) – Threshold of comparing numeric values.

Raises:

TypeError – Comparison of two values can’t be done due to types mismatch.

Return type:

bool

approx_equal_to_by_random_subs(other, order=1, abs_tol=1e-10)

Checks if object’s dictionary values are numerically identical to the other object values.

Symbols contained in the difference of the two objects, if any, are substituted by random numeric values prior to norm check.

Parameters:
  • other (LinearDictCombiner) – Object to compare to.

  • order (int, default: 1) – Parameter specifying the norm formula (see numpy.linalg.norm() documentation).

  • abs_tol (float, default: 1e-10) – Threshold against which the norm of the difference is checked.

Return type:

bool

property basis_states: List[StateStringT]

Returns the basis states with nonzero coefficient as a list.

clone()

Performs shallow copy of the object.

Return type:

TypeVar(SYMBOLICTYPE, bound= Symbolic)

property coefficients: List[int | float | complex | Expr]

Returns the scalar coefficients of individual basis vectors as a list.

compress(abs_tol=1e-10, symbol_sub_type=CompressSymbolSubType.NONE)

Combines duplicate terms, removing those with negligible coefficient.

Parameters:
  • abs_tol (float, default: 1e-10) – Tolerance for comparing values to zero.

  • symbol_sub_type (Union[CompressSymbolSubType, str], default: CompressSymbolSubType.NONE) – Defines the behaviour for dealing with symbolic expressions in coefficients. If “none”, symbolic expressions are left intact. If “unity”, substitutes all free symbols with 1, and removes all imaginary and real components below tolerance. If “random”, substitutes all free symbols with a random number between 0 and 1, and removes imaginary and real components below tolerance.

Warning

When symbol_sub_type != "none", this method assumes significant expression structure is known a priori, and is best suited to operators which have simple product expressions, such as excitation operators for VQE ansatzes and digital quantum simulation. Otherwise, it may remove terms relevant to computation. Each expression is of the form \(f(a_1,a_2,\ldots,a_n)\) for some symbols \(a_i\). \(|f(a_1,a_2,\ldots,a_n)|\) is assumed to monotonically increase in both real and imaginary components for all \(a_i \in [0, 1]\).

Returns:

LinearDictCombiner – Updated instance of LinearDictCombiner.

copy()

Performs deep copy of the object.

Return type:

TypeVar(SYMBOLICTYPE, bound= Symbolic)

df()

Returns a Pandas DataFrame object of the dictionary.

Return type:

DataFrame

empty()

Checks if dictionary is empty.

Return type:

bool

evalf(*args, **kwargs)

Evaluates symbolic expressions stored in dict values and replaces them with the results.

Parameters:
  • args (Any) – Args to be passed to sympy.evalf().

  • kwargs (Any) – Kwargs to be passed to sympy.evalf().

Returns:

LinearDictCombiner – Updated instance of LinearDictCombiner.

free_symbols()

Returns the free symbols in the coefficient values.

free_symbols_ordered()

Returns the free symbols in the dict, ordered alphabetically.

Returns:

SymbolSet – Ordered set of symbols.

classmethod from_ndarray(state_vector, modes=None, reverse=False)

Returns an instance representing the provided ndarray state vector.

This method will take a state vector as a ndarray column vector and convert it to a State object. Modes - and the bit position in the state index to which each corresponds - can be defined with the modes parameter. In the absence of this parameter, a default register of the appropriate size is implicit, with the index being assumed to correspond to an ILO-BE ordering of the default register.

In keeping with numpy convention, 1-D arrays and 2-D arrays with shape (\(N\),1) are treated as column vectors. The length \(N\) of the vector must be either 0 or a power of 2. Differently shaped arrays are not accepted.

Parameters:
  • state_vector (ndarray) – The state vector representing the state to be created.

  • modes (Optional[Iterable[TypeVar(ModeT)]], default: None) – An ordering of modes used for defining indices, from most significant to least significant. Default behaviour as above.

  • reverse (default: False) – If True, reverse bit order of state vector indices (e.g. for changing endianness).

Returns:

An instance of this class representing the provided ndarray state vector.

Raises:

ValueError – If the input state vector has invalid shape.

classmethod from_sparray(state_vector, modes=None, reverse=False)

Returns an instance representing the provided scipy sparse array state_vector.

This method will take a state vector as a scipy sparse array and convert it to a State object. Modes - and the bit position in the state index to which each corresponds - can be defined with the modes parameter. In the absence of this parameter, a default register of the appropriate size is implicit, with the index being assumed to correspond to an ILO-BE ordering of the default register.

The shape of the array must be (\(N\), 1) where \(N\) is either 0 or a power of 2. Differently shaped arrays are not accepted.

Parameters:
  • state_vector (spmatrix) – The state vector representing the state to be created.

  • modes (Optional[Iterable[TypeVar(ModeT)]], default: None) – An ordering of modes used for defining indices, from most significant to least significant. Default behaviour as above.

  • reverse (default: False) – If True, reverse bit order of state vector indices (e.g. for changing endianness).

Returns:

An instance of this class representing state_vector.

classmethod from_string(input_string)

Constructs a child class instance from a string.

Parameters:

input_string (str) – String in the format coeff1 [(coeff1_1, term1_1), ..., (coeff1_n, term1_n)], ..., coeffn [(coeffn_1, termn_1), ...].

Returns:

TypeVar(StateT, bound= State) – Child class object.

get_numeric_representation(symbol_map=None, dtype=complex, backend=None)

Returns a state vector representation of this state, with an optional symbol substitution map.

This proceeds by substituting symbols for numeric values according to the provided map, before converting to a ndarray using the to_ndarray() method. Qubits are ordered according to an ILO-BE convention. See the documentation of the to_ndarray() method for further details.

Danger

This method requires exponential resources.

Parameters:
Returns:

Union[_SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], bool, int, float, complex, str, bytes, _NestedSequence[Union[bool, int, float, complex, str, bytes]]] – A vector representing the object.

get_symbolic_representation(symbol_map=None)

Constructs a sympy symbolic statevector representation.

Qubits will be ordered according to an ILO-BE convention. See to_index() for further details.

Danger

This method requires exponential resources.

Parameters:

symbol_map (Union[SymbolDict, Dict[Symbol, Expr], Dict[Symbol, float], Dict[Symbol, Union[float, complex, Expr]], Callable[[Symbol], Expr], str, None], default: None) – A symbol substitution map before constructing the representation, to replace symbolic coefficients with numerical ones.

Returns:

Expr – A symbolic statevector representation.

is_all_coeff_complex()

Check if all coefficients have complex values.

Returns:

boolFalse if a non-complex value occurs before any free symbols in the dict values, or True if no non-complex values occur.

Warning

Returns None if a free symbol occurs before any non-complex values in the coefficients.

is_all_coeff_imag()

Check if all coefficients have purely imaginary values.

Returns:

boolFalse if a non-complex value occurs before any free symbols in the dict values, or True if no non-complex values occur.

Warning

Returns None if a free symbol occurs before any non-imaginary values in the coefficients.

is_all_coeff_real()

Check if all coefficients have real values.

Returns:

boolFalse if a non-real value occurs before any free symbols in the dict values, or True if no non-real values occur.

Warning

Returns None if a free symbol occurs before any non-real values in the dict coefficients.

is_all_coeff_symbolic()

Check if all coefficients contain free symbols.

Returns:

bool – Whether all coefficients contain free symbols.

is_any_coeff_complex()

Check if any coefficients have complex values.

Returns:

boolTrue if a complex value occurs before any free symbols in the dict values, or False if no complex values occur.

Warning

Returns None if a free symbol occurs before any complex values in the coefficients.

is_any_coeff_imag()

Check if any coefficients have imaginary values.

Returns:

boolTrue if an imaginary value occurs before any free symbols in the dict values, or False if no imaginary values occur.

Warning

Returns None if a free symbol occurs before any imaginary values in the coefficients.

is_any_coeff_real()

Check if any coefficients have real values.

Returns:

boolTrue if a real value occurs before any free symbols in the dict values, or False if no real values occur.

Warning

Returns None if a free symbol occurs before any real values in the coefficients.

is_any_coeff_symbolic()

Check if any coefficients contain free symbols.

Returns:

bool – Whether any coefficients contain free symbols.

is_basis_state()

Checks this object represents a scalar multiple of a single basis state.

Return type:

bool

is_normalized(order=2, abs_tol=1e-10)

Returns True if operator has unit p-norm, else False.

Parameters:
  • order (int, default: 2) – Norm order.

  • abs_tol (float, default: 1e-10) – Tolerance threshold for comparison with unity.

Raises:

ValueError – Coefficients contain free symbols.

Return type:

bool

is_parallel_with(other, abs_tol=1e-10)

Returns True if other is parallel with this (i.e. a scalar multiple of this), otherwise False.

Parameters:
  • other (LinearDictCombiner) – The other object to compare against

  • abs_tol (Optional[float], default: 1e-10) – Tolerance threshold for comparison. Set to None to test for exact equivalence.

Returns:

boolTrue if other is parallel with this, otherwise False.

is_unit_1norm(abs_tol=1e-10)

Returns True if operator has unit 1-norm, else False.

Parameters:

abs_tol (float, default: 1e-10) – Tolerance threshold for comparison with unity.

Return type:

bool

is_unit_2norm(abs_tol=1e-10)

Returns True if operator has unit 1-norm, else False.

Parameters:

abs_tol (float, default: 1e-10) – Tolerance threshold for comparison with unity.

Return type:

bool

is_unit_norm(order=2, abs_tol=1e-10)

Returns True if operator has unit p-norm, else False.

Parameters:
  • order (int, default: 2) – Norm order.

  • abs_tol (float, default: 1e-10) – Tolerance threshold for comparison with unity.

Raises:

ValueError – Coefficients contain free symbols.

Return type:

bool

items()

Returns dictionary items.

Return type:

ItemsView[Any, Union[int, float, complex, Expr]]

classmethod key_from_str(key_str)

Converts a string to an instance of this class’s basis state type.

Parameters:

key_str (str) –

Return type:

TypeVar(StateStringT, bound= StateString)

classmethod load_h5(name)

Loads a state object from .h5 file.

Parameters:

name (Union[str, Group]) – Name of .h5 file to be loaded.

Returns:

TypeVar(StateT, bound= State) – Loaded integral operator object.

make_hashable()

Return a hashable representation of the object.

Returns:

str – A string representation of this instance.

map(mapping)

Updates dictionary values, using a mapping function provided.

Parameters:

mapping (Callable[[Union[int, float, complex, Expr]], Union[int, float, complex, Expr]]) – Mapping function to update the dict.

Returns:

LinearDictCombiner – This instance.

property n_qubits: int

Returns number of qubits in state space.

property n_symbols: int

Returns the number of free symbols in the object.

norm_coefficients(order=2)

Returns the p-norm of the coefficients.

Parameters:

order (int, default: 2) – Norm order.

Return type:

Union[complex, float]

normalized(norm_value=1.0, norm_order=2)

Returns a copy of this object with normalised coefficients.

Parameters:
  • norm_value (float, default: 1.0) – The desired norm of the returned operator.

  • norm_order (int, default: 2) – The order of the norm to be used.

Returns:

LinearDictCombiner – A copy of the object with coefficients normalised to the desired value.

property num_modes: int

Returns the number of modes.

property num_qubits: int

Returns number of qubits in state space.

print_table()

Print dictionary formatted as a table.

Return type:

NoReturn

remove_global_phase()

Returns a copy with a global phase applied such that the first element has a real coefficient.

This is an alias for set_global_phase() - see this method for greater control over the phase to be applied.

Returns:

LinearDictCombiner – A copy of the object with a global phase applied such that the first element has a real coefficient.

reversed_order()

Reverses the order of terms and returns it as a new object.

Return type:

LinearDictCombiner

save_h5(name)

Dumps state object to .h5 file.

Parameters:

name (Union[str, Group]) – Destination filename of .h5 file.

Return type:

None

set_global_phase(phase=0.0)

Returns a copy with a global phase applied such that the first element has the desired phase.

Parameters:
  • phase (Union[int, float, complex, Expr], default: 0.0) – The phase to yield on the first element, in half-turns (i.e. multiples of pi).

  • phase. (A symbolic expression can be assigned to) –

Returns:

LinearDictCombiner – A copy of the object with the desired global phase applied.

simplify(*args, **kwargs)

Simplifies expressions stored in dictionary values.

Parameters:
  • args (Any) – Args to be passed to sympy.simplify().

  • kwargs (Any) – Kwargs to be passed to sympy.simplify().

Returns:

LinearDictCombiner – Updated instance of LinearDictCombiner.

property single_term: StateStringT

Returns the stored configuration as a StateString, if only a single configuration is stored.

Raises:

RuntimeError – if more or less than one configuration is stored

Returns:

The single configuration occupation vector.

split()

Generates State objects containing only single configurations, preserving coefficients.

Return type:

Generator[TypeVar(StateT, bound= State), None, None]

property state_symbols

Returns the free symbols within the coefficients of the state.

string_class

alias of QubitStateString

subs(symbol_map)

Returns a new objects with symbols substituted.

Parameters:

symbol_map (Union[SymbolDict, Dict[Symbol, Expr], Dict[Symbol, float], Dict[Symbol, Union[float, complex, Expr]], Callable[[Symbol], Expr], str]) – A mapping for substitution of free symbols.

Returns:

TypeVar(SYMBOLICTYPE, bound= Symbolic) – A copy of self with symbols substituted according to the provided map.

symbol_substitution(symbol_map=None)

Substitutes free symbols for numerical values according to a map.

Parameters:

symbol_map (Union[SymbolDict, Dict[Symbol, Expr], Dict[Symbol, float], Dict[Symbol, Union[float, complex, Expr]], Callable[[Symbol], Expr], str, None], default: None) –

Return type:

LinearDictCombiner

sympify(*args, **kwargs)

Sympifies dictionary values.

Replaces values with their corresponding symbolic expressions.

Parameters:
  • args (Any) – Args to be passed to sympy.sympify().

  • kwargs (Any) – Kwargs to be passed to sympy.sympify().

Returns:

LinearDictCombiner – Updated instance of LinearDictCombiner.

Raises:

RuntimeError – Sympification fails.

property terms: List[Any]

Returns dictionary keys.

to_ndarray(modes=None, dtype=complex, reverse=False)

Returns a state vector representation of this state.

Modes - and the bit position in the state index to which each corresponds - can be defined with the modes parameter. In the absence of this parameter, a default register of the appropriate size is implicit, with the index being assumed to correspond to an ILO-BE ordering of the default register. See below for examples.

Parameters:
  • modes (Optional[List[TypeVar(ModeT)]], default: None) – An ordering of modes used for defining indices, from most significant to least significant. Default behaviour as above.

  • dtype (default: complex) – The numpy dtype to be used for the returned vector.

  • reverse (bool, default: False) – If True, reverse bit order of state vector indices (e.g. for changing endianness).

Returns:

ndarray – A dense numpy ndarray representation of the state.

Examples

>>> qss0 = StateString({0:1,1:1,2:0,3:0})
>>> qss1 = StateString({0:1,1:0,2:1,3:0})
>>> qs = State({qss0: 0.9, qss1: 0.1})
>>> state_vector = qs.to_ndarray()
>>> print(state_vector)
[[0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0.1+0.j]
 [0. +0.j]
 [0.9+0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]]
>>> state_vector = qs.to_ndarray([0,2,3,1])
>>> print(state_vector)
[[0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0.9+0.j]
 [0. +0.j]
 [0. +0.j]
 [0.1+0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]]
to_sparray(modes=None, matrix_type=scipy.sparse.csr_array, dtype=complex, reverse=False)

Returns a scipy sparse array state vector representation of this state.

Modes - and the bit position in the state index to which each corresponds - can be defined with the modes parameter. In the absence of this parameter, a default register of the appropriate size is implicit, with the index being assumed to correspond to an ILO-BE ordering of the default register. See to_ndarray() for examples.

Parameters:
  • modes (Optional[List[TypeVar(ModeT)]], default: None) – An ordering of modes used for defining indices, from most significant to least significant. Default behaviour as above.

  • matrix_type (default: scipy.sparse.csr_array) – The type of the sparse matrix to be generated.

  • dtype (default: complex) – The numpy dtype to be used for the returned vector.

  • reverse (bool, default: False) – If True, reverse bit order of state vector indices (e.g. for changing endianness).

Returns:

A scipy sparse array representation of the state.

unsympify(precision=15, partial=False)

Unsympifies dictionary values.

Replaces symbolic expressions with their corresponding numeric values.

Parameters:
  • precision (int, default: 15) – The number of decimal digits of precision used for evaluation.

  • partial (bool, default: False) – Set to True to allow partial unsympification where terms containing free symbols are present. By default, free symbols in any coefficient will cause an exception.

Returns:

LinearDictCombiner – Updated instance of LinearDictCombiner.

Raises:

TypeError – Unsympification fails.

vdot(other)

Calculates the inner product with another State object.

The other State is treated as the ket, this one is treated as the bra - i.e. the coefficient

Parameters:

other (TypeVar(StateT, bound= State)) – Another State forming the ket of the inner product.

Returns:

Union[int, float, complex, Expr] – The inner product between self and other.

classmethod zero()

Return object with a zero dict entry.

Examples

>>> print(LinearDictCombiner.zero())
(0)
class QubitStateString(data)

Bases: StateString

Represents a computational basis state of a register of qubits.

Qubits are represented by Qubit objects. This class does not contain capacity for storing a scalar coefficient associated with the basis state (i.e. it represents a ray, not a vector) – see QubitState for an arbitrary state in the qubit state space. Note that instances of this class are immutable after creation.

Parameters:

data (Union[Dict[TypeVar(ModeT), Union[int, bool]], List[Union[int, bool]], Tuple[Union[int, bool]]]) – The basis state to be represented. Generally this will be in the form of a dictionary mapping qubits to 0 or 1 states, as per the example below. For backwards compatibility, this can additionally be instantiated using a list of integer occupation numbers, for which a default set of modes will be assumed.

Raises:

ValueError – If provided state values are not 0 or 1.

Examples

>>> qss = QubitStateString({Qubit(0):1, Qubit(1):1, Qubit(2):0, Qubit(5):0})
>>> print(qss)
{q[0]: 1, q[1]: 1, q[2]: 0, q[5]: 0}
property all_modes: FrozenSet

Returns all mode objects in the space of which this StateString is a basis state.

classmethod from_index(state_index, modes=None, reverse=False)

Creates an instance from the index of a state vector corresponding to a single basis state.

Modes - and the bit position in the state index to which each corresponds - can be defined with the modes parameter. In the absence of this parameter, a default register of the appropriate size is implicit, with the index being assumed to correspond to an ILO-BE ordering of the default register. See below for examples.

Parameters:
  • state_index (int) – The index of a state vector corresponding to the basis state to which the created object will correspond.

  • modes (Optional[Iterable[TypeVar(ModeT)]], default: None) – A collection of modes, the state values of which are represented by the state vector, in the appropriate ordering.

  • reverse (default: False) – If True, reverse the bits of the index.

Returns:

TypeVar(StateStringT, bound= StateString) – An instance of this class corresponding to the basis state to which the provided index corresponds.

Examples

>>> index = 12
>>> statestring = StateString.from_index(index)
>>> print(statestring)
{0: 1, 1: 1, 2: 0, 3: 0}
>>> statestring = StateString.from_index(index,modes=[3,0,1,2])
>>> print(statestring)
{3: 1, 0: 1, 1: 0, 2: 0}
classmethod from_list_int(data)

Construct a StateString from a list of integers or booleans.

The integers within the list should correspond to the states of individual modes. Modes will be assumed to be indexed in the [0, len(data)) range in ascending order.

Parameters:

data (List[Union[int, bool]]) – State values to assign for the default mode set.

Returns:

TypeVar(StateStringT, bound= StateString) – An instance of this class representing the basis state with provided state values, using a default set of modes.

classmethod from_string(data)

Constructs a class instance from a string.

This method will make a best effort to interpret a string as an instance of this class. It is provided largely for backwards compatibility. Caution is advised.

Parameters:
  • input_string – String in the format coeff1 [(coeff1_1, term1_1), ..., (coeff1_n, term1_n)], ..., coeffn [(coeffn_1, termn_1), ...].

  • data (str) –

Returns:

QubitStateString – Child class object.

property hamming_weight: int

Returns the Hamming weight of the basis state.

classmethod load_h5(name)

Loads a state string object from .h5 file.

Parameters:

name (Union[str, Group]) – Name of .h5 file to be loaded.

Returns:

TypeVar(StateStringT, bound= StateString) – Loaded integral operator object.

mode_class

alias of Qubit

property num_modes: int

Returns the number of modes in the space of which this StateString is a basis state.

occupations_ordered()

Returns a list of integer or boolean occupation numbers corresponding to modes ordered in increasing lexicographic order.

Return type:

List[Union[int, bool]]

save_h5(name)

Dumps state string object to .h5 file.

Parameters:

name (Union[str, Group]) – Destination filename of .h5 file.

Return type:

None

to_index(modes=None, reverse=False)

Returns the index of the state vector to which this basis state corresponds.

The ordering of modes when defining indexing into the state vector can be controlled with the modes parameter. By default, modes will be ordered following an ILO-BE convention - see examples.

Parameters:
  • modes (Optional[Iterable[TypeVar(ModeT)]], default: None) – An ordering of modes used for defining state vector indices, from most significant to least significant.

  • reverse (default: False) – If True, reverse the order of bits in the state vector index.

Returns:

int – A state vector index corresponding to this basis state.

Raises:

ValueError – If provided modes are not the same as those of the state.

Examples

>>> statestring = StateString({0:1,1:1,2:0,3:0})
>>> index = statestring.to_index()
>>> print(index)
12
>>> index = statestring.to_index([0,2,3,1])
>>> print(index)
9
class State(data=None, coeff=1.0)

Bases: LinearDictCombiner, Representable, Generic[StateStringT]

A generic class for representing a state vector within some arbitrary Hilbert space.

This class is generic with regard to the nature of the underlying modes. Typically, one should use subclasses which represent basis vectors within a specific space - see the documentation for QubitState and FermionState.

Within this class, StateString-derived objects are mapped in a dict-like fashion to scalar coefficients, in order to represent a linear combination of basis states. Subclasses must define the string_class attribute, which gives the type (derived from StateString) of the object representing an individual basis state.

Examples

>>> qs0 = State([1, 1, 0, 0], 1)
>>> print(qs0)
(1, {0: 1, 1: 1, 2: 0, 3: 0})
>>> qss = StateString({0:1,1:1,2:0,3:0})
>>> qs1 = State(qss, 1)
>>> print(qs1)
(1, {0: 1, 1: 1, 2: 0, 3: 0})
>>> qss0 = StateString({0:1,1:1,2:0,3:0})
>>> qss1 = StateString({0:1,1:0,2:1,3:0})
>>> qs2 = State(((0.9, qss0), (0.1, qss1)))
>>> print(qs2)
(0.9, {0: 1, 1: 1, 2: 0, 3: 0}), (0.1, {0: 1, 1: 0, 2: 1, 3: 0})
>>> qss0 = StateString({0:1,1:1,2:0,3:0})
>>> qss1 = StateString({0:1,1:0,2:1,3:0})
>>> qs3 = State({qss0: 0.9, qss1: 0.1})
>>> print(qs3)
(0.9, {0: 1, 1: 1, 2: 0, 3: 0}), (0.1, {0: 1, 1: 0, 2: 1, 3: 0})
Parameters:
approx_equal_to(other, abs_tol=1e-10)

Checks if object’s dictionary values are numerically identical to the other object values.

Parameters:
  • other (LinearDictCombiner) – Object to compare to.

  • abs_tol (float, default: 1e-10) – Threshold of comparing numeric values.

Raises:

TypeError – Comparison of two values can’t be done due to types mismatch.

Return type:

bool

approx_equal_to_by_random_subs(other, order=1, abs_tol=1e-10)

Checks if object’s dictionary values are numerically identical to the other object values.

Symbols contained in the difference of the two objects, if any, are substituted by random numeric values prior to norm check.

Parameters:
  • other (LinearDictCombiner) – Object to compare to.

  • order (int, default: 1) – Parameter specifying the norm formula (see numpy.linalg.norm() documentation).

  • abs_tol (float, default: 1e-10) – Threshold against which the norm of the difference is checked.

Return type:

bool

property basis_states: List[StateStringT]

Returns the basis states with nonzero coefficient as a list.

clone()

Performs shallow copy of the object.

Return type:

TypeVar(SYMBOLICTYPE, bound= Symbolic)

property coefficients: List[int | float | complex | Expr]

Returns the scalar coefficients of individual basis vectors as a list.

compress(abs_tol=1e-10, symbol_sub_type=CompressSymbolSubType.NONE)

Combines duplicate terms, removing those with negligible coefficient.

Parameters:
  • abs_tol (float, default: 1e-10) – Tolerance for comparing values to zero.

  • symbol_sub_type (Union[CompressSymbolSubType, str], default: CompressSymbolSubType.NONE) – Defines the behaviour for dealing with symbolic expressions in coefficients. If “none”, symbolic expressions are left intact. If “unity”, substitutes all free symbols with 1, and removes all imaginary and real components below tolerance. If “random”, substitutes all free symbols with a random number between 0 and 1, and removes imaginary and real components below tolerance.

Warning

When symbol_sub_type != "none", this method assumes significant expression structure is known a priori, and is best suited to operators which have simple product expressions, such as excitation operators for VQE ansatzes and digital quantum simulation. Otherwise, it may remove terms relevant to computation. Each expression is of the form \(f(a_1,a_2,\ldots,a_n)\) for some symbols \(a_i\). \(|f(a_1,a_2,\ldots,a_n)|\) is assumed to monotonically increase in both real and imaginary components for all \(a_i \in [0, 1]\).

Returns:

LinearDictCombiner – Updated instance of LinearDictCombiner.

copy()

Performs deep copy of the object.

Return type:

TypeVar(SYMBOLICTYPE, bound= Symbolic)

df()

Returns a Pandas DataFrame object of the dictionary.

Return type:

DataFrame

empty()

Checks if dictionary is empty.

Return type:

bool

evalf(*args, **kwargs)

Evaluates symbolic expressions stored in dict values and replaces them with the results.

Parameters:
  • args (Any) – Args to be passed to sympy.evalf().

  • kwargs (Any) – Kwargs to be passed to sympy.evalf().

Returns:

LinearDictCombiner – Updated instance of LinearDictCombiner.

free_symbols()

Returns the free symbols in the coefficient values.

free_symbols_ordered()

Returns the free symbols in the dict, ordered alphabetically.

Returns:

SymbolSet – Ordered set of symbols.

classmethod from_ndarray(state_vector, modes=None, reverse=False)

Returns an instance representing the provided ndarray state vector.

This method will take a state vector as a ndarray column vector and convert it to a State object. Modes - and the bit position in the state index to which each corresponds - can be defined with the modes parameter. In the absence of this parameter, a default register of the appropriate size is implicit, with the index being assumed to correspond to an ILO-BE ordering of the default register.

In keeping with numpy convention, 1-D arrays and 2-D arrays with shape (\(N\),1) are treated as column vectors. The length \(N\) of the vector must be either 0 or a power of 2. Differently shaped arrays are not accepted.

Parameters:
  • state_vector (ndarray) – The state vector representing the state to be created.

  • modes (Optional[Iterable[TypeVar(ModeT)]], default: None) – An ordering of modes used for defining indices, from most significant to least significant. Default behaviour as above.

  • reverse (default: False) – If True, reverse bit order of state vector indices (e.g. for changing endianness).

Returns:

An instance of this class representing the provided ndarray state vector.

Raises:

ValueError – If the input state vector has invalid shape.

classmethod from_sparray(state_vector, modes=None, reverse=False)

Returns an instance representing the provided scipy sparse array state_vector.

This method will take a state vector as a scipy sparse array and convert it to a State object. Modes - and the bit position in the state index to which each corresponds - can be defined with the modes parameter. In the absence of this parameter, a default register of the appropriate size is implicit, with the index being assumed to correspond to an ILO-BE ordering of the default register.

The shape of the array must be (\(N\), 1) where \(N\) is either 0 or a power of 2. Differently shaped arrays are not accepted.

Parameters:
  • state_vector (spmatrix) – The state vector representing the state to be created.

  • modes (Optional[Iterable[TypeVar(ModeT)]], default: None) – An ordering of modes used for defining indices, from most significant to least significant. Default behaviour as above.

  • reverse (default: False) – If True, reverse bit order of state vector indices (e.g. for changing endianness).

Returns:

An instance of this class representing state_vector.

classmethod from_string(input_string)

Constructs a child class instance from a string.

Parameters:

input_string (str) – String in the format coeff1 [(coeff1_1, term1_1), ..., (coeff1_n, term1_n)], ..., coeffn [(coeffn_1, termn_1), ...].

Returns:

TypeVar(StateT, bound= State) – Child class object.

get_numeric_representation()

Placeholder, unimplemented method.

get_symbolic_representation()

Placeholder, unimplemented method.

is_all_coeff_complex()

Check if all coefficients have complex values.

Returns:

boolFalse if a non-complex value occurs before any free symbols in the dict values, or True if no non-complex values occur.

Warning

Returns None if a free symbol occurs before any non-complex values in the coefficients.

is_all_coeff_imag()

Check if all coefficients have purely imaginary values.

Returns:

boolFalse if a non-complex value occurs before any free symbols in the dict values, or True if no non-complex values occur.

Warning

Returns None if a free symbol occurs before any non-imaginary values in the coefficients.

is_all_coeff_real()

Check if all coefficients have real values.

Returns:

boolFalse if a non-real value occurs before any free symbols in the dict values, or True if no non-real values occur.

Warning

Returns None if a free symbol occurs before any non-real values in the dict coefficients.

is_all_coeff_symbolic()

Check if all coefficients contain free symbols.

Returns:

bool – Whether all coefficients contain free symbols.

is_any_coeff_complex()

Check if any coefficients have complex values.

Returns:

boolTrue if a complex value occurs before any free symbols in the dict values, or False if no complex values occur.

Warning

Returns None if a free symbol occurs before any complex values in the coefficients.

is_any_coeff_imag()

Check if any coefficients have imaginary values.

Returns:

boolTrue if an imaginary value occurs before any free symbols in the dict values, or False if no imaginary values occur.

Warning

Returns None if a free symbol occurs before any imaginary values in the coefficients.

is_any_coeff_real()

Check if any coefficients have real values.

Returns:

boolTrue if a real value occurs before any free symbols in the dict values, or False if no real values occur.

Warning

Returns None if a free symbol occurs before any real values in the coefficients.

is_any_coeff_symbolic()

Check if any coefficients contain free symbols.

Returns:

bool – Whether any coefficients contain free symbols.

is_basis_state()

Checks this object represents a scalar multiple of a single basis state.

Return type:

bool

is_normalized(order=2, abs_tol=1e-10)

Returns True if operator has unit p-norm, else False.

Parameters:
  • order (int, default: 2) – Norm order.

  • abs_tol (float, default: 1e-10) – Tolerance threshold for comparison with unity.

Raises:

ValueError – Coefficients contain free symbols.

Return type:

bool

is_parallel_with(other, abs_tol=1e-10)

Returns True if other is parallel with this (i.e. a scalar multiple of this), otherwise False.

Parameters:
  • other (LinearDictCombiner) – The other object to compare against

  • abs_tol (Optional[float], default: 1e-10) – Tolerance threshold for comparison. Set to None to test for exact equivalence.

Returns:

boolTrue if other is parallel with this, otherwise False.

is_unit_1norm(abs_tol=1e-10)

Returns True if operator has unit 1-norm, else False.

Parameters:

abs_tol (float, default: 1e-10) – Tolerance threshold for comparison with unity.

Return type:

bool

is_unit_2norm(abs_tol=1e-10)

Returns True if operator has unit 1-norm, else False.

Parameters:

abs_tol (float, default: 1e-10) – Tolerance threshold for comparison with unity.

Return type:

bool

is_unit_norm(order=2, abs_tol=1e-10)

Returns True if operator has unit p-norm, else False.

Parameters:
  • order (int, default: 2) – Norm order.

  • abs_tol (float, default: 1e-10) – Tolerance threshold for comparison with unity.

Raises:

ValueError – Coefficients contain free symbols.

Return type:

bool

items()

Returns dictionary items.

Return type:

ItemsView[Any, Union[int, float, complex, Expr]]

classmethod key_from_str(key_str)

Converts a string to an instance of this class’s basis state type.

Parameters:

key_str (str) –

Return type:

TypeVar(StateStringT, bound= StateString)

classmethod load_h5(name)

Loads a state object from .h5 file.

Parameters:

name (Union[str, Group]) – Name of .h5 file to be loaded.

Returns:

TypeVar(StateT, bound= State) – Loaded integral operator object.

make_hashable()

Return a hashable representation of the object.

Returns:

str – A string representation of this instance.

map(mapping)

Updates dictionary values, using a mapping function provided.

Parameters:

mapping (Callable[[Union[int, float, complex, Expr]], Union[int, float, complex, Expr]]) – Mapping function to update the dict.

Returns:

LinearDictCombiner – This instance.

property n_symbols: int

Returns the number of free symbols in the object.

norm_coefficients(order=2)

Returns the p-norm of the coefficients.

Parameters:

order (int, default: 2) – Norm order.

Return type:

Union[complex, float]

normalized(norm_value=1.0, norm_order=2)

Returns a copy of this object with normalised coefficients.

Parameters:
  • norm_value (float, default: 1.0) – The desired norm of the returned operator.

  • norm_order (int, default: 2) – The order of the norm to be used.

Returns:

LinearDictCombiner – A copy of the object with coefficients normalised to the desired value.

property num_modes: int

Returns the number of modes.

print_table()

Print dictionary formatted as a table.

Return type:

NoReturn

remove_global_phase()

Returns a copy with a global phase applied such that the first element has a real coefficient.

This is an alias for set_global_phase() - see this method for greater control over the phase to be applied.

Returns:

LinearDictCombiner – A copy of the object with a global phase applied such that the first element has a real coefficient.

reversed_order()

Reverses the order of terms and returns it as a new object.

Return type:

LinearDictCombiner

save_h5(name)

Dumps state object to .h5 file.

Parameters:

name (Union[str, Group]) – Destination filename of .h5 file.

Return type:

None

set_global_phase(phase=0.0)

Returns a copy with a global phase applied such that the first element has the desired phase.

Parameters:
  • phase (Union[int, float, complex, Expr], default: 0.0) – The phase to yield on the first element, in half-turns (i.e. multiples of pi).

  • phase. (A symbolic expression can be assigned to) –

Returns:

LinearDictCombiner – A copy of the object with the desired global phase applied.

simplify(*args, **kwargs)

Simplifies expressions stored in dictionary values.

Parameters:
  • args (Any) – Args to be passed to sympy.simplify().

  • kwargs (Any) – Kwargs to be passed to sympy.simplify().

Returns:

LinearDictCombiner – Updated instance of LinearDictCombiner.

property single_term: StateStringT

Returns the stored configuration as a StateString, if only a single configuration is stored.

Raises:

RuntimeError – if more or less than one configuration is stored

Returns:

The single configuration occupation vector.

split()

Generates State objects containing only single configurations, preserving coefficients.

Return type:

Generator[TypeVar(StateT, bound= State), None, None]

string_class

alias of StateString

subs(symbol_map)

Returns a new objects with symbols substituted.

Parameters:

symbol_map (Union[SymbolDict, Dict[Symbol, Expr], Dict[Symbol, float], Dict[Symbol, Union[float, complex, Expr]], Callable[[Symbol], Expr], str]) – A mapping for substitution of free symbols.

Returns:

TypeVar(SYMBOLICTYPE, bound= Symbolic) – A copy of self with symbols substituted according to the provided map.

symbol_substitution(symbol_map=None)

Substitutes free symbols for numerical values according to a map.

Parameters:

symbol_map (Union[SymbolDict, Dict[Symbol, Expr], Dict[Symbol, float], Dict[Symbol, Union[float, complex, Expr]], Callable[[Symbol], Expr], str, None], default: None) –

Return type:

LinearDictCombiner

sympify(*args, **kwargs)

Sympifies dictionary values.

Replaces values with their corresponding symbolic expressions.

Parameters:
  • args (Any) – Args to be passed to sympy.sympify().

  • kwargs (Any) – Kwargs to be passed to sympy.sympify().

Returns:

LinearDictCombiner – Updated instance of LinearDictCombiner.

Raises:

RuntimeError – Sympification fails.

property terms: List[Any]

Returns dictionary keys.

to_ndarray(modes=None, dtype=complex, reverse=False)

Returns a state vector representation of this state.

Modes - and the bit position in the state index to which each corresponds - can be defined with the modes parameter. In the absence of this parameter, a default register of the appropriate size is implicit, with the index being assumed to correspond to an ILO-BE ordering of the default register. See below for examples.

Parameters:
  • modes (Optional[List[TypeVar(ModeT)]], default: None) – An ordering of modes used for defining indices, from most significant to least significant. Default behaviour as above.

  • dtype (default: complex) – The numpy dtype to be used for the returned vector.

  • reverse (bool, default: False) – If True, reverse bit order of state vector indices (e.g. for changing endianness).

Returns:

ndarray – A dense numpy ndarray representation of the state.

Examples

>>> qss0 = StateString({0:1,1:1,2:0,3:0})
>>> qss1 = StateString({0:1,1:0,2:1,3:0})
>>> qs = State({qss0: 0.9, qss1: 0.1})
>>> state_vector = qs.to_ndarray()
>>> print(state_vector)
[[0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0.1+0.j]
 [0. +0.j]
 [0.9+0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]]
>>> state_vector = qs.to_ndarray([0,2,3,1])
>>> print(state_vector)
[[0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]
 [0.9+0.j]
 [0. +0.j]
 [0. +0.j]
 [0.1+0.j]
 [0. +0.j]
 [0. +0.j]
 [0. +0.j]]
to_sparray(modes=None, matrix_type=scipy.sparse.csr_array, dtype=complex, reverse=False)

Returns a scipy sparse array state vector representation of this state.

Modes - and the bit position in the state index to which each corresponds - can be defined with the modes parameter. In the absence of this parameter, a default register of the appropriate size is implicit, with the index being assumed to correspond to an ILO-BE ordering of the default register. See to_ndarray() for examples.

Parameters:
  • modes (Optional[List[TypeVar(ModeT)]], default: None) – An ordering of modes used for defining indices, from most significant to least significant. Default behaviour as above.

  • matrix_type (default: scipy.sparse.csr_array) – The type of the sparse matrix to be generated.

  • dtype (default: complex) – The numpy dtype to be used for the returned vector.

  • reverse (bool, default: False) – If True, reverse bit order of state vector indices (e.g. for changing endianness).

Returns:

A scipy sparse array representation of the state.

unsympify(precision=15, partial=False)

Unsympifies dictionary values.

Replaces symbolic expressions with their corresponding numeric values.

Parameters:
  • precision (int, default: 15) – The number of decimal digits of precision used for evaluation.

  • partial (bool, default: False) – Set to True to allow partial unsympification where terms containing free symbols are present. By default, free symbols in any coefficient will cause an exception.

Returns:

LinearDictCombiner – Updated instance of LinearDictCombiner.

Raises:

TypeError – Unsympification fails.

vdot(other)

Calculates the inner product with another State object.

The other State is treated as the ket, this one is treated as the bra - i.e. the coefficient

Parameters:

other (TypeVar(StateT, bound= State)) – Another State forming the ket of the inner product.

Returns:

Union[int, float, complex, Expr] – The inner product between self and other.

classmethod zero()

Return object with a zero dict entry.

Examples

>>> print(LinearDictCombiner.zero())
(0)
class StateString(data)

Bases: UserDict, Generic[ModeT]

Represents a basis vector in an arbitrary Hilbert space.

This class is generic with regard to the nature of the underlying modes. Typically, one should use subclasses which represent basis vectors within a specific space - see the documentation for QubitStateString and FermionStateString. Subclasses must define the mode_class attribute, which determines the class of the underlying mode.

Parameters:

data (Union[Dict[TypeVar(ModeT), Union[int, bool]], List[Union[int, bool]], Tuple[Union[int, bool]]]) –

property all_modes: FrozenSet

Returns all mode objects in the space of which this StateString is a basis state.

classmethod from_index(state_index, modes=None, reverse=False)

Creates an instance from the index of a state vector corresponding to a single basis state.

Modes - and the bit position in the state index to which each corresponds - can be defined with the modes parameter. In the absence of this parameter, a default register of the appropriate size is implicit, with the index being assumed to correspond to an ILO-BE ordering of the default register. See below for examples.

Parameters:
  • state_index (int) – The index of a state vector corresponding to the basis state to which the created object will correspond.

  • modes (Optional[Iterable[TypeVar(ModeT)]], default: None) – A collection of modes, the state values of which are represented by the state vector, in the appropriate ordering.

  • reverse (default: False) – If True, reverse the bits of the index.

Returns:

TypeVar(StateStringT, bound= StateString) – An instance of this class corresponding to the basis state to which the provided index corresponds.

Examples

>>> index = 12
>>> statestring = StateString.from_index(index)
>>> print(statestring)
{0: 1, 1: 1, 2: 0, 3: 0}
>>> statestring = StateString.from_index(index,modes=[3,0,1,2])
>>> print(statestring)
{3: 1, 0: 1, 1: 0, 2: 0}
classmethod from_list_int(data)

Construct a StateString from a list of integers or booleans.

The integers within the list should correspond to the states of individual modes. Modes will be assumed to be indexed in the [0, len(data)) range in ascending order.

Parameters:

data (List[Union[int, bool]]) – State values to assign for the default mode set.

Returns:

TypeVar(StateStringT, bound= StateString) – An instance of this class representing the basis state with provided state values, using a default set of modes.

classmethod from_string(data)

Generate a class instance from a string.

This method will make a best effort to interpret a string as an instance of this class. It is provided largely for backwards compatibility. Caution is advised.

Parameters:

data (str) – A string from which to attempt to generate an instance of this class.

Returns:

TypeVar(StateStringT, bound= StateString) – A class instance generated from the input string.

property hamming_weight: int

Returns the Hamming weight of the basis state.

classmethod load_h5(name)

Loads a state string object from .h5 file.

Parameters:

name (Union[str, Group]) – Name of .h5 file to be loaded.

Returns:

TypeVar(StateStringT, bound= StateString) – Loaded integral operator object.

mode_class

alias of int

property num_modes: int

Returns the number of modes in the space of which this StateString is a basis state.

occupations_ordered()

Returns a list of integer or boolean occupation numbers corresponding to modes ordered in increasing lexicographic order.

Return type:

List[Union[int, bool]]

save_h5(name)

Dumps state string object to .h5 file.

Parameters:

name (Union[str, Group]) – Destination filename of .h5 file.

Return type:

None

to_index(modes=None, reverse=False)

Returns the index of the state vector to which this basis state corresponds.

The ordering of modes when defining indexing into the state vector can be controlled with the modes parameter. By default, modes will be ordered following an ILO-BE convention - see examples.

Parameters:
  • modes (Optional[Iterable[TypeVar(ModeT)]], default: None) – An ordering of modes used for defining state vector indices, from most significant to least significant.

  • reverse (default: False) – If True, reverse the order of bits in the state vector index.

Returns:

int – A state vector index corresponding to this basis state.

Raises:

ValueError – If provided modes are not the same as those of the state.

Examples

>>> statestring = StateString({0:1,1:1,2:0,3:0})
>>> index = statestring.to_index()
>>> print(index)
12
>>> index = statestring.to_index([0,2,3,1])
>>> print(index)
9