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 beingFermionStateString
objects (configurations) and values being the corresponding configuration coefficients. TheFermionState
is initialized from aFermionStateString
and a coefficient, atuple
oftuple
elements, each containing a coefficient and aFermionStateString
object, or a dict, withFermionStateString
objects as keys and coefficients as values. For a single basis state, it can also be initialized with alist
of integers, wherein a default set of modes (indexed from 0 upwards) will be assumed. See below for examples.- Parameters:
data (
Union
[List
[int
],StateString
,Tuple
[Tuple
[Union
[int
,float
,complex
,Expr
],StateString
]],Dict
[StateString
,Union
[int
,float
,complex
,Expr
]]], default:None
) – Information regarding the state to be created. A variety of input formats are parsed - see examples below for details.coeff (
Union
[int
,float
,complex
,Expr
], default:1.0
) – An optional additional coefficient, used when a single basis state is being created. See below for example.
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=ABS_TOL_OPERATOR)¶
Checks if object’s dictionary values are numerically identical to the other object values.
- approx_equal_to_by_random_subs(other, order=1, abs_tol=ABS_TOL_OPERATOR)¶
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.
- property basis_states: List[StateStringT]¶
Returns the basis states with nonzero coefficient as a
list
.
- property coefficients: List[int | float | complex | Expr]¶
Returns the scalar coefficients of individual basis vectors as a
list
.
- compress(abs_tol=ABS_TOL_OPERATOR, symbol_sub_type=CompressSymbolSubType.NONE)¶
Combines duplicate terms, removing those with negligible coefficient.
- Parameters:
abs_tol (
float
, default:ABS_TOL_OPERATOR
) – Tolerance for comparing values to zero.symbol_sub_type (
Union
[CompressSymbolSubType
,str
], default:CompressSymbolSubType.NONE
) – Defines the behavior 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 with negligible terms removed.
- df()¶
Returns a Pandas DataFrame object of the dictionary.
- Return type:
DataFrame
- evalf(*args, **kwargs)¶
Evaluates symbolic expressions stored in
dict
values and replaces them with the results.
- free_symbols()¶
Returns the free symbols in the coefficient values.
- free_symbols_ordered()¶
Returns the free symbols in the dict, ordered alphabetically.
- Returns:
SymbolEnsemble
– 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 aState
object. Modes - and the bit position in the state index to which each corresponds - can be defined with themodes
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 behavior as above.reverse (default:
False
) – IfTrue
, 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 themodes
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 behavior as above.reverse (default:
False
) – IfTrue
, 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.
- get_numeric_representation()¶
Placeholder, unimplemented method.
- get_symbolic_representation()¶
Placeholder, unimplemented method.
- is_all_coeff_complex()¶
Check if all coefficients have complex values.
- Returns:
bool
–False
if a non-complex value occurs before any free symbols in thedict
values, orTrue
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:
bool
–False
if a non-complex value occurs before any free symbols in thedict
values, orTrue
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:
bool
–False
if a non-real value occurs before any free symbols in thedict
values, orTrue
if no non-real values occur.
Warning
Returns
None
if a free symbol occurs before any non-real values in thedict
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:
bool
–True
if a complex value occurs before any free symbols in thedict
values, orFalse
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:
bool
–True
if an imaginary value occurs before any free symbols in thedict
values, orFalse
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:
bool
–True
if a real value occurs before any free symbols in thedict
values, orFalse
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:
- is_normalized(order=2, abs_tol=ABS_TOL_OPERATOR)¶
Returns True if operator has unit p-norm, else False.
- Parameters:
- Raises:
ValueError – Coefficients contain free symbols.
- Return type:
- is_parallel_with(other, abs_tol=ABS_TOL_OPERATOR)¶
Returns
True
if other is parallel with this (i.e. a scalar multiple of this), otherwiseFalse
.
- is_unit_1norm(abs_tol=ABS_TOL_OPERATOR)¶
Returns True if operator has unit 1-norm, else False.
- is_unit_2norm(abs_tol=ABS_TOL_OPERATOR)¶
Returns True if operator has unit 1-norm, else False.
- is_unit_norm(order=2, abs_tol=ABS_TOL_OPERATOR)¶
Returns True if operator has unit p-norm, else False.
- Parameters:
- Raises:
ValueError – Coefficients contain free symbols.
- Return type:
- classmethod key_from_str(key_str)¶
Converts a string to an instance of this class’s basis state type.
- classmethod load_h5(name)¶
Loads a state object from .h5 file.
- 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.
- norm_coefficients(order=2)¶
Returns the p-norm of the coefficients.
- normalized(norm_value=1.0, norm_order=2)¶
Returns a copy of this object with normalized coefficients.
- 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 asNone
, a default register will be assumed if possible. See the mapping class documentation for further details.
- Returns:
QubitState
– MappedQubitState
.
- 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.
- set_global_phase(phase=0.0)¶
Returns a copy with a global phase applied such that the first element has the desired phase.
- simplify(*args, **kwargs)¶
Simplifies expressions stored in dictionary values.
- 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.
- string_class¶
alias of
FermionStateString
- subs(symbol_map)¶
Returns a new objects with symbols substituted.
- Parameters:
symbol_map (
Union
[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.
- sympify(*args, **kwargs)¶
Sympifies dictionary values.
Replaces values with their corresponding symbolic expressions.
- Parameters:
- Returns:
LinearDictCombiner
– Updated instance ofLinearDictCombiner
.- Raises:
RuntimeError – Sympification fails.
- 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 behavior as above.dtype (default:
complex
) – The numpydtype
to be used for the returned vector.reverse (
bool
, default:False
) – IfTrue
, reverse bit order of state vector indices (e.g. for changing endianness).
- Returns:
ndarray
– A dense numpyndarray
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. Seeto_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 behavior as above.matrix_type (default:
scipy.sparse.csr_array
) – The type of the sparse matrix to be generated.dtype (default:
complex
) – The numpydtype
to be used for the returned vector.reverse (
bool
, default:False
) – IfTrue
, 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:
- Returns:
LinearDictCombiner
– Updated instance ofLinearDictCombiner
.- Raises:
TypeError – Unsympification fails.
- 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
) – IfTrue
, 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 alist
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.
- 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.
- classmethod load_h5(name)¶
Loads a state string object from .h5 file.
- 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.
- 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 asNone
, a default register will be assumed if possible. See the mapping class documentation for further details.
- Returns:
QubitStateString
– MappedQubitStateString
.
- save_h5(name)¶
Dumps state string object to .h5 file.
- 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:
- 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. TheQubitState
may be initialized from aQubitStateString
and a coefficient, atuple
oftuple
elements, each containing a coefficient and aQubitStateString
object, or a dict, withQubitStateString
objects as keys and coefficients as values. For a single basis state, it can also be initialized with alist
of integers, wherein a default set of qubits (indexed from 0 upwards) will be assumed. See below for examples.- Parameters:
data (
Union
[List
[int
],StateString
,Tuple
[Tuple
[Union
[int
,float
,complex
,Expr
],StateString
]],Dict
[StateString
,Union
[int
,float
,complex
,Expr
]]], default:None
) – Information regarding the state to be created. A variety of input formats are parsed - see examples below for details.coeff (
Union
[int
,float
,complex
,Expr
], default:1.0
) – An optional additional coefficient, used when a single basis state is being created. See below for example.
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=ABS_TOL_OPERATOR)¶
Checks if object’s dictionary values are numerically identical to the other object values.
- approx_equal_to_by_random_subs(other, order=1, abs_tol=ABS_TOL_OPERATOR)¶
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.
- property basis_states: List[StateStringT]¶
Returns the basis states with nonzero coefficient as a
list
.
- property coefficients: List[int | float | complex | Expr]¶
Returns the scalar coefficients of individual basis vectors as a
list
.
- compress(abs_tol=ABS_TOL_OPERATOR, symbol_sub_type=CompressSymbolSubType.NONE)¶
Combines duplicate terms, removing those with negligible coefficient.
- Parameters:
abs_tol (
float
, default:ABS_TOL_OPERATOR
) – Tolerance for comparing values to zero.symbol_sub_type (
Union
[CompressSymbolSubType
,str
], default:CompressSymbolSubType.NONE
) – Defines the behavior 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 with negligible terms removed.
- df()¶
Returns a Pandas DataFrame object of the dictionary.
- Return type:
DataFrame
- evalf(*args, **kwargs)¶
Evaluates symbolic expressions stored in
dict
values and replaces them with the results.
- free_symbols()¶
Returns the free symbols in the coefficient values.
- free_symbols_ordered()¶
Returns the free symbols in the dict, ordered alphabetically.
- Returns:
SymbolEnsemble
– 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 aState
object. Modes - and the bit position in the state index to which each corresponds - can be defined with themodes
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 behavior as above.reverse (default:
False
) – IfTrue
, 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 themodes
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 behavior as above.reverse (default:
False
) – IfTrue
, 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.
- 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 theto_ndarray()
method. Qubits are ordered according to an ILO-BE convention. See the documentation of theto_ndarray()
method for further details.Danger
This method requires exponential resources.
- Parameters:
symbol_map (
Union
[Dict
[Symbol
,Expr
],Dict
[Symbol
,float
],Dict
[Symbol
,Union
[float
,complex
,Expr
]],Callable
[[Symbol
],Expr
],str
,None
], default:None
) – A symbol substitution map applied before constructing the representation.dtype (
Union
[dtype
[Any
],None
,type
[Any
],_SupportsDType
[dtype
[Any
]],str
,tuple
[Any
,int
],tuple
[Any
,SupportsIndex
|Sequence
[SupportsIndex
]],list
[Any
],_DTypeDict
,tuple
[Any
,Any
]], default:complex
) – Specifies the numpydtype
to which the return array should be converted.backend (
None
, default:None
) – Unused compatibility argument.
- Returns:
Union
[_SupportsArray
[dtype
[Any
]],_NestedSequence
[_SupportsArray
[dtype
[Any
]]],bool
,int
,float
,complex
,str
,bytes
,_NestedSequence
[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
[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:
bool
–False
if a non-complex value occurs before any free symbols in thedict
values, orTrue
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:
bool
–False
if a non-complex value occurs before any free symbols in thedict
values, orTrue
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:
bool
–False
if a non-real value occurs before any free symbols in thedict
values, orTrue
if no non-real values occur.
Warning
Returns
None
if a free symbol occurs before any non-real values in thedict
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:
bool
–True
if a complex value occurs before any free symbols in thedict
values, orFalse
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:
bool
–True
if an imaginary value occurs before any free symbols in thedict
values, orFalse
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:
bool
–True
if a real value occurs before any free symbols in thedict
values, orFalse
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:
- is_normalized(order=2, abs_tol=ABS_TOL_OPERATOR)¶
Returns True if operator has unit p-norm, else False.
- Parameters:
- Raises:
ValueError – Coefficients contain free symbols.
- Return type:
- is_parallel_with(other, abs_tol=ABS_TOL_OPERATOR)¶
Returns
True
if other is parallel with this (i.e. a scalar multiple of this), otherwiseFalse
.
- is_unit_1norm(abs_tol=ABS_TOL_OPERATOR)¶
Returns True if operator has unit 1-norm, else False.
- is_unit_2norm(abs_tol=ABS_TOL_OPERATOR)¶
Returns True if operator has unit 1-norm, else False.
- is_unit_norm(order=2, abs_tol=ABS_TOL_OPERATOR)¶
Returns True if operator has unit p-norm, else False.
- Parameters:
- Raises:
ValueError – Coefficients contain free symbols.
- Return type:
- classmethod key_from_str(key_str)¶
Converts a string to an instance of this class’s basis state type.
- classmethod load_h5(name)¶
Loads a state object from .h5 file.
- 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.
- norm_coefficients(order=2)¶
Returns the p-norm of the coefficients.
- normalized(norm_value=1.0, norm_order=2)¶
Returns a copy of this object with normalized coefficients.
- 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.
- set_global_phase(phase=0.0)¶
Returns a copy with a global phase applied such that the first element has the desired phase.
- simplify(*args, **kwargs)¶
Simplifies expressions stored in dictionary values.
- 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.
- property state_symbols: SymbolEnsemble¶
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
[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.
- sympify(*args, **kwargs)¶
Sympifies dictionary values.
Replaces values with their corresponding symbolic expressions.
- Parameters:
- Returns:
LinearDictCombiner
– Updated instance ofLinearDictCombiner
.- Raises:
RuntimeError – Sympification fails.
- 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 behavior as above.dtype (default:
complex
) – The numpydtype
to be used for the returned vector.reverse (
bool
, default:False
) – IfTrue
, reverse bit order of state vector indices (e.g. for changing endianness).
- Returns:
ndarray
– A dense numpyndarray
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. Seeto_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 behavior as above.matrix_type (default:
scipy.sparse.csr_array
) – The type of the sparse matrix to be generated.dtype (default:
complex
) – The numpydtype
to be used for the returned vector.reverse (
bool
, default:False
) – IfTrue
, 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:
- Returns:
LinearDictCombiner
– Updated instance ofLinearDictCombiner
.- Raises:
TypeError – Unsympification fails.
- 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) – seeQubitState
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
) – IfTrue
, 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 alist
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.
- 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.
- classmethod load_h5(name)¶
Loads a state string object from .h5 file.
- 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.
- save_h5(name)¶
Dumps state string object to .h5 file.
- 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:
- 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
andFermionState
.Within this class,
StateString
-derived objects are mapped in adict
-like fashion to scalar coefficients, in order to represent a linear combination of basis states. Subclasses must define thestring_class
attribute, which gives the type (derived fromStateString
) 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=ABS_TOL_OPERATOR)¶
Checks if object’s dictionary values are numerically identical to the other object values.
- approx_equal_to_by_random_subs(other, order=1, abs_tol=ABS_TOL_OPERATOR)¶
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.
- property basis_states: List[StateStringT]¶
Returns the basis states with nonzero coefficient as a
list
.
- property coefficients: List[int | float | complex | Expr]¶
Returns the scalar coefficients of individual basis vectors as a
list
.
- compress(abs_tol=ABS_TOL_OPERATOR, symbol_sub_type=CompressSymbolSubType.NONE)¶
Combines duplicate terms, removing those with negligible coefficient.
- Parameters:
abs_tol (
float
, default:ABS_TOL_OPERATOR
) – Tolerance for comparing values to zero.symbol_sub_type (
Union
[CompressSymbolSubType
,str
], default:CompressSymbolSubType.NONE
) – Defines the behavior 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 with negligible terms removed.
- df()¶
Returns a Pandas DataFrame object of the dictionary.
- Return type:
DataFrame
- evalf(*args, **kwargs)¶
Evaluates symbolic expressions stored in
dict
values and replaces them with the results.
- free_symbols()¶
Returns the free symbols in the coefficient values.
- free_symbols_ordered()¶
Returns the free symbols in the dict, ordered alphabetically.
- Returns:
SymbolEnsemble
– 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 aState
object. Modes - and the bit position in the state index to which each corresponds - can be defined with themodes
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 behavior as above.reverse (default:
False
) – IfTrue
, 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 themodes
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 behavior as above.reverse (default:
False
) – IfTrue
, 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.
- get_numeric_representation()¶
Placeholder, unimplemented method.
- get_symbolic_representation()¶
Placeholder, unimplemented method.
- is_all_coeff_complex()¶
Check if all coefficients have complex values.
- Returns:
bool
–False
if a non-complex value occurs before any free symbols in thedict
values, orTrue
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:
bool
–False
if a non-complex value occurs before any free symbols in thedict
values, orTrue
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:
bool
–False
if a non-real value occurs before any free symbols in thedict
values, orTrue
if no non-real values occur.
Warning
Returns
None
if a free symbol occurs before any non-real values in thedict
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:
bool
–True
if a complex value occurs before any free symbols in thedict
values, orFalse
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:
bool
–True
if an imaginary value occurs before any free symbols in thedict
values, orFalse
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:
bool
–True
if a real value occurs before any free symbols in thedict
values, orFalse
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:
- is_normalized(order=2, abs_tol=ABS_TOL_OPERATOR)¶
Returns True if operator has unit p-norm, else False.
- Parameters:
- Raises:
ValueError – Coefficients contain free symbols.
- Return type:
- is_parallel_with(other, abs_tol=ABS_TOL_OPERATOR)¶
Returns
True
if other is parallel with this (i.e. a scalar multiple of this), otherwiseFalse
.
- is_unit_1norm(abs_tol=ABS_TOL_OPERATOR)¶
Returns True if operator has unit 1-norm, else False.
- is_unit_2norm(abs_tol=ABS_TOL_OPERATOR)¶
Returns True if operator has unit 1-norm, else False.
- is_unit_norm(order=2, abs_tol=ABS_TOL_OPERATOR)¶
Returns True if operator has unit p-norm, else False.
- Parameters:
- Raises:
ValueError – Coefficients contain free symbols.
- Return type:
- classmethod key_from_str(key_str)¶
Converts a string to an instance of this class’s basis state type.
- classmethod load_h5(name)¶
Loads a state object from .h5 file.
- 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.
- norm_coefficients(order=2)¶
Returns the p-norm of the coefficients.
- normalized(norm_value=1.0, norm_order=2)¶
Returns a copy of this object with normalized coefficients.
- 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.
- set_global_phase(phase=0.0)¶
Returns a copy with a global phase applied such that the first element has the desired phase.
- simplify(*args, **kwargs)¶
Simplifies expressions stored in dictionary values.
- 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.
- string_class¶
alias of
StateString
- subs(symbol_map)¶
Returns a new objects with symbols substituted.
- Parameters:
symbol_map (
Union
[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.
- sympify(*args, **kwargs)¶
Sympifies dictionary values.
Replaces values with their corresponding symbolic expressions.
- Parameters:
- Returns:
LinearDictCombiner
– Updated instance ofLinearDictCombiner
.- Raises:
RuntimeError – Sympification fails.
- 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 behavior as above.dtype (default:
complex
) – The numpydtype
to be used for the returned vector.reverse (
bool
, default:False
) – IfTrue
, reverse bit order of state vector indices (e.g. for changing endianness).
- Returns:
ndarray
– A dense numpyndarray
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. Seeto_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 behavior as above.matrix_type (default:
scipy.sparse.csr_array
) – The type of the sparse matrix to be generated.dtype (default:
complex
) – The numpydtype
to be used for the returned vector.reverse (
bool
, default:False
) – IfTrue
, 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:
- Returns:
LinearDictCombiner
– Updated instance ofLinearDictCombiner
.- Raises:
TypeError – Unsympification fails.
- 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
andFermionStateString
. Subclasses must define themode_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
) – IfTrue
, 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 alist
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.
- 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.
- classmethod load_h5(name)¶
Loads a state string object from .h5 file.
- 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.
- save_h5(name)¶
Dumps state string object to .h5 file.
- 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:
- 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