inquanto.operators
InQuanto representation of quantum operators.
- class ChemistryRestrictedIntegralOperator(constant, one_body, two_body, dtype=None)
Bases:
BaseChemistryIntegralOperator
Handles a (restricted-orbital) chemistry integral operator.
Stores constant, one- and two-body spatial integral values following chemistry notation,
two_body[p, q, r, s]
= \((pq|rs)\).- Parameters:
constant (
float
) – Constant energy term, electron independent.one_body (
ndarray
) – One-body integrals.two_body (
ndarray
) – Two-body electron repulsion integrals (ERI).
- TOLERANCE = 1e-08
Internal tolerance used when iterating over terms. Terms with magnitude smaller than this are not returned by
items()
.
- approx_equal(other, rtol=1.0e-5, atol=1.0e-8, equal_nan=False)
Test for approximate equality with another instance of this class by comparing integral arrays.
Arguments are passed directly to
numpy.allclose()
for equality comparison - see numpy documentation for further details.- Parameters:
other (
ChemistryRestrictedIntegralOperator
) – The other operator to compare for approximate equality.rtol (
float
, default:1.0e-5
) – The relative tolerance parameter, as defined bynumpy.allclose()
.atol (
float
, default:1.0e-8
) – The absolute tolerance parameter, as defined bynumpy.allclose()
.equal_nan (default:
False
) – Whether to compare NaN’s as equal, as defined bynumpy.allclose()
.
- Returns:
bool
–True
if other instance is approximately equal to this one, otherwiseFalse
.
- astype(dtype)
Returns a copy of the current integral operator, cast to a new
dtype
.- Parameters:
dtype (
Any
) – Thedtype
to cast into.- Returns:
ChemistryRestrictedIntegralOperator
– New integral operator with components cast todtype
.
- copy()
Performs a deep copy of object.
- Return type:
BaseChemistryIntegralOperator
- df()
Returns a
pandas.DataFrame
object showing all terms in the operator.- Return type:
DataFrame
- double_factorize(tol1=-1.0, tol2=None, method=DecompositionMethod.EIG, diagonalize_one_body=True, diagonalize_one_body_offset=True, combine_one_body_terms=True)
Double factorizes the two-electron integrals and returns the Hamiltonian in diagonal form.
The Hamiltonian can be written as \(\hat{H} = H_0 + \hat{H}_1 + \hat{S} + \hat{V}\) where \(\hat{S}+\hat{V}\) is the Coulomb interaction. \(V = \frac{1}{2}\sum_{ijkl} (ij|kl) a_i^\dagger a_j a_k^\dagger a_l\) is a reordered two-body operator and \(\hat{S}\) is a one-body offset term given by \(\hat{S} = \sum_{ij} s_{ij} a_i^\dagger a_j\) where \(s_{ij} = -\frac{1}{2}\sum_k (ik|kj)\). \(H_0\) and \(\hat{H}_1\) are the constant and one-electron terms respectively.
The first level of factorization decomposes the electron repulsion integrals tensor into the form: \((pq|rs)=\sum_t^{N_\gamma} V_{pq}^t \gamma^t V_{rs}^t\). This may be performed using an eigenvalue decomposition (
method='eig'
), or a pivoted, incomplete Cholesky decomposition (method="cho"
) (see J. Chem. Phys. 118, 9481–9484 (2003) and J. Chem. Phys. 139, 134105 (2013)). The second factorization is diagonalization of the \(V_{pq}^t\) matrix for each t: \(V_{pq}^t = \sum_u^{N_\lambda^t} U_{pu}^t \lambda_u^t U_{qu}^t\).At the first factorization stage, truncation depends on the decomposition method. With
"eig"
, truncation is performed by discarding eigenvalues, starting from the smallest in magnitude, until the sum of those discarded magnitudes exceeds the thresholdtol1
. With"cho"
, the decomposition is constructed iteratively until the error is less thantol1
. At the second factorization level, truncation is always performed by discarding low-magnitude eigenvalues.One-body-like terms are consolidated and diagonalized by default: \(\tilde{h}_{pq} = h_{pq} + s_{pq} = \sum_r W_{pr} \omega_r W_{qr}\). One-body diagonalization is not truncated.
Warning
This is not intended for reduction of classical memory usage, only for truncating the two-body terms of the Hamiltonian for quantum simulation.
- Parameters:
tol1 (
float
, default:-1.0
) – Truncation threshold for first diagonalization of ERI matrix. If negative, no truncation is performed.tol2 (
Optional
[float
], default:None
) – Truncation threshold for second diagonalization of ERI matrix. IfNone
, same astol1
. If negative, no truncation is performed.method (
Union
[DecompositionMethod
,str
], default:DecompositionMethod.EIG
) – Decomposition method used for the first level of factorization."eig"
for an eigenvalue decomposition,"cho"
for a pivoted, incomplete Cholesky decomposition.diagonalize_one_body (
bool
, default:True
) – Whether to diagonalize the physical one-body integrals \(h_{pq}\).diagonalize_one_body_offset (
bool
, default:True
) – Whether to diagonalize the one-body offset integrals \(s_{pq}\)combine_one_body_terms (
bool
, default:True
) – Whether to consolidate the one-body and one-body offset integrals into effective one-body integrals. Requiresdiagonalize_one_body == diagonalize_one_body_offset
.
- Returns:
DoubleFactorizedHamiltonian
– Hamiltonian operator storing two-body integrals in double factorized form and, optionally, diagonalized one-body integrals.
- property dtype: dtype
Returns numpy data type of the two-body integral terms.
- effective_potential(rdm1)
Calculates the effective Coulombic potential for a given 1-RDM.
- Parameters:
rdm1 (
RestrictedOneBodyRDM
) – Restricted, one-body reduced density matrix object.- Returns:
ndarray
– Effective potential matrix.
- effective_potential_spin(rdm1)
Calculates the contribution to the effective Coulomb potential due to a spin imbalance.
This is defined as the contribution to the effective potential matrix from the difference of the alpha and beta 1-RDMs .
- Parameters:
rdm1 (
RestrictedOneBodyRDM
) – Restricted, one-body reduced density matrix object.- Returns:
ndarray
– Effective potential matrix.
- energy(rdm1, rdm2=None)
Calculate total energy based on the one- and two-body reduced density matrices.
If
rdm2
is not given, this method returns the mean-field energy.- Parameters:
rdm1 (
RestrictedOneBodyRDM
) – Restricted, one-body reduced density matrix object.rdm2 (
Optional
[RestrictedTwoBodyRDM
], default:None
) – Restricted, two-body reduced density matrix object.
- Returns:
float
– Total energy.
- energy_electron_mean_field(rdm1)
Calculates the electronic energy in the mean-field approximation.
- Parameters:
rdm1 (
RestrictedOneBodyRDM
) – Restricted, one-body reduced density matrix object.- Returns:
Tuple
[float
,float
] – The mean-field electronic energy (one-body + two-body), and the mean-field Coulomb contribution (two-body only).
- classmethod from_FermionOperator(operator, dtype=float)
Convert a two-body fermionic operator to restricted-orbital integral operator.
The one-body terms are stored in a matrix,
_one_body[p, q]
, and the two-body terms are stored in a tensor,_two_body[p, q, r, s]
.- Parameters:
operator (
FermionOperator
) – Input fermionic operator.dtype (default:
float
) – Desired term valuedtype
.
- Returns:
ChemistryRestrictedIntegralOperator
– The converted operator.
Warning
This converter assumes that
operator
represents a spin-restricted operator.
- static from_fcidump(filename)
Generate a ChemistryRestrictedIntegralOperator object from an FCIDUMP file.
FCIDUMP files typically contain information regarding the molecular orbital integrals, number of orbitals, number of electrons, spin and spatial symmetry. Only the symmetry information is discarded by this method.
- Parameters:
filename (
str
) – The FCIDUMP filename.- Returns:
Tuple
[ChemistryRestrictedIntegralOperator
,int
,int
,int
] – A tuple containing the operator generated from the FCIDUMP file, the number of orbitals in the system, the number of electrons in the system, and the spin multiplicity of the system.
- property imag: ChemistryRestrictedIntegralOperator
Extract the imaginary part of the integral operator.
- Returns:
New integral operator object with only the imaginary parts of all elements remaining.
- items(yield_constant=True, yield_one_body=True, yield_two_body=True)
Generates the constant, one- and two-body operator terms contained in the operator object.
- Parameters:
- Yields:
Next requested
FermionOperatorString
and constant/integral value.- Return type:
- classmethod load_h5(name)
Loads operator object from .h5 file.
- norm(*args, **kwargs)
Calculates the norm of the integral operator.
Sums the norm of the constant, one-body and two-body parts using
numpy.linalg.norm()
.- Parameters:
*args – Additional arguments passed to
numpy.linalg.norm()
.**kwargs – Additional keyword arguments passed to
numpy.linalg.norm()
.
- Returns:
float
– Norm of this instance.
- qubit_encode(mapping=None, qubits=None)
Performs qubit encoding (mapping), using provided mapping class, of this instance.
This proceeds by creation of a
FermionOperator
class, via theto_FermionOperator()
method, before mapping to aQubitOperator
using the provided mapping scheme. Please see the documentation forto_FermionOperator()
for finer grained control over operator generation.- Parameters:
mapping (
Optional
[QubitMapping
], default:None
) –QubitMapping
-derived instance. Default mapping procedure isQubitMappingJordanWigner
.qubits (
Optional
[List
[Qubit
]], default:None
) – The qubit register. If left asNone
, a default register will be assumed if possible. SeeQubitMapping
documentation for further details.
- Returns:
QubitOperator
– MappedQubitOperator
object.
- property real: ChemistryRestrictedIntegralOperator
Extract the real part of the integral operator.
- Returns:
New integral operator object with only the real parts of all elements remaining.
- rotate(rotation, check_unitary=True, check_unitary_atol=1e-15)
Performs an in-place unitary rotation of the chemistry integrals.
- Parameters:
- Returns:
ChemistryRestrictedIntegralOperator
– This instance after rotation.
- save_h5(name)
Dumps operator object to .h5 file.
- to_FermionOperator(yield_constant=True, yield_one_body=True, yield_two_body=True)
Converts chemistry integral operator to
FermionOperator
.- Parameters:
- Returns:
FermionOperator
– Integral operator in general fermionic operator form.
- to_compact_integral_operator(symmetry)
Converts two-body integrals into compact form.
Compacts the two-body integrals into a
CompactTwoBodyIntegrals
object.- Parameters:
symmetry (
Union
[int
,str
]) – Target symmetry. Four-fold symmetry (4
,"4"
or"s4"
) or eight-fold symmetry (8
,"8"
or"s8"
) are supported.- Returns:
ChemistryRestrictedIntegralOperatorCompact
– Equivalent integral operator with two-body integrals stored in compact form.
- two_body_iijj()
Returns pair-diagonal elements of two-body integrals, \((ii|jj)\) in chemist notation.
- Returns:
ndarray
– 2D array of pair-diagonal two body-integrals.
- class ChemistryRestrictedIntegralOperatorCompact(constant, one_body, two_body, dtype=None)
Bases:
BaseChemistryIntegralOperator
Handles a (restricted-orbital) chemistry integral operator, with integrals stored in a compact form.
Stores constant, one- and two-body spatial integral values following chemistry notation, i.e.
two_body[p, q, r, s]
= \((pq|rs)\). Two-body integrals are stored as aCompactTwoBodyIntegralsS4
orCompactTwoBodyIntegralsS8
object rather than anumpy.ndarray
, which reduces memory load, at the expense of some operations taking longer.- Parameters:
constant (
float
) – Constant energy term, electron independent.one_body (
ndarray
) – One-body energy integrals.two_body (
Union
[CompactTwoBodyIntegralsS4
,CompactTwoBodyIntegralsS8
]) – Two-body electron repulsion integrals (ERI).
- TOLERANCE = 1e-08
Internal tolerance used when iterating over terms. Terms with magnitude smaller than this are not returned by
items()
.
- approx_equal(other, rtol=1.0e-5, atol=1.0e-8, equal_nan=False)
Test for approximate equality with another instance of this class by comparing integral arrays.
Arguments are passed directly to
numpy.allclose()
for equality comparison - see numpy documentation for further details.- Parameters:
other (
ChemistryRestrictedIntegralOperatorCompact
) – The other operator to compare for approximate equality.rtol (
float
, default:1.0e-5
) – The relative tolerance parameter, as defined bynumpy.allclose()
.atol (
float
, default:1.0e-8
) – The absolute tolerance parameter, as defined bynumpy.allclose()
.equal_nan (
bool
, default:False
) – Whether to compare NaN’s as equal, as defined bynumpy.allclose()
.
- Returns:
bool
–True
if other instance is approximately equal to this, otherwiseFalse
.
- astype(dtype)
Returns a copy of the current integral operator, cast to a new
dtype
.- Parameters:
dtype (
Any
) – Thedtype
to cast into.- Returns:
ChemistryRestrictedIntegralOperatorCompact
– New integral operator with components cast todtype
.
- copy()
Performs a deep copy of object.
- Return type:
BaseChemistryIntegralOperator
- df()
Returns a
pandas.DataFrame
object showing all terms in the operator.- Return type:
DataFrame
- double_factorize(tol1=-1.0, tol2=None, method=DecompositionMethod.EIG, diagonalize_one_body=True, diagonalize_one_body_offset=True, combine_one_body_terms=True)
Double factorizes the two-electron integrals and returns the Hamiltonian in diagonal form.
The Hamiltonian can be written as \(\hat{H} = H_0 + \hat{H}_1 + \hat{S} + \hat{V}\) where \(\hat{S}+\hat{V}\) is the Coulomb interaction. \(V = \frac{1}{2}\sum_{ijkl} (ij|kl) a_i^\dagger a_j a_k^\dagger a_l\) is a reordered two-body operator and \(\hat{S}\) is a one-body offset term given by \(\hat{S} = \sum_{ij} s_{ij} a_i^\dagger a_j\) where \(s_{ij} = -\frac{1}{2}\sum_k (ik|kj)\). \(H_0\) and \(\hat{H}_1\) are the constant and one-electron terms respectively.
The first level of factorization decomposes the electron repulsion integrals tensor into the form: \((pq|rs)=\sum_t^{N_\gamma} V_{pq}^t \gamma^t V_{rs}^t\). This may be performed using an eigenvalue decomposition (
method='eig'
), or a pivoted, incomplete Cholesky decomposition (method="cho"
) (see J. Chem. Phys. 118, 9481–9484 (2003) and J. Chem. Phys. 139, 134105 (2013)). The second factorization is diagonalization of the \(V_{pq}^t\) matrix for each t: \(V_{pq}^t = \sum_u^{N_\lambda^t} U_{pu}^t \lambda_u^t U_{qu}^t\).At the first factorization stage, truncation depends on the decomposition method. With
"eig"
, truncation is performed by discarding eigenvalues, starting from the smallest in magnitude, until the sum of those discarded magnitudes exceeds the thresholdtol1
. With"cho"
, the decomposition is constructed iteratively until the error is less thantol1
. At the second factorization level, truncation is always performed by discarding low-magnitude eigenvalues.One-body-like terms are consolidated and diagonalized by default: \(\tilde{h}_{pq} = h_{pq} + s_{pq} = \sum_r W_{pr} \omega_r W_{qr}\). One-body diagonalization is not truncated.
Warning
This is not intended for reduction of classical memory usage, only for truncating the two-body terms of the Hamiltonian for quantum simulation.
- Parameters:
tol1 (
float
, default:-1.0
) – Truncation threshold for first diagonalization of ERI matrix. If negative, no truncation is performed.tol2 (
Optional
[float
], default:None
) – Truncation threshold for second diagonalization of ERI matrix. IfNone
, same astol1
. If negative, no truncation is performed.method (
Union
[DecompositionMethod
,str
], default:DecompositionMethod.EIG
) – Decomposition method used for the first level of factorization."eig"
for an eigenvalue decomposition,"cho"
for a pivoted, incomplete Cholesky decomposition.diagonalize_one_body (
bool
, default:True
) – Whether to diagonalize the physical one-body integrals \(h_{pq}\).diagonalize_one_body_offset (
bool
, default:True
) – Whether to diagonalize the one-body offset integrals \(s_{pq}\)combine_one_body_terms (
bool
, default:True
) – Whether to consolidate the one-body and one-body offset integrals into effective one-body integrals. Requiresdiagonalize_one_body == diagonalize_one_body_offset
.
- Returns:
DoubleFactorizedHamiltonian
– Hamiltonian operator storing two-body integrals in double factorized form and, optionally, diagonalized one-body integrals.
- property dtype: dtype
Returns numpy data type of the two-body integral terms.
- effective_potential(rdm1)
Calculates the effective Coulombic potential for a given 1-RDM.
- Parameters:
rdm1 (
RestrictedOneBodyRDM
) – Restricted, one-body reduced density matrix object.- Returns:
ndarray
– Effective potential matrix.
- effective_potential_spin(rdm1)
Calculates the contribution to the effective Coulomb potential due to a spin imbalance.
This is defined as the contribution to the effective potential matrix from the difference of the alpha and beta 1-RDMs.
- Parameters:
rdm1 (
RestrictedOneBodyRDM
) – Restricted, one-body reduced density matrix object.- Returns:
ndarray
– Effective potential matrix.
- energy(rdm1, rdm2=None)
Calculate total energy based on the one- and two-body reduced density matrices.
If
rdm2
is not given, this method returns the mean-field energy.- Parameters:
rdm1 (
RestrictedOneBodyRDM
) – Restricted, one-body reduced density matrix object.rdm2 (
Optional
[RestrictedTwoBodyRDM
], default:None
) – Restricted, two-body reduced density matrix object.
- Returns:
float
– Total energy.
- energy_electron_mean_field(rdm1)
Calculates the electronic energy in the mean-field approximation.
- Parameters:
rdm1 (
RestrictedOneBodyRDM
) – Restricted, one-body reduced density matrix object.- Returns:
Tuple
[float
,float
] – The mean-field electronic energy (one-body + two-body), and the mean-field Coulomb contribution (two-body only).
- classmethod from_FermionOperator(operator, dtype=float, symmetry='s4')
Convert a 2-body fermionic operator to compact, restricted-orbital integral operator.
The one-body terms are stored in a matrix,
_one_body[p, q]
, and the two-body terms are stored in aCompactTwoBodyIntegrals
object,_two_body[p, q, r, s]
- Parameters:
operator (
FermionOperator
) – Input fermion operator.dtype (default:
float
) – Desired term valuedtype
.symmetry (
Union
[str
,int
], default:"s4"
) – Target symmetry. Four-fold symmetry (4
,"4"
or"s4"
) or eight-fold symmetry (8
,"8"
or"s8"
) are supported.
- Returns:
Output integral operator.
Warning
Currently, this converter assumes all the terms in the integral operator are represented by the aabb and bbaa blocks of fermion operator terms, and they are supposed to overwrite the (contracted) aaaa and bbbb terms - it might give faulty results if this is not the case.
- property imag
Extract the imaginary part of the integral operator.
- Returns:
New integral operator object with only the imaginary parts of all elements remaining.
- items(yield_constant=True, yield_one_body=True, yield_two_body=True)
Generates the constant, one- and two-body operator terms contained in the operator object.
- Parameters:
- Yields:
Next requested
FermionOperatorString
and constant/integral value.- Return type:
- classmethod load_h5(name)
Loads operator object from .h5 file.
- norm()
Calculates the Frobenius norm of the integral operator.
Sums the norm of the constant, one-body and two-body parts.
- Returns:
Norm of integral operator.
- qubit_encode(mapping=None, qubits=None)
Performs qubit encoding (mapping), using provided mapping class, of this instance.
This proceeds by creation of a
FermionOperator
class, via theto_FermionOperator()
method, before mapping to aQubitOperator
using the provided mapping scheme. Please see the documentation forto_FermionOperator()
for finer grained control over operator generation.- Parameters:
mapping (
Optional
[QubitMapping
], default:None
) –QubitMapping
-derived instance. Default mapping procedure isQubitMappingJordanWigner
.qubits (
Optional
[List
[Qubit
]], default:None
) – The qubit register. If left asNone
, a default register will be assumed if possible. SeeQubitMapping
documentation for further details.
- Returns:
QubitOperator
– MappedQubitOperator
object.
- property real
Extract the real part of the integral operator.
- Returns:
New integral operator object with only the real parts of all elements remaining.
- rotate(rotation, check_unitary=True, check_unitary_atol=1e-15)
Performs an in-place unitary rotation of the chemistry integrals.
Rotation must be real-valued (orthogonal) for compact integrals.
- Raises:
ValueError – If dimensions of rotation matrix are not compatible with integrals.
- Parameters:
- Returns:
ChemistryRestrictedIntegralOperatorCompact
– This instance after rotation.
- save_h5(name)
Dumps operator object to .h5 file.
- to_FermionOperator(yield_constant=True, yield_one_body=True, yield_two_body=True)
Converts chemistry integral operator to
FermionOperator
.- Parameters:
- Returns:
FermionOperator
– Integral operator in general fermionic operator form.
- to_uncompacted_integral_operator()
Convert to a
ChemistryRestrictedIntegralOperator
object.Unpacks the compact two-body integrals into a four-dimensional
numpy.ndarray
.- Returns:
Equivalent integral operator object with un-compacted integrals.
- two_body_iijj()
Returns pair-diagonal elements of two-body integrals, \((ii|jj)\) in chemist’s notation.
- Returns:
2D array of pair-diagonal two body-integrals.
- class ChemistryUnrestrictedIntegralOperator(constant, one_body_aa, one_body_bb, two_body_aaaa, two_body_bbbb, two_body_aabb, two_body_bbaa)
Bases:
BaseChemistryIntegralOperator
Handles a (unrestricted-orbital) chemistry integral operator.
Stores constant, one- and two-body spatial integral values following chemist notation, i.e.
two_body[p, q, r, s]
= \((pq|rs)\)- Parameters:
constant (
float
) – Constant energy term, electron independent.one_body_aa (
ndarray
) – One-body integrals for the alpha (a) spin channel.one_body_bb (
ndarray
) – One-body integrals for the beta (b) spin channel.two_body_aaaa (
ndarray
) – Two-body electron repulsion integrals (ERI) with spatial orbitals in the aaaa spin channels respectively.two_body_bbbb (
ndarray
) – ERI with spatial orbitals in the bbbb spin channels.two_body_aabb (
ndarray
) – ERI with spatial orbitals in the aabb spin channels.two_body_bbaa (
ndarray
) – ERI with spatial orbitals in the bbaa spin channels.
- TOLERANCE = 1e-08
Internal tolerance used when iterating over terms. Terms with magnitude smaller than this are not returned by
items()
.
- approx_equal(other, rtol=1.0e-5, atol=1.0e-8, equal_nan=False)
Test for approximate equality with another instance of this class by comparing integral arrays.
Arguments are passed directly to
numpy.allclose()
for equality comparison - see numpy documentation for further details.- Parameters:
other (
ChemistryUnrestrictedIntegralOperator
) – The other operator to compare for approximate equality.rtol (
float
, default:1.0e-5
) – The relative tolerance parameter, as defined bynumpy.allclose()
.atol (
float
, default:1.0e-8
) – The absolute tolerance parameter, as defined bynumpy.allclose()
.equal_nan (
bool
, default:False
) – Whether to compare NaN’s as equal, as defined bynumpy.allclose()
.
- Returns:
bool
–True
if other instance is approximately equal to this one, otherwiseFalse
.
- copy()
Performs a deep copy of object.
- Return type:
BaseChemistryIntegralOperator
- df()
Returns a
pandas.DataFrame
object showing all terms in the operator.- Return type:
DataFrame
- double_factorize(tol1=-1.0, tol2=None, method=DecompositionMethod.EIG, diagonalize_one_body=True, diagonalize_one_body_offset=True, combine_one_body_terms=True)
Double factorizes the two-electron integrals and returns the Hamiltonian in diagonal form.
The Hamiltonian can be written as \(\hat{H} = H_0 + \hat{H}_1 + \hat{S} + \hat{V}\) where \(\hat{S}+\hat{V}\) is the Coulomb interaction. \(V = \frac{1}{2}\sum_{ijkl} (ij|kl) a_i^\dagger a_j a_k^\dagger a_l\) is a reordered two-body operator and \(\hat{S}\) is a one-body offset term given by \(\hat{S} = \sum_{ij} s_{ij} a_i^\dagger a_j\) where \(s_{ij} = -\frac{1}{2}\sum_k (ik|kj)\). \(H_0\) and \(\hat{H}_1\) are the constant and one-electron terms respectively.
The first level of factorization decomposes the electron repulsion integrals tensor into the form: \((pq|rs)=\sum_t^{N_\gamma} V_{pq}^t \gamma^t V_{rs}^t\). This may be performed using an eigenvalue decomposition (
method='eig'
), or a pivoted, incomplete Cholesky decomposition (method="cho"
) (see J. Chem. Phys. 118, 9481–9484 (2003) and J. Chem. Phys. 139, 134105 (2013)). The second factorization is diagonalization of the \(V_{pq}^t\) matrix for each t: \(V_{pq}^t = \sum_u^{N_\lambda^t} U_{pu}^t \lambda_u^t U_{qu}^t\).At the first factorization stage, truncation depends on the decomposition method. With
"eig"
, truncation is performed by discarding eigenvalues, starting from the smallest in magnitude, until the sum of those discarded magnitudes exceeds the thresholdtol1
. With"cho"
, the decomposition is constructed iteratively until the error is less thantol1
. At the second factorization level, truncation is always performed by discarding low-magnitude eigenvalues.One-body-like terms are consolidated and diagonalized by default: \(\tilde{h}_{pq} = h_{pq} + s_{pq} = \sum_r W_{pr} \omega_r W_{qr}\). One-body diagonalization is not truncated.
Warning
This is not intended for reduction of classical memory usage, only for truncating the two-body terms of the Hamiltonian for quantum simulation.
- Parameters:
tol1 (
float
, default:-1.0
) – Truncation threshold for first diagonalization of ERI matrix. If negative, no truncation is performed.tol2 (
Optional
[float
], default:None
) – Truncation threshold for second diagonalization of ERI matrix. IfNone
, same astol1
. If negative, no truncation is performed.method (
Union
[DecompositionMethod
,str
], default:DecompositionMethod.EIG
) – Decomposition method used for the first level of factorization."eig"
for an eigenvalue decomposition,"cho"
for a pivoted, incomplete Cholesky decomposition.diagonalize_one_body (
bool
, default:True
) – Whether to diagonalize the physical one-body integrals \(h_{pq}\).diagonalize_one_body_offset (
bool
, default:True
) – Whether to diagonalize the one-body offset integrals \(s_{pq}\)combine_one_body_terms (
bool
, default:True
) – Whether to consolidate the one-body and one-body offset integrals into effective one-body integrals. Requiresdiagonalize_one_body == diagonalize_one_body_offset
.
- Returns:
DoubleFactorizedHamiltonian
– Hamiltonian operator storing two-body integrals in double factorized form and, optionally, diagonalized one-body integrals.
- effective_potential(rdm1)
Calculates the effective Coulombic potential for a given 1-RDM.
- Parameters:
rdm1 (
UnrestrictedOneBodyRDM
) – Unrestricted, one-body reduced density matrix.- Returns:
List
[ndarray
] – Effective potentials for the alpha and beta spin channels.
- energy(rdm1, rdm2=None)
Calculate total energy based on the one- and two-body reduced density matrices.
If
rdm2
is not given, this method returns the mean-field energy.- Parameters:
rdm1 (
UnrestrictedOneBodyRDM
) – Unrestricted, one-body reduced density matrix object.rdm2 (
Optional
[UnrestrictedTwoBodyRDM
], default:None
) – Unrestricted, two-body reduced density matrix object.
- Returns:
float
– Total energy.
- energy_electron_mean_field(rdm1)
Calculates the electronic energy in the mean-field approximation.
- Parameters:
rdm1 (
UnrestrictedOneBodyRDM
) – Unrestricted, one-body reduced density matrix object.- Returns:
Tuple
[float
,float
] – The mean-field electronic energy (one-body + two-body), and the mean-field Coulomb contribution (two-body only).
- classmethod from_FermionOperator(operator)
Convert a 2-body fermionic operator to unrestricted-orbital integral operator.
The one-body terms are stored in matrices,
_one_body_aa[p, q]
and_one_body_bb
, and the two-body terms are stored in tensors,_two_body_aaaa[p, q, r, s]
,_two_body_bbbb[...]
,_two_body_aabb[...]
and_two_body_bbaa[...]
.- Parameters:
operator (
FermionOperator
) – Input fermion operator.- Returns:
ChemistryUnrestrictedIntegralOperator
– The converted operator.
Warning
The same-spin (aaaa and bbbb) blocks returned are contracted - this is fine for use in quantum chemistry calculations with density matrices having unit elements (e.g. Slater determinants) - for other purposes one should be careful.
- items(yield_constant=True, yield_one_body=True, yield_two_body=True)
Generates the constant, one- and two-body operator terms contained in the operator object.
- Parameters:
- Yields:
Next requested
FermionOperatorString
and constant/integral value.- Return type:
- classmethod load_h5(name)
Loads operator object from .h5 file.
- qubit_encode(mapping=None, qubits=None)
Performs qubit encoding (mapping), using provided mapping class, of this instance.
This proceeds by creation of a
FermionOperator
class, via theto_FermionOperator()
method, before mapping to aQubitOperator
using the provided mapping scheme. Please see the documentation forto_FermionOperator()
for finer grained control over operator generation.- Parameters:
mapping (
Optional
[QubitMapping
], default:None
) –QubitMapping
-derived instance. Default mapping procedure isQubitMappingJordanWigner
.qubits (
Optional
[List
[Qubit
]], default:None
) – The qubit register. If left asNone
, a default register will be assumed if possible. SeeQubitMapping
documentation for further details.
- Returns:
QubitOperator
– MappedQubitOperator
object.
- rotate(rotation_aa, rotation_bb, check_unitary=True, check_unitary_atol=1e-15)
Performs an in-place unitary rotation of the chemistry integrals.
Each spin block is rotated separately.
- Parameters:
rotation_aa (
ndarray
) – Unitary rotation matrix for the alpha spin block.rotation_bb (
ndarray
) – Unitary rotation matrix for the beta spin block.check_unitary (
bool
, default:True
) – Whether to perform the check for unitarity of the rotation matrices.check_unitary_atol (
float
, default:1e-15
) – Absolute tolerance of unitarity checks.
- Returns:
ChemistryUnrestrictedIntegralOperator
– This instance after rotation.
- save_h5(name)
Dumps operator object to .h5 file.
- to_FermionOperator(yield_constant=True, yield_one_body=True, yield_two_body=True)
Converts chemistry integral operator to
FermionOperator
.- Parameters:
- Returns:
FermionOperator
– Integral operator in general fermionic operator form.
- to_compact_integral_operator(symmetry)
Converts two-body integrals into compact form.
Compacts the two-body integrals into a
CompactTwoBodyIntegrals
object.- Parameters:
symmetry (
Union
[int
,str
]) – Target symmetry. Four-fold symmetry (4
,"4"
or"s4"
) or eight-fold symmetry (8
,"8"
or"s8"
) are supported.- Returns:
ChemistryUnrestrictedIntegralOperatorCompact
– Equivalent integral operator with two-body integrals stored in compact form.
- class ChemistryUnrestrictedIntegralOperatorCompact(constant, one_body_aa, one_body_bb, two_body_aaaa, two_body_bbbb, two_body_aabb, two_body_bbaa, dtype=None)
Bases:
BaseChemistryIntegralOperator
Handles a (unrestricted-orbital) chemistry integral operator, with integrals stored in a compact form.
Stores constant, one- and two-body spatial integral values following chemistry notation, i.e.
two_body[p, q, r, s]
= \((pq|rs)\). Two-body integrals are stored as aCompactTwoBodyIntegralsS4
orCompactTwoBodyIntegralsS8
object rather than anumpy.ndarray
, which reduces memory load, at the expense of some operations taking longer.Note
The
symmetry
class instance attribute is determined by the symmetry of thetwo_body_aaaa
input. The aabb and bbaa integral tensors are incompatible with s8 symmetry.- Parameters:
constant (
float
) – Constant energy term, electron independent.one_body_aa (
ndarray
) – One-body energy integrals for the alpha (a) spin channel.one_body_bb (
ndarray
) – One-body energy integrals for the beta (b) spin channel.two_body_aaaa (
Union
[CompactTwoBodyIntegralsS4
,CompactTwoBodyIntegralsS8
]) – Two-body electron repulsion integrals (ERI) with spatial orbitals in the aaaa spin channels respectively.two_body_bbbb (
Union
[CompactTwoBodyIntegralsS4
,CompactTwoBodyIntegralsS8
]) – ERI with spatial orbitals in the bbbb spin channels.two_body_aabb (
CompactTwoBodyIntegralsS4
) – ERI with spatial orbitals in the aabb spin channels.two_body_bbaa (
CompactTwoBodyIntegralsS4
) – ERI with spatial orbitals in the bbaa spin channels.
- TOLERANCE = 1e-08
Internal tolerance used when iterating over terms. Terms with magnitude smaller than this are not returned by
items()
.
- approx_equal(other, rtol=1.0e-5, atol=1.0e-8, equal_nan=False)
Test for approximate equality with another instance of this class by comparing integral arrays.
Arguments are passed directly to
numpy.allclose()
for equality comparison - see numpy documentation for further details.- Parameters:
other (
ChemistryUnrestrictedIntegralOperatorCompact
) – The other operator to compare for approximate equality.rtol (
float
, default:1.0e-5
) – The relative tolerance parameter, as defined bynumpy.allclose()
.atol (
float
, default:1.0e-8
) – The absolute tolerance parameter, as defined bynumpy.allclose()
.equal_nan (
bool
, default:False
) – Whether to compare NaN’s as equal, as defined bynumpy.allclose()
.
- Returns:
bool
–True
if other instance is approximately equal to this, otherwiseFalse
.
- copy()
Performs a deep copy of object.
- Return type:
BaseChemistryIntegralOperator
- df()
Returns a
pandas.DataFrame
object showing all terms in the operator.- Return type:
DataFrame
- double_factorize(tol1=-1.0, tol2=None, method=DecompositionMethod.EIG, diagonalize_one_body=True, diagonalize_one_body_offset=True, combine_one_body_terms=True)
Double factorizes the two-electron integrals and returns the Hamiltonian in diagonal form.
The Hamiltonian can be written as \(\hat{H} = H_0 + \hat{H}_1 + \hat{S} + \hat{V}\) where \(\hat{S}+\hat{V}\) is the Coulomb interaction. \(V = \frac{1}{2}\sum_{ijkl} (ij|kl) a_i^\dagger a_j a_k^\dagger a_l\) is a reordered two-body operator and \(\hat{S}\) is a one-body offset term given by \(\hat{S} = \sum_{ij} s_{ij} a_i^\dagger a_j\) where \(s_{ij} = -\frac{1}{2}\sum_k (ik|kj)\). \(H_0\) and \(\hat{H}_1\) are the constant and one-electron terms respectively.
The first level of factorization decomposes the electron repulsion integrals tensor into the form: \((pq|rs)=\sum_t^{N_\gamma} V_{pq}^t \gamma^t V_{rs}^t\). This may be performed using an eigenvalue decomposition (
method='eig'
), or a pivoted, incomplete Cholesky decomposition (method="cho"
) (see J. Chem. Phys. 118, 9481–9484 (2003) and J. Chem. Phys. 139, 134105 (2013)). The second factorization is diagonalization of the \(V_{pq}^t\) matrix for each t: \(V_{pq}^t = \sum_u^{N_\lambda^t} U_{pu}^t \lambda_u^t U_{qu}^t\).At the first factorization stage, truncation depends on the decomposition method. With
"eig"
, truncation is performed by discarding eigenvalues, starting from the smallest in magnitude, until the sum of those discarded magnitudes exceeds the thresholdtol1
. With"cho"
, the decomposition is constructed iteratively until the error is less thantol1
. At the second factorization level, truncation is always performed by discarding low-magnitude eigenvalues.One-body-like terms are consolidated and diagonalized by default: \(\tilde{h}_{pq} = h_{pq} + s_{pq} = \sum_r W_{pr} \omega_r W_{qr}\). One-body diagonalization is not truncated.
Warning
This is not intended for reduction of classical memory usage, only for truncating the two-body terms of the Hamiltonian for quantum simulation.
- Parameters:
tol1 (
float
, default:-1.0
) – Truncation threshold for first diagonalization of ERI matrix. If negative, no truncation is performed.tol2 (
Optional
[float
], default:None
) – Truncation threshold for second diagonalization of ERI matrix. IfNone
, same astol1
. If negative, no truncation is performed.method (
Union
[DecompositionMethod
,str
], default:DecompositionMethod.EIG
) – Decomposition method used for the first level of factorization."eig"
for an eigenvalue decomposition,"cho"
for a pivoted, incomplete Cholesky decomposition.diagonalize_one_body (
bool
, default:True
) – Whether to diagonalize the physical one-body integrals \(h_{pq}\).diagonalize_one_body_offset (
bool
, default:True
) – Whether to diagonalize the one-body offset integrals \(s_{pq}\)combine_one_body_terms (
bool
, default:True
) – Whether to consolidate the one-body and one-body offset integrals into effective one-body integrals. Requiresdiagonalize_one_body == diagonalize_one_body_offset
.
- Returns:
DoubleFactorizedHamiltonian
– Hamiltonian operator storing two-body integrals in double factorized form and, optionally, diagonalized one-body integrals.
- effective_potential(rdm1)
Calculates the effective Coulombic potential for a given 1-RDM.
- Parameters:
rdm1 (
UnrestrictedOneBodyRDM
) – Unrestricted, one-body reduced density matrix.- Returns:
List
[ndarray
] – Effective potentials for the alpha and beta spin channels.
- energy(rdm1, rdm2=None)
Calculate total energy based on the one- and two-body reduced density matrices.
If
rdm2
is not given, this method returns the mean-field energy.- Parameters:
rdm1 (
UnrestrictedOneBodyRDM
) – Unrestricted, one-body reduced density matrix object.rdm2 (
Optional
[UnrestrictedTwoBodyRDM
], default:None
) – Unrestricted, two-body reduced density matrix object.
- Returns:
float
– Total energy.
- energy_electron_mean_field(rdm1)
Calculates the electronic energy in the mean-field approximation.
- Parameters:
rdm1 (
UnrestrictedOneBodyRDM
) – Unrestricted, one-body reduced density matrix object.- Returns:
Tuple
[float
,float
] – The mean-field electronic energy (one-body + two-body), and the mean-field Coulomb contribution (two-body only).
- classmethod from_FermionOperator(operator, symmetry='s4')
Convert a 2-body fermionic operator to unrestricted-orbital integral operator.
The one-body terms are stored in matrices,
_one_body_aa[p, q]
and_one_body_bb
, and the two-body terms are stored inCompactTwoBodyIntegrals
objects,_two_body_aaaa[p, q, r, s]
,_two_body_bbbb[...]
,_two_body_aabb[...]
and_two_body_bbaa[...]
.- Parameters:
operator (
FermionOperator
) – Input fermion operator.symmetry (
Union
[str
,int
], default:"s4"
) – Target symmetry. Four-fold symmetry (4
,"4"
or"s4"
) or eight-fold symmetry (8
,"8"
or"s8"
) are supported.
- Returns:
ChemistryUnrestrictedIntegralOperatorCompact
– Output integral operator.
Warning
The same-spin (aaaa and bbbb) blocks returned are contracted - this is fine for use in quantum chemistry calculations with density matrices having unit elements (e.g. Slater determinants) - for other purposes one should be careful.
- items(yield_constant=True, yield_one_body=True, yield_two_body=True)
Generates the constant, one- and two-body operator terms contained in the operator object.
- Parameters:
- Yields:
Next requested
FermionOperatorString
and constant/integral value.- Return type:
- classmethod load_h5(name)
Loads operator object from .h5 file.
- qubit_encode(mapping=None, qubits=None)
Performs qubit encoding (mapping), using provided mapping class, of this instance.
This proceeds by creation of a
FermionOperator
class, via theto_FermionOperator()
method, before mapping to aQubitOperator
using the provided mapping scheme. Please see the documentation forto_FermionOperator()
for finer grained control over operator generation.- Parameters:
mapping (
Optional
[QubitMapping
], default:None
) –QubitMapping
-derived instance. Default mapping procedure isQubitMappingJordanWigner
.qubits (
Optional
[List
[Qubit
]], default:None
) – The qubit register. If left asNone
, a default register will be assumed if possible. SeeQubitMapping
documentation for further details.
- Returns:
QubitOperator
– MappedQubitOperator
object.
- rotate(rotation_aa, rotation_bb, check_unitary=True, check_unitary_atol=1e-15)
Performs an in-place unitary rotation of the chemistry integrals.
Each spin block is rotated separately. Rotation must be real-valued (orthogonal) for compact integrals.
- Parameters:
rotation_aa (
ndarray
) – Real, unitary rotation matrix for the alpha spin basis.rotation_bb (
ndarray
) – Real, unitary rotation matrix for the beta spin basis.check_unitary (
bool
, default:True
) – Whether to perform the check for unitarity of the rotation matrices.check_unitary_atol (
float
, default:1e-15
) – Absolute tolerance of unitarity checks.
- Returns:
ChemistryUnrestrictedIntegralOperatorCompact
– This instance after rotation.
- save_h5(name)
Dumps operator object to .h5 file.
- to_FermionOperator(yield_constant=True, yield_one_body=True, yield_two_body=True)
Converts chemistry integral operator to
FermionOperator
.- Parameters:
- Returns:
FermionOperator
– Integral operator in general fermionic operator form.
- to_uncompacted_integral_operator()
Convert to a
ChemistryUnrestrictedIntegralOperator
object.Unpacks the compact two-body integrals into a four-dimensional
numpy.ndarray
.- Returns:
ChemistryUnrestrictedIntegralOperator
– Equivalent integral operator object with un-compacted integrals.
- class CompactTwoBodyIntegralsS4(compact_array)
Bases:
BaseCompactTwoBodyIntegrals
Stores a two-body integral tensor in
s4
symmetry reduced form.Allows simple, 4-indexed
[i,j,k,l]
array-like access through index transformation.- Parameters:
compact_array (
ndarray
) – Two-body integrals in a four-fold symmetry-reduced form. Anumpy.ndarray
with shape \((n_{\text{pair}_{ij}}, n_{\text{pair}_{kl}}\)) where \(n_\text{pair} = n_{\text{orb}} (n_{\text{orb}} + 1) / 2\). This array may be rectangular to due to different numbers of alpha/beta spin orbitals in the \(h_{aabb}\) ERI tensor in an unrestricted spin picture.
- astype(dtype)
Returns a copy of the current compact integrals, with the compact array cast to a new type.
- Parameters:
dtype (
Any
) – The numpydtype
to cast into.- Returns:
CompactTwoBodyIntegralsS4
– New compact integrals object with compact array cast to the givendtype
.
- static check_s4_symmetry(uncompact_array, rtol=1.0e-5, atol=1.0e-8, equal_nan=False)
Tests whether the input ERI tensor has four-fold (
s4
) index symmetries.Checks for symmetries under index swaps \(i \leftrightarrow j\) and \(k \leftrightarrow l\).
- Parameters:
- Returns:
bool
–True
if the input array hass4
symmetry,False
otherwise.
- property dtype: dtype
Returns numpy data type of the compact array.
- classmethod from_uncompacted_integrals(two_body, symmetry, check_symmetry=False, rtol=1.0e-5, atol=1.0e-8, equal_nan=False)
Builds a compact integrals object from an uncompacted array of two body integrals (a rank-4 tensor).
- Parameters:
two_body (
ndarray
) – 4D array.symmetry (
Union
[str
,int
]) – Code to specify target symmetry. Uses the same convention as pyscf. Currently supportss4
ands8
symmetry.check_symmetry (
bool
, default:False
) – Whether the input array should be checked for the requested symmetry.rtol (
float
, default:1.0e-5
) – Relative tolerance on symmetry checks.atol (
float
, default:1.0e-8
) – Absolute tolerance.equal_nan (
bool
, default:False
) – Whether to compareNaN
values as equal.
- Returns:
Union
[CompactTwoBodyIntegralsS4
,CompactTwoBodyIntegralsS8
] – Object containing the same information as the input array in a compact form.
- property imag: CompactTwoBodyIntegralsS4
Extract the imaginary part of the two-body integrals.
- Returns:
New compact object containing only the imaginary part of the integrals.
- static pairs(n_orb)
Yields unique index pairs, and their pair index.
Does not return multiple equivalent pairs i.e. {2, 1} will appear, but {1, 2} will not.
- property real: CompactTwoBodyIntegralsS4
Extract the real part of the two-body integrals.
- Returns:
New compact object containing only the real part of the integrals.
- rotate(u_ij, u_kl=None)
Perform a rotation of the compact two-body integrals.
- Parameters:
u_ij (
ndarray
) – A real, orthogonal matrix of dimensions (\(n_{\text{orb}_{ij}}\), \(n_{\text{orb}_{ij}}\)). For rotating the first two indices of the two-body integrals tensor.u_kl (
Optional
[ndarray
], default:None
) – A real, orthogonal matrix of dimensions (\(n_{\text{orb}_{kl}}\), \(n_{\text{orb}_{kl}}\)). For rotating the second two indices of the two-body integrals tensor.
- Return type:
- class CompactTwoBodyIntegralsS8(compact_array)
Bases:
BaseCompactTwoBodyIntegrals
Stores a two-body integral tensor in
s8
symmetry reduced form.Allows simple, 4-indexed
[i,j,k,l]
array-like access through index transformation.Note
This symmetry class can only be used for ERI tensors that describe orbitals with the same spin i.e. the restricted spin ERI tensor, or the aaaa and bbbb unrestricted ERI tensors. It cannot be used for the aabb unrestricted tensor, because that block does not respect \(ij \leftrightarrow kl\) swap symmetry.
- Parameters:
compact_array (
ndarray
) – Two-body integrals in an eight-fold symmetry-reduced form. Anumpy.ndarray
with shape \((n_{pp})\) where \(n_{pp} = n_\text{pair} (n_\text{pair} + 1) / 2\) and \(n_\text{pair} = n_{\text{orb}} (n_{\text{orb}} + 1) / 2.\)
- astype(dtype)
Returns a copy of the current compact integrals, with the compact array cast to a new type.
- Parameters:
dtype (
Any
) – The numpydtype
to cast into.- Returns:
CompactTwoBodyIntegralsS8
– New compact integrals object with compact array cast to the givendtype
.
- static check_s8_symmetry(uncompact_array, rtol=1.0e-5, atol=1.0e-8, equal_nan=False)
Tests whether the input ERI tensor has eight-fold (
s8
) index symmetries.Checks for symmetries under index swaps \(i \leftrightarrow j\) and \(k \leftrightarrow l\), and pair index swaps \(ij \leftrightarrow kl\).
- Parameters:
- Returns:
bool
– True if the input array has s8 symmetry, false otherwise.
- property dtype: dtype
Returns numpy data type of the compact array.
- classmethod from_uncompacted_integrals(two_body, symmetry, check_symmetry=False, rtol=1.0e-5, atol=1.0e-8, equal_nan=False)
Builds a compact integrals object from an uncompacted array of two body integrals (a rank-4 tensor).
- Parameters:
two_body (
ndarray
) – 4D array.symmetry (
Union
[str
,int
]) – Code to specify target symmetry. Uses the same convention as pyscf. Currently supportss4
ands8
symmetry.check_symmetry (
bool
, default:False
) – Whether the input array should be checked for the requested symmetry.rtol (
float
, default:1.0e-5
) – Relative tolerance on symmetry checks.atol (
float
, default:1.0e-8
) – Absolute tolerance.equal_nan (
bool
, default:False
) – Whether to compareNaN
values as equal.
- Returns:
Union
[CompactTwoBodyIntegralsS4
,CompactTwoBodyIntegralsS8
] – Object containing the same information as the input array in a compact form.
- property imag: CompactTwoBodyIntegralsS8
Extract the imaginary part of the two-body integrals.
- Returns:
New compact object containing only the imaginary part of the integrals.
- static pairs(n_orb)
Yields unique index pairs, and their pair index.
Does not return multiple equivalent pairs i.e. {2, 1} will appear, but {1, 2} will not.
- property real: CompactTwoBodyIntegralsS8
Extract the real part of the two-body integrals.
- Returns:
New compact object containing only the real part of the integrals.
- rotate(u)
Perform a rotation of the compact two-body integrals.
- Parameters:
u (
ndarray
) – A real, orthogonal matrix of dimensions (\(n_{\text{orb}}\), \(n_{\text{orb}}\)).- Return type:
- class DecompositionMethod(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
Enum
Methods for factorization of two electron integrals tensor.
- CHOLESKY = 'cho'
- EIG = 'eig'
- class DoubleFactorizedHamiltonian(constant, one_body, one_body_offset, two_body)
Bases:
object
Restricted-spin hamiltonian operator, with two-body integrals stored in double factorized form.
Stores a hamiltonian of the form \(\hat{H} = H_0 + \hat{H}_1 + \hat{S} + \hat{V}\) where \(\hat{S}+\hat{V}\) is the coulomb interaction. \(\hat{V} = \frac{1}{2}\sum_{ijkl} (ij|kl) a_i^\dagger a_j a_k^\dagger a_l\) is a reordered two-body operator and \(\hat{S}\) is a one-body offset to the two-body operator given by \(\hat{S}=\sum_{ij}s_{ij}a_i^\dagger a_j\) where \(s_{ij} = -\frac{1}{2}\sum_k (ik|kj)\). \(H_0\) and \(\hat{H}_1\) are the constant and one-electron terms respectively.
Double factorized two-body operator has the form: \(V = (1/2)\sum_t^{N_\gamma} R(U_t) A_t R(U_t)^\dagger\) where \(A_t = \gamma^t\left( \sum_u^{N_\lambda^t} \lambda_u^t a_u^\dagger a_u \right)^2\) and \(R(U_t)\) is a basis rotation operator.
One-body-like terms may be consolidated into a single effective-one-body term: \(\hat{H}_1' = \hat{H}_1 + \hat{S}\). One-body term(s) may be stored as arrays, or diagonalized. When diagonalized, one-body terms are given by: \(\hat{H}_1 = R(W)\left( \sum_i^N \omega_i a_i^\dagger a_i\right) R(W)^\dagger\).
- Parameters:
constant (
float
) – Constant (electron-independent) energy.one_body (
Union
[DiagonalizedOneBodyIntegrals
,ndarray
[Any
,dtype
[TypeVar
(_ScalarType_co
, bound=generic
, covariant=True)]]]) – One-body integrals. These are the physical one-body integrals \(\hat{H}_1\) ifone_body_offset != None
, or effective one-body integrals \(\hat{H}_1'\) ifone_body_offset == None
.one_body_offset (
Union
[DiagonalizedOneBodyIntegrals
,ndarray
[Any
,dtype
[TypeVar
(_ScalarType_co
, bound=generic
, covariant=True)]],None
]) – Contracted ERI tensor \(s_{ij}\). IfNone
, they are assumed to be part ofone_body
.two_body (
DoubleFactorizedTwoBodyIntegrals
) – Double factorized two-body integrals.
- items(include_constant=True, include_one_body=True, include_one_body_offset=True, include_two_body=True, square_two_body_sum=True)
Iterate through all fermion operators alongside accompanying rotation matrices.
- Parameters:
include_constant (
bool
, default:True
) – Whether to include the constant energy term.include_one_body (
bool
, default:True
) – Whether to include the physical/effective one-body terms.include_one_body_offset (
bool
, default:True
) – Whether to include the one-body offset terms. Ifone_body_offset == None
, this term is omitted anyway.include_two_body (
bool
, default:True
) – Whether to include the two-body terms.square_two_body_sum (
bool
, default:True
) – Whether to square the linear combination of number operators in the two-body term.
- Yields:
Fermion operators terms, corresponding rotation matrices.
- Return type:
Iterator
[Tuple
[FermionOperator
,ndarray
[Any
,dtype
[float
]]]]
- class FCIDumpRestricted
Bases:
object
This class reads FCIDUMP files and facilitates transformations to native InQuanto objects.
Symmetry information is not extracted from the FCIDUMP files. To be used in InQuanto, symmetry information should be passed by the user to the relevant space object. The vanilla information is, however, stored in the specification attribute, so a user can map from FCIDUMP integer values to irrep labels using their own code.
Notes
Currently this functionality is tested against pyscf, psi4 and nwchem FCIDUMP files for restricted systems only. User experience may differ when using this with files generated by packages not listed here.
- Parameters:
filename – The name of the FCIDUMP file to be handled by the object.
- get_system_specification()
Read the system specification block of the FCIDUMP file and process the contents into a dictionary.
- Parameters:
filename – The name of the FCIDUMP file.
- Returns:
Dict
– A dictionary where each key is a named element of the system specification block.
- load(filename)
Load the contents of the FCIDUMP file in one IO operation.
This method populates the
constant
,one_body_list
, andtwo_body_list
attributes.
- one_body_to_array()
Unpack the one-body data into a \(N\times N\) matrix, where \(N\) is the number of spatial orbitals.
Elements which are permutationally equivalent to those in the FCIDUMP file are filled with the appropriate value.
- to_ChemistryRestrictedIntegralOperator()
Generate a
ChemistryRestrictedIntegralOperator
object from the provided file.The integrals from the file are unpacked and distributed into the full \(N\times N\) one-body matrix and \(N\times N\times N\times N\) two-body tensor, where \(N\) is the number of spatial orbitals.
- Parameters:
filename – The name of the FCIDUMP file.
- Returns:
ChemistryRestrictedIntegralOperator
– AChemistryRestrictedIntegralOperator
object corresponding to the integrals contained in the FCIDUMP file represented by this instance.
- to_arrays()
Transform the one- and two-body data into their unpacked array forms.
Chemist notation is followed, and permutationally equivalent elements to those in the FCIDUMP file are filled.
- two_body_to_tensor()
Unpack the one-body data into an \(N\times N\times N\times N\) tensor, where \(N\) is the number of spatial orbitals.
Elements which are permutationally equivalent to those in the FCIDUMP file are filled with the appropriate value.
- write(filename, constant, one_body, two_body, norb, nelec, multiplicity, orbsym=None, isym=None, tolerance=1e-12)
Write an FCIDUMP file corresponding to the provided constant, one body and two body quantities.
- Parameters:
filename (
str
) – The name of the file to write the FCIDUMP to.constant (
float
) – The constant term of the Hamiltonian.one_body (
ndarray
[Any
,dtype
[TypeVar
(_ScalarType_co
, bound=generic
, covariant=True)]]) – The spatial orbital, one-body integrals as a numpy array.two_body (
ndarray
[Any
,dtype
[TypeVar
(_ScalarType_co
, bound=generic
, covariant=True)]]) – The spatial orbital, two-body integrals as a numpy array.norb (
int
) – The number of spatial orbitals in the system.nelec (
int
) – The number of electrons in the system.multiplicity (
int
) – The spin multiplicity of the system.orbsym (
Optional
[List
[int
]], default:None
) – The integer value of the irreps of the spatial orbitals.isym (
Optional
[int
], default:None
) – The integer value of the point group.tolerance (
float
, default:1e-12
) – Write integrals to the file with a value greater than this number.
- Return type:
- class FermionOperator(data=None, coeff=1.0)
Bases:
Operator
Represents an operator on a Fermionic Hilbert space.
The operator is stored as a
dict
, with the keys beingFermionOperatorString
objects (terms) and values being the corresponding term coefficients. This can be directly instantiated with atuple
, alist
oftuple
s, or adict
.See examples below, and the documentation for the
from_tuple()
andfrom_list()
methods for further detail.- Parameters:
data (
Union
[Tuple
,FermionOperatorString
,List
[Tuple
[Union
[int
,float
,complex
,Expr
],Union
[FermionOperatorString
,str
]]],Dict
[FermionOperatorString
,Union
[int
,float
,complex
,Expr
]]], default:None
) – Input data from which the fermion operator is built. Multiple input formats are supported.coeff (
Union
[int
,float
,complex
,Expr
], default:1.0
) – Multiplicative scalar coefficient. Used only whendata
is of typetuple
orFermionOperatorString
.
Examples
>>> fos = FermionOperatorString(((1, 0), (2, 1))) >>> op = FermionOperator(fos, 1.0) >>> print(op) (1.0, F1 F2^) >>> op = FermionOperator({fos: 1.0}) >>> print(op) (1.0, F1 F2^)
- class TrotterizeCoefficientsLocation(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
-
Determines where coefficients will be stored upon performing Trotterization.
- INNER = 'inner'
All coefficients will be stored in the “inner” coefficients, within the component QubitOperators in the Trotterized result.
- MIXED = 'mixed'
The Trotter step factor will be stored in the “outer” coefficients, whereas the original coefficients of the original Operator will remain in the component Operators.
- OUTER = 'outer'
All coefficients will be stored in the “outer” coefficients, the coefficients stored directly in the generated OperatorList.
- capitalize()
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
- casefold()
Return a version of the string suitable for caseless comparisons.
- center(width, fillchar=' ', /)
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
- count(sub[, start[, end]]) int
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
- encode(encoding='utf-8', errors='strict')
Encode the string using the codec registered for encoding.
- encoding
The encoding in which to encode the string.
- errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(suffix[, start[, end]]) bool
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
- expandtabs(tabsize=8)
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(*args, **kwargs) str
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).
- format_map(mapping) str
Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).
- index(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- isalnum()
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
- isalpha()
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
- isascii()
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
- isdecimal()
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
- isdigit()
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
- isidentifier()
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.
- islower()
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
- isnumeric()
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.
- isprintable()
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in repr() or if it is empty.
- isspace()
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
- istitle()
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
- isupper()
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
- join(iterable, /)
Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
- ljust(width, fillchar=' ', /)
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
- lower()
Return a copy of the string converted to lowercase.
- lstrip(chars=None, /)
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- static maketrans()
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
- partition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
- removeprefix(prefix, /)
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
- removesuffix(suffix, /)
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
- replace(old, new, count=-1, /)
Return a copy with all occurrences of substring old replaced by new.
- count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
- rfind(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- rjust(width, fillchar=' ', /)
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
- rpartition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
- rsplit(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
- rstrip(chars=None, /)
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the front of the string and works to the end.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
- splitlines(keepends=False)
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
- startswith(prefix[, start[, end]]) bool
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
- strip(chars=None, /)
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase()
Convert uppercase characters to lowercase and lowercase characters to uppercase.
- title()
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
- translate(table, /)
Replace each character in the string using the given translation table.
- table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
- upper()
Return a copy of the string converted to uppercase.
- zfill(width, /)
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
- apply_bra(fock_state)
Performs an operation on a
inquanto.states.FermionState
representing a bra.This transforms the provided
inquanto.states.FermionState
with the operator on the right. Conjugation on theinquanto.states.FermionState
object is not performed.- Parameters:
fock_state (
FermionState
) – Object representing a bra.- Returns:
FermionState
– A representation of the post-operation bra.
- apply_ket(fock_state)
Performs an operation on a ket
inquanto.states.FermionState
state.- Parameters:
fock_state (
FermionState
) – FermionState object (ket state).- Returns:
FermionState
– New ket state.
- approx_equal_to(other, abs_tol=1e-10)
Checks for equality between this instance and another
FermionOperator
.First, dictionary equivalence is tested for. If
False
, operators are compared in normal-ordered form, and difference is compared toabs_tol
.- Parameters:
other (
FermionOperator
) – An operator to test for equality with.abs_tol (
float
, default:1e-10
) – Tolerance threshold for negligible terms in comparison.
- Returns:
bool
–True
if this operator is equal to other, otherwiseFalse
.
Danger
This method may use the
normal_ordered()
method internally, which may be exponentially costly.
- 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.
- as_scalar(abs_tol=None)
If the operator is a sum of identity terms or zero, return the sum of the coefficients, otherwise return
None
.Note that this does not perform combination of terms and will return zero only if all coefficients are zero.
- Parameters:
abs_tol (
float
, default:None
) – Tolerance for checking if coefficients are zero. Set toNone
to test using a standard
:param python
==
comparison.:
- classmethod ca(a, b)
Return object with a single one-body creation-annihilation pair with a unit coefficient in its
dict
.- Parameters:
- Returns:
The creation-annihilation operator pair.
Examples
>>> print(FermionOperator.ca(2, 0)) (1.0, F2^ F0 )
- classmethod caca(a, b, c, d)
Return object with a single two-body creation-annihilation pair with a unit coefficient in its
dict
.Ordered as creation-annihilation-creation-annihilation.
- Parameters:
a (
int
) – Index of fermionic mode to which the first creation operator is applied.b (
int
) – Index of fermionic mode to which the first annihilation operator is applied.c (
int
) – Index of fermionic mode to which the second creation operator is applied.d (
int
) – Index of fermionic mode to which the second annihilation operator is applied.
- Returns:
The composed two-body operator.
Examples
>>> print(FermionOperator.caca(2, 0, 3, 1)) (1.0, F2^ F0 F3^ F1 )
- classmethod ccaa(a, b, c, d)
Return object with a single two-body creation-annihilation pair with a unit coefficient in its
dict
.Ordered as creation-creation-annihilation-annihilation.
- Parameters:
a (
int
) – Index of fermionic mode to which the first creation operator is applied.b (
int
) – Index of fermionic mode to which the second creation operator is applied.c (
int
) – Index of fermionic mode to which the first annihilation operator is applied.d (
int
) – Index of fermionic mode to which the second annihilation operator is applied.
- Returns:
The composed two-body operator.
Examples
>>> print(FermionOperator.ccaa(3, 2, 1, 0)) (1.0, F3^ F2^ F1 F0 )
- commutator(other_operator)
Returns the commutator of this instance with
other_operator
.This calculation is performed by explicit calculation through multiplication.
- Parameters:
other_operator (
FermionOperator
) – The other fermionic operator.- Returns:
FermionOperator
– The commutator.
- commutes_with(other_operator, abs_tol=1e-10)
Returns
True
if this instance commutes withother_operator
(within tolerance), otherwiseFalse
.- Parameters:
other_operator (
FermionOperator
) – The other fermionic operator.abs_tol (
float
, default:1e-10
) – Tolerance threshold for negligible terms in the commutator.
- Returns:
bool
–True
if operators commute (within tolerance) otherwiseFalse
.
- 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 ofLinearDictCombiner
.
- classmethod constant(value)
Return object with a provided constant entry in its
dict
.- Returns:
Operator representation of provided constant scalar.
Examples
>>> print(FermionOperator.constant(0.5)) (0.5, )
- dagger()
Returns the Hermitian conjugate of an operator.
- Return type:
- 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:
SymbolSet
– Ordered set of symbols.
- freeze(index_map, occupation)
Adaptation of OpenFermion’s freeze_orbitals method with mask and consistent index pruning.
- Parameters:
index_map (
List
[int
]) – A list of integers orNone
entries, whose size is equal to the number of spin-orbitals, whereNone
indicates orbitals to be frozen and the remaining sequence of integers is expected to be continuous.occupation (
List
[int
]) – Alist
of 1s and 0s of the same length asindex_map
, indicating occupied and unoccupied orbitals.
- Returns:
FermionOperator
– New operator with frozen orbitals removed.
- classmethod from_list(data)
Construct
FermionOperator
from alist
oftuple
s.- Parameters:
data (
List
[Tuple
[Union
[int
,float
,complex
,Expr
],FermionOperatorString
]]) – Data representing a fermion operator term or sum of fermion operator terms. Each term in thelist
must be atuple
containing a scalar multiplicative coefficient, followed by aFermionOperatorString
ortuple
(seeFermionOperator.from_tuple()
).- Returns:
FermionOperator
– Fermion operator object corresponding to a valid input.
Examples
>>> fos0 = FermionOperatorString(((1, 0), (2, 1))) >>> fos1 = FermionOperatorString(((1, 0), (3, 1))) >>> op = FermionOperator.from_list([(0.9, fos0), (0.1, fos1)]) >>> print(op) (0.9, F1 F2^), (0.1, F1 F3^) >>> op = FermionOperator.from_list([(0.9, ((1, 0), (2, 1))), (0.1, fos1)]) >>> print(op) (0.9, F1 F2^), (0.1, F1 F3^)
- classmethod from_string(input_string)
Constructs a child class instance from a string.
- Parameters:
input_string (
str
) – String in the formatcoeff1 [(coeff1_1, term1_1), ..., (coeff1_n, term1_n)], ..., coeffn [(coeffn_1, termn_1), ...]
.- Returns:
Child class object.
- classmethod from_tuple(data, coeff=1.0)
Construct
FermionOperator
from atuple
of terms.- Parameters:
data (
Tuple
) – Data representing a fermion operator term, which may be a product of single fermion creation or anihilation operators. Creation and annihilation operators acting on orbital indexq
are given bytuple
s(q, 0)
and(q, 1)
respectively. A product of single operators is given by atuple
oftuple
s; for example, the number operator:((q, 1), (q, 0))
.coeff (
Union
[int
,float
,complex
,Expr
], default:1.0
) – Multiplicative scalar coefficient.
- Returns:
FermionOperator
– Fermion operator object corresponding to a valid input.
Examples
>>> op = FermionOperator.from_tuple(((1, 0), (2, 1)), 1.0) >>> print(op) (1.0, F1 F2^)
- classmethod identity()
Return object with an identity entry in its
dict
.Examples
>>> print(FermionOperator.identity()) (1.0, )
- infer_num_spin_orbs()
Returns the number of modes that this operator acts upon, inferring the existence of modes with index from 0 to the maximum index.
- Returns:
int
– The minimum number of spin orbitals in the Fock space to which thisFermionOperator
operates on.
Examples
>>> op = FermionOperator.from_string("(1.0, F1 F2^)") >>> print(op.infer_num_spin_orbs()) 3
- 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_antihermitian(abs_tol=1e-10)
Returns
True
if operator is anti-Hermitian (within a tolerance), elseFalse
.This explicitly calculates the Hermitian conjugate, multiplies by -1 and tests for equality. Normal-ordering is performed before comparison.
- Parameters:
abs_tol (
float
, default:1e-10
) – Tolerance threshold for negligible terms in comparison.- Returns:
bool
–True
if operator is anti-Hermitian, otherwiseFalse
.
Danger
This method uses the
normal_ordered()
method internally, which may be exponentially costly.
- 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_commuting_operator()
Returns
True
if every term in operator commutes with every other term, otherwiseFalse
.- Return type:
- is_hermitian(abs_tol=1e-10)
Returns
True
if operator is Hermitian (within a tolerance), elseFalse
.This explicitly calculates the Hermitian conjugate and tests for equality. Normal-ordering is performed before comparison.
- Parameters:
abs_tol (
float
, default:1e-10
) – Tolerance threshold for negligible terms in comparison.- Returns:
bool
–True
if operator is Hermitian, otherwiseFalse
.
Danger
This method uses the
normal_ordered()
method internally, which may be exponentially costly.
- is_normal_ordered()
Returns whether or not term is in normal-ordered form.
The assumed convention for normal ordering is for all creation operators to be to the left of annihilation operators, and each “block” of creation/annihilation operators are ordered with orbital indices in descending order (from left to right).
- Returns:
bool
–True
if operator is normal-ordered,False
otherwise.
Examples
>>> op = FermionOperator.from_string("(3.5, F1 F2^)") >>> print(op.is_normal_ordered()) False >>> op = FermionOperator.from_string("(3.5, F1^ F2^)") >>> print(op.is_normal_ordered()) False
- is_normalized(order=2, abs_tol=1e-10)
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=1e-10)
Returns
True
if other is parallel with this (i.e. a scalar multiple of this), otherwiseFalse
.
- is_self_inverse(abs_tol=1e-10)
Returns
True
if operator is its own inverse (within a tolerance),False
otherwise.This explicitly calculates the square of the operator and compares to the identity. Normal-ordering is performed before comparison.
- Parameters:
abs_tol (
float
, default:1e-10
) – Tolerance threshold for negligible terms in comparison.- Returns:
bool
–True
if operator is self-inverse, otherwiseFalse
.
Danger
This method uses the
normal_ordered()
method internally, which may be exponentially costly.
- is_two_body_number_conserving(check_spin_symmetry=False)
Query whether operator has correct form to be a molecular Hamiltonian.
This method is a copy of the OpenFermion
is_two_body_number_conserving()
method.Require that term is particle-number conserving (same number of raising and lowering operators). Require that term has 0, 2 or 4 ladder operators. Require that term conserves spin (parity of raising operators equals parity of lowering operators).
- Parameters:
check_spin_symmetry (
bool
, default:False
) – Whether to check if operator conserves spin.- Returns:
bool
–True
if operator conserves electron number (and, optionally, spin),False
otherwise.
Examples
>>> op = FermionOperator.from_string("(1.0, F1^ F0)") >>> print(op.is_two_body_number_conserving()) True >>> op = FermionOperator.from_string("(1.0, F0^)") >>> print(op.is_two_body_number_conserving()) False >>> op = FermionOperator.from_string("(1.0, F1^ F0^)") >>> print(op.is_two_body_number_conserving()) False >>> op = FermionOperator.from_string("(1.0, F1^ F0)") >>> print(op.is_two_body_number_conserving(check_spin_symmetry=True)) False
- is_unit_1norm(abs_tol=1e-10)
Returns True if operator has unit 1-norm, else False.
- is_unit_2norm(abs_tol=1e-10)
Returns True if operator has unit 1-norm, else False.
- is_unit_norm(order=2, abs_tol=1e-10)
Returns True if operator has unit p-norm, else False.
- Parameters:
- Raises:
ValueError – Coefficients contain free symbols.
- Return type:
- is_unitary(abs_tol=1e-10)
Returns True if operator is unitary (within a tolerance), False otherwise.
This explicitly calculates the Hermitian conjugate, right-multiplies by the initial operator and tests for equality to the identity. Normal-ordering is performed before comparison.
- Parameters:
abs_tol (
float
, default:1e-10
) – Tolerance threshold for negligible terms in comparison.- Returns:
bool
–True
if operator is unitary, otherwiseFalse
.
Danger
This method uses the
normal_ordered()
method internally, which may be exponentially costly.
- static key_from_str(key_str)
Returns a
FermionOperatorString
instance initiated from the input string.- Parameters:
key_str (
str
) – An input string describing theFermionOperatorString
to be created -
:param see
FermionOperatorString.from_string()
for more detail.:- Returns:
FermionOperatorString
– A generatedFermionOperatorString
instance.
- list_class
alias of
FermionOperatorList
- 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.
- normal_ordered()
Returns a normal-ordered version of
FermionOperator
.Normal-ordering the operator moves all creation operators to the left of annihilation operators, and orders orbital indices in descending order (from left to right).
Danger
This may be exponential in runtime.
- Returns:
FermionOperator
– The operator in normal-ordered form.
Examples
>>> op = FermionOperator.from_string("(0.5, F1 F2^), (0.2, F1 F2 F3^ F4^)") >>> op_no = op.normal_ordered() >>> print(op_no) (-0.5, F2^ F1 ), (0.2, F4^ F3^ F2 F1 )
- normalized(norm_value=1.0, norm_order=2)
Returns a copy of this object with normalised coefficients.
- property num_spin_orbs: int
Return the number of spin-orbitals that this operator explicitly acts on.
- permuted_operator(permutation)
Permutes the indices in a
FermionOperator
.Permutation is according to a
list
or adict
of indices, mapping the old to a new operator order.- Parameters:
permutation (
Union
[Dict
,List
[int
]]) – Mapping from the old operator terms indices to the new ones. In case if alist
is given, its indices acts as keys (old indices) and its values correspond to the new indices of an operator. If adict
is given, it can only contain the indices to be permuted for higher efficiency.- Returns:
FermionOperator
– PermutedFermionOperator
object.
Examples
>>> op = FermionOperator.ccaa(1,4,5,6) + FermionOperator.ca(0,4) >>> print(op) (1.0, F1^ F4^ F5 F6 ), (1.0, F0^ F4 ) >>> print(op.permuted_operator([0,4,2,3,1,5,6])) (1.0, F4^ F1^ F5 F6 ), (1.0, F0^ F1 ) >>> print(op.permuted_operator({1:4, 4:1})) (1.0, F4^ F1^ F5 F6 ), (1.0, F0^ F1 )
- qubit_encode(mapping=None, qubits=None)
Performs qubit encoding (mapping), using provided mapping class, of this instance.
- Parameters:
mapping (
QubitMapping
, default:None
) –QubitMapping
-derived instance. Default mapping procedure isQubitMappingJordanWigner
.qubits (
Optional
[List
[Qubit
]], default:None
) – The qubit register. If left asNone
, a default register will be assumed if possible. SeeQubitMapping
documentation for further details.
- Returns:
QubitOperator
– MappedQubitOperator
object.
- 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
- 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.
- split()
Generates single-term
FermionOperator
objects.
- 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.
- sympify(*args, **kwargs)
Sympifies dictionary values.
Replaces values with their corresponding symbolic expressions.
- Parameters:
- Returns:
LinearDictCombiner
– Updated instance ofLinearDictCombiner
.- Raises:
RuntimeError – Sympification fails.
- to_ChemistryRestrictedIntegralOperator()
Convert fermion operator into a restricted integral operator.
Uses the
ChemistryRestrictedIntegralOperator.from_FermionOperator()
method internally.- Return type:
ChemistryRestrictedIntegralOperator
- to_ChemistryUnrestrictedIntegralOperator()
Convert fermion operator into an unrestricted integral operator.
Uses the
ChemistryUnrestrictedIntegralOperator.from_FermionOperator()
method internally.- Return type:
ChemistryUnrestrictedIntegralOperator
- to_latex(imaginary_unit='\\\\text{i}', **kwargs)
Generate a LaTeX representation of the operator.
- Parameters:
imaginary_unit (
str
, default:r"\\text{i}"
) – Symbol to use for the imaginary unit.**kwargs – Keyword arguments passed to the
to_latex()
method of component operator strings (FermionOperatorString
orQubitOperatorString
).
- Returns:
str
– LaTeX compilable equation string.
Examples
>>> from inquanto.operators import FermionOperator >>> from sympy import sympify >>> c = sympify("c") >>> fo = FermionOperator([(-c, "F1 F2^"), (c**2, "F1^"), (c, "F0 F5 F3^")]) >>> print(fo.to_latex()) - c a_{1} a_{2}^{\dagger} + c^{2} a_{1}^{\dagger} + c a_{0} a_{5} a_{3}^{\dagger} >>> fo = FermionOperator([(1.0, "F0^ F1^ F3^"), (-1.0j, "F3 F1 F0")]) >>> print(fo.to_latex()) a_{0}^{\dagger} a_{1}^{\dagger} a_{3}^{\dagger} -\text{i} a_{3} a_{1} a_{0} >>> from sympy import sqrt >>> fo = FermionOperator([(sqrt(2), "F0^ F1"), (0.5-8j, "F5 F5^"), (2j, "F1^ F1^")]) >>> print(fo.to_latex(imaginary_unit=r"\text{j}", operator_symbol="f")) \sqrt{2} f_{0}^{\dagger} f_{1} + (0.5-8.0\text{j}) f_{5} f_{5}^{\dagger} + 2.0\text{j} f_{1}^{\dagger} f_{1}^{\dagger}
>>> from inquanto.operators import QubitOperator, QubitOperatorString >>> qos1 = QubitOperatorString.from_string("X1 Y2 Z3") >>> qos2 = QubitOperatorString.from_string("Z0 Y1 X4") >>> qos3 = QubitOperatorString.from_list([(("a", [0]), "I"), (("b", [1]), "Z"), (("c", [2]), "Z")]) >>> qo = QubitOperator({qos1: -1.0, qos2: 3+4j, qos3: c}) >>> print(qo.to_latex()) - X_{1} Y_{2} Z_{3} + (3.0+ 4.0\text{i}) Z_{0} Y_{1} X_{4} + c I_{0} Z_{1} Z_{2} >>> qo = QubitOperator({qos3: 3j}) >>> print(qo.to_latex(imaginary_unit="j", show_labels=True)) 3.0j I^{\text{a}}_{0} Z^{\text{b}}_{1} Z^{\text{c}}_{2}
- trotterize(trotter_number=1, trotter_order=1, constant=1.0, coefficients_location=TrotterizeCoefficientsLocation.OUTER)
Trotterizes the operator, treating the operator as an exponent.
- Assuming that this operator is an exponent, this will generate an instance with each element corresponding to a
single exponent in the Trotter product of exponentials.
- Parameters:
trotter_number (
int
, default:1
) – The number of time-slices in the Trotter approximation.trotter_order (
int
, default:1
) – The order of the Trotter-Suzuki approximation being used. Currently, this supports values1
(i.e. \(AB\)) and2
(i.e. \(A/2\,B/2\,B/2\,A/2\))constant (
Union
[float
,complex
], default:1.0
) – An additional constant factor to multiply each exponent by, which may be useful when, for example, constructing a time evolution operator.coefficients_location (
TrotterizeCoefficientsLocation
, default:TrotterizeCoefficientsLocation.OUTER
) – By default, the coefficient of each term in the input operator is multiplied by the Trotter factor and stored in the outer coefficient of the returned instance, with the coefficient of each innerOperator
set to 1. This behaviour can be controlled with this argument - set to"outer"
for default behaviour. On the other hand, setting this parameter to"inner"
will store all scalars in the innerOperator
coefficient, with the outer coefficients of the returned instance set to 1. Setting this parameter to"mixed"
will store the Trotter factor in the outer coefficients of the returned instance, with the inner coefficients of each term left untouched. See examples for a comparison.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – A Trotterized form of the exponential product, where each element is an individual exponent.
Examples
>>> from inquanto.operators import QubitOperator >>> op1 = QubitOperator("X0 Y1 Z3", 4.6) + QubitOperator("Z1 Z2 Z3 Z5", -5.6j) >>> trotter_operator = op1.trotterize(trotter_number=2) >>> print(trotter_operator) 2.3 [(1.0, X0 Y1 Z3)], -2.8j [(1.0, Z1 Z2 Z3 Z5)], 2.3 [(1.0, X0 Y1 Z3)], -2.8j [(1.0, Z1 Z2 Z3 Z5)] >>> from inquanto.operators import QubitOperator >>> op1 = QubitOperator("X0 Y1 Z3", 4.6) + QubitOperator("Z1 Z2 Z3 Z5", -5.6j) >>> trotter_operator = op1.trotterize(trotter_number=2,coefficients_location="inner") >>> print(trotter_operator) 1.0 [(2.3, X0 Y1 Z3)], 1.0 [(-2.8j, Z1 Z2 Z3 Z5)], 1.0 [(2.3, X0 Y1 Z3)], 1.0 [(-2.8j, Z1 Z2 Z3 Z5)] >>> from inquanto.operators import QubitOperator >>> op1 = QubitOperator("X0 Y1 Z3", 4.6) + QubitOperator("Z1 Z2 Z3 Z5", -5.6j) >>> trotter_operator = op1.trotterize(trotter_number=2,coefficients_location="mixed") >>> print(trotter_operator) 0.5 [(4.6, X0 Y1 Z3)], 0.5 [(-5.6j, Z1 Z2 Z3 Z5)], 0.5 [(4.6, X0 Y1 Z3)], 0.5 [(-5.6j, Z1 Z2 Z3 Z5)]
- truncated(tolerance=1e-8, normal_ordered=True)
Prunes
FermionOperator
terms with coefficients below provided threshold.- Parameters:
tolerance (default:
1e-8
) – Threshold below which terms are removed.normal_ordered (default:
True
) – Should the operator be returned in normal-ordered form.
- Returns:
FermionOperator
– New, modified operator.
Examples
>>> op = FermionOperator.from_string("(0.999, F0 F1^), (0.001, F2^ F1 )") >>> print(op.truncated(tolerance=0.005, normal_ordered=False)) (0.999, F0 F1^) >>> print(op.truncated(tolerance=0.005)) (-0.999, F1^ F0 )
- class FermionOperatorList(data=None, coeff=1.0)
Bases:
OperatorList
Stores
tuple
s ofFermionOperator
objects and corresponding coefficient values in an orderedlist
.In contrast to
FermionOperator
, this class is not assumed to represent a linear combination. Typically, this will be of use when considering sequences of operators upon which some nonlinear operation is performed. For instance, this may be used to store a Trotterised combination of exponentiatedFermionOperator
objects. This class may be instantiated from aFermionOperator
or aFermionOperatorString
object and a scalar or symbolic coefficient. It may also be instantiated with alist
containing two-elementtuple
s of scalar or symbolic coefficients andFermionOperator
objects. In contrast toFermionOperator
, in this class the ordering of terms is well-defined and consistent.- Parameters:
data (
Union
[FermionOperator
,FermionOperatorString
,List
[Tuple
[Union
[int
,float
,complex
,Expr
],FermionOperator
]]], default:None
) – Input data from which thelist
of fermion operators is built. SeeFermionOperator
for methods of constructing terms.coeff (
Union
[int
,float
,complex
,Expr
], default:1.0
) – Multiplicative scalar coefficient. Used only ifdata
is not of typelist
.
Examples
>>> from sympy import sympify >>> op1 = FermionOperator(FermionOperatorString(((1, 0), (2, 1))), 3.5) >>> op2 = FermionOperator(FermionOperatorString(((0, 0), (3, 1))), 1.5) >>> fto = FermionOperatorList([(sympify("a"), op1), (sympify("b"), op2)]) >>> print(fto) a [(3.5, F1 F2^)], b [(1.5, F0 F3^)] >>> fto = FermionOperatorList(op1) >>> print(fto) 1.0 [(3.5, F1 F2^)] >>> fto = FermionOperatorList(FermionOperatorString(((1, 0), (2, 1)))) >>> print(fto) 1.0 [(1.0, F1 F2^)]
- class CompressScalarsBehavior(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
-
Governs compression of scalars method behaviour.
- ALL = 'all'
Combine all coefficients possible, simplifying inner terms.
- ONLY_IDENTITIES_AND_ZERO = 'simple'
Only compress based on terms which are a scalar multiple of the identity operator, or zero.
- OUTER = 'outer'
Combine all “outer” coefficients (coefficients stored directly in the top-level OperatorList) into one.
- capitalize()
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
- casefold()
Return a version of the string suitable for caseless comparisons.
- center(width, fillchar=' ', /)
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
- count(sub[, start[, end]]) int
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
- encode(encoding='utf-8', errors='strict')
Encode the string using the codec registered for encoding.
- encoding
The encoding in which to encode the string.
- errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(suffix[, start[, end]]) bool
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
- expandtabs(tabsize=8)
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(*args, **kwargs) str
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).
- format_map(mapping) str
Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).
- index(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- isalnum()
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
- isalpha()
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
- isascii()
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
- isdecimal()
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
- isdigit()
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
- isidentifier()
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.
- islower()
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
- isnumeric()
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.
- isprintable()
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in repr() or if it is empty.
- isspace()
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
- istitle()
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
- isupper()
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
- join(iterable, /)
Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
- ljust(width, fillchar=' ', /)
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
- lower()
Return a copy of the string converted to lowercase.
- lstrip(chars=None, /)
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- static maketrans()
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
- partition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
- removeprefix(prefix, /)
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
- removesuffix(suffix, /)
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
- replace(old, new, count=-1, /)
Return a copy with all occurrences of substring old replaced by new.
- count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
- rfind(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- rjust(width, fillchar=' ', /)
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
- rpartition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
- rsplit(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
- rstrip(chars=None, /)
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the front of the string and works to the end.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
- splitlines(keepends=False)
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
- startswith(prefix[, start[, end]]) bool
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
- strip(chars=None, /)
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase()
Convert uppercase characters to lowercase and lowercase characters to uppercase.
- title()
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
- translate(table, /)
Replace each character in the string using the given translation table.
- table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
- upper()
Return a copy of the string converted to uppercase.
- zfill(width, /)
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
- class FactoryCoefficientsLocation(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
-
Determines where the
from_Operator()
method places coefficients.- INNER = 'inner'
Coefficients are left within the component operators.
- OUTER = 'outer'
Coefficients are moved to be directly stored at the top-level of the OperatorList.
- capitalize()
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
- casefold()
Return a version of the string suitable for caseless comparisons.
- center(width, fillchar=' ', /)
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
- count(sub[, start[, end]]) int
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
- encode(encoding='utf-8', errors='strict')
Encode the string using the codec registered for encoding.
- encoding
The encoding in which to encode the string.
- errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(suffix[, start[, end]]) bool
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
- expandtabs(tabsize=8)
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(*args, **kwargs) str
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).
- format_map(mapping) str
Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).
- index(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- isalnum()
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
- isalpha()
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
- isascii()
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
- isdecimal()
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
- isdigit()
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
- isidentifier()
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.
- islower()
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
- isnumeric()
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.
- isprintable()
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in repr() or if it is empty.
- isspace()
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
- istitle()
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
- isupper()
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
- join(iterable, /)
Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
- ljust(width, fillchar=' ', /)
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
- lower()
Return a copy of the string converted to lowercase.
- lstrip(chars=None, /)
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- static maketrans()
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
- partition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
- removeprefix(prefix, /)
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
- removesuffix(suffix, /)
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
- replace(old, new, count=-1, /)
Return a copy with all occurrences of substring old replaced by new.
- count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
- rfind(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- rjust(width, fillchar=' ', /)
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
- rpartition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
- rsplit(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
- rstrip(chars=None, /)
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the front of the string and works to the end.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
- splitlines(keepends=False)
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
- startswith(prefix[, start[, end]]) bool
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
- strip(chars=None, /)
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase()
Convert uppercase characters to lowercase and lowercase characters to uppercase.
- title()
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
- translate(table, /)
Replace each character in the string using the given translation table.
- table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
- upper()
Return a copy of the string converted to uppercase.
- zfill(width, /)
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
- collapse_as_linear_combination(ignore_outer_coefficients=False)
Treating this instance as a linear combination, return it in the form of an
Operator
.By default, each term is multiplied by its corresponding scalar coefficient, then all such multiplied terms are summed to yield a single
Operator
. The first step may be skipped (i.e. the scalar coefficients associated with each constituentOperator
may be ignored) by settingignore_outer_coefficients
toTrue
.
- collapse_as_product(reverse=False, ignore_outer_coefficients=False)
Treating this instqnce as a product of separate terms, return the full product as an
Operator
.By default, each
Operator
in theOperatorList
is multiplied by its corresponding coefficient, and the product is taken sequentially with the leftmost term given by the first element of theOperatorList
. This behaviour can be reversed with thereverse
parameter - if set toTrue
, the leftmost term will be given by the last element ofOperatorList
.If
ignore_outer_coefficients
is set toTrue
, the first step (the multiplication ofOperator
terms by their corresponding coefficients) is skipped - i.e. the “outer” coefficients stored in theOperatorList
are ignored.Danger
In the general case, the number of terms in the expansion will blow up exponentially (and thus the runtime of this method will also blow up exponentially).
- Parameters:
- Returns:
TypeVar
(OperatorT
, bound= Operator) – The product of each component operator.
- compress_scalars_as_product(abs_tol=1e-12, inner_coefficient=False, coefficients_to_compress=CompressScalarsBehavior.ONLY_IDENTITIES_AND_ZERO)
Treating the
OperatorList
as a product, compress identity terms or resolve to zero if possible.To do this, we iterate through the (coefficient, operator) pairs in the
OperatorList
. If any coefficient or operator is zero, then return an emptyOperatorList
, as the product will be zero. If the iteration operator is an identity, it will be treated as a scalar multiplier, itself multiplied by its associated coefficient, with the operator itself removed from theOperatorList
. These multipliers are multiplied together and – if they do not equate to 1 – are prepended to theOperatorList
as a separate identity term.By default, (coefficient, operator) pairs which are not identity or zero will be ignored. This behaviour may be controlled with the
coefficients_to_compress
parameter. This can be set to"outer"
to include all"outer"
coefficients of the (coefficient, operator) pairs in the prepended identity term. It can also be set to"all"
to additionally bring coefficients within the non-identity operators into the prepended identity term – i.e. for operators where all the “inner” coefficients are equal. See examples for a comparison.The prepended identity term will, by default, store the multiplied scalar factor in the “outer” coefficient of the (coefficient, operator) pair. The
inner_coefficient
parameter may be set toTrue
to instead store it within the operator.Note
Term simplification is not performed on component operators. It is possible that a component operator will resolve on simplification to the identity or zero. This method will not catch these occurrences.
- Parameters:
abs_tol (
float
, default:1e-12
) – Numerical threshold for comparison of numbers to 0 and 1. Set toNone
to use exact identity.inner_coefficient (
bool
, default:False
) – Set toTrue
to store generated scalar factors within the identity term, as described above.coefficients_to_compress (
CompressScalarsBehavior
, default:CompressScalarsBehavior.ONLY_IDENTITIES_AND_ZERO
) – Controls which scalar factors will be combined, as described above.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – TheOperatorList
with identity and zero terms combined, as described above.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0", 2) + QubitOperator("Z1", 2) >>> op2 = 3 * QubitOperator.identity() >>> qol = QubitOperatorList([(5, op1), (7, op2)]) >>> result = qol.compress_scalars_as_product() >>> print(result) 21.0 [(1.0, )], 5 [(2, X0), (2.0, Z1)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0", 2) + QubitOperator("Z1", 2) >>> op2 = 3 * QubitOperator.identity() >>> qol = QubitOperatorList([(5, op1), (7, op2)]) >>> result = qol.compress_scalars_as_product(inner_coefficient=True) >>> print(result) 1 [(21.0, )], 5 [(2, X0), (2.0, Z1)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0", 2) + QubitOperator("Z1", 2) >>> op2 = 3 * QubitOperator.identity() >>> qol = QubitOperatorList([(5, op1), (7, op2)]) >>> result = qol.compress_scalars_as_product(coefficients_to_compress="outer") >>> print(result) 105.0 [(1.0, )], 1.0 [(2, X0), (2.0, Z1)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0", 2) + QubitOperator("Z1", 2) >>> op2 = 3 * QubitOperator.identity() >>> qol = QubitOperatorList([(5, op1), (7, op2)]) >>> result = qol.compress_scalars_as_product(coefficients_to_compress="all") >>> print(result) 210.0 [(1.0, )], 1.0 [(1.0, X0), (1.0, Z1)]
- copy()
Returns a deep copy of this instance.
- Return type:
LinearListCombiner
- df()
Returns a pandas
DataFrame
object of the dictionary.
- evalf(*args, **kwargs)
Numerically evaluates symbolic expressions stored in the left and right values of list items and replaces them with the results.
- free_symbols_ordered()
Returns the free symbols in the coefficients, ordered alphabetically.
- Returns:
SymbolSet
– Ordered set of symbols.
- classmethod from_Operator(input, additional_coefficient=1.0, coefficients_location=FactoryCoefficientsLocation.INNER)
Converts an
Operator
to anOperatorList
with terms in arbitrary order.Each term in the
Operator
is split into a separate componentOperator
in theOperatorList
. The resulting location of each scalar coefficient in the inputOperator
can be controlled with thecoefficients_location
parameter. Setting this to"inner"
will leave coefficients stored as part of the component operators, a value of"outer"
will move the coefficients to the “outer” level.- Parameters:
input (
Operator
) – The input operator to split into anOperatorList
.additional_coefficient (
Union
[int
,float
,complex
,Expr
], default:1.0
) – An additional factor to include in the “outer” coefficients of the generatedOperatorList
.coefficients_location (
FactoryCoefficientsLocation
, default:FactoryCoefficientsLocation.INNER
) – The destination of the coefficients of the input operator, as described above.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – AnOperatorList
as described above.- Raises:
ValueError – On invalid input to the
coefficients_location
parameter.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op = QubitOperator("X0", 2.) + QubitOperator("Z1", 2.) >>> qol = QubitOperatorList.from_Operator(op) >>> print(qol) 1.0 [(2.0, X0)], 1.0 [(2.0, Z1)] >>> op = QubitOperator("X0", 2.) + QubitOperator("Z1", 2.) >>> qol = QubitOperatorList.from_Operator(op,coefficients_location='outer') >>> print(qol) 2.0 [(1.0, X0)], 2.0 [(1.0, Z1)]
- classmethod from_string(input_string)
Constructs a child class instance from a string.
- infer_num_spin_orbs()
Returns the number of modes that the component operators act upon, inferring the existence of modes with index from 0 to the maximum index.
- Returns:
int
– The minimum number of spin orbitals in the Fock space to which this operator list operates on.
Examples
>>> op1 = FermionOperator(FermionOperatorString(((1, 0), (2, 1))), 1.) >>> op2 = FermionOperator(FermionOperatorString(((0, 0), (6, 1))), 1.) >>> fto = FermionOperatorList([(1., op1), (1., op2)]) >>> print(fto.infer_num_spin_orbs()) 7
- make_hashable()
Return a hashable representation of the object.
- Returns:
str
– A string representation of this instance.
- map(mapping)
Updates right values of items in-place, using a mapping function provided.
- property num_spin_orbs: int
Return the number of spin-orbitals that this operator explicitly acts on.
- operator_class
alias of
FermionOperator
- qubit_encode(mapping=None, qubits=None)
Performs qubit encoding (mapping), using provided mapping function, of the current
FermionOperatorList
.Terms are treated and mapped independently.
- Parameters:
mapping (
QubitMapping
, default:None
) – Mapping class. Default mapping procedure is the Jordan-Wigner transformation.qubits (
Optional
[List
[Qubit
]], 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:
QubitOperatorList
– MappedQubitOperatorList
.
- retrotterize(new_trotter_number, initial_trotter_number=1, new_trotter_order=1, initial_trotter_order=1, constant=1.0, inner_coefficients=False)
Retrotterize an expression given a
OperatorList
representing a product of exponentials.This method assumes that
self
represents a product of exponentials, with each constituentOperator
corresponding to the exponentiated term of a single exponential in a product. Scalar factors within theOperatorList
are treated as scalar multipliers within each exponent.The
OperatorList
is first untrotterized using the providedinitial_trotter_number
andinitial_trotter_order
, then subsequently Trotterized using the providednew_trotter_number
andnew_trotter_order
. The returnedOperatorList
corresponds to the generated product of exponentials, in a similar manner to the originalOperatorList
.- Parameters:
new_trotter_number (
int
) – The desired number of Trotter steps in the final Trotter-Suzuki expansion.initial_trotter_number (
int
, default:1
) – The number of Trotter steps in the original Trotter-Suzuki expansion.new_trotter_order (
int
, default:1
) – The desired order of the final Trotter-Suzuki expansion. Currently, only a first order (\(ABABAB...\)) or second order (\(ABBAABBA...\)) expansion is supported.initial_trotter_order (
int
, default:1
) – The order of the original Trotter-Suzuki expansion used. Currently, only a first order (\(ABABAB...\)) expansion is supported.constant (
Union
[float
,complex
], default:1.0
) – An additional constant multiplier in the exponent.inner_coefficients (
bool
, default:False
) – By default, generated scalar factors in each exponent are stored in the coefficients of the generatedOperatorList
, with the coefficient of each innerOperator
unchanged. Set this toTrue
to instead store all scalar factors as coefficients in eachOperator
, with the outer coefficients of theOperatorList
left unchanged. See examples for a comparison.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) –:- The exponential product retrotterized with the provided new Trotter number and order. Each element is an
individual exponent.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1./2.,op1),(1./2.,op2),(1./2.,op1),(1./2.,op2)]) >>> retrotterised = qol.retrotterize(new_trotter_number=4,initial_trotter_number=2) >>> print(retrotterised) 0.25 [(1.0, X0 X1)], 0.25 [(1.0, Z0)], 0.25 [(1.0, X0 X1)], 0.25 [(1.0, Z0)], 0.25 [(1.0, X0 X1)], 0.25 [(1.0, Z0)], 0.25 [(1.0, X0 X1)], 0.25 [(1.0, Z0)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1./2.,op1),(1./2.,op2),(1./2.,op1),(1./2.,op2)]) >>> retrotterised = qol.retrotterize(new_trotter_number=4,initial_trotter_number=2,inner_coefficients=True) >>> print(retrotterised) 0.5 [(0.5, X0 X1)], 0.5 [(0.5, Z0)], 0.5 [(0.5, X0 X1)], 0.5 [(0.5, Z0)], 0.5 [(0.5, X0 X1)], 0.5 [(0.5, Z0)], 0.5 [(0.5, X0 X1)], 0.5 [(0.5, Z0)]
- reversed_order()
Reverses internal
list
order and returns it as a new object.- Return type:
LinearListCombiner
- simplify(*args, **kwargs)
Simplifies expressions stored in left and right values of list items.
- sublist(sublist_indices)
Returns a new instance containing a subset of the terms in the original object.
- Parameters:
sublist_indices (
list
[int
]) – Indices of elements in this instance selected to constitute a new object.- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – A sublist of this instance.- Raises:
ValueError – If
sublist_indices
contains indices not contained in this instance, or if this instanceis empty. –
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 Y1 Z3", 4.6) >>> op2 = QubitOperator("Z0", -1.6j) >>> op3 = QubitOperator("Z1 Z2 Z3 Z5", -5.6j) >>> long_operator = QubitOperatorList([(1, op1), (1, op2), (1, op3)]) >>> short_operator = long_operator.sublist([0, 2]) >>> print(short_operator) 1 [(4.6, X0 Y1 Z3)], 1 [(-5.6j, Z1 Z2 Z3 Z5)]
- 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
) – Maps symbol-representing keys to the value the symbol should be substituted for.- Returns:
LinearListCombiner
– This instance with symbols key symbols replaced by their values.
- sympify(*args, **kwargs)
Sympifies left and right values of list items.
Replaces left and right values with their corresponding symbolic expressions.
- Parameters:
- Returns:
LinearListCombiner
– Updated instance ofLinearListCombiner
.- Raises:
RuntimeError – Sympification fails.
- trotterize_as_linear_combination(trotter_number, trotter_order=1, constant=1.0, inner_coefficients=False)
Trotterize an exponent linear combination of Operators.
This method assumes that
self
represents the exponential of a linear combination ofOperator
objects, each corresponding to a term in this linear combination. Trotterization is performed at the level of theseOperator
instances. TheOperator
objects contained within the returnedOperatorList
correspond to exponents within the Trotter sequence.- Parameters:
trotter_number (
int
) – The number of Trotter steps in the Trotter-Suzuki expansion.trotter_order (
int
, default:1
) – The order of the Trotter-Suzuki approximation to be used. The first- and the second-order options are supported.constant (
Union
[float
,complex
], default:1.0
) – An additional constant multiplier in the exponent.inner_coefficients (
bool
, default:False
) – By default, generated scalar factors in each exponent are stored in the coefficients of the generatedOperatorList
, with the coefficient of each innerOperator
unchanged. Set this toTrue
to instead store all scalar factors as coefficients in eachOperator
, with the outer coefficients of theOperatorList
left unchanged. See examples for a comparison.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – A Trotterized form of the exponential product, where each element is an individual exponent.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1.,op1),(1.,op2)]) >>> result = qol.trotterize_as_linear_combination(2) >>> print(result) 0.5 [(1.0, X0 X1)], 0.5 [(1.0, Z0)], 0.5 [(1.0, X0 X1)], 0.5 [(1.0, Z0)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1.,op1),(1.,op2)]) >>> result = qol.trotterize_as_linear_combination(2,inner_coefficients=True) >>> print(result) 1.0 [(0.5, X0 X1)], 1.0 [(0.5, Z0)], 1.0 [(0.5, X0 X1)], 1.0 [(0.5, Z0)]
- 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 (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:
LinearListCombiner
– Updated instance ofLinearListCombiner
.- Raises:
TypeError – Unsympification fails.
- untrotterize(trotter_number, trotter_order=1)
Reverse a Trotter-Suzuki expansion given a product of exponentials as an
OperatorList
.This method assumes that the
OperatorList
represents a product of exponentials, with eachOperator
in the list corresponding to an exponent of a single exponential in the product. Scalar factors within theOperatorList
are treated as scalar multipliers within each exponent. AnOperator
corresponding to the exponent of a single, untrotterized exponential is returned.- Parameters:
- Returns:
TypeVar
(OperatorT
, bound= Operator) – The exponent of the untrotterised operator.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1./2.,op1),(1./2.,op2),(1./2.,op1),(1./2.,op2)]) >>> untrotterised = qol.untrotterize(2) >>> print(untrotterised) (1.0, X0 X1), (1.0, Z0)
- untrotterize_partitioned(trotter_number, trotter_order=1, inner_coefficients=False)
Reverse a Trotter-Suzuki expansion given a product of exponentials as an
OperatorList
, maintaining separation of exponents.This method assumes that
self
represents a product of exponentials, with each constituentOperator
corresponding to the exponentiated term of a single exponential within a product. Scalar factors within thisOperatorList
are treated as scalar multipliers within each exponent. AOperatorList
is returned wherein each term represents a single term in the exponent of the single, untrotterized exponential.- Parameters:
trotter_number (
int
) – The number of Trotter steps within the Trotter expansion to be reversed.trotter_order (
int
, default:1
) – The order of the Trotter-Suzuki expansion used. Currently, only a first order (\(ABABAB...\)) expansion is supported.inner_coefficients (
bool
, default:False
) – By default, generated scalar factors in each exponent are stored in the coefficients of the generatedOperatorList
, with the coefficient of each innerOperator
unchanged. Set this toTrue
to instead store all scalar factors as coefficients in eachOperator
, with the outer coefficients of theOperatorList
left unchanged. See examples for a comparison.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – The terms in the exponent of the untrotterised operator as aOperatorList
.- Raises:
ValueError – If the provided Trotter number is not compatible with the
OperatorList
.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1./2.,op1),(1./2.,op2),(1./2.,op1),(1./2.,op2)]) >>> untrotterised = qol.untrotterize_partitioned(2) >>> print(untrotterised) 1.0 [(1.0, X0 X1)], 1.0 [(1.0, Z0)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1./2.,op1),(1./2.,op2),(1./2.,op1),(1./2.,op2)]) >>> untrotterised = qol.untrotterize_partitioned(2,inner_coefficients=True) >>> print(untrotterised) 0.5 [(2.0, X0 X1)], 0.5 [(2.0, Z0)]
- class FermionOperatorString(initializer: tuple | List[Tuple[int, int]] | Tuple[Tuple[int, int]] = None)
Bases:
tuple
Represents a single fermionic string of creation and annihilation operators.
Internally this is a
tuple
oftuple
objects, each of which contains two integers, with the first indicating a spin orbital number, and the second being either 1 or 0, corresponding to creation and annihilation operators correspondingly. Defined to constitute a single term ininquanto.operators.FermionOperator
.Examples
>>> FermionOperatorString(((3, 1), (2, 0))) ((3, 1), (2, 0)) >>> FermionOperatorString((1, 1)) ((1, 1),) >>> print(FermionOperatorString(((3, 1), (2, 0)))) F3^ F2
- FERMION_ANNIHILATION = 0
Integer used to indicate a fermion operator is an annihilation operator.
- FERMION_CREATION = 1
Integer used to indicate a fermion operator is a creation operator.
- apply_bra(fock_state, power=1)
Performs an operation on a
inquanto.states.FermionState
representing a bra.This transforms the provided
inquanto.states.FermionState
with the operator string on the right. Conjugation on theinquanto.states.FermionState
object is not performed.- Parameters:
fock_state (
FermionState
) – state object representing a bra.power (
int
, default:1
) – Power of operation (how many times operator acts on a bra state).
- Returns:
FermionState
– A representation of the post-operation bra.
Examples
>>> f_op_string = FermionOperatorString.from_string("F1^ F0") >>> bra = FermionState([0, 1]) >>> print(bra) (1.0, {0: 0, 1: 1}) >>> print(f_op_string.apply_bra(bra)) (1.0, {0: 1, 1: 0}) >>> bra = FermionState([1, 0]) >>> print(f_op_string.apply_bra(bra)) (0)
- apply_ket(fock_state, power=1)
Performs an operation on a ket
inquanto.states.FermionState
state.- Parameters:
fock_state (
FermionState
) – Input fermion state (ket state).power (
int
, default:1
) – Power of operation (how many times operator acts on a ket state).
- Returns:
FermionState
– New ket state.
Examples
>>> f_op_string = FermionOperatorString.from_string("F1^ F0") >>> ket = FermionState([1, 0]) >>> print(ket) (1.0, {0: 1, 1: 0}) >>> print(f_op_string.apply_ket(ket)) (1.0, {0: 0, 1: 1}) >>> ket = FermionState([0, 1]) >>> print(f_op_string.apply_ket(ket)) (0)
- apply_state(fock_state, state_type, power)
Implements a general operation on a
FermionState
object representing a bra or a ket.- Parameters:
fock_state (
FermionState
) – Input fermion state.state_type (
StateType
) – Indicates whether the input state object represents a bra or a ket.power (
int
) – Power of operation.
- Returns:
FermionState
– New state object.
- dagger()
Performs a conjugation operation on a fermion creation-annihilation operator string.
Reverses order and swaps creation and annihilation labels.
- Returns:
FermionOperatorString
– The Hermitian conjugate of the current operator string.
Examples
>>> f_op_string = FermionOperatorString.from_string("F3^ F1^ F2 F0") >>> print(f_op_string.dagger()) F0^ F2^ F1 F3
- classmethod from_string(string)
Generates a class instance from a string.
- Parameters:
string (
str
) – Formatted string input.- Returns:
FermionOperatorString
– String of fermion creation/annihilation operators corresponding to a valid input python string.
Examples
>>> FermionOperatorString.from_string("F3^ F2") ((3, 1), (2, 0)) >>> FermionOperatorString.from_string("3^ 2") ((3, 1), (2, 0))
- is_particle_conserving()
Checks if operator string is particle-conserving.
- Returns:
bool
–True
if the operator string conserves particle number,False
if not.
Examples
>>> FermionOperatorString.from_string("F3^ F2").is_particle_conserving() True >>> FermionOperatorString.from_string("F3^ F2 F0").is_particle_conserving() False
- to_latex(operator_symbol='a', index_to_latex=None)
Generate a LaTeX representation of the operator string.
- Parameters:
- Returns:
str
– LaTeX compilable equation string.
Examples
>>> fos = FermionOperatorString(((0, 1), (0, 0))) >>> print(fos.to_latex()) a_{0}^{\dagger} a_{0} >>> fos = FermionOperatorString(((0,1), (1, 1), (4, 5))) >>> print(fos.to_latex(operator_symbol="c")) c_{0}^{\dagger} c_{1}^{\dagger} c_{4} >>> fos = FermionOperatorString.from_string("F5^ F6^ F3 F4") >>> print(fos.to_latex(operator_symbol="f")) f_{5}^{\dagger} f_{6}^{\dagger} f_{3} f_{4}
- class IntegralType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
Enum
Describes spin formalism used in integral operators.
- RESTRICTED = 'r'
- UNRESTRICTED = 'u'
- class OrbitalOptimizer(v_init=None, occ=None, split_rotation=False, functional=None, minimizer=None, point_group=None, orbital_irreps=None, reduce_free_parameters=True)
Bases:
OrbitalTransformer
Handles minimization of a functional of molecular orbital coefficients.
- Parameters:
v_init (
array
, default:None
) – Initial orbital coefficients.occ (
array
, default:None
) – Molecular orbital occupations (ifsplit_rotation=True
).split_rotation (
bool
, default:False
) – IfTrue
, do not allow mixing between occupied and virtual orbitals.functional (
Callable
, default:None
) – The objective function to be minimized.minimizer (
GeneralMinimizer
, default:None
) – An InQuanto minimizer.point_group (
Union
[PointGroup
,str
], default:None
) – If passed, symmetry information will be used to reduce free parameters.orbital_irreps (
list
, default:None
) – Orbital irreducible representations, needed ifpoint_group
is passed.reduce_free_parameters (
bool
, default:True
) – IfTrue
, the objective function will be simplified to depend on fewer parameters.
- static compute_unitary(v_init=None, v_final=None, check_unitary=True, check_unitary_atol=1e-15)
Computes the unitary relating square matrices
v_init
andv_final
whose columns contain the initial and final orbitals.Computes the matrix \(U = V_\text{init}^{-1} V_\text{final}\).
- Parameters:
v_init (
Optional
[ndarray
], default:None
) – Initial orbitals.v_final (
Optional
[ndarray
], default:None
) – Final orbitals.check_unitary (
bool
, default:True
) – Whether to check for the unitarity of the resulting matrix.check_unitary_atol (
float
, default:1e-15
) – Absolute tolerance of unitarity check.
- Returns:
ndarray
– Unitary matrix relating initial and final orbitals.
- construct_random_variables(v=None, low=-0.1, high=0.1, seed=None)
Constructs \(n (n - 1)/2\) variables sampled from uniform distribution where \(n\) is the number of orbitals.
Uniform distribution is specified by given high, low and seed.
- Parameters:
- Returns:
ndarray
– Array of random initial variables.
- static gram_schmidt(v, overlap=None)
Orthogonalises column vectors in
v
using Gram-Schmidt algorithm with respect to an overlap matrix.- Parameters:
v (
ndarray
) – Orbitals/vectors to be orthonormalised.overlap (
ndarray
, default:None
) – Overlap matrix.
- Returns:
ndarray
– Orthogonalised vectors.
- map_variables_to_rotation_matrix(variables=None)
Maps \(n (n - 1)/2\) variables to an \(n\times n\) unitary matrix.
- Parameters:
variables (
Optional
[array
], default:None
) – Variables to be mapped to a unitary matrix.- Returns:
ndarray
– Unitary rotation matrix.
- map_variables_to_skew_matrix(variables=None)
Constructs an \(n\times n\) skew-symmetric matrix from \(n (n - 1)/2\) variables.
- Parameters:
variables (
Optional
[array
], default:None
) – Variables to be mapped to a skew-symmetric matrix.- Returns:
ndarray
– Skew symmetric matrix.
- optimize(orb_init=None, initial_variables=None, functional=None, random_initial_variables=False)
Minimizes a functional which depends on orbital coefficients.
- Parameters:
orb_init (
Optional
[List
[float
]], default:None
) – Initial orbitals.initial_variables (
Optional
[List
[int
]], default:None
) – Initial guess variables.functional (
Optional
[Callable
], default:None
) – The functional to minimize, must be callable and a function of only MO coefficients.random_initial_variables (
bool
, default:False
) – Should starting variables be randomised.
- Returns:
Tuple
[List
,ndarray
,float
] – New MO coefficients, unitary fororb_init
-> new orbitals, final value of objective function.
- static orthonormalize(v, overlap=None)
Finds the closest orthonormal set of vectors with respect to overlap matrix.
- Parameters:
v (
ndarray
) – Column vectors/molecular orbitals.overlap (
Optional
[ndarray
], default:None
) – Overlap matrix.
- Returns:
ndarray
– Orthonormalised array of column vectors.
- transform(v, tu)
Apply unitary,
tu
, to an array of column vectors.- Parameters:
v (
ndarray
) – Array of column vectors.tu (
ndarray
) – Unitary matrix.
- Returns:
ndarray
– Transformed set of column vectors in numpy array.
- class OrbitalTransformer(v_init=None, v_final=None)
Bases:
object
Class holding convenience functions for manipulating molecular orbitals.
Initialised with initial and final orbital arrays.
- Parameters:
- static compute_unitary(v_init=None, v_final=None, check_unitary=True, check_unitary_atol=1e-15)
Computes the unitary relating square matrices
v_init
andv_final
whose columns contain the initial and final orbitals.Computes the matrix \(U = V_\text{init}^{-1} V_\text{final}\).
- Parameters:
v_init (
Optional
[ndarray
], default:None
) – Initial orbitals.v_final (
Optional
[ndarray
], default:None
) – Final orbitals.check_unitary (
bool
, default:True
) – Whether to check for the unitarity of the resulting matrix.check_unitary_atol (
float
, default:1e-15
) – Absolute tolerance of unitarity check.
- Returns:
ndarray
– Unitary matrix relating initial and final orbitals.
- static gram_schmidt(v, overlap=None)
Orthogonalises column vectors in
v
using Gram-Schmidt algorithm with respect to an overlap matrix.- Parameters:
v (
ndarray
) – Orbitals/vectors to be orthonormalised.overlap (
ndarray
, default:None
) – Overlap matrix.
- Returns:
ndarray
– Orthogonalised vectors.
- static orthonormalize(v, overlap=None)
Finds the closest orthonormal set of vectors with respect to overlap matrix.
- Parameters:
v (
ndarray
) – Column vectors/molecular orbitals.overlap (
Optional
[ndarray
], default:None
) – Overlap matrix.
- Returns:
ndarray
– Orthonormalised array of column vectors.
- transform(v, tu)
Apply unitary,
tu
, to an array of column vectors.- Parameters:
v (
ndarray
) – Array of column vectors.tu (
ndarray
) – Unitary matrix.
- Returns:
ndarray
– Transformed set of column vectors in numpy array.
- class QubitOperator(data=None, coeff=1.0)
Bases:
QubitPauliOperator
,Operator
InQuanto’s representation of a linear operator acting on a \(2^N\) dimensional Hilbert space with Pauli operators.
Can be constructed from a string, a
list
or atuple
oftuple
s (containing a qubit index (integer) and a string with a Pauli gate symbol), aQubitOperatorString
together with a single coefficient, or a dictionary with each item containing aQubitOperatorString
and a coefficient.- Parameters:
data (
Union
[str
,Iterable
[Tuple
[int
,str
]],dict
[QubitOperatorString
,Union
[int
,float
,complex
,Expr
]],QubitOperatorString
], default:None
) – Data defined as a string"X0 Y1"
, iterable of tuples((0, 'Y'), (1, 'X'))
,QubitOperatorString
, or as a dictionary ofQubitOperatorString
andCoeffType
objects.coeff (
Union
[int
,float
,complex
,Expr
], default:1.0
) – Coefficient attached todata
.
Example
>>> op0 = QubitOperator("X0 Y1 Z3", 4.6) >>> print(op0) (4.6, X0 Y1 Z3)
>>> op1 = QubitOperator(((0, "X"), (1, "Y"), (3, "Z")), 4.6) >>> print(op1) (4.6, X0 Y1 Z3)
>>> op2 = QubitOperator([(0, "X"), (1, "Y"), (3, "Z")], 4.6) >>> print(op2) (4.6, X0 Y1 Z3)
>>> qs = QubitOperatorString.from_string("X0 Y1 Z3") >>> op3 = QubitOperator(qs, 4.6) >>> print(op3) (4.6, X0 Y1 Z3)
>>> qs0 = QubitOperatorString.from_string("X0 Y1 Z3") >>> qs1 = QubitOperatorString.from_tuple([(0, Pauli.Y), (1, Pauli.X)]) >>> dictionary = {qs0: 4.6, qs1: -1.7j} >>> op4 = QubitOperator(dictionary) >>> print(op4) (4.6, X0 Y1 Z3), (-1.7j, Y0 X1)
- class TrotterizeCoefficientsLocation(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
-
Determines where coefficients will be stored upon performing Trotterization.
- INNER = 'inner'
All coefficients will be stored in the “inner” coefficients, within the component QubitOperators in the Trotterized result.
- MIXED = 'mixed'
The Trotter step factor will be stored in the “outer” coefficients, whereas the original coefficients of the original Operator will remain in the component Operators.
- OUTER = 'outer'
All coefficients will be stored in the “outer” coefficients, the coefficients stored directly in the generated OperatorList.
- capitalize()
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
- casefold()
Return a version of the string suitable for caseless comparisons.
- center(width, fillchar=' ', /)
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
- count(sub[, start[, end]]) int
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
- encode(encoding='utf-8', errors='strict')
Encode the string using the codec registered for encoding.
- encoding
The encoding in which to encode the string.
- errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(suffix[, start[, end]]) bool
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
- expandtabs(tabsize=8)
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(*args, **kwargs) str
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).
- format_map(mapping) str
Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).
- index(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- isalnum()
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
- isalpha()
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
- isascii()
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
- isdecimal()
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
- isdigit()
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
- isidentifier()
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.
- islower()
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
- isnumeric()
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.
- isprintable()
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in repr() or if it is empty.
- isspace()
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
- istitle()
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
- isupper()
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
- join(iterable, /)
Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
- ljust(width, fillchar=' ', /)
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
- lower()
Return a copy of the string converted to lowercase.
- lstrip(chars=None, /)
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- static maketrans()
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
- partition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
- removeprefix(prefix, /)
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
- removesuffix(suffix, /)
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
- replace(old, new, count=-1, /)
Return a copy with all occurrences of substring old replaced by new.
- count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
- rfind(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- rjust(width, fillchar=' ', /)
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
- rpartition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
- rsplit(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
- rstrip(chars=None, /)
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the front of the string and works to the end.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
- splitlines(keepends=False)
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
- startswith(prefix[, start[, end]]) bool
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
- strip(chars=None, /)
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase()
Convert uppercase characters to lowercase and lowercase characters to uppercase.
- title()
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
- translate(table, /)
Replace each character in the string using the given translation table.
- table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
- upper()
Return a copy of the string converted to uppercase.
- zfill(width, /)
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
- property all_nontrivial_qubits: set[Qubit]
Returns a set of all qubits acted upon by this operator nontrivially (i.e. with an X,Y or Z).
- property all_qubits: Set[Qubit]
- The set of all qubits the operator ranges over (including qubits
that were provided explicitly as identities)
- Return type:
Set[Qubit]
- Type:
return
- anticommutator(other_operator, abs_tol=None)
Calculates the anticommutator with another
QubitOperator
, within a tolerance.- Parameters:
other_operator (
QubitOperator
) – The otherQubitOperator
.abs_tol (
Optional
[float
], default:None
) – Threshold below which terms are deemed negligible.
- Returns:
QubitOperator
– The anticommutator of the two operators.
- anticommutes_with(other_operator, abs_tol=1e-10)
Calculates whether operator anticommutes with another
QubitOperator
, within a tolerance.If both operators are single Pauli strings, we use tket’s
commutes_with()
method and flip the result. Otherwise, it calculates the whole anticommutator and checks if it is zero.- Parameters:
other_operator (
QubitOperator
) – The otherQubitOperator
.abs_tol (
float
, default:1e-10
) – Threshold below which terms are deemed negligible.
- Returns:
bool
–True
if operators anticommute, within tolerance, otherwiseFalse
.
- antihermitian_part()
Return the anti-Hermitian (all imaginary-coefficient terms) part of the original
QubitOperator
.In case the original
QubitOperator
object contains symbolic coefficients that do not have an associated type, those will be cast to the imaginaryExpr
type. :rtype:QubitOperator
Examples
>>> qo = QubitOperator.from_string("(1.0, X0 Y1), (0.1j, Y0 X1), (0.5 + 0.2j, Z0 Z1)") >>> print(qo.antihermitian_part()) (0.1j, Y0 X1), (0.2j, Z0 Z1) >>> a = Symbol('a', real=True) >>> b = Symbol('b', imaginary=True) >>> c = Symbol('c') >>> p_str_a = QubitOperatorString.from_string("X0 Y1") >>> p_str_b = QubitOperatorString.from_string("Y0 X1") >>> p_str_c = QubitOperatorString.from_string("Z0 Z1") >>> qo = QubitOperator({p_str_a: a, p_str_b: b, p_str_c: c}) >>> print(qo.antihermitian_part()) (b, Y0 X1), (1.0*I*im(c), Z0 Z1)
- approx_equal_to(other, abs_tol=1e-10)
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=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.
- as_scalar(abs_tol=None)
If the operator is a sum of identity terms or zero, return the sum of the coefficients, otherwise return
None
.Note that this does not perform combination of terms and will return zero only if all coefficients are zero.
- Parameters:
abs_tol (
float
, default:None
) – Tolerance for checking if coefficients are zero. Set toNone
to test using a standard
:param python
==
comparison.:
- commutator(other_operator, abs_tol=None)
Calculate the commutator with another operator.
Computes commutator. Small terms in the result may be discarded.
- Parameters:
other_operator (
QubitOperator
) – The otherQubitOperator
.abs_tol (
Optional
[float
], default:None
) – Threshold below which terms are discarded. Set to a negative value to skip.
- Returns:
QubitOperator
– The commutator.
- commutes_with(other_operator, abs_tol=1e-10)
Calculates whether operator commutes with another
QubitOperator
, within a tolerance.If both operators are single Pauli strings, we use tket. Otherwise, it calculates the whole commutator and checks if it is zero.
- Parameters:
other_operator (
QubitOperator
) – The otherQubitOperator
.abs_tol (
float
, default:1e-10
) – Threshold below which terms are deemed negligible.
- Returns:
bool
–True
if operators commute, within tolerance, otherwiseFalse
.
- compress(abs_tol=1e-10, symbol_sub_type=CompressSymbolSubType.NONE)
Adapted from
pytket.QubitPauliOperator
to account for non-sympy coefficients.- Parameters:
abs_tol (
float
, default:1e-10
) – The threshold below which to remove values.symbol_sub_type (
CompressSymbolSubType
, 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.
- Return type:
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]\).
- dagger()
Return the Hermitian conjugate of
QubitOperator
.- Return type:
- df()
Returns a Pandas DataFrame object of the dictionary.
- Return type:
DataFrame
- dot_state(state, qubits=None)
Calculate the result of operating on a given qubit state.
Can accept right-hand state as a
QubitState
,QubitStateString
or anumpy.ndarray
. In the former two cases, we maintain a symbolic representation of both operator and state, and each Pauli is implemented in sequence. Resultant states are returned asQubitState
. This should support sympy parametrised states and operators, but the use of parametrised states and operators is untested. In this case, the optional qubits parameter is ignored.For a
numpy.ndarray
, we delegate to pytket’sQubitPauliOperator.dot_state()
method - this should be faster for dense states, but slower for sparse ones. Here, a register of qubits may be specified in thequbits
parameter to determine the meaning of the indices of the provided state vector. From the pytket documentation:When
qubits
is an explicitlist
, the qubits are ordered withqubits[0]
as the most significant qubit for indexing into state.If
None
, qubits sequentially indexed from 0 in the default register and ordered by ILO-BE soQubit(0)
is the most significant.
- Parameters:
state (
Union
[QubitState
,QubitStateString
,ndarray
]) – Input qubit state to operated on.qubits (
Optional
[List
[Qubit
]], default:None
) – For ndarray input, determines sequencing of qubits in the state, if not mapped to the default register. Ignored for other input types.
- Returns:
Union
[QubitState
,ndarray
] – Output state.
- eigenspectrum(hamming_weight=None, nroots=None, threshold=1e-5, check_hermitian=False, check_hermitian_atol=1e-10)
Returns the eigenspectrum of a Hermitian operator, optionally filtered by a given Hamming weight.
More precisely, if
hamming_weight
is provided, only those eigenvalues whose eigenstates’ computational components have coefficients larger thanthreshold
and match the provided Hamming weight will be returned.If argument
nroots
is provided, an iterative sparse matrix diagonalisation procedure is invoked. Otherwise, the whole dense matrix is diagonalised.Notes
If this operator results from a Jordan-Wigner fermion-qubit encoding, filtering by Hamming weight corresponds to particle conservation. The operator is assumed to be Hermitian.
Warning
This method scales exponentially. Use only for testing on small systems.
- Parameters:
hamming_weight (
Optional
[int
], default:None
) – Hamming weight for filtering the roots.nroots (
Optional
[int
], default:None
) – How many roots to calculate (invokes iterative diagonalisation).threshold (
float
, default:1e-5
) – State coefficient threshold for checking Hamming weight.check_hermitian (
bool
, default:False
) – Whether to check the hermiticity of the operator. Usesis_hermitian()
.check_hermitian_atol (
float
, default:1e-10
) – Absolute tolerance for hermiticity check. Passed tois_hermitian()
.
- Returns:
ndarray
– Array of (filtered) eigenvalues.
- ensure_hermitian(tolerance=1e-10)
Eliminate all insignificant imaginary parts of numeric coefficients.
- Raises:
ValueError – imaginary symbolic, or significant imaginary numeric coefficient.
- Parameters:
tolerance (
float
, default:1e-10
) – Threshold determining whether a numerical imag coefficient is significant.- Returns:
QubitOperator
– This instance.
- evalf(*args, **kwargs)
Evaluates symbolic expressions stored in
dict
values and replaces them with the results.
- exponentiate_commuting_operator(additional_exponent=1.0, check_commuting=True)
Exponentiate a
QubitOperator
where all terms commute, returning as a product of operators.As all terms are mutually commuting, exponentiation reduces to a product of exponentials of individual terms (i.e. \(e^{\sum_i{P_i}} = \prod_i{e^{P_i}}\)). Each individual exponential can further be expanded trigonometrically. While storing these as a product is efficient, expanding the product will result in an exponential number of terms, and thus this method returns the result in factorised form, as a
QubitOperatorList
.- Parameters:
- Returns:
QubitOperatorList
– The exponentiated operator in factorised form.- Raises:
ValueError – commutativity checking is performed and the operator is not a commuting set of terms.
- exponentiate_single_term(additional_exponent=1.0, coeff_cutoff=1e-14)
Exponentiates a single weighted Pauli string through trigonometric expansion.
This will except if the operator contains more than one term. It will attempt to maintain single term if rotation is sufficiently close to an integer multiple of \(pi/2\). Set
coeff_cutoff
toNone
to disable this behaviour.- Parameters:
additional_exponent (
complex
, default:1.0
) – Optional additional factor in exponent.coeff_cutoff (
Optional
[float
], default:1e-14
) – If a Pauli string is weighted by an integer multiple of \(pi/2\) and exponentiated, the resulting expansion will have a single Pauli term (as opposed to two). If this parameter is notNone
, it will be used to determine a threshold for cutting off negligible terms in the trigonometric expansion to avoid floating point errors resulting in illusory growth in the number of terms. Set toNone
to disable this behaviour.
- Returns:
QubitOperator
– The exponentiated operator.- Raises:
ValueError – the operator is not a single term.
- 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_QubitPauliOperator(qop, unsympify_coefficients=True)
Generate an instance of this class from a tket
QubitPauliOperator
.Component
QubitPauliString
s will be converted toQubitOperatorString
s. By default, coefficients without free symbols will be converted to float (if real) or complex (otherwise). To disable this, setunsympify_coefficients = False
. For finer grained control over unsympification, generate withunsympify_coefficients = False
and unsympify after generation. Seeunsympify()
for further details.- Parameters:
qop (
QubitPauliOperator
) – TheQubitPauliOperator
to be converted.unsympify_coefficients (
bool
, default:True
) – Whether to cast coefficents to standard python float/complex. Set toFalse
to disable.
- Returns:
The converted operator.
- classmethod from_list(pauli_list)
Construct a QubitPauliOperator from a serializable JSON list format, as returned by QubitPauliOperator.to_list()
- classmethod from_string(input_string)
Constructs a child class instance from a string.
- Parameters:
input_string (
str
) – String in the formatcoeff1 [(coeff1_1, term1_1), ..., (coeff1_n, term1_n)], ..., coeffn [(coeffn_1, termn_1), ...]
.- Returns:
Child class object.
- get(key, default)
Get the coefficient value of the provided Pauli string.
- Parameters:
key (
QubitPauliString
)
- hermitian_factorisation()
Returns a
tuple
of the real and imaginary parts of the originalQubitOperator
.For example, both P and Q from \(O = P + iQ\).
In case the original
QubitOperator
object contains symbolic coefficients that do not have an associated type, those will be cast into both the real and imaginaryExpr
types and assigned to both objects (imaginary component will be multiplied by \(-I\) in order to return its real part).- Returns:
Tuple
[QubitOperator
,QubitOperator
] – Real and imaginary parts of the qubit operator.
Examples
>>> qo = QubitOperator.from_string("(1.0, X0 Y1), (0.1j, Y0 X1), (0.5 + 0.2j, Z0 Z1)") >>> re_qo, im_qo = qo.hermitian_factorisation() >>> print(re_qo) (1.0, X0 Y1), (0.5, Z0 Z1) >>> print(im_qo) (0.1, Y0 X1), (0.2, Z0 Z1) >>> a = Symbol('a', real=True) >>> b = Symbol('b', imaginary=True) >>> c = Symbol('c') >>> p_str_a = QubitOperatorString.from_string("X0 Y1") >>> p_str_b = QubitOperatorString.from_string("Y0 X1") >>> p_str_c = QubitOperatorString.from_string("Z0 Z1") >>> qo = QubitOperator({p_str_a: a, p_str_b: b, p_str_c: c}) >>> re_qo, im_qo = qo.hermitian_factorisation() >>> print(re_qo) (a, X0 Y1), (re(c), Z0 Z1) >>> print(im_qo) (-I*b, Y0 X1), (im(c), Z0 Z1)
- hermitian_part()
Return the Hermitian (all real-coefficient terms) part of the original
QubitOperator
.In case the original
QubitOperator
object contains symbolic coefficients that do not have an associated type, those will be cast to the realExpr
type. :rtype:QubitOperator
Examples
>>> qo = QubitOperator.from_string("(1.0, X0 Y1), (0.1j, Y0 X1), (0.5 + 0.2j, Z0 Z1)") >>> print(qo.hermitian_part()) (1.0, X0 Y1), (0.5, Z0 Z1) >>> a = Symbol('a', real=True) >>> b = Symbol('b', imaginary=True) >>> c = Symbol('c') >>> p_str_a = QubitOperatorString.from_string("X0 Y1") >>> p_str_b = QubitOperatorString.from_string("Y0 X1") >>> p_str_c = QubitOperatorString.from_string("Z0 Z1") >>> qo = QubitOperator({p_str_a: a, p_str_b: b, p_str_c: c}) >>> print(qo.hermitian_part()) (a, X0 Y1), (re(c), Z0 Z1)
- classmethod identity()
Return an identity operator. :rtype:
QubitOperator
Examples
>>> print(QubitOperator.identity()) (1.0, )
- 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_antihermitian(tolerance=1e-10)
Check if operator is anti-Hermitian (purely imaginary coefficients).
Check is performed by looking for symbolic or significant numeric real part in at least one coefficient
- 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_commuting_operator()
Returns
True
if every term in operator commutes with every other term, otherwiseFalse
.- Return type:
- is_hermitian(tolerance=1e-10)
Check if operator is Hermitian.
Check is performed by looking for symbolic or significant numeric imaginary part in at least one coefficient
- static is_hermitian_coeff(coeff, tolerance=1e-10)
Determine whether the given coefficient can be present in a Hermitian
QubitOperator
.
- is_normalized(order=2, abs_tol=1e-10)
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=1e-10)
Returns
True
if other is parallel with this (i.e. a scalar multiple of this), otherwiseFalse
.
- is_self_inverse(abs_tol=1e-10)
Check if operator is its own inverse.
- is_unit_1norm(abs_tol=1e-10)
Returns True if operator has unit 1-norm, else False.
- is_unit_2norm(abs_tol=1e-10)
Returns True if operator has unit 1-norm, else False.
- is_unit_norm(order=2, abs_tol=1e-10)
Returns True if operator has unit p-norm, else False.
- Parameters:
- Raises:
ValueError – Coefficients contain free symbols.
- Return type:
- is_unitary(abs_tol=1e-10)
Check if operator is unitary.
Checking is performed by multiplying the operator by its Hermitian conjugate and comparing against the identity.
- Parameters:
abs_tol (default:
1e-10
) – Tolerance threshold for comparison with identity.- Returns:
bool
–True
if unitary,False
otherwise.
- static key_from_str(key_str)
Returns a
QubitOperatorString
instance initialised from the input string.- Parameters:
key_str (
str
) – Input python string.- Returns:
QubitOperatorString
– Operator string initialised from input.
- list_class
alias of
QubitOperatorList
- 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 normalised coefficients.
- pad(register_qubits=None, zero_to_max=False)
Modify
QubitOperator
in-place by replacing implicit identities with explicit identities.By default, this will assume a minimal register - i.e. the register contains only qubits acted on by any term in the
QubitOperator
. A specific register of qubits may be provided by setting theregister_qubits
parameter. This must contain all qubits acted on by theQubitOperator
. Alternatively,zero_to_max
may be set toTrue
in order to assume that the qubit register is indexed on \([0, N)\), where \(N\) is the highest integer indexed qubit in the originalQubitOperator
. These modes of operation are incompatible and this method will except ifzero_to_max
is set toTrue
andregister_qubits
is provided. Seepadded()
for a non-in-place version of this method.- Parameters:
- Raises:
PaddingIncompatibleArgumentsError – If register_qubits has been provided while
zero_to_max
is set toTrue
.PaddingInferenceError – If
zero_to_max
is set toTrue
and maximum qubit index cannot be inferred, for instance by non-integer labelled qubits.PaddingInvalidRegisterError – If
QubitOperator
acts on qubits not in provided register.
- Return type:
-
>>> qs = QubitOperator("X0") + QubitOperator("X1") >>> qs.pad() >>> print(qs) (1.0, X0 I1), (1.0, I0 X1)
>>> qs = QubitOperator("X0") >>> qs.pad([Qubit(0),Qubit(1)]) >>> print(qs) (1.0, X0 I1)
>>> qs = QubitOperator("X1") >>> print(qs.padded(zero_to_max=True)) (1.0, I0 X1)
- padded(register_qubits=None, zero_to_max=False)
Return a copy of the
QubitOperator
with implicit identities replaced by explicit identities.By default, this will assume a minimal register - i.e. the register contains only qubits acted on by any term in the
QubitOperator
. A specific register of qubits may be provided by setting theregister_qubits
parameter. This must contain all qubits acted on by theQubitOperator
. Alternatively,zero_to_max
may be set toTrue
in order to assume that the qubit register is indexed on \([0, N)\), where \(N\) is the highest integer indexed qubit in the originalQubitOperator
. These modes of operation are incompatible and this method will except ifzero_to_max
is set toTrue
andregister_qubits
is provided. Seepad()
for an in-place version of this method.- Parameters:
- Raises:
PaddingIncompatibleArgumentsError – If
register_qubits
has been provided whilezero_to_max
is set toTrue
.PaddingInferenceError – If
zero_to_max
is set toTrue
and maximum qubit index cannot be inferred, for instance by non-integer labelled qubits.PaddingInvalidRegisterError – If
QubitOperator
acts on qubits not in provided register.
- Returns:
QubitOperator
– ModifiedQubitOperator
.
Examples
>>> qs = QubitOperator("X0") + QubitOperator("X1") >>> qs_padded = qs.padded() >>> print(qs_padded) (1.0, X0 I1), (1.0, I0 X1)
>>> qs = QubitOperator("X0") >>> qs_padded = qs.padded([Qubit(0),Qubit(1)]) >>> print(qs_padded) (1.0, X0 I1)
>>> qs = QubitOperator("X1") >>> qs_padded = qs.padded(zero_to_max=True) >>> print(qs_padded) (1.0, I0 X1)
- property pauli_strings: List[QubitOperatorString]
Return the Pauli strings within the operator sum as a list.
- qubitwise_anticommutes_with(other_operator)
Calculates whether two single-term QubitOperators qubit-wise anticommute.
Two Pauli strings qubit-wise anticommute if every Pauli acting on a given qubit anticommutes with the Pauli acting on the same qubit in the other string. This necessitates that the Paulis are different, and both non-identity, for every qubit.
This method is currently not defined for
QubitOperator
objects consisting of multiple terms.- Parameters:
other_operator (
QubitOperator
) – The other single-termQubitOperator
.- Returns:
bool
–True
if the operators qubit-wise anticommute, otherwiseFalse
.- Raises:
ValueError – either operator consists of more than a single term.
- qubitwise_commutes_with(other_operator)
Calculates whether two single-term
QubitOperator
s qubit-wise commute.Two Pauli strings qubit-wise commute if every Pauli acting on a given qubit commutes with the Pauli acting on the same qubit in the other string. This necessitates that either the Paulis are the same, or that at least one is an identity.
This method is currently not defined for
QubitOperator
s consisting of multiple terms.- Parameters:
other_operator (
QubitOperator
) – The other single-termQubitOperator
.- Returns:
bool
–True
if the operators qubit-wise commute, otherwiseFalse
.- Raises:
ValueError – either operator consists of more than a single term.
- 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
- 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.
- state_expectation(state, *args, **kwargs)
Calculate expectation value of operator with input state.
Can accept right-hand state as a
QubitState
or anumpy.ndarray
. In the first case, we maintain a symbolic representation of both operator and state, and each Pauli is implemented in sequence. This should support sympy parametrised states and operators, but the use of parametrised states and operators is untested. For anumpy.ndarray
, we delegate to pytket’sQubitPauliOperator.dot_state()
method and return anumpy.ndarray
- this should be faster for dense states, but slower for sparse ones.- Parameters:
state (
Union
[QubitState
,ndarray
]) – The state to be acted upon.*args – Additional arguments passed to
pytket.utils.operators.QubitPauliOperator.state_expectation()
.**kwargs – Additional keyword arguments passed to
pytket.utils.operators.QubitPauliOperator.state_expectation()
.
- Returns:
complex
– Expectation value ofQubitOperator
.
- subs(symbol_map)
Substitution for symbolic expressions.
- Parameters:
symbol_map (
Union
[SymbolDict
,dict
[Union
[str
,Symbol
],Union
[float
,complex
,Expr
,None
]]]) – A map from sympy symbols to sympy expressions, floating-point or complex values.- Returns:
QubitOperator
– A newQubitOperator
object with symbols substituted.
- 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.
- symplectic_representation(qubits=None)
Generate the symplectic representation of the operator.
This is a binary \((M\times 2N)\) matrix where \(M\) is the number of terms and \(N\) is the number of qubits. In the leftmost half of the matrix, the element indexed by
[i,j]
isTrue
where qubitj
is acted on by an \(X\) or a \(Y\) in termi
, and otherwise isFalse
. In the rightmost half, element indexed by[i,j]
isTrue
where qubitj-num_qubits
is acted on by a \(Y\) or a \(Z\) in termi
, and otherwise isFalse
.Notes
If qubits is not specified, a minimal register will be assumed and columns will be assigned to qubits in ascending numerical order by index.
- Parameters:
qubits (
Optional
[List
[Qubit
]], default:None
) – A register of qubits. If not provided, a minimal register is assumed.- Returns:
ndarray
– The symplectic form of this operator- Raises:
ValueError – operator contains qubits which are not in the provided qubits argument.
- to_QubitPauliOperator()
Converts this object to a tket
QubitPauliOperator
.Component
QubitOperatorString
s will be converted to tketQubitPauliString
s. Note that coefficients will implicitly be converted to sympy objects in accordance with theQubitPauliOperator
API.- Returns:
The converted operator.
- to_latex(imaginary_unit='\\\\text{i}', **kwargs)
Generate a LaTeX representation of the operator.
- Parameters:
imaginary_unit (
str
, default:r"\\text{i}"
) – Symbol to use for the imaginary unit.**kwargs – Keyword arguments passed to the
to_latex()
method of component operator strings (FermionOperatorString
orQubitOperatorString
).
- Returns:
str
– LaTeX compilable equation string.
Examples
>>> from inquanto.operators import FermionOperator >>> from sympy import sympify >>> c = sympify("c") >>> fo = FermionOperator([(-c, "F1 F2^"), (c**2, "F1^"), (c, "F0 F5 F3^")]) >>> print(fo.to_latex()) - c a_{1} a_{2}^{\dagger} + c^{2} a_{1}^{\dagger} + c a_{0} a_{5} a_{3}^{\dagger} >>> fo = FermionOperator([(1.0, "F0^ F1^ F3^"), (-1.0j, "F3 F1 F0")]) >>> print(fo.to_latex()) a_{0}^{\dagger} a_{1}^{\dagger} a_{3}^{\dagger} -\text{i} a_{3} a_{1} a_{0} >>> from sympy import sqrt >>> fo = FermionOperator([(sqrt(2), "F0^ F1"), (0.5-8j, "F5 F5^"), (2j, "F1^ F1^")]) >>> print(fo.to_latex(imaginary_unit=r"\text{j}", operator_symbol="f")) \sqrt{2} f_{0}^{\dagger} f_{1} + (0.5-8.0\text{j}) f_{5} f_{5}^{\dagger} + 2.0\text{j} f_{1}^{\dagger} f_{1}^{\dagger}
>>> from inquanto.operators import QubitOperator, QubitOperatorString >>> qos1 = QubitOperatorString.from_string("X1 Y2 Z3") >>> qos2 = QubitOperatorString.from_string("Z0 Y1 X4") >>> qos3 = QubitOperatorString.from_list([(("a", [0]), "I"), (("b", [1]), "Z"), (("c", [2]), "Z")]) >>> qo = QubitOperator({qos1: -1.0, qos2: 3+4j, qos3: c}) >>> print(qo.to_latex()) - X_{1} Y_{2} Z_{3} + (3.0+ 4.0\text{i}) Z_{0} Y_{1} X_{4} + c I_{0} Z_{1} Z_{2} >>> qo = QubitOperator({qos3: 3j}) >>> print(qo.to_latex(imaginary_unit="j", show_labels=True)) 3.0j I^{\text{a}}_{0} Z^{\text{b}}_{1} Z^{\text{c}}_{2}
- to_list()
- Generate a list serialized representation of QubitPauliOperator,
suitable for writing to JSON.
- Returns:
JSON serializable list of dictionaries.
- Return type:
List[Dict[str, Any]]
- to_sparse_matrix(qubits=None)
Represents the sparse operator as a dense operator under the ordering scheme specified by
qubits
, and generates the corresponding matrix.When
qubits
is an explicit list, the qubits are ordered withqubits[0]
as the most significant qubit for indexing into the matrix.If
None
, then no padding qubits are introduced and we use the ILO-BE convention, e.g.Qubit("a", 0)
is more significant thanQubit("a", 1)
orQubit("b")
.Giving a number specifies the number of qubits to use in the final operator, treated as sequentially indexed from 0 in the default register (padding with identities as necessary) and ordered by ILO-BE so
Qubit(0)
is the most significant.
- Parameters:
qubits (Union[List[Qubit], int, None], optional) – Sequencing of qubits in the matrix, either as an explicit list, number of qubits to pad to, or infer from the operator. Defaults to None
- Returns:
A sparse matrix representation of the operator.
- Return type:
csc_matrix
- toeplitz_decomposition()
Returns a tuple of the Hermitian and anti-Hermitian parts of the original
QubitOperator
.In case the original
QubitOperator
object contains symbolic coefficients that do not have an associated type, those will be cast into both the real and imaginaryExpr
types and assigned to both objects.- Returns:
Tuple
[QubitOperator
] – Hermitian and anti-Hermitian parts of operator.
Examples
>>> qo = QubitOperator.from_string("(1.0, X0 Y1), (0.1j, Y0 X1), (0.5 + 0.2j, Z0 Z1)") >>> herm_qo, antiherm_qo = qo.toeplitz_decomposition() >>> print(herm_qo) (1.0, X0 Y1), (0.5, Z0 Z1) >>> print(antiherm_qo) (0.1j, Y0 X1), (0.2j, Z0 Z1) >>> a = Symbol('a', real=True) >>> b = Symbol('b', imaginary=True) >>> c = Symbol('c') >>> p_str_a = QubitOperatorString.from_string("X0 Y1") >>> p_str_b = QubitOperatorString.from_string("Y0 X1") >>> p_str_c = QubitOperatorString.from_string("Z0 Z1") >>> qo = QubitOperator({p_str_a: a, p_str_b: b, p_str_c: c}) >>> herm_qo, antiherm_qo = qo.toeplitz_decomposition() >>> print(herm_qo) (a, X0 Y1), (re(c), Z0 Z1) >>> print(antiherm_qo) (1.0*b, Y0 X1), (1.0*I*im(c), Z0 Z1)
- totally_commuting_decomposition(abs_tol=1e-10)
Decomposes into two separate operators, one including the totally commuting terms and the other including all other terms.
This will return two
QubitOperator
s. The first is comprised of all terms which commute with all other terms, the second comprised of terms which do not. An emptyQubitOperator
will be returned if either of these sets is empty.- Parameters:
abs_tol (
float
, default:1e-10
) – Tolerance threshold used for determining commutativity - seecommutator()
for details.- Returns:
Tuple
[QubitOperator
,QubitOperator
] – The totally commuting operator, and the remainder operator.
- trotterize(trotter_number=1, trotter_order=1, constant=1.0, coefficients_location=TrotterizeCoefficientsLocation.OUTER)
Trotterizes the operator, treating the operator as an exponent.
- Assuming that this operator is an exponent, this will generate an instance with each element corresponding to a
single exponent in the Trotter product of exponentials.
- Parameters:
trotter_number (
int
, default:1
) – The number of time-slices in the Trotter approximation.trotter_order (
int
, default:1
) – The order of the Trotter-Suzuki approximation being used. Currently, this supports values1
(i.e. \(AB\)) and2
(i.e. \(A/2\,B/2\,B/2\,A/2\))constant (
Union
[float
,complex
], default:1.0
) – An additional constant factor to multiply each exponent by, which may be useful when, for example, constructing a time evolution operator.coefficients_location (
TrotterizeCoefficientsLocation
, default:TrotterizeCoefficientsLocation.OUTER
) – By default, the coefficient of each term in the input operator is multiplied by the Trotter factor and stored in the outer coefficient of the returned instance, with the coefficient of each innerOperator
set to 1. This behaviour can be controlled with this argument - set to"outer"
for default behaviour. On the other hand, setting this parameter to"inner"
will store all scalars in the innerOperator
coefficient, with the outer coefficients of the returned instance set to 1. Setting this parameter to"mixed"
will store the Trotter factor in the outer coefficients of the returned instance, with the inner coefficients of each term left untouched. See examples for a comparison.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – A Trotterized form of the exponential product, where each element is an individual exponent.
Examples
>>> from inquanto.operators import QubitOperator >>> op1 = QubitOperator("X0 Y1 Z3", 4.6) + QubitOperator("Z1 Z2 Z3 Z5", -5.6j) >>> trotter_operator = op1.trotterize(trotter_number=2) >>> print(trotter_operator) 2.3 [(1.0, X0 Y1 Z3)], -2.8j [(1.0, Z1 Z2 Z3 Z5)], 2.3 [(1.0, X0 Y1 Z3)], -2.8j [(1.0, Z1 Z2 Z3 Z5)] >>> from inquanto.operators import QubitOperator >>> op1 = QubitOperator("X0 Y1 Z3", 4.6) + QubitOperator("Z1 Z2 Z3 Z5", -5.6j) >>> trotter_operator = op1.trotterize(trotter_number=2,coefficients_location="inner") >>> print(trotter_operator) 1.0 [(2.3, X0 Y1 Z3)], 1.0 [(-2.8j, Z1 Z2 Z3 Z5)], 1.0 [(2.3, X0 Y1 Z3)], 1.0 [(-2.8j, Z1 Z2 Z3 Z5)] >>> from inquanto.operators import QubitOperator >>> op1 = QubitOperator("X0 Y1 Z3", 4.6) + QubitOperator("Z1 Z2 Z3 Z5", -5.6j) >>> trotter_operator = op1.trotterize(trotter_number=2,coefficients_location="mixed") >>> print(trotter_operator) 0.5 [(4.6, X0 Y1 Z3)], 0.5 [(-5.6j, Z1 Z2 Z3 Z5)], 0.5 [(4.6, X0 Y1 Z3)], 0.5 [(-5.6j, Z1 Z2 Z3 Z5)]
- class QubitOperatorList(data=None, coeff=1.0)
Bases:
OperatorList
Ordered list of
QubitOperator
objects associated with parameters.Stores tuples of
QubitOperator
objects and corresponding coefficient values in an ordered list. In contrast toQubitOperator
, this class is not assumed to comprise a linear combination. Typically, this will be of use when considering sequences of operators upon which some non-linear operation is performed. For instance, this may be used to store a Trotterised combination of exponentiatedQubitOperator
s.This class may be instantiated from a
QubitOperator
or aQubitOperatorString
object and a scalar or symbolic coefficient. It may also be instantiated with a list of tuples of scalar or symbolic coefficients andQubitOperator
objects.- Parameters:
data (
Union
[QubitOperator
,QubitOperatorString
,List
[Tuple
[Union
[int
,float
,complex
,Expr
],QubitOperator
]]], default:None
) – Input data from which the list of qubit operators is built. SeeQubitOperator
for methods of constructing terms.coeff (
Union
[int
,float
,complex
,Expr
], default:1.0
) – Multiplicative scalar coefficient. Used only ifdata
is not of typelist
.
Examples
>>> op1 = QubitOperator("X0 Y1 Z3", 4.6) >>> op2 = QubitOperator([(0, "Z")], -1.6j) >>> op3 = QubitOperator("Z1 Z2 Z3 Z5", -5.6j) >>> trotter_operator = QubitOperatorList([(1, op1), (1, op2), (1, op3)]) >>> print(trotter_operator) 1 [(4.6, X0 Y1 Z3)], 1 [(-1.6j, Z0)], 1 [(-5.6j, Z1 Z2 Z3 Z5)]
>>> op1 = QubitOperator("X0 Y1 Z3", 4.6) >>> op2 = QubitOperator([(0, "Z")], -1.6j) >>> trotter_operator = QubitOperatorList([(sympify("a"), op1), (sympify("b"), op2)]) >>> print(trotter_operator) a [(4.6, X0 Y1 Z3)], b [(-1.6j, Z0)]
- class CompressScalarsBehavior(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
-
Governs compression of scalars method behaviour.
- ALL = 'all'
Combine all coefficients possible, simplifying inner terms.
- ONLY_IDENTITIES_AND_ZERO = 'simple'
Only compress based on terms which are a scalar multiple of the identity operator, or zero.
- OUTER = 'outer'
Combine all “outer” coefficients (coefficients stored directly in the top-level OperatorList) into one.
- capitalize()
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
- casefold()
Return a version of the string suitable for caseless comparisons.
- center(width, fillchar=' ', /)
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
- count(sub[, start[, end]]) int
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
- encode(encoding='utf-8', errors='strict')
Encode the string using the codec registered for encoding.
- encoding
The encoding in which to encode the string.
- errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(suffix[, start[, end]]) bool
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
- expandtabs(tabsize=8)
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(*args, **kwargs) str
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).
- format_map(mapping) str
Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).
- index(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- isalnum()
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
- isalpha()
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
- isascii()
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
- isdecimal()
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
- isdigit()
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
- isidentifier()
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.
- islower()
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
- isnumeric()
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.
- isprintable()
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in repr() or if it is empty.
- isspace()
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
- istitle()
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
- isupper()
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
- join(iterable, /)
Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
- ljust(width, fillchar=' ', /)
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
- lower()
Return a copy of the string converted to lowercase.
- lstrip(chars=None, /)
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- static maketrans()
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
- partition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
- removeprefix(prefix, /)
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
- removesuffix(suffix, /)
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
- replace(old, new, count=-1, /)
Return a copy with all occurrences of substring old replaced by new.
- count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
- rfind(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- rjust(width, fillchar=' ', /)
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
- rpartition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
- rsplit(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
- rstrip(chars=None, /)
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the front of the string and works to the end.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
- splitlines(keepends=False)
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
- startswith(prefix[, start[, end]]) bool
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
- strip(chars=None, /)
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase()
Convert uppercase characters to lowercase and lowercase characters to uppercase.
- title()
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
- translate(table, /)
Replace each character in the string using the given translation table.
- table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
- upper()
Return a copy of the string converted to uppercase.
- zfill(width, /)
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
- class ExpandExponentialProductCoefficientsBehavior(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
-
Governs behaviour for expansion of exponential products of commuting operators.
- BRING_INTO_OPERATOR = 'compact'
Treat top-level coefficients of the QubitOperatorList as being outside the exponential; multiply generated component QubitOperators by them and return QubitOperatorList with unit top-level coefficients.
- IGNORE = 'ignore'
Drop top-level coefficients entirely.
- IN_EXPONENT = 'inside'
Treat top-level coefficients of the QubitOperatorList as being within the exponent.
- OUTSIDE_EXPONENT = 'outside'
Treat top-level coefficients of the QubitOperatorList as being outside the exponential; return them as top-level coefficients of the generated QubitOperatorList.
- capitalize()
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
- casefold()
Return a version of the string suitable for caseless comparisons.
- center(width, fillchar=' ', /)
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
- count(sub[, start[, end]]) int
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
- encode(encoding='utf-8', errors='strict')
Encode the string using the codec registered for encoding.
- encoding
The encoding in which to encode the string.
- errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(suffix[, start[, end]]) bool
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
- expandtabs(tabsize=8)
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(*args, **kwargs) str
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).
- format_map(mapping) str
Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).
- index(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- isalnum()
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
- isalpha()
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
- isascii()
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
- isdecimal()
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
- isdigit()
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
- isidentifier()
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.
- islower()
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
- isnumeric()
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.
- isprintable()
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in repr() or if it is empty.
- isspace()
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
- istitle()
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
- isupper()
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
- join(iterable, /)
Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
- ljust(width, fillchar=' ', /)
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
- lower()
Return a copy of the string converted to lowercase.
- lstrip(chars=None, /)
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- static maketrans()
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
- partition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
- removeprefix(prefix, /)
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
- removesuffix(suffix, /)
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
- replace(old, new, count=-1, /)
Return a copy with all occurrences of substring old replaced by new.
- count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
- rfind(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- rjust(width, fillchar=' ', /)
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
- rpartition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
- rsplit(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
- rstrip(chars=None, /)
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the front of the string and works to the end.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
- splitlines(keepends=False)
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
- startswith(prefix[, start[, end]]) bool
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
- strip(chars=None, /)
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase()
Convert uppercase characters to lowercase and lowercase characters to uppercase.
- title()
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
- translate(table, /)
Replace each character in the string using the given translation table.
- table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
- upper()
Return a copy of the string converted to uppercase.
- zfill(width, /)
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
- class FactoryCoefficientsLocation(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
-
Determines where the
from_Operator()
method places coefficients.- INNER = 'inner'
Coefficients are left within the component operators.
- OUTER = 'outer'
Coefficients are moved to be directly stored at the top-level of the OperatorList.
- capitalize()
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
- casefold()
Return a version of the string suitable for caseless comparisons.
- center(width, fillchar=' ', /)
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
- count(sub[, start[, end]]) int
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
- encode(encoding='utf-8', errors='strict')
Encode the string using the codec registered for encoding.
- encoding
The encoding in which to encode the string.
- errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(suffix[, start[, end]]) bool
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
- expandtabs(tabsize=8)
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(*args, **kwargs) str
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).
- format_map(mapping) str
Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).
- index(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- isalnum()
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
- isalpha()
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
- isascii()
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
- isdecimal()
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
- isdigit()
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
- isidentifier()
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.
- islower()
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
- isnumeric()
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.
- isprintable()
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in repr() or if it is empty.
- isspace()
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
- istitle()
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
- isupper()
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
- join(iterable, /)
Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
- ljust(width, fillchar=' ', /)
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
- lower()
Return a copy of the string converted to lowercase.
- lstrip(chars=None, /)
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- static maketrans()
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
- partition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
- removeprefix(prefix, /)
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
- removesuffix(suffix, /)
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
- replace(old, new, count=-1, /)
Return a copy with all occurrences of substring old replaced by new.
- count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
- rfind(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- rjust(width, fillchar=' ', /)
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
- rpartition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
- rsplit(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
- rstrip(chars=None, /)
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the front of the string and works to the end.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
- splitlines(keepends=False)
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
- startswith(prefix[, start[, end]]) bool
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
- strip(chars=None, /)
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase()
Convert uppercase characters to lowercase and lowercase characters to uppercase.
- title()
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
- translate(table, /)
Replace each character in the string using the given translation table.
- table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
- upper()
Return a copy of the string converted to uppercase.
- zfill(width, /)
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
- property all_nontrivial_qubits: set[Qubit]
Returns a set of all qubits acted upon by the operators in this QubitOperatorList nontrivially (i.e. with an X,Y or Z).
- property all_qubits: Set[Qubit]
Returns a set of all qubits included in any operator in the QubitOperatorList.
- build_subset(indices)
Builds a subset of the class based on a list of indices passed by a user.
- Parameters:
indices (
List
[int
]) – Indices of the items which are selected to for the subset as a newQubitOperatorList
instance.- Raises:
ValueError – the number of requested indices is larger than the number of elements in this instance.
- Returns:
QubitOperatorList
– Subset of terms of the initial object.
- collapse_as_linear_combination(ignore_outer_coefficients=False)
Treating this instance as a linear combination, return it in the form of an
Operator
.By default, each term is multiplied by its corresponding scalar coefficient, then all such multiplied terms are summed to yield a single
Operator
. The first step may be skipped (i.e. the scalar coefficients associated with each constituentOperator
may be ignored) by settingignore_outer_coefficients
toTrue
.
- collapse_as_product(reverse=False, ignore_outer_coefficients=False)
Treating this instqnce as a product of separate terms, return the full product as an
Operator
.By default, each
Operator
in theOperatorList
is multiplied by its corresponding coefficient, and the product is taken sequentially with the leftmost term given by the first element of theOperatorList
. This behaviour can be reversed with thereverse
parameter - if set toTrue
, the leftmost term will be given by the last element ofOperatorList
.If
ignore_outer_coefficients
is set toTrue
, the first step (the multiplication ofOperator
terms by their corresponding coefficients) is skipped - i.e. the “outer” coefficients stored in theOperatorList
are ignored.Danger
In the general case, the number of terms in the expansion will blow up exponentially (and thus the runtime of this method will also blow up exponentially).
- Parameters:
- Returns:
TypeVar
(OperatorT
, bound= Operator) – The product of each component operator.
- compatibility_matrix(abs_tol=1e-10)
Returns the compatibility matrix of the operator list.
This matrix is the adjacency matrix of the compatibility graph of the
OperatorList
. It is a boolean \((N\times N) matrix where :math:`N\) is the number of operators in theOperatorList
. Element indexed by[n,m]
isTrue
if operators indexed byn
andm
commute, otherwiseFalse
.- Parameters:
abs_tol (
float
, default:1e-10
) – Tolerance threshold used for determining commutativity - seeQubitOperator.commutator()
for details.- Returns:
ndarray
– The compatibility matrix of the operator list.
- compress_scalars_as_product(abs_tol=1e-12, inner_coefficient=False, coefficients_to_compress=CompressScalarsBehavior.ONLY_IDENTITIES_AND_ZERO)
Treating the
OperatorList
as a product, compress identity terms or resolve to zero if possible.To do this, we iterate through the (coefficient, operator) pairs in the
OperatorList
. If any coefficient or operator is zero, then return an emptyOperatorList
, as the product will be zero. If the iteration operator is an identity, it will be treated as a scalar multiplier, itself multiplied by its associated coefficient, with the operator itself removed from theOperatorList
. These multipliers are multiplied together and – if they do not equate to 1 – are prepended to theOperatorList
as a separate identity term.By default, (coefficient, operator) pairs which are not identity or zero will be ignored. This behaviour may be controlled with the
coefficients_to_compress
parameter. This can be set to"outer"
to include all"outer"
coefficients of the (coefficient, operator) pairs in the prepended identity term. It can also be set to"all"
to additionally bring coefficients within the non-identity operators into the prepended identity term – i.e. for operators where all the “inner” coefficients are equal. See examples for a comparison.The prepended identity term will, by default, store the multiplied scalar factor in the “outer” coefficient of the (coefficient, operator) pair. The
inner_coefficient
parameter may be set toTrue
to instead store it within the operator.Note
Term simplification is not performed on component operators. It is possible that a component operator will resolve on simplification to the identity or zero. This method will not catch these occurrences.
- Parameters:
abs_tol (
float
, default:1e-12
) – Numerical threshold for comparison of numbers to 0 and 1. Set toNone
to use exact identity.inner_coefficient (
bool
, default:False
) – Set toTrue
to store generated scalar factors within the identity term, as described above.coefficients_to_compress (
CompressScalarsBehavior
, default:CompressScalarsBehavior.ONLY_IDENTITIES_AND_ZERO
) – Controls which scalar factors will be combined, as described above.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – TheOperatorList
with identity and zero terms combined, as described above.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0", 2) + QubitOperator("Z1", 2) >>> op2 = 3 * QubitOperator.identity() >>> qol = QubitOperatorList([(5, op1), (7, op2)]) >>> result = qol.compress_scalars_as_product() >>> print(result) 21.0 [(1.0, )], 5 [(2, X0), (2.0, Z1)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0", 2) + QubitOperator("Z1", 2) >>> op2 = 3 * QubitOperator.identity() >>> qol = QubitOperatorList([(5, op1), (7, op2)]) >>> result = qol.compress_scalars_as_product(inner_coefficient=True) >>> print(result) 1 [(21.0, )], 5 [(2, X0), (2.0, Z1)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0", 2) + QubitOperator("Z1", 2) >>> op2 = 3 * QubitOperator.identity() >>> qol = QubitOperatorList([(5, op1), (7, op2)]) >>> result = qol.compress_scalars_as_product(coefficients_to_compress="outer") >>> print(result) 105.0 [(1.0, )], 1.0 [(2, X0), (2.0, Z1)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0", 2) + QubitOperator("Z1", 2) >>> op2 = 3 * QubitOperator.identity() >>> qol = QubitOperatorList([(5, op1), (7, op2)]) >>> result = qol.compress_scalars_as_product(coefficients_to_compress="all") >>> print(result) 210.0 [(1.0, )], 1.0 [(1.0, X0), (1.0, Z1)]
- compute_jacobian(symbols, as_sympy_sparse=False)
Generate symbolic sparse Jacobian Matrix.
If the number of terms in the operator list is \(N\) and the number of symbols in the symbols
list
is \(M\) then the resultant matrix has a shape \((N, M) and :math:`J_{i,j} = \frac{\partial c_i}{\partial \theta_j}\)- Parameters:
- Returns:
Union
[List
,ImmutableSparseMatrix
] – Jacobian Matrix inlist
oftuple
s of the form(i, j, J_ij)
(this format is referred as a row-sorted list of non-zero elements of the matrix.)
Examples
>>> op0 = QubitOperator("X0 Y2 Z3", 4.6) >>> op1 = QubitOperator(((0, "X"), (1, "Y"), (3, "Z")), 0.1 + 2.0j) >>> op2 = QubitOperator([(0, "X"), (1, "Z"), (3, "Z")], -1.3) >>> qs = QubitOperatorString.from_string("X0 Y1 Y3") >>> op3 = QubitOperator(qs, 0.8) >>> qs0 = QubitOperatorString.from_string("X0 Y1 Z3 X4") >>> qs1 = QubitOperatorString.from_tuple([(0, Pauli.Y), (1, Pauli.X)]) >>> dictionary = {qs0: 2.1, qs1: -1.7j} >>> op4 = QubitOperator(dictionary)
>>> a, b, c = sympify("a,b,c") >>> trotter_operator = QubitOperatorList([(a**3, op1), (2, op2), (b, op3), (c, op4)]) >>> print(trotter_operator) a**3 [(0.1+2j, X0 Y1 Z3)], 2 [(-1.3, X0 Z1 Z3)], b [(0.8, X0 Y1 Y3)], c [(2.1, X0 Y1 Z3 X4), (-1.7j, Y0 X1)]
>>> jacobian_matrix = trotter_operator.compute_jacobian([a, b]) >>> print(jacobian_matrix) [(0, 0, 3*a**2), (2, 1, 1)]
>>> jacobian_matrix = trotter_operator.compute_jacobian([a, b], as_sympy_sparse=True) >>> print(jacobian_matrix) Matrix([[3*a**2, 0], [0, 0], [0, 1], [0, 0]])
- copy()
Returns a deep copy of this instance.
- Return type:
LinearListCombiner
- df()
Returns a pandas
DataFrame
object of the dictionary.
- dot_state_as_linear_combination(state, qubits=None)
Operate upon a state acting as a linear combination of the component operators.
Associated scalar constants are treated as scalar multiplier of their respective QubitOperator terms. This method can accept right-hand state as a
QubitState
,QubitStateString
or anumpy.ndarray
. In the former two cases, we maintain a symbolic representation of both operator and state, and each Pauli is implemented in sequence. Resultant states are returned asQubitState
. In this case, the optional qubits parameter is ignored.For a
numpy.ndarray
, we delegate to pytket’sQubitPauliOperator.dot_state()
method - this should be faster for dense states, but slower for sparse ones. Here, a register of qubits may be specified in thequbits
parameter to determine the meaning of the indices of the provided state vector. From the pytket documentation:When
qubits
is an explicit list, the qubits are ordered withqubits[0]
as the most significant qubit for indexing into state.If
None
, qubits sequentially indexed from 0 in the default register and ordered by ILO-BE soQubit(0)
is the most significant.
- Parameters:
state (
Union
[QubitState
,QubitStateString
,ndarray
]) – Input qubit state to operated on.qubits (
Optional
[List
[Qubit
]], default:None
) – For ndarray input, determines sequencing of qubits in the state, if not mapped to the default register. Ignored for other input types.
- Returns:
Union
[QubitState
,ndarray
] – Output state.
- dot_state_as_product(state, reverse=False, qubits=None)
Operate upon a state with each component operator in sequence, starting from operator indexed 0.
This will apply each operator in sequence, starting from the top of the list - i.e. the top of the list is on the right hand side when acting on a ket. Ordering can be controlled with the
reverse
parameter. Associated scalar constants are treated as scalar multipliers.The right-hand state ket can be accepted as a
QubitState
,QubitStateString
or andarray
. In the former two cases, we maintain a symbolic representation of both operator and state, and each Pauli is implemented in sequence. Resultant states are returned asQubitState
. In this case, thequbits
parameter is ignored.For
ndarray
s, we delegate to pytket’sQubitPauliOperatorString.dot_state()
method - this should be faster for dense states, but slower for sparse ones. Here, a register of qubits may be specified in thequbits
parameter to determine the meaning of the indices of the provided state vector. From the pytket documentation:When
qubits
is an explicit list, the qubits are ordered withqubits[0]
as the most significant qubit for indexing into state.If
None
, qubits sequentially indexed from 0 in the default register and ordered by ILO-BE soQubit(0)
is the most significant.
Danger
In the general case, this will blow up exponentially.
- Parameters:
state (
Union
[QubitState
,QubitStateString
,ndarray
]) – The state to be acted upon.reverse (
bool
, default:False
) – Set toTrue
to reverse order of operations applied (i.e. treat the 0th indexed operator as the leftmost operator).
- Returns:
Union
[QubitState
,ndarray
] – The state yielded from acting on input state in the type as described above.
- equality_matrix(abs_tol=1e-10)
Returns the equality matrix of the operator list.
The equality matrix is a boolean \((N\times N)\) matrix where \(N\) is the number of operators in the
OperatorList
. Element indexed by[n,m]
isTrue
if operators indexed byn
andm
are equal, otherwiseFalse
.- Parameters:
abs_tol (
Optional
[float
], default:1e-10
) – Threshold of comparing numeric values. Set toNone
to test for exact equivalence.- Returns:
ndarray
– The equality matrix of theQubitOperatorList
.
- evalf(*args, **kwargs)
Numerically evaluates symbolic expressions stored in the left and right values of list items and replaces them with the results.
- expand_exponential_product_commuting_operators(expansion_coefficients_behavior=ExpandExponentialProductCoefficientsBehavior.IN_EXPONENT, additional_exponent=1.0, check_commuting=True, combine_scalars=True)
Trigonometrically expand a
QubitOperatorList
representing a product of exponentials of operators with mutually commuting terms.Given a
QubitOperatorList
, this method interprets it as a product of exponentials of the component operators. This means that for aQubitOperatorList
consisting of terms (\(c_i\),:math:hat{O}_i), it is interpreted as \(\prod_i{e^{c_i \hat{O}_i}}\). Component operators must consist of terms which all mutually commute.Each component operator is first expanded as its own exponential product (as they consist of terms which all mutually commute, \(e^{A+B} = e^A e^B\)). Each of the individual exponentiated terms are trigonometrically expanded. These are then concatenated to return a
QubitOperatorList
with the desired form.Notes
Typically this may be used upon an operator generated by Trotterization methods to yield a computable form of the exponential product. While this method scales polynomially, expansion of the resulting operator or calculating its action on a state will typically be exponentially costly.
By default, this method will combine constant scalar multiplicative factors (obtained by, for instance, \(pi\) rotations) into one identity term prepended to the generated
QubitOperatorList
. This behaviour can be disabled by setting combine_scalars toFalse
. For more detail, and for control over the process of combining constant factors, seecompress_scalars_as_product()
.- Parameters:
expansion_coefficients_behavior (
ExpandExponentialProductCoefficientsBehavior
, default:ExpandExponentialProductCoefficientsBehavior.IN_EXPONENT
) – By default, it will be assumed that the “outer” coefficients associated with each component operator are within the exponent, as per the above formula. This may be set to “outside” to instead assume that they are scalar multiples of the exponential itself, rather than the exponent (i.e. \(\prod_i{c_i e^{\hat{O}_i}}\)). In this case, the coefficients will be returned as the outer coefficients of the returned QubitOperatorList, as input. Set to “compact” to assume similar structure to “outside”, but returning coefficients within the componentQubitOperators
. Set to “ignore” to drop the ‘outer’ coefficients entirely. See examples for a comparison.additional_exponent (
complex
, default:1.0
) – Optional additional factor in each exponent.check_commuting (default:
True
) – Set toFalse
to skip checking whether all terms in each component operator commute.combine_scalars (default:
True
) – Set toFalse
to disable combination of identity and zero terms.
- Returns:
QubitOperatorList
– The trigonometrically expanded form of the inputQubitOperatorList
.
Examples
>>> import sympy >>> op= QubitOperator("X0", -1.j * sympy.Symbol('x')) >>> qol = QubitOperatorList([(2, op)]) >>> result = qol.expand_exponential_product_commuting_operators() >>> print(result) 1 [(1.0*cos(2.0*x), ), (-1.0*I*sin(2.0*x), X0)] >>> import sympy >>> op = QubitOperator("X0", -1.j * sympy.Symbol('x')) >>> qol = QubitOperatorList([(2, op)]) >>> result = qol.expand_exponential_product_commuting_operators(expansion_coefficients_behavior="outside") >>> print(result) 2 [(1.0*cos(1.0*x), ), (-1.0*I*sin(1.0*x), X0)] >>> import sympy >>> op = QubitOperator("X0", -1.j * sympy.Symbol('x')) >>> qol = QubitOperatorList([(2, op)]) >>> result = qol.expand_exponential_product_commuting_operators(expansion_coefficients_behavior="ignore") >>> print(result) 1 [(1.0*cos(1.0*x), ), (-1.0*I*sin(1.0*x), X0)] >>> import sympy >>> op = QubitOperator("X0", -1.j * sympy.Symbol('x')) >>> qol = QubitOperatorList([(2, op)]) >>> result = qol.expand_exponential_product_commuting_operators(expansion_coefficients_behavior="compact") >>> print(result) 1.0 [(2.0*cos(1.0*x), ), (-2.0*I*sin(1.0*x), X0)]
- free_symbols_ordered()
Returns the free symbols in the coefficients, ordered alphabetically.
- Returns:
SymbolSet
– Ordered set of symbols.
- classmethod from_Operator(input, additional_coefficient=1.0, coefficients_location=FactoryCoefficientsLocation.INNER)
Converts an
Operator
to anOperatorList
with terms in arbitrary order.Each term in the
Operator
is split into a separate componentOperator
in theOperatorList
. The resulting location of each scalar coefficient in the inputOperator
can be controlled with thecoefficients_location
parameter. Setting this to"inner"
will leave coefficients stored as part of the component operators, a value of"outer"
will move the coefficients to the “outer” level.- Parameters:
input (
Operator
) – The input operator to split into anOperatorList
.additional_coefficient (
Union
[int
,float
,complex
,Expr
], default:1.0
) – An additional factor to include in the “outer” coefficients of the generatedOperatorList
.coefficients_location (
FactoryCoefficientsLocation
, default:FactoryCoefficientsLocation.INNER
) – The destination of the coefficients of the input operator, as described above.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – AnOperatorList
as described above.- Raises:
ValueError – On invalid input to the
coefficients_location
parameter.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op = QubitOperator("X0", 2.) + QubitOperator("Z1", 2.) >>> qol = QubitOperatorList.from_Operator(op) >>> print(qol) 1.0 [(2.0, X0)], 1.0 [(2.0, Z1)] >>> op = QubitOperator("X0", 2.) + QubitOperator("Z1", 2.) >>> qol = QubitOperatorList.from_Operator(op,coefficients_location='outer') >>> print(qol) 2.0 [(1.0, X0)], 2.0 [(1.0, Z1)]
- classmethod from_list(ops, symbol_format='term{}')
Converts a list of
QubitOperator
s to aQubitOperatorList
.Each
QubitOperator
in the list will be a separate entry in the generatedQubitOperatorList
. Fresh symbols will be generated to represent the “outer” coefficients of the generatedQubitOperatorList
.- Parameters:
ops (
List
[QubitOperator
]) –QubitOperator
s which will comprise the terms of the generatedQubitOperatorList
.symbol_format (default:
r"term{}"
) – A raw string containing one positional substitution (in which a numerical index will be placed), used to generate each symbolic coefficient.
- Returns:
QubitOperatorList
– Terms corresponding to the inputQubitOperator
s, and coefficients as newly generated symbols.
- classmethod from_string(input_string)
Constructs a child class instance from a string.
- incompatibility_matrix(abs_tol=1e-10)
Returns the incompatibility matrix of the operator list.
This matrix is the adjacency matrix of the incompatibility graph of the
OperatorList
. It is a boolean \((N\times N) matrix where :math:`N\) is the number of operators in theOperatorList
. Element indexed by[n,m]
isFalse
if operators indexed byn
andm
commute, otherwiseTrue
.- Parameters:
abs_tol (
float
, default:1e-10
) – Tolerance threshold used for determining commutativity - seeQubitOperator.commutator()
for details.- Returns:
ndarray
– The incompatibility matrix of the operator list.
- make_hashable()
Return a hashable representation of the object.
- Returns:
str
– A string representation of this instance.
- map(mapping)
Updates right values of items in-place, using a mapping function provided.
- operator_class
alias of
QubitOperator
- parallelity_matrix(abs_tol=1e-10)
Returns the “parallelity matrix” of the operator list.
This matrix is a boolean \((N\times N)\) matrix where \(N\) is the number of operators in the
OperatorList
. Element indexed by[n,m]
isTrue
if operators indexed byn
andm
are parallel - i.e. they are a scalar multiples of each other, otherwiseFalse
.
- qubitwise_compatibility_matrix()
Returns the qubit-wise compatibility matrix of the operator list.
This matrix is the adjacency matrix of the qubit-wise compatibility graph of the
OperatorList
. It is a boolean \((N\times N)\) matrix where \(N\) is the number of operators in theOperatorList
. Element indexed by[n,m]
isTrue
if operators indexed byn
andm
qubit-wise commute, otherwiseFalse
. SeeQubitOperator.qubitwise_commutes_with()
for further details on qubit-wise commutativity.Note that individual
QubitOperator
objects within theOperatorList
must be comprised of single terms for this to be well-defined.- Returns:
ndarray
– The qubit-wise compatibility matrix of the operator list.
- qubitwise_incompatibility_matrix()
Returns the qubit-wise incompatibility matrix of the operator list.
This matrix is the adjacency matrix of the qubit-wise incompatibility graph of the
OperatorList
. It is a boolean \((N\times N) matrix where :math:`N\) is the number of operators in theOperatorList
.Element indexed by
[n,m]
isFalse
if operators indexed byn
andm
qubit-wise commute, otherwiseTrue
. SeeQubitOperator.qubitwise_commutes_with()
for further details on qubit-wise commutativity.Note that individual
QubitOperator
s within theOperatorList
must be comprised of single terms for this to be well-defined.Returns: The qubit-wise incompatibility matrix of the operator list.
- Return type:
ndarray
- reduce_exponents_by_commutation(abs_tol=1e-10)
Given a
QubitOperatorList
representing a product of exponentials, combine terms by commutation.Given a
QubitOperatorList
, this method interprets it as a product of exponentials of the component operators. This means that for aQubitOperatorList
consisting of terms (\(c_i\),:math:hat{O}_i), it is interpreted as \(\prod_i{e^{c_i \hat{O}_i}}\). This method attempts to combine terms which are scalar multiples of one another. Each term is commuted backwards through theQubitOperatorList
until it reaches an operator with which it does not commute with. If it encounters an operator which is a scalar multiple of the term, then the terms are combined. Otherwise, the term is left unchanged.- Parameters:
abs_tol (
float
, default:1e-10
) – Tolerance threshold used for determining commutativity - seeQubitOperator.commutator()
for details.- Returns:
QubitOperatorList
– A reduced form of theQubitOperatorList
as described above.
- retrotterize(new_trotter_number, initial_trotter_number=1, new_trotter_order=1, initial_trotter_order=1, constant=1.0, inner_coefficients=False)
Retrotterize an expression given a
OperatorList
representing a product of exponentials.This method assumes that
self
represents a product of exponentials, with each constituentOperator
corresponding to the exponentiated term of a single exponential in a product. Scalar factors within theOperatorList
are treated as scalar multipliers within each exponent.The
OperatorList
is first untrotterized using the providedinitial_trotter_number
andinitial_trotter_order
, then subsequently Trotterized using the providednew_trotter_number
andnew_trotter_order
. The returnedOperatorList
corresponds to the generated product of exponentials, in a similar manner to the originalOperatorList
.- Parameters:
new_trotter_number (
int
) – The desired number of Trotter steps in the final Trotter-Suzuki expansion.initial_trotter_number (
int
, default:1
) – The number of Trotter steps in the original Trotter-Suzuki expansion.new_trotter_order (
int
, default:1
) – The desired order of the final Trotter-Suzuki expansion. Currently, only a first order (\(ABABAB...\)) or second order (\(ABBAABBA...\)) expansion is supported.initial_trotter_order (
int
, default:1
) – The order of the original Trotter-Suzuki expansion used. Currently, only a first order (\(ABABAB...\)) expansion is supported.constant (
Union
[float
,complex
], default:1.0
) – An additional constant multiplier in the exponent.inner_coefficients (
bool
, default:False
) – By default, generated scalar factors in each exponent are stored in the coefficients of the generatedOperatorList
, with the coefficient of each innerOperator
unchanged. Set this toTrue
to instead store all scalar factors as coefficients in eachOperator
, with the outer coefficients of theOperatorList
left unchanged. See examples for a comparison.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) –:- The exponential product retrotterized with the provided new Trotter number and order. Each element is an
individual exponent.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1./2.,op1),(1./2.,op2),(1./2.,op1),(1./2.,op2)]) >>> retrotterised = qol.retrotterize(new_trotter_number=4,initial_trotter_number=2) >>> print(retrotterised) 0.25 [(1.0, X0 X1)], 0.25 [(1.0, Z0)], 0.25 [(1.0, X0 X1)], 0.25 [(1.0, Z0)], 0.25 [(1.0, X0 X1)], 0.25 [(1.0, Z0)], 0.25 [(1.0, X0 X1)], 0.25 [(1.0, Z0)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1./2.,op1),(1./2.,op2),(1./2.,op1),(1./2.,op2)]) >>> retrotterised = qol.retrotterize(new_trotter_number=4,initial_trotter_number=2,inner_coefficients=True) >>> print(retrotterised) 0.5 [(0.5, X0 X1)], 0.5 [(0.5, Z0)], 0.5 [(0.5, X0 X1)], 0.5 [(0.5, Z0)], 0.5 [(0.5, X0 X1)], 0.5 [(0.5, Z0)], 0.5 [(0.5, X0 X1)], 0.5 [(0.5, Z0)]
- reversed_order()
Reverses internal
list
order and returns it as a new object.n.b. the constructor’s
data
argument expects (coeff, operator) ordering of the elements if it is passed as alist
, butself._list
is stored in (operator, coeff) ordering- Return type:
- simplify(*args, **kwargs)
Simplifies expressions stored in left and right values of list items.
- split_totally_commuting_set(abs_tol=1e-10)
For a
QubitOperatorList
, separate it into a totally commuting part and a remainder.This will return two
QubitOperatorList
instances - the first comprised of all the componentQubitOperator
s which commute with all other terms, the second comprised of all other terms. An emptyQubitOperatorList
will be returned if either of these sets is empty.- Parameters:
abs_tol (
float
, default:1e-10
) – Tolerance threshold used for determining commutativity - seeQubitOperator.commutator()
for details.- Returns:
A pair of
QubitOperatorList
s - the first representing the totally commuting set, the second representing the rest of the operator.
- sublist(sublist_indices)
Returns a new instance containing a subset of the terms in the original object.
- Parameters:
sublist_indices (
list
[int
]) – Indices of elements in this instance selected to constitute a new object.- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – A sublist of this instance.- Raises:
ValueError – If
sublist_indices
contains indices not contained in this instance, or if this instanceis empty. –
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 Y1 Z3", 4.6) >>> op2 = QubitOperator("Z0", -1.6j) >>> op3 = QubitOperator("Z1 Z2 Z3 Z5", -5.6j) >>> long_operator = QubitOperatorList([(1, op1), (1, op2), (1, op3)]) >>> short_operator = long_operator.sublist([0, 2]) >>> print(short_operator) 1 [(4.6, X0 Y1 Z3)], 1 [(-5.6j, Z1 Z2 Z3 Z5)]
- 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
) – Maps symbol-representing keys to the value the symbol should be substituted for.- Returns:
LinearListCombiner
– This instance with symbols key symbols replaced by their values.
- sympify(*args, **kwargs)
Sympifies left and right values of list items.
Replaces left and right values with their corresponding symbolic expressions.
- Parameters:
- Returns:
LinearListCombiner
– Updated instance ofLinearListCombiner
.- Raises:
RuntimeError – Sympification fails.
- to_sparse_matrices(qubits=None)
Returns a list of sparse matrices representing each element of the
QubitOperatorList
.Outer coefficients are treated by multiplying their corresponding
QubitOperator
s. Otherwise, this method acts largely as a wrapper forQubitOperator.to_sparse_matrix()
, which derives from the base pytketQubitPauliOperator.to_sparse_matrix()
method. The qubits parameter specifies the ordering scheme for qubits. Note that if no explicit qubits are provided, we use the set of all qubits included in any operator in theQubitOperatorList
(i.e.self.all_qubits
), ordered ILO-BE as per pytket. From the pytket docs:When
qubits
is an explicit list, the qubits are ordered withqubits[0]
as the most significant qubit for indexing into the matrix.If
None
, then no padding qubits are introduced and we use the ILO-BE convention, e.g.Qubit("a",0)
is more significant thanQubit("a",1)
orQubit("b")
.Giving a number specifies the number of qubits to use in the final operator, treated as sequentially indexed from 0 in the default register (padding with identities as necessary) and ordered by ILO-BE so
Qubit(0)
is the most significant.
- trotterize_as_linear_combination(trotter_number, trotter_order=1, constant=1.0, inner_coefficients=False)
Trotterize an exponent linear combination of Operators.
This method assumes that
self
represents the exponential of a linear combination ofOperator
objects, each corresponding to a term in this linear combination. Trotterization is performed at the level of theseOperator
instances. TheOperator
objects contained within the returnedOperatorList
correspond to exponents within the Trotter sequence.- Parameters:
trotter_number (
int
) – The number of Trotter steps in the Trotter-Suzuki expansion.trotter_order (
int
, default:1
) – The order of the Trotter-Suzuki approximation to be used. The first- and the second-order options are supported.constant (
Union
[float
,complex
], default:1.0
) – An additional constant multiplier in the exponent.inner_coefficients (
bool
, default:False
) – By default, generated scalar factors in each exponent are stored in the coefficients of the generatedOperatorList
, with the coefficient of each innerOperator
unchanged. Set this toTrue
to instead store all scalar factors as coefficients in eachOperator
, with the outer coefficients of theOperatorList
left unchanged. See examples for a comparison.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – A Trotterized form of the exponential product, where each element is an individual exponent.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1.,op1),(1.,op2)]) >>> result = qol.trotterize_as_linear_combination(2) >>> print(result) 0.5 [(1.0, X0 X1)], 0.5 [(1.0, Z0)], 0.5 [(1.0, X0 X1)], 0.5 [(1.0, Z0)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1.,op1),(1.,op2)]) >>> result = qol.trotterize_as_linear_combination(2,inner_coefficients=True) >>> print(result) 1.0 [(0.5, X0 X1)], 1.0 [(0.5, Z0)], 1.0 [(0.5, X0 X1)], 1.0 [(0.5, Z0)]
- 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 (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:
LinearListCombiner
– Updated instance ofLinearListCombiner
.- Raises:
TypeError – Unsympification fails.
- untrotterize(trotter_number, trotter_order=1)
Reverse a Trotter-Suzuki expansion given a product of exponentials as an
OperatorList
.This method assumes that the
OperatorList
represents a product of exponentials, with eachOperator
in the list corresponding to an exponent of a single exponential in the product. Scalar factors within theOperatorList
are treated as scalar multipliers within each exponent. AnOperator
corresponding to the exponent of a single, untrotterized exponential is returned.- Parameters:
- Returns:
TypeVar
(OperatorT
, bound= Operator) – The exponent of the untrotterised operator.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1./2.,op1),(1./2.,op2),(1./2.,op1),(1./2.,op2)]) >>> untrotterised = qol.untrotterize(2) >>> print(untrotterised) (1.0, X0 X1), (1.0, Z0)
- untrotterize_partitioned(trotter_number, trotter_order=1, inner_coefficients=False)
Reverse a Trotter-Suzuki expansion given a product of exponentials as an
OperatorList
, maintaining separation of exponents.This method assumes that
self
represents a product of exponentials, with each constituentOperator
corresponding to the exponentiated term of a single exponential within a product. Scalar factors within thisOperatorList
are treated as scalar multipliers within each exponent. AOperatorList
is returned wherein each term represents a single term in the exponent of the single, untrotterized exponential.- Parameters:
trotter_number (
int
) – The number of Trotter steps within the Trotter expansion to be reversed.trotter_order (
int
, default:1
) – The order of the Trotter-Suzuki expansion used. Currently, only a first order (\(ABABAB...\)) expansion is supported.inner_coefficients (
bool
, default:False
) – By default, generated scalar factors in each exponent are stored in the coefficients of the generatedOperatorList
, with the coefficient of each innerOperator
unchanged. Set this toTrue
to instead store all scalar factors as coefficients in eachOperator
, with the outer coefficients of theOperatorList
left unchanged. See examples for a comparison.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – The terms in the exponent of the untrotterised operator as aOperatorList
.- Raises:
ValueError – If the provided Trotter number is not compatible with the
OperatorList
.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1./2.,op1),(1./2.,op2),(1./2.,op1),(1./2.,op2)]) >>> untrotterised = qol.untrotterize_partitioned(2) >>> print(untrotterised) 1.0 [(1.0, X0 X1)], 1.0 [(1.0, Z0)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1./2.,op1),(1./2.,op2),(1./2.,op1),(1./2.,op2)]) >>> untrotterised = qol.untrotterize_partitioned(2,inner_coefficients=True) >>> print(untrotterised) 0.5 [(2.0, X0 X1)], 0.5 [(2.0, Z0)]
- class QubitOperatorString
Bases:
QubitPauliString
Handles a Pauli string: a term in
QubitOperator
.- property all_nontrivial_qubits: set[Qubit]
Returns a set of all qubits acted upon by this string nontrivially (i.e. with an X,Y or Z).
- anticommutator(other)
Calculates the commutator of this with another
QubitOperatorString
.A quick check is first performed to determine if the operators anticommute, returning a zero
QubitOperator
if so. If not, the anticommutator is determined by explicit multiplication.Notes
The anticommutator is returned as a
QubitOperator
, not aQubitOperatorString
. This is due to the fact that the anticommutator will include a scalar factor in \(\{1,\mathrm{i},-1,-\mathrm{i}\}\), rather than being an unweighted Pauli string.- Parameters:
other (
QubitOperatorString
) – The other Pauli string.- Returns:
QubitOperator
– The anticommutator of the two Pauli strings.
- anticommutes_with(other)
Returns
True
if thisQubitOperatorString
anticommutes with the other, otherwiseFalse
.This counts whether an even or odd number of qubits have differing non-identity Paulis acting on them, returning
False
in the case of even andTrue
in the case of odd.- Parameters:
other (
QubitOperatorString
) – The other Pauli string.- Returns:
bool
–True
if the two Pauli strings anticommute, elseFalse
.
- commutator(other)
Calculates the commutator of this with another
QubitOperatorString
.This operator is treated as being on the left (i.e. \(A\) in \(AB\)-\(BA\)). A quick check is first performed to determine if the operators commute, returning a zero
QubitOperator
if so. If not, the commutator is determined by explicit multiplication.Notes
The commutator is returned as a
QubitOperator
, not aQubitOperatorString
. This is due to the fact that the commutator will include a scalar factor in \(\{1,\mathrm{i},-1,-\mathrm{i}\}\), rather than being an unweighted Pauli string.- Parameters:
other (
QubitOperatorString
) – The other Pauli string.- Returns:
QubitOperator
– The commutator of the two Pauli strings.
- commutes_with(self: pytket._tket.pauli.QubitPauliString, other: pytket._tket.pauli.QubitPauliString) bool
- Returns:
True if the two strings commute, else False
- compress(self: pytket._tket.pauli.QubitPauliString) None
Removes I terms to compress the sparse representation.
- dot_state(state, qubits=None)
Calculate the result of operating on a given qubit state.
Can accept right-hand state as a
QubitState
,QubitStateString
or anumpy.ndarray
. In the former two cases, we maintain a symbolic representation of both operator and state, and each Pauli is implemented in sequence. Resultant states are returned asQubitState
. This should support sympy parametrised states and operators, but the use of parametrised states and operators is untested.For a
numpy.ndarray
, we delegate to pytket’sQubitPauliOperatorString.dot_state()
method - this should be faster for dense states, but slower for sparse ones. Here, a register of qubits may be specified in thequbits
parameter to determine the meaning of the indices of the provided state vector. From the pytket documentation:When
qubits
is an explicitlist
, the qubits are ordered withqubits[0]
as the most significant qubit for indexing into state.If
None
, qubits sequentially indexed from 0 in the default register and ordered by ILO-BE soQubit(0)
is the most significant.
- Parameters:
state (
Union
[QubitState
,QubitStateString
,ndarray
]) – Input qubit state to operated on.qubits (
Optional
[List
[Qubit
]], default:None
) – For ndarray input, determines sequencing of qubits in the state, if not mapped to the default register. Ignored for other input types.
- Returns:
Union
[QubitState
,ndarray
] – Output state.
- classmethod from_QubitPauliString(qps)
Generates an instance of this class from a tket
QubitPauliString
.- Parameters:
qps (
QubitPauliString
) – Apytket.pauli.QubitPauliString
to be converted.- Returns:
A converted Pauli string.
- classmethod from_list(s)
Construct
QubitOperatorString
from list of tuples.- Parameters:
s (
List
[Tuple
[Tuple
[str
,List
[int
]],str
]]) –tuple
s of the form((qubit_label, [qubit_index]), pauli)
.- Returns:
QubitOperatorString
– Output operator string.- Raises:
ValueError – if multiple Paulis are acting on a single qubit.
Examples
>>> qo = QubitOperatorString.from_list([(("q", [0]), "X"), (("q", [1]), "Y")]) >>> print(qo) X0 Y1
- classmethod from_string(s)
Constructs
QubitOperatorString
from a string.The string should contain Pauli gate symbols (\(X\), \(Y\) or \(Z\)) followed by index of a qubit on which it acts, with different pairs separated by space.
- Parameters:
s (
str
) – A python string representing a Pauli word.- Returns:
QubitOperatorString
– Output operator string.- Raises:
ValueError – If multiple Paulis are acting on a single qubit.
Examples
>>> qs = QubitOperatorString.from_string("X1 X3 X5") >>> print(qs) X1 X3 X5
- classmethod from_symplectic_row(symplectic_row, qubits=None)
Generate a
QubitOperatorString
from symplectic row vector form.This is a length \(2N\) vector where \(N\) is the number of qubits. The first \(N\) entries indicate if an \(X\) is performed on each qubit, and the next \(N\) entries indicate if a \(Z\) is performed on the qubit. Qubits are assigned based on provided qubit register from left to right, if
qubits
is not provided then a default register indexed from 0 toself.num_qubits-1
is assumed.- Parameters:
- Returns:
QubitOperatorString
– The operator described bysymplectic_row
.
- classmethod from_tuple(t)
Constructs
QubitOperatorString
from atuple
.Accepts a
list
of two-elementtuple
s, with the left value being an index of a qubit and the right value being a Pauli object (Pauli.X
,Pauli.Y
orPauli.Z
) designating a gate acting on this qubit.- Parameters:
t (
List
[Tuple
[int
,Pauli
]]) – Alist
oftuple
s representing a Pauli word.- Raises:
ValueError – if multiple Paulis are acting on a single qubit.
- Returns:
QubitOperatorString
– Output operator string.
Examples
>>> qs = QubitOperatorString.from_tuple([(1, Pauli.X), (3, Pauli.X), (5, Pauli.X)]) >>> print(qs) X1 X3 X5
- property map
the QubitPauliString’s underlying dict mapping
Qubit
toPauli
- Type:
return
- padded(register_qubits=None, zero_to_max=False)
Return a copy of the
QubitOperatorString
with implicit identities replaced with explicit identities.A qubit register should be provided in order to determine which qubits the operator acts on. Alternatively,
zero_to_max
may be set to True in order to assume that the qubit register is indexed \([0, N)\), where \(N\) is the highest integer indexed qubit in the originalQubitOperatorString
.These modes of operation are incompatible and this method will except ifzero_to_max
is set toTrue
andqubits_register
is provided.- Parameters:
- Returns:
QubitOperatorString
– A copy of theQubitOperatorString
with implicit identities over the specified register replaced with explicit identities.- Raises:
PaddingIncompatibleArgumentsError – If
register_qubits
has been provided whilezero_to_max
is set toTrue
.PaddingInferenceError – If
zero_to_max
is set toTrue
and maximum qubit index cannot be inferred, for instance by non-integer labelled qubits.PaddingInvalidRegisterError – If
zero_to_max
is not set and no qubit register is provided, or if string acts on qubits not in register.
Examples
>>> qs = QubitOperatorString.from_string("X0") >>> print(qs.padded([Qubit(0),Qubit(1)])) X0 I1
>>> qs = QubitOperatorString.from_string("X1") >>> print(qs.padded(zero_to_max=True)) I0 X1
- property pauli_list: List[Pauli]
Return list of Pauli objects contained in a
QubitOperatorString
.
- property qubit_id_list: List[Qubit]
Return list of Qubits contained in a
QubitOperatorString
.
- property qubit_list: List[Qubit]
Return list of Qubits contained in a
QubitOperatorString
.
- qubitwise_anticommutes_with(other)
Returns
True
if this Pauli string qubit-wise anticommutes with another Pauli string, otherwiseFalse
.Two Pauli strings qubit-wise anticommute if every Pauli acting on a given qubit anticommutes with the Pauli acting on the same qubit in the other string. This necessitates that the Paulis are different, and both non-identity, for every qubit.
Warning
By necessity, this method assumes that both Pauli strings act on a register comprised of the union of the qubits acted on by the two Pauli strings. This includes explicit identity operations, but not implicit ones. Caution should be used where
QubitOperatorString
s involve implicit identities. Consider padding with explicit identities with thepadded()
method.- Parameters:
other (
QubitOperatorString
) – The otherQubitOperatorString
.- Returns:
bool
–True
if the twoQubitOperatorString
s qubit-wise anticommute, elseFalse
.
- qubitwise_commutes_with(other)
Returns
True
if this Pauli string qubit-wise commutes with another Pauli string, otherwiseFalse
.Two Pauli strings qubit-wise commute if every Pauli acting on a given qubit commutes with the Pauli acting on the same qubit in the other string. This necessitates that either the Paulis are the same, or that at least one is an identity.
- Parameters:
other (
QubitOperatorString
) – The other Pauli string.- Returns:
bool
–True
if the Pauli strings are qubit-wise commuting, otherwiseFalse
.
- register_size(at_least_one=False)
Return the size of the qubit register acted on by this string.
The maximum qubit index plus one.
- state_expectation(*args, **kwargs)
Overloaded function.
state_expectation(self: pytket._tket.pauli.QubitPauliString, state: numpy.ndarray[numpy.complex128[m, 1]]) -> complex
Calculates the expectation value of the state with the pauli string. Maps the qubits of the statevector with sequentially-indexed qubits in the default register, with
Qubit(0)
being the most significant qubit.- Parameters:
state – statevector for qubits
Qubit(0)
toQubit(n-1)
- Returns:
expectation value with respect to state
state_expectation(self: pytket._tket.pauli.QubitPauliString, state: numpy.ndarray[numpy.complex128[m, 1]], qubits: Sequence[pytket._tket.unit_id.Qubit]) -> complex
Calculates the expectation value of the state with the pauli string. Maps the qubits of the statevector according to the ordered list qubits, with
qubits[0]
being the most significant qubit.- Parameters:
state – statevector
qubits – order of qubits in state from most to least significant
- Returns:
expectation value with respect to state
- to_QubitPauliString()
Returns self converted to a tket
QubitPauliString
.
- to_circuit(n_qubits=None)
Generate a circuit which implements the Pauli string as a set of single-qubit gates.
- to_dict()
Returns the underlying dictionary of
QubitOperatorString
.- Return type:
Dict
[Qubit
,Pauli
]
- to_latex(show_indices=True, show_labels=False, swap_scripts=False, text_labels=True)
Generate a LaTeX representation of the operator string.
- Parameters:
show_indices (
bool
, default:True
) – Toggle whether the index on each Pauli operator should be printed.show_labels (
bool
, default:False
) – Toggle whether the label on each Pauli operator should be printed.swap_scripts (
bool
, default:False
) – By default, indices are printed as subscripts and labels as superscripts. Set toTrue
to swap them.text_labels (
bool
, default:True
) – IfTrue
, labels are wrapped intext{}
.
- Returns:
str
– LaTeX compilable equation string.
Examples
>>> qos = QubitOperatorString.from_string("X0 X1 X2") >>> print(qos.to_latex()) X_{0} X_{1} X_{2} >>> print(qos.to_latex(show_labels=True, text_labels=False)) X^{q}_{0} X^{q}_{1} X^{q}_{2} >>> qos = QubitOperatorString.from_list([(("Alice", [0, 1]), "X"), (("Bob", [1]), "Y")]) >>> print(qos.to_latex(show_labels=True)) X^{\text{Alice}}_{0, 1} Y^{\text{Bob}}_{1} >>> print(qos.to_latex(show_labels=True, show_indices=False, swap_scripts=True)) X_{\text{Alice}} Y_{\text{Bob}}
- to_list(self: pytket._tket.pauli.QubitPauliString) list
A JSON-serializable representation of the QubitPauliString.
- Returns:
a list of
Qubit
-to-Pauli
entries, represented as dicts.
- to_sparse_matrix(*args, **kwargs)
Overloaded function.
to_sparse_matrix(self: pytket._tket.pauli.QubitPauliString) -> scipy.sparse.csc_matrix[numpy.complex128]
Represents the sparse string as a dense string (without padding for extra qubits) and generates the matrix for the tensor. Uses the ILO-BE convention, so
Qubit("a", 0)
is more significant thatQubit("a", 1)
andQubit("b")
for indexing into the matrix.- Returns:
a sparse matrix corresponding to the operator
to_sparse_matrix(self: pytket._tket.pauli.QubitPauliString, n_qubits: int) -> scipy.sparse.csc_matrix[numpy.complex128]
Represents the sparse string as a dense string over n_qubits qubits (sequentially indexed from 0 in the default register) and generates the matrix for the tensor. Uses the ILO-BE convention, so
Qubit(0)
is the most significant bit for indexing into the matrix.- Parameters:
n_qubits – the number of qubits in the full operator
- Returns:
a sparse matrix corresponding to the operator
to_sparse_matrix(self: pytket._tket.pauli.QubitPauliString, qubits: Sequence[pytket._tket.unit_id.Qubit]) -> scipy.sparse.csc_matrix[numpy.complex128]
Represents the sparse string as a dense string and generates the matrix for the tensor. Orders qubits according to qubits (padding with identities if they are not in the sparse string), so
qubits[0]
is the most significant bit for indexing into the matrix.- Parameters:
qubits – the ordered list of qubits in the full operator
- Returns:
a sparse matrix corresponding to the operator
- class RestrictedOneBodyRDM(rdm1, rdms=None)
Bases:
OneBodyRDM
One-body reduced density matrix in a spin restricted representation.
- Parameters:
rdm1 (
ndarray
) – Reduced one-body density matrix as a 2D array. \(\text{1RDM}_{ij} = \langle a_{i,\alpha}^\dagger a_{j,\alpha}\rangle + \langle a_{i,\beta}^\dagger a_{j,\beta}\rangle\)rdms (
Optional
[ndarray
], default:None
) – Spin density matrix. If unspecified, spin symmetry is assumed and so the alpha and beta parts of the RDM exactly cancel. \(\text{1RDM}_{ij}^s = \langle a_{i,\alpha}^\dagger a_{j,\alpha}\rangle - \langle a_{i,\beta}^\dagger a_{j,\beta}\rangle\)
- copy()
Performs a deep copy of object.
- Return type:
RDM
- get_block(mask)
Return a new RDM spanning a subset of the original’s orbitals.
All orbitals not specified in
mask
are ignored.- Parameters:
mask (
ndarray
) – Indices of orbitals to retain.- Returns:
RestrictedOneBodyRDM
– New, smaller RDM with only the target orbitals.
- get_occupations(as_int=True)
Returns the diagonal elements of the 1-RDM.
- classmethod load_h5(name)
Loads RDM object from .h5 file.
- mean_field_rdm2()
Calculate the mean-field two-body RDM object.
- Returns:
RestrictedTwoBodyRDM
– Two body RDM object.
- rotate(rotation)
Rotate the density matrix to a new basis.
- Parameters:
rotation (
ndarray
) – Rotation matrix as a 2D array.- Returns:
RestrictedOneBodyRDM
– RDM after rotation.
- save_h5(name)
Dumps RDM object to .h5 file.
- set_block(mask, rdm)
Set the RDM entries for a specified set of orbitals.
- Parameters:
mask (
ndarray
) – Indices of orbitals to be edited.rdm (
RestrictedOneBodyRDM
) – RDM object to replace target orbitals.
- Returns:
RestrictedOneBodyRDM
– Updated RDM object with target orbitals overwritten.
- class RestrictedTwoBodyRDM(rdm2)
Bases:
RDM
Two-body reduced density matrix in a spin restricted representation.
- Parameters:
rdm2 (
ndarray
) – Reduced two-body density matrix as a 4D array. \(\text{2RDM}_{ijkl} = \sum_{\sigma,\sigma'\in \{\alpha,\beta\}}\langle a_{i,\sigma}^\dagger a_{k, \sigma'}^\dagger a_{l, \sigma'} a_{j, \sigma}\rangle\)
- copy()
Performs a deep copy of object.
- Return type:
RDM
- classmethod load_h5(name)
Loads RDM object from .h5 file.
- rotate(rotation)
Rotate the density matrix to a new basis.
- Parameters:
rotation (
ndarray
) – Rotation matrix as a 2D array.- Returns:
RestrictedTwoBodyRDM
– RDM after rotation.
- class SymmetryOperatorFermionic(*args, **kwargs)
Bases:
FermionOperator
,SymmetryOperator
Represents a symmetry operator in a fermionic Hilbert space.
This is an extension of
FermionOperator
, providing functionality relating to validating symmetries and finding symmetry sectors.- Parameters:
data – Input data from which the Fermion operator is built. Multiple input formats are supported.
coeff – Multiplicative scalar coefficient. Used only when
data
is of typetuple
orFermionOperatorString
.
- class TrotterizeCoefficientsLocation(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
-
Determines where coefficients will be stored upon performing Trotterization.
- INNER = 'inner'
All coefficients will be stored in the “inner” coefficients, within the component QubitOperators in the Trotterized result.
- MIXED = 'mixed'
The Trotter step factor will be stored in the “outer” coefficients, whereas the original coefficients of the original Operator will remain in the component Operators.
- OUTER = 'outer'
All coefficients will be stored in the “outer” coefficients, the coefficients stored directly in the generated OperatorList.
- capitalize()
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
- casefold()
Return a version of the string suitable for caseless comparisons.
- center(width, fillchar=' ', /)
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
- count(sub[, start[, end]]) int
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
- encode(encoding='utf-8', errors='strict')
Encode the string using the codec registered for encoding.
- encoding
The encoding in which to encode the string.
- errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(suffix[, start[, end]]) bool
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
- expandtabs(tabsize=8)
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(*args, **kwargs) str
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).
- format_map(mapping) str
Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).
- index(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- isalnum()
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
- isalpha()
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
- isascii()
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
- isdecimal()
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
- isdigit()
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
- isidentifier()
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.
- islower()
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
- isnumeric()
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.
- isprintable()
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in repr() or if it is empty.
- isspace()
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
- istitle()
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
- isupper()
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
- join(iterable, /)
Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
- ljust(width, fillchar=' ', /)
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
- lower()
Return a copy of the string converted to lowercase.
- lstrip(chars=None, /)
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- static maketrans()
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
- partition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
- removeprefix(prefix, /)
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
- removesuffix(suffix, /)
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
- replace(old, new, count=-1, /)
Return a copy with all occurrences of substring old replaced by new.
- count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
- rfind(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- rjust(width, fillchar=' ', /)
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
- rpartition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
- rsplit(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
- rstrip(chars=None, /)
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the front of the string and works to the end.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
- splitlines(keepends=False)
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
- startswith(prefix[, start[, end]]) bool
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
- strip(chars=None, /)
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase()
Convert uppercase characters to lowercase and lowercase characters to uppercase.
- title()
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
- translate(table, /)
Replace each character in the string using the given translation table.
- table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
- upper()
Return a copy of the string converted to uppercase.
- zfill(width, /)
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
- apply_bra(fock_state)
Performs an operation on a
inquanto.states.FermionState
representing a bra.This transforms the provided
inquanto.states.FermionState
with the operator on the right. Conjugation on theinquanto.states.FermionState
object is not performed.- Parameters:
fock_state (
FermionState
) – Object representing a bra.- Returns:
FermionState
– A representation of the post-operation bra.
- apply_ket(fock_state)
Performs an operation on a ket
inquanto.states.FermionState
state.- Parameters:
fock_state (
FermionState
) – FermionState object (ket state).- Returns:
FermionState
– New ket state.
- approx_equal_to(other, abs_tol=1e-10)
Checks for equality between this instance and another
FermionOperator
.First, dictionary equivalence is tested for. If
False
, operators are compared in normal-ordered form, and difference is compared toabs_tol
.- Parameters:
other (
FermionOperator
) – An operator to test for equality with.abs_tol (
float
, default:1e-10
) – Tolerance threshold for negligible terms in comparison.
- Returns:
bool
–True
if this operator is equal to other, otherwiseFalse
.
Danger
This method may use the
normal_ordered()
method internally, which may be exponentially costly.
- 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.
- as_scalar(abs_tol=None)
If the operator is a sum of identity terms or zero, return the sum of the coefficients, otherwise return
None
.Note that this does not perform combination of terms and will return zero only if all coefficients are zero.
- Parameters:
abs_tol (
float
, default:None
) – Tolerance for checking if coefficients are zero. Set toNone
to test using a standard
:param python
==
comparison.:
- classmethod ca(a, b)
Return object with a single one-body creation-annihilation pair with a unit coefficient in its
dict
.- Parameters:
- Returns:
The creation-annihilation operator pair.
Examples
>>> print(FermionOperator.ca(2, 0)) (1.0, F2^ F0 )
- classmethod caca(a, b, c, d)
Return object with a single two-body creation-annihilation pair with a unit coefficient in its
dict
.Ordered as creation-annihilation-creation-annihilation.
- Parameters:
a (
int
) – Index of fermionic mode to which the first creation operator is applied.b (
int
) – Index of fermionic mode to which the first annihilation operator is applied.c (
int
) – Index of fermionic mode to which the second creation operator is applied.d (
int
) – Index of fermionic mode to which the second annihilation operator is applied.
- Returns:
The composed two-body operator.
Examples
>>> print(FermionOperator.caca(2, 0, 3, 1)) (1.0, F2^ F0 F3^ F1 )
- classmethod ccaa(a, b, c, d)
Return object with a single two-body creation-annihilation pair with a unit coefficient in its
dict
.Ordered as creation-creation-annihilation-annihilation.
- Parameters:
a (
int
) – Index of fermionic mode to which the first creation operator is applied.b (
int
) – Index of fermionic mode to which the second creation operator is applied.c (
int
) – Index of fermionic mode to which the first annihilation operator is applied.d (
int
) – Index of fermionic mode to which the second annihilation operator is applied.
- Returns:
The composed two-body operator.
Examples
>>> print(FermionOperator.ccaa(3, 2, 1, 0)) (1.0, F3^ F2^ F1 F0 )
- commutator(other_operator)
Returns the commutator of this instance with
other_operator
.This calculation is performed by explicit calculation through multiplication.
- Parameters:
other_operator (
FermionOperator
) – The other fermionic operator.- Returns:
FermionOperator
– The commutator.
- commutes_with(other_operator, abs_tol=1e-10)
Returns
True
if this instance commutes withother_operator
(within tolerance), otherwiseFalse
.- Parameters:
other_operator (
FermionOperator
) – The other fermionic operator.abs_tol (
float
, default:1e-10
) – Tolerance threshold for negligible terms in the commutator.
- Returns:
bool
–True
if operators commute (within tolerance) otherwiseFalse
.
- 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 ofLinearDictCombiner
.
- classmethod constant(value)
Return object with a provided constant entry in its
dict
.- Returns:
Operator representation of provided constant scalar.
Examples
>>> print(FermionOperator.constant(0.5)) (0.5, )
- dagger()
Returns the Hermitian conjugate of an operator.
- Return type:
- 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:
SymbolSet
– Ordered set of symbols.
- freeze(index_map, occupation)
Adaptation of OpenFermion’s freeze_orbitals method with mask and consistent index pruning.
- Parameters:
index_map (
List
[int
]) – A list of integers orNone
entries, whose size is equal to the number of spin-orbitals, whereNone
indicates orbitals to be frozen and the remaining sequence of integers is expected to be continuous.occupation (
List
[int
]) – Alist
of 1s and 0s of the same length asindex_map
, indicating occupied and unoccupied orbitals.
- Returns:
FermionOperator
– New operator with frozen orbitals removed.
- classmethod from_list(data)
Construct
FermionOperator
from alist
oftuple
s.- Parameters:
data (
List
[Tuple
[Union
[int
,float
,complex
,Expr
],FermionOperatorString
]]) – Data representing a fermion operator term or sum of fermion operator terms. Each term in thelist
must be atuple
containing a scalar multiplicative coefficient, followed by aFermionOperatorString
ortuple
(seeFermionOperator.from_tuple()
).- Returns:
FermionOperator
– Fermion operator object corresponding to a valid input.
Examples
>>> fos0 = FermionOperatorString(((1, 0), (2, 1))) >>> fos1 = FermionOperatorString(((1, 0), (3, 1))) >>> op = FermionOperator.from_list([(0.9, fos0), (0.1, fos1)]) >>> print(op) (0.9, F1 F2^), (0.1, F1 F3^) >>> op = FermionOperator.from_list([(0.9, ((1, 0), (2, 1))), (0.1, fos1)]) >>> print(op) (0.9, F1 F2^), (0.1, F1 F3^)
- classmethod from_string(input_string)
Constructs a child class instance from a string.
- Parameters:
input_string (
str
) – String in the formatcoeff1 [(coeff1_1, term1_1), ..., (coeff1_n, term1_n)], ..., coeffn [(coeffn_1, termn_1), ...]
.- Returns:
Child class object.
- classmethod from_tuple(data, coeff=1.0)
Construct
FermionOperator
from atuple
of terms.- Parameters:
data (
Tuple
) – Data representing a fermion operator term, which may be a product of single fermion creation or anihilation operators. Creation and annihilation operators acting on orbital indexq
are given bytuple
s(q, 0)
and(q, 1)
respectively. A product of single operators is given by atuple
oftuple
s; for example, the number operator:((q, 1), (q, 0))
.coeff (
Union
[int
,float
,complex
,Expr
], default:1.0
) – Multiplicative scalar coefficient.
- Returns:
FermionOperator
– Fermion operator object corresponding to a valid input.
Examples
>>> op = FermionOperator.from_tuple(((1, 0), (2, 1)), 1.0) >>> print(op) (1.0, F1 F2^)
- classmethod identity()
Return object with an identity entry in its
dict
.Examples
>>> print(FermionOperator.identity()) (1.0, )
- infer_num_spin_orbs()
Returns the number of modes that this operator acts upon, inferring the existence of modes with index from 0 to the maximum index.
- Returns:
int
– The minimum number of spin orbitals in the Fock space to which thisFermionOperator
operates on.
Examples
>>> op = FermionOperator.from_string("(1.0, F1 F2^)") >>> print(op.infer_num_spin_orbs()) 3
- 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_antihermitian(abs_tol=1e-10)
Returns
True
if operator is anti-Hermitian (within a tolerance), elseFalse
.This explicitly calculates the Hermitian conjugate, multiplies by -1 and tests for equality. Normal-ordering is performed before comparison.
- Parameters:
abs_tol (
float
, default:1e-10
) – Tolerance threshold for negligible terms in comparison.- Returns:
bool
–True
if operator is anti-Hermitian, otherwiseFalse
.
Danger
This method uses the
normal_ordered()
method internally, which may be exponentially costly.
- 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_commuting_operator()
Returns
True
if every term in operator commutes with every other term, otherwiseFalse
.- Return type:
- is_hermitian(abs_tol=1e-10)
Returns
True
if operator is Hermitian (within a tolerance), elseFalse
.This explicitly calculates the Hermitian conjugate and tests for equality. Normal-ordering is performed before comparison.
- Parameters:
abs_tol (
float
, default:1e-10
) – Tolerance threshold for negligible terms in comparison.- Returns:
bool
–True
if operator is Hermitian, otherwiseFalse
.
Danger
This method uses the
normal_ordered()
method internally, which may be exponentially costly.
- is_normal_ordered()
Returns whether or not term is in normal-ordered form.
The assumed convention for normal ordering is for all creation operators to be to the left of annihilation operators, and each “block” of creation/annihilation operators are ordered with orbital indices in descending order (from left to right).
- Returns:
bool
–True
if operator is normal-ordered,False
otherwise.
Examples
>>> op = FermionOperator.from_string("(3.5, F1 F2^)") >>> print(op.is_normal_ordered()) False >>> op = FermionOperator.from_string("(3.5, F1^ F2^)") >>> print(op.is_normal_ordered()) False
- is_normalized(order=2, abs_tol=1e-10)
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=1e-10)
Returns
True
if other is parallel with this (i.e. a scalar multiple of this), otherwiseFalse
.
- is_self_inverse(abs_tol=1e-10)
Returns
True
if operator is its own inverse (within a tolerance),False
otherwise.This explicitly calculates the square of the operator and compares to the identity. Normal-ordering is performed before comparison.
- Parameters:
abs_tol (
float
, default:1e-10
) – Tolerance threshold for negligible terms in comparison.- Returns:
bool
–True
if operator is self-inverse, otherwiseFalse
.
Danger
This method uses the
normal_ordered()
method internally, which may be exponentially costly.
- is_symmetry_of(operator)
Check if operator is symmetry of given operator.
Checks by determining if operator commutes with all terms of other operator.
True
if it commutes,False
otherwise.- Parameters:
operator (
FermionOperator
) – Operator to compare to.- Returns:
bool
–True
if this is a symmetry ofoperator
, otherwiseFalse
.
- is_two_body_number_conserving(check_spin_symmetry=False)
Query whether operator has correct form to be a molecular Hamiltonian.
This method is a copy of the OpenFermion
is_two_body_number_conserving()
method.Require that term is particle-number conserving (same number of raising and lowering operators). Require that term has 0, 2 or 4 ladder operators. Require that term conserves spin (parity of raising operators equals parity of lowering operators).
- Parameters:
check_spin_symmetry (
bool
, default:False
) – Whether to check if operator conserves spin.- Returns:
bool
–True
if operator conserves electron number (and, optionally, spin),False
otherwise.
Examples
>>> op = FermionOperator.from_string("(1.0, F1^ F0)") >>> print(op.is_two_body_number_conserving()) True >>> op = FermionOperator.from_string("(1.0, F0^)") >>> print(op.is_two_body_number_conserving()) False >>> op = FermionOperator.from_string("(1.0, F1^ F0^)") >>> print(op.is_two_body_number_conserving()) False >>> op = FermionOperator.from_string("(1.0, F1^ F0)") >>> print(op.is_two_body_number_conserving(check_spin_symmetry=True)) False
- is_unit_1norm(abs_tol=1e-10)
Returns True if operator has unit 1-norm, else False.
- is_unit_2norm(abs_tol=1e-10)
Returns True if operator has unit 1-norm, else False.
- is_unit_norm(order=2, abs_tol=1e-10)
Returns True if operator has unit p-norm, else False.
- Parameters:
- Raises:
ValueError – Coefficients contain free symbols.
- Return type:
- is_unitary(abs_tol=1e-10)
Returns True if operator is unitary (within a tolerance), False otherwise.
This explicitly calculates the Hermitian conjugate, right-multiplies by the initial operator and tests for equality to the identity. Normal-ordering is performed before comparison.
- Parameters:
abs_tol (
float
, default:1e-10
) – Tolerance threshold for negligible terms in comparison.- Returns:
bool
–True
if operator is unitary, otherwiseFalse
.
Danger
This method uses the
normal_ordered()
method internally, which may be exponentially costly.
- static key_from_str(key_str)
Returns a
FermionOperatorString
instance initiated from the input string.- Parameters:
key_str (
str
) – An input string describing theFermionOperatorString
to be created -
:param see
FermionOperatorString.from_string()
for more detail.:- Returns:
FermionOperatorString
– A generatedFermionOperatorString
instance.
- list_class
alias of
FermionOperatorList
- 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.
- normal_ordered()
Returns a normal-ordered version of
FermionOperator
.Normal-ordering the operator moves all creation operators to the left of annihilation operators, and orders orbital indices in descending order (from left to right).
Danger
This may be exponential in runtime.
- Returns:
FermionOperator
– The operator in normal-ordered form.
Examples
>>> op = FermionOperator.from_string("(0.5, F1 F2^), (0.2, F1 F2 F3^ F4^)") >>> op_no = op.normal_ordered() >>> print(op_no) (-0.5, F2^ F1 ), (0.2, F4^ F3^ F2 F1 )
- normalized(norm_value=1.0, norm_order=2)
Returns a copy of this object with normalised coefficients.
- property num_spin_orbs: int
Return the number of spin-orbitals that this operator explicitly acts on.
- permuted_operator(permutation)
Permutes the indices in a
FermionOperator
.Permutation is according to a
list
or adict
of indices, mapping the old to a new operator order.- Parameters:
permutation (
Union
[Dict
,List
[int
]]) – Mapping from the old operator terms indices to the new ones. In case if alist
is given, its indices acts as keys (old indices) and its values correspond to the new indices of an operator. If adict
is given, it can only contain the indices to be permuted for higher efficiency.- Returns:
FermionOperator
– PermutedFermionOperator
object.
Examples
>>> op = FermionOperator.ccaa(1,4,5,6) + FermionOperator.ca(0,4) >>> print(op) (1.0, F1^ F4^ F5 F6 ), (1.0, F0^ F4 ) >>> print(op.permuted_operator([0,4,2,3,1,5,6])) (1.0, F4^ F1^ F5 F6 ), (1.0, F0^ F1 ) >>> print(op.permuted_operator({1:4, 4:1})) (1.0, F4^ F1^ F5 F6 ), (1.0, F0^ F1 )
- qubit_encode(mapping=None, qubits=None)
Performs qubit encoding (mapping), using provided mapping class, of this instance.
- Parameters:
mapping (
QubitMapping
, default:None
) –QubitMapping
-derived instance. Default mapping procedure isQubitMappingJordanWigner
.qubits (
Optional
[List
[Qubit
]], default:None
) – The qubit register. If left asNone
, a default register will be assumed if possible. SeeQubitMapping
documentation for further details.
- Returns:
QubitOperator
– MappedQubitOperator
object.
- 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
- 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.
- split()
Generates single-term
FermionOperator
objects.
- 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.
- symmetry_sector(state)
Find the symmetry sector that a fermionic state is in by direct expectation value calculation.
- Parameters:
state (
FermionState
) – Input fermionic state.- Returns:
Union
[complex
,float
,int
] – The symmetry sector of the state (i.e. the expectation value).
Notes
Validity is not checked and providing symmetry-broken states may lead to odd results.
Danger
Due to direct expectation value calculation, this may scale exponentially in the general case, although it should be okay for sparse states and operators e.g. \(\mathbb{Z}_2\) symmetries on number states.
- sympify(*args, **kwargs)
Sympifies dictionary values.
Replaces values with their corresponding symbolic expressions.
- Parameters:
- Returns:
LinearDictCombiner
– Updated instance ofLinearDictCombiner
.- Raises:
RuntimeError – Sympification fails.
- to_ChemistryRestrictedIntegralOperator()
Convert fermion operator into a restricted integral operator.
Uses the
ChemistryRestrictedIntegralOperator.from_FermionOperator()
method internally.- Return type:
ChemistryRestrictedIntegralOperator
- to_ChemistryUnrestrictedIntegralOperator()
Convert fermion operator into an unrestricted integral operator.
Uses the
ChemistryUnrestrictedIntegralOperator.from_FermionOperator()
method internally.- Return type:
ChemistryUnrestrictedIntegralOperator
- to_latex(imaginary_unit='\\\\text{i}', **kwargs)
Generate a LaTeX representation of the operator.
- Parameters:
imaginary_unit (
str
, default:r"\\text{i}"
) – Symbol to use for the imaginary unit.**kwargs – Keyword arguments passed to the
to_latex()
method of component operator strings (FermionOperatorString
orQubitOperatorString
).
- Returns:
str
– LaTeX compilable equation string.
Examples
>>> from inquanto.operators import FermionOperator >>> from sympy import sympify >>> c = sympify("c") >>> fo = FermionOperator([(-c, "F1 F2^"), (c**2, "F1^"), (c, "F0 F5 F3^")]) >>> print(fo.to_latex()) - c a_{1} a_{2}^{\dagger} + c^{2} a_{1}^{\dagger} + c a_{0} a_{5} a_{3}^{\dagger} >>> fo = FermionOperator([(1.0, "F0^ F1^ F3^"), (-1.0j, "F3 F1 F0")]) >>> print(fo.to_latex()) a_{0}^{\dagger} a_{1}^{\dagger} a_{3}^{\dagger} -\text{i} a_{3} a_{1} a_{0} >>> from sympy import sqrt >>> fo = FermionOperator([(sqrt(2), "F0^ F1"), (0.5-8j, "F5 F5^"), (2j, "F1^ F1^")]) >>> print(fo.to_latex(imaginary_unit=r"\text{j}", operator_symbol="f")) \sqrt{2} f_{0}^{\dagger} f_{1} + (0.5-8.0\text{j}) f_{5} f_{5}^{\dagger} + 2.0\text{j} f_{1}^{\dagger} f_{1}^{\dagger}
>>> from inquanto.operators import QubitOperator, QubitOperatorString >>> qos1 = QubitOperatorString.from_string("X1 Y2 Z3") >>> qos2 = QubitOperatorString.from_string("Z0 Y1 X4") >>> qos3 = QubitOperatorString.from_list([(("a", [0]), "I"), (("b", [1]), "Z"), (("c", [2]), "Z")]) >>> qo = QubitOperator({qos1: -1.0, qos2: 3+4j, qos3: c}) >>> print(qo.to_latex()) - X_{1} Y_{2} Z_{3} + (3.0+ 4.0\text{i}) Z_{0} Y_{1} X_{4} + c I_{0} Z_{1} Z_{2} >>> qo = QubitOperator({qos3: 3j}) >>> print(qo.to_latex(imaginary_unit="j", show_labels=True)) 3.0j I^{\text{a}}_{0} Z^{\text{b}}_{1} Z^{\text{c}}_{2}
- trotterize(trotter_number=1, trotter_order=1, constant=1.0, coefficients_location=TrotterizeCoefficientsLocation.OUTER)
Trotterizes the operator, treating the operator as an exponent.
- Assuming that this operator is an exponent, this will generate an instance with each element corresponding to a
single exponent in the Trotter product of exponentials.
- Parameters:
trotter_number (
int
, default:1
) – The number of time-slices in the Trotter approximation.trotter_order (
int
, default:1
) – The order of the Trotter-Suzuki approximation being used. Currently, this supports values1
(i.e. \(AB\)) and2
(i.e. \(A/2\,B/2\,B/2\,A/2\))constant (
Union
[float
,complex
], default:1.0
) – An additional constant factor to multiply each exponent by, which may be useful when, for example, constructing a time evolution operator.coefficients_location (
TrotterizeCoefficientsLocation
, default:TrotterizeCoefficientsLocation.OUTER
) – By default, the coefficient of each term in the input operator is multiplied by the Trotter factor and stored in the outer coefficient of the returned instance, with the coefficient of each innerOperator
set to 1. This behaviour can be controlled with this argument - set to"outer"
for default behaviour. On the other hand, setting this parameter to"inner"
will store all scalars in the innerOperator
coefficient, with the outer coefficients of the returned instance set to 1. Setting this parameter to"mixed"
will store the Trotter factor in the outer coefficients of the returned instance, with the inner coefficients of each term left untouched. See examples for a comparison.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – A Trotterized form of the exponential product, where each element is an individual exponent.
Examples
>>> from inquanto.operators import QubitOperator >>> op1 = QubitOperator("X0 Y1 Z3", 4.6) + QubitOperator("Z1 Z2 Z3 Z5", -5.6j) >>> trotter_operator = op1.trotterize(trotter_number=2) >>> print(trotter_operator) 2.3 [(1.0, X0 Y1 Z3)], -2.8j [(1.0, Z1 Z2 Z3 Z5)], 2.3 [(1.0, X0 Y1 Z3)], -2.8j [(1.0, Z1 Z2 Z3 Z5)] >>> from inquanto.operators import QubitOperator >>> op1 = QubitOperator("X0 Y1 Z3", 4.6) + QubitOperator("Z1 Z2 Z3 Z5", -5.6j) >>> trotter_operator = op1.trotterize(trotter_number=2,coefficients_location="inner") >>> print(trotter_operator) 1.0 [(2.3, X0 Y1 Z3)], 1.0 [(-2.8j, Z1 Z2 Z3 Z5)], 1.0 [(2.3, X0 Y1 Z3)], 1.0 [(-2.8j, Z1 Z2 Z3 Z5)] >>> from inquanto.operators import QubitOperator >>> op1 = QubitOperator("X0 Y1 Z3", 4.6) + QubitOperator("Z1 Z2 Z3 Z5", -5.6j) >>> trotter_operator = op1.trotterize(trotter_number=2,coefficients_location="mixed") >>> print(trotter_operator) 0.5 [(4.6, X0 Y1 Z3)], 0.5 [(-5.6j, Z1 Z2 Z3 Z5)], 0.5 [(4.6, X0 Y1 Z3)], 0.5 [(-5.6j, Z1 Z2 Z3 Z5)]
- truncated(tolerance=1e-8, normal_ordered=True)
Prunes
FermionOperator
terms with coefficients below provided threshold.- Parameters:
tolerance (default:
1e-8
) – Threshold below which terms are removed.normal_ordered (default:
True
) – Should the operator be returned in normal-ordered form.
- Returns:
FermionOperator
– New, modified operator.
Examples
>>> op = FermionOperator.from_string("(0.999, F0 F1^), (0.001, F2^ F1 )") >>> print(op.truncated(tolerance=0.005, normal_ordered=False)) (0.999, F0 F1^) >>> print(op.truncated(tolerance=0.005)) (-0.999, F1^ F0 )
- class SymmetryOperatorFermionicFactorised(data=None, coeff=1.0)
Bases:
FermionOperatorList
,SymmetryOperator
Stores a factorised form of fermionic symmetry operators.
Our symmetry operators may be an exponentiated sum of ladder operator strings. Expanding this out as a single
SymmetryOperatorFermionic
would blow up exponentially. However, we know that many properties can be calculated without this cost - particularly when sets of terms are known to map to single Pauli strings. Here, we store the symmetry operator in factorised form - the overall symmetry operator is the product of those contained in theoperators
member. To make calculation easier, we also enforce that the component operators must all mutually commute.- Parameters:
data (
Union
[FermionOperator
,FermionOperatorString
,List
[Tuple
[Union
[int
,float
,complex
,Expr
],FermionOperator
]]], default:None
)
- class CompressScalarsBehavior(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
-
Governs compression of scalars method behaviour.
- ALL = 'all'
Combine all coefficients possible, simplifying inner terms.
- ONLY_IDENTITIES_AND_ZERO = 'simple'
Only compress based on terms which are a scalar multiple of the identity operator, or zero.
- OUTER = 'outer'
Combine all “outer” coefficients (coefficients stored directly in the top-level OperatorList) into one.
- capitalize()
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
- casefold()
Return a version of the string suitable for caseless comparisons.
- center(width, fillchar=' ', /)
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
- count(sub[, start[, end]]) int
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
- encode(encoding='utf-8', errors='strict')
Encode the string using the codec registered for encoding.
- encoding
The encoding in which to encode the string.
- errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(suffix[, start[, end]]) bool
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
- expandtabs(tabsize=8)
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(*args, **kwargs) str
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).
- format_map(mapping) str
Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).
- index(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- isalnum()
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
- isalpha()
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
- isascii()
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
- isdecimal()
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
- isdigit()
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
- isidentifier()
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.
- islower()
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
- isnumeric()
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.
- isprintable()
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in repr() or if it is empty.
- isspace()
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
- istitle()
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
- isupper()
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
- join(iterable, /)
Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
- ljust(width, fillchar=' ', /)
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
- lower()
Return a copy of the string converted to lowercase.
- lstrip(chars=None, /)
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- static maketrans()
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
- partition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
- removeprefix(prefix, /)
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
- removesuffix(suffix, /)
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
- replace(old, new, count=-1, /)
Return a copy with all occurrences of substring old replaced by new.
- count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
- rfind(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- rjust(width, fillchar=' ', /)
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
- rpartition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
- rsplit(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
- rstrip(chars=None, /)
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the front of the string and works to the end.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
- splitlines(keepends=False)
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
- startswith(prefix[, start[, end]]) bool
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
- strip(chars=None, /)
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase()
Convert uppercase characters to lowercase and lowercase characters to uppercase.
- title()
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
- translate(table, /)
Replace each character in the string using the given translation table.
- table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
- upper()
Return a copy of the string converted to uppercase.
- zfill(width, /)
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
- class FactoryCoefficientsLocation(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
-
Determines where the
from_Operator()
method places coefficients.- INNER = 'inner'
Coefficients are left within the component operators.
- OUTER = 'outer'
Coefficients are moved to be directly stored at the top-level of the OperatorList.
- capitalize()
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
- casefold()
Return a version of the string suitable for caseless comparisons.
- center(width, fillchar=' ', /)
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
- count(sub[, start[, end]]) int
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
- encode(encoding='utf-8', errors='strict')
Encode the string using the codec registered for encoding.
- encoding
The encoding in which to encode the string.
- errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(suffix[, start[, end]]) bool
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
- expandtabs(tabsize=8)
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(*args, **kwargs) str
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).
- format_map(mapping) str
Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).
- index(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- isalnum()
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
- isalpha()
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
- isascii()
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
- isdecimal()
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
- isdigit()
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
- isidentifier()
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.
- islower()
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
- isnumeric()
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.
- isprintable()
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in repr() or if it is empty.
- isspace()
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
- istitle()
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
- isupper()
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
- join(iterable, /)
Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
- ljust(width, fillchar=' ', /)
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
- lower()
Return a copy of the string converted to lowercase.
- lstrip(chars=None, /)
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- static maketrans()
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
- partition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
- removeprefix(prefix, /)
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
- removesuffix(suffix, /)
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
- replace(old, new, count=-1, /)
Return a copy with all occurrences of substring old replaced by new.
- count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
- rfind(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- rjust(width, fillchar=' ', /)
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
- rpartition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
- rsplit(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
- rstrip(chars=None, /)
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the front of the string and works to the end.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
- splitlines(keepends=False)
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
- startswith(prefix[, start[, end]]) bool
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
- strip(chars=None, /)
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase()
Convert uppercase characters to lowercase and lowercase characters to uppercase.
- title()
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
- translate(table, /)
Replace each character in the string using the given translation table.
- table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
- upper()
Return a copy of the string converted to uppercase.
- zfill(width, /)
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
- collapse_as_linear_combination(ignore_outer_coefficients=False)
Treating this instance as a linear combination, return it in the form of an
Operator
.By default, each term is multiplied by its corresponding scalar coefficient, then all such multiplied terms are summed to yield a single
Operator
. The first step may be skipped (i.e. the scalar coefficients associated with each constituentOperator
may be ignored) by settingignore_outer_coefficients
toTrue
.
- collapse_as_product(reverse=False, ignore_outer_coefficients=False)
Treating this instqnce as a product of separate terms, return the full product as an
Operator
.By default, each
Operator
in theOperatorList
is multiplied by its corresponding coefficient, and the product is taken sequentially with the leftmost term given by the first element of theOperatorList
. This behaviour can be reversed with thereverse
parameter - if set toTrue
, the leftmost term will be given by the last element ofOperatorList
.If
ignore_outer_coefficients
is set toTrue
, the first step (the multiplication ofOperator
terms by their corresponding coefficients) is skipped - i.e. the “outer” coefficients stored in theOperatorList
are ignored.Danger
In the general case, the number of terms in the expansion will blow up exponentially (and thus the runtime of this method will also blow up exponentially).
- Parameters:
- Returns:
TypeVar
(OperatorT
, bound= Operator) – The product of each component operator.
- compress_scalars_as_product(abs_tol=1e-12, inner_coefficient=False, coefficients_to_compress=CompressScalarsBehavior.ONLY_IDENTITIES_AND_ZERO)
Treating the
OperatorList
as a product, compress identity terms or resolve to zero if possible.To do this, we iterate through the (coefficient, operator) pairs in the
OperatorList
. If any coefficient or operator is zero, then return an emptyOperatorList
, as the product will be zero. If the iteration operator is an identity, it will be treated as a scalar multiplier, itself multiplied by its associated coefficient, with the operator itself removed from theOperatorList
. These multipliers are multiplied together and – if they do not equate to 1 – are prepended to theOperatorList
as a separate identity term.By default, (coefficient, operator) pairs which are not identity or zero will be ignored. This behaviour may be controlled with the
coefficients_to_compress
parameter. This can be set to"outer"
to include all"outer"
coefficients of the (coefficient, operator) pairs in the prepended identity term. It can also be set to"all"
to additionally bring coefficients within the non-identity operators into the prepended identity term – i.e. for operators where all the “inner” coefficients are equal. See examples for a comparison.The prepended identity term will, by default, store the multiplied scalar factor in the “outer” coefficient of the (coefficient, operator) pair. The
inner_coefficient
parameter may be set toTrue
to instead store it within the operator.Note
Term simplification is not performed on component operators. It is possible that a component operator will resolve on simplification to the identity or zero. This method will not catch these occurrences.
- Parameters:
abs_tol (
float
, default:1e-12
) – Numerical threshold for comparison of numbers to 0 and 1. Set toNone
to use exact identity.inner_coefficient (
bool
, default:False
) – Set toTrue
to store generated scalar factors within the identity term, as described above.coefficients_to_compress (
CompressScalarsBehavior
, default:CompressScalarsBehavior.ONLY_IDENTITIES_AND_ZERO
) – Controls which scalar factors will be combined, as described above.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – TheOperatorList
with identity and zero terms combined, as described above.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0", 2) + QubitOperator("Z1", 2) >>> op2 = 3 * QubitOperator.identity() >>> qol = QubitOperatorList([(5, op1), (7, op2)]) >>> result = qol.compress_scalars_as_product() >>> print(result) 21.0 [(1.0, )], 5 [(2, X0), (2.0, Z1)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0", 2) + QubitOperator("Z1", 2) >>> op2 = 3 * QubitOperator.identity() >>> qol = QubitOperatorList([(5, op1), (7, op2)]) >>> result = qol.compress_scalars_as_product(inner_coefficient=True) >>> print(result) 1 [(21.0, )], 5 [(2, X0), (2.0, Z1)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0", 2) + QubitOperator("Z1", 2) >>> op2 = 3 * QubitOperator.identity() >>> qol = QubitOperatorList([(5, op1), (7, op2)]) >>> result = qol.compress_scalars_as_product(coefficients_to_compress="outer") >>> print(result) 105.0 [(1.0, )], 1.0 [(2, X0), (2.0, Z1)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0", 2) + QubitOperator("Z1", 2) >>> op2 = 3 * QubitOperator.identity() >>> qol = QubitOperatorList([(5, op1), (7, op2)]) >>> result = qol.compress_scalars_as_product(coefficients_to_compress="all") >>> print(result) 210.0 [(1.0, )], 1.0 [(1.0, X0), (1.0, Z1)]
- copy()
Returns a deep copy of this instance.
- Return type:
LinearListCombiner
- df()
Returns a pandas
DataFrame
object of the dictionary.
- evalf(*args, **kwargs)
Numerically evaluates symbolic expressions stored in the left and right values of list items and replaces them with the results.
- free_symbols_ordered()
Returns the free symbols in the coefficients, ordered alphabetically.
- Returns:
SymbolSet
– Ordered set of symbols.
- classmethod from_Operator(input, additional_coefficient=1.0, coefficients_location=FactoryCoefficientsLocation.INNER)
Converts an
Operator
to anOperatorList
with terms in arbitrary order.Each term in the
Operator
is split into a separate componentOperator
in theOperatorList
. The resulting location of each scalar coefficient in the inputOperator
can be controlled with thecoefficients_location
parameter. Setting this to"inner"
will leave coefficients stored as part of the component operators, a value of"outer"
will move the coefficients to the “outer” level.- Parameters:
input (
Operator
) – The input operator to split into anOperatorList
.additional_coefficient (
Union
[int
,float
,complex
,Expr
], default:1.0
) – An additional factor to include in the “outer” coefficients of the generatedOperatorList
.coefficients_location (
FactoryCoefficientsLocation
, default:FactoryCoefficientsLocation.INNER
) – The destination of the coefficients of the input operator, as described above.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – AnOperatorList
as described above.- Raises:
ValueError – On invalid input to the
coefficients_location
parameter.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op = QubitOperator("X0", 2.) + QubitOperator("Z1", 2.) >>> qol = QubitOperatorList.from_Operator(op) >>> print(qol) 1.0 [(2.0, X0)], 1.0 [(2.0, Z1)] >>> op = QubitOperator("X0", 2.) + QubitOperator("Z1", 2.) >>> qol = QubitOperatorList.from_Operator(op,coefficients_location='outer') >>> print(qol) 2.0 [(1.0, X0)], 2.0 [(1.0, Z1)]
- classmethod from_string(input_string)
Constructs a child class instance from a string.
- infer_num_spin_orbs()
Returns the number of modes that the component operators act upon, inferring the existence of modes with index from 0 to the maximum index.
- Returns:
int
– The minimum number of spin orbitals in the Fock space to which this operator list operates on.
Examples
>>> op1 = FermionOperator(FermionOperatorString(((1, 0), (2, 1))), 1.) >>> op2 = FermionOperator(FermionOperatorString(((0, 0), (6, 1))), 1.) >>> fto = FermionOperatorList([(1., op1), (1., op2)]) >>> print(fto.infer_num_spin_orbs()) 7
- is_symmetry_of(operator)
Check if operator is symmetry of given operator.
Checks by determining if operator commutes with all terms of other operator.
True
if it commutes,False
otherwise.- Parameters:
operator (
FermionOperator
) – Operator to compare to.- Returns:
bool
–True
if this is a symmetry ofoperator
, otherwiseFalse
.
Danger
This calls
to_symmetry_operator_fermionic()
and thus may scale exponentially!
- make_hashable()
Return a hashable representation of the object.
- Returns:
str
– A string representation of this instance.
- map(mapping)
Updates right values of items in-place, using a mapping function provided.
- property num_spin_orbs: int
Return the number of spin-orbitals that this operator explicitly acts on.
- operator_class
alias of
FermionOperator
- qubit_encode(mapping=None, qubits=None)
Performs qubit encoding (mapping), using provided mapping function, of the current
FermionOperatorList
.Terms are treated and mapped independently.
- Parameters:
mapping (
QubitMapping
, default:None
) – Mapping class. Default mapping procedure is the Jordan-Wigner transformation.qubits (
Optional
[List
[Qubit
]], 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:
QubitOperatorList
– MappedQubitOperatorList
.
- retrotterize(new_trotter_number, initial_trotter_number=1, new_trotter_order=1, initial_trotter_order=1, constant=1.0, inner_coefficients=False)
Retrotterize an expression given a
OperatorList
representing a product of exponentials.This method assumes that
self
represents a product of exponentials, with each constituentOperator
corresponding to the exponentiated term of a single exponential in a product. Scalar factors within theOperatorList
are treated as scalar multipliers within each exponent.The
OperatorList
is first untrotterized using the providedinitial_trotter_number
andinitial_trotter_order
, then subsequently Trotterized using the providednew_trotter_number
andnew_trotter_order
. The returnedOperatorList
corresponds to the generated product of exponentials, in a similar manner to the originalOperatorList
.- Parameters:
new_trotter_number (
int
) – The desired number of Trotter steps in the final Trotter-Suzuki expansion.initial_trotter_number (
int
, default:1
) – The number of Trotter steps in the original Trotter-Suzuki expansion.new_trotter_order (
int
, default:1
) – The desired order of the final Trotter-Suzuki expansion. Currently, only a first order (\(ABABAB...\)) or second order (\(ABBAABBA...\)) expansion is supported.initial_trotter_order (
int
, default:1
) – The order of the original Trotter-Suzuki expansion used. Currently, only a first order (\(ABABAB...\)) expansion is supported.constant (
Union
[float
,complex
], default:1.0
) – An additional constant multiplier in the exponent.inner_coefficients (
bool
, default:False
) – By default, generated scalar factors in each exponent are stored in the coefficients of the generatedOperatorList
, with the coefficient of each innerOperator
unchanged. Set this toTrue
to instead store all scalar factors as coefficients in eachOperator
, with the outer coefficients of theOperatorList
left unchanged. See examples for a comparison.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) –:- The exponential product retrotterized with the provided new Trotter number and order. Each element is an
individual exponent.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1./2.,op1),(1./2.,op2),(1./2.,op1),(1./2.,op2)]) >>> retrotterised = qol.retrotterize(new_trotter_number=4,initial_trotter_number=2) >>> print(retrotterised) 0.25 [(1.0, X0 X1)], 0.25 [(1.0, Z0)], 0.25 [(1.0, X0 X1)], 0.25 [(1.0, Z0)], 0.25 [(1.0, X0 X1)], 0.25 [(1.0, Z0)], 0.25 [(1.0, X0 X1)], 0.25 [(1.0, Z0)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1./2.,op1),(1./2.,op2),(1./2.,op1),(1./2.,op2)]) >>> retrotterised = qol.retrotterize(new_trotter_number=4,initial_trotter_number=2,inner_coefficients=True) >>> print(retrotterised) 0.5 [(0.5, X0 X1)], 0.5 [(0.5, Z0)], 0.5 [(0.5, X0 X1)], 0.5 [(0.5, Z0)], 0.5 [(0.5, X0 X1)], 0.5 [(0.5, Z0)], 0.5 [(0.5, X0 X1)], 0.5 [(0.5, Z0)]
- reversed_order()
Reverses internal
list
order and returns it as a new object.- Return type:
LinearListCombiner
- simplify(*args, **kwargs)
Simplifies expressions stored in left and right values of list items.
- sublist(sublist_indices)
Returns a new instance containing a subset of the terms in the original object.
- Parameters:
sublist_indices (
list
[int
]) – Indices of elements in this instance selected to constitute a new object.- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – A sublist of this instance.- Raises:
ValueError – If
sublist_indices
contains indices not contained in this instance, or if this instanceis empty. –
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 Y1 Z3", 4.6) >>> op2 = QubitOperator("Z0", -1.6j) >>> op3 = QubitOperator("Z1 Z2 Z3 Z5", -5.6j) >>> long_operator = QubitOperatorList([(1, op1), (1, op2), (1, op3)]) >>> short_operator = long_operator.sublist([0, 2]) >>> print(short_operator) 1 [(4.6, X0 Y1 Z3)], 1 [(-5.6j, Z1 Z2 Z3 Z5)]
- 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
) – Maps symbol-representing keys to the value the symbol should be substituted for.- Returns:
LinearListCombiner
– This instance with symbols key symbols replaced by their values.
- symmetry_sector(state)
Find the symmetry sector that a fermionic state is in by direct expectation value calculation.
As all terms commute, we take the product of their individual expectation values. For certain symmetry operators (e.g. parity operators) this should be polynomially hard.
- Parameters:
state (
FermionState
) – Input fermionic state.- Returns:
Union
[complex
,float
,int
] – The symmetry sector of the state (i.e. the expectation value).
Danger
Due to direct expectation value calculation, this may scale exponentially in the general case, although it should be okay for sparse states and operators e.g. \(\mathbb{Z}_2\) symmetries on number states.
- sympify(*args, **kwargs)
Sympifies left and right values of list items.
Replaces left and right values with their corresponding symbolic expressions.
- Parameters:
- Returns:
LinearListCombiner
– Updated instance ofLinearListCombiner
.- Raises:
RuntimeError – Sympification fails.
- to_symmetry_operator_fermionic()
Convert to a
SymmetryOperatorFermionic
.Danger
This may scale exponentially depending on the operator!
- Returns:
SymmetryOperatorFermionic
– The expanded form of the symmetry operator.
- trotterize_as_linear_combination(trotter_number, trotter_order=1, constant=1.0, inner_coefficients=False)
Trotterize an exponent linear combination of Operators.
This method assumes that
self
represents the exponential of a linear combination ofOperator
objects, each corresponding to a term in this linear combination. Trotterization is performed at the level of theseOperator
instances. TheOperator
objects contained within the returnedOperatorList
correspond to exponents within the Trotter sequence.- Parameters:
trotter_number (
int
) – The number of Trotter steps in the Trotter-Suzuki expansion.trotter_order (
int
, default:1
) – The order of the Trotter-Suzuki approximation to be used. The first- and the second-order options are supported.constant (
Union
[float
,complex
], default:1.0
) – An additional constant multiplier in the exponent.inner_coefficients (
bool
, default:False
) – By default, generated scalar factors in each exponent are stored in the coefficients of the generatedOperatorList
, with the coefficient of each innerOperator
unchanged. Set this toTrue
to instead store all scalar factors as coefficients in eachOperator
, with the outer coefficients of theOperatorList
left unchanged. See examples for a comparison.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – A Trotterized form of the exponential product, where each element is an individual exponent.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1.,op1),(1.,op2)]) >>> result = qol.trotterize_as_linear_combination(2) >>> print(result) 0.5 [(1.0, X0 X1)], 0.5 [(1.0, Z0)], 0.5 [(1.0, X0 X1)], 0.5 [(1.0, Z0)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1.,op1),(1.,op2)]) >>> result = qol.trotterize_as_linear_combination(2,inner_coefficients=True) >>> print(result) 1.0 [(0.5, X0 X1)], 1.0 [(0.5, Z0)], 1.0 [(0.5, X0 X1)], 1.0 [(0.5, Z0)]
- 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 (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:
LinearListCombiner
– Updated instance ofLinearListCombiner
.- Raises:
TypeError – Unsympification fails.
- untrotterize(trotter_number, trotter_order=1)
Reverse a Trotter-Suzuki expansion given a product of exponentials as an
OperatorList
.This method assumes that the
OperatorList
represents a product of exponentials, with eachOperator
in the list corresponding to an exponent of a single exponential in the product. Scalar factors within theOperatorList
are treated as scalar multipliers within each exponent. AnOperator
corresponding to the exponent of a single, untrotterized exponential is returned.- Parameters:
- Returns:
TypeVar
(OperatorT
, bound= Operator) – The exponent of the untrotterised operator.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1./2.,op1),(1./2.,op2),(1./2.,op1),(1./2.,op2)]) >>> untrotterised = qol.untrotterize(2) >>> print(untrotterised) (1.0, X0 X1), (1.0, Z0)
- untrotterize_partitioned(trotter_number, trotter_order=1, inner_coefficients=False)
Reverse a Trotter-Suzuki expansion given a product of exponentials as an
OperatorList
, maintaining separation of exponents.This method assumes that
self
represents a product of exponentials, with each constituentOperator
corresponding to the exponentiated term of a single exponential within a product. Scalar factors within thisOperatorList
are treated as scalar multipliers within each exponent. AOperatorList
is returned wherein each term represents a single term in the exponent of the single, untrotterized exponential.- Parameters:
trotter_number (
int
) – The number of Trotter steps within the Trotter expansion to be reversed.trotter_order (
int
, default:1
) – The order of the Trotter-Suzuki expansion used. Currently, only a first order (\(ABABAB...\)) expansion is supported.inner_coefficients (
bool
, default:False
) – By default, generated scalar factors in each exponent are stored in the coefficients of the generatedOperatorList
, with the coefficient of each innerOperator
unchanged. Set this toTrue
to instead store all scalar factors as coefficients in eachOperator
, with the outer coefficients of theOperatorList
left unchanged. See examples for a comparison.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – The terms in the exponent of the untrotterised operator as aOperatorList
.- Raises:
ValueError – If the provided Trotter number is not compatible with the
OperatorList
.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1./2.,op1),(1./2.,op2),(1./2.,op1),(1./2.,op2)]) >>> untrotterised = qol.untrotterize_partitioned(2) >>> print(untrotterised) 1.0 [(1.0, X0 X1)], 1.0 [(1.0, Z0)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1./2.,op1),(1./2.,op2),(1./2.,op1),(1./2.,op2)]) >>> untrotterised = qol.untrotterize_partitioned(2,inner_coefficients=True) >>> print(untrotterised) 0.5 [(2.0, X0 X1)], 0.5 [(2.0, Z0)]
- class SymmetryOperatorPauli(*args, **kwargs)
Bases:
QubitOperator
,SymmetryOperator
Represents a symmetry operator in a qubit Hilbert space.
This is an extension of
QubitOperator
, providing functionality relating to validating symmetries and finding symmetry sectors.- Parameters:
data – Data defined as a string
"X0 Y1"
, iterable of tuples((0, 'Y'), (1, 'X'))
,QubitOperatorString
, or as a dictionary ofQubitOperatorString
andCoeffType
objects.coeff – Coefficient attached to
data
.
- class TrotterizeCoefficientsLocation(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
-
Determines where coefficients will be stored upon performing Trotterization.
- INNER = 'inner'
All coefficients will be stored in the “inner” coefficients, within the component QubitOperators in the Trotterized result.
- MIXED = 'mixed'
The Trotter step factor will be stored in the “outer” coefficients, whereas the original coefficients of the original Operator will remain in the component Operators.
- OUTER = 'outer'
All coefficients will be stored in the “outer” coefficients, the coefficients stored directly in the generated OperatorList.
- capitalize()
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
- casefold()
Return a version of the string suitable for caseless comparisons.
- center(width, fillchar=' ', /)
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
- count(sub[, start[, end]]) int
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
- encode(encoding='utf-8', errors='strict')
Encode the string using the codec registered for encoding.
- encoding
The encoding in which to encode the string.
- errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(suffix[, start[, end]]) bool
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
- expandtabs(tabsize=8)
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(*args, **kwargs) str
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).
- format_map(mapping) str
Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).
- index(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- isalnum()
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
- isalpha()
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
- isascii()
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
- isdecimal()
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
- isdigit()
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
- isidentifier()
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.
- islower()
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
- isnumeric()
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.
- isprintable()
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in repr() or if it is empty.
- isspace()
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
- istitle()
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
- isupper()
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
- join(iterable, /)
Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
- ljust(width, fillchar=' ', /)
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
- lower()
Return a copy of the string converted to lowercase.
- lstrip(chars=None, /)
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- static maketrans()
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
- partition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
- removeprefix(prefix, /)
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
- removesuffix(suffix, /)
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
- replace(old, new, count=-1, /)
Return a copy with all occurrences of substring old replaced by new.
- count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
- rfind(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- rjust(width, fillchar=' ', /)
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
- rpartition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
- rsplit(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
- rstrip(chars=None, /)
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the front of the string and works to the end.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
- splitlines(keepends=False)
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
- startswith(prefix[, start[, end]]) bool
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
- strip(chars=None, /)
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase()
Convert uppercase characters to lowercase and lowercase characters to uppercase.
- title()
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
- translate(table, /)
Replace each character in the string using the given translation table.
- table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
- upper()
Return a copy of the string converted to uppercase.
- zfill(width, /)
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
- property all_nontrivial_qubits: set[Qubit]
Returns a set of all qubits acted upon by this operator nontrivially (i.e. with an X,Y or Z).
- property all_qubits: Set[Qubit]
- The set of all qubits the operator ranges over (including qubits
that were provided explicitly as identities)
- Return type:
Set[Qubit]
- Type:
return
- anticommutator(other_operator, abs_tol=None)
Calculates the anticommutator with another
QubitOperator
, within a tolerance.- Parameters:
other_operator (
QubitOperator
) – The otherQubitOperator
.abs_tol (
Optional
[float
], default:None
) – Threshold below which terms are deemed negligible.
- Returns:
QubitOperator
– The anticommutator of the two operators.
- anticommutes_with(other_operator, abs_tol=1e-10)
Calculates whether operator anticommutes with another
QubitOperator
, within a tolerance.If both operators are single Pauli strings, we use tket’s
commutes_with()
method and flip the result. Otherwise, it calculates the whole anticommutator and checks if it is zero.- Parameters:
other_operator (
QubitOperator
) – The otherQubitOperator
.abs_tol (
float
, default:1e-10
) – Threshold below which terms are deemed negligible.
- Returns:
bool
–True
if operators anticommute, within tolerance, otherwiseFalse
.
- antihermitian_part()
Return the anti-Hermitian (all imaginary-coefficient terms) part of the original
QubitOperator
.In case the original
QubitOperator
object contains symbolic coefficients that do not have an associated type, those will be cast to the imaginaryExpr
type. :rtype:QubitOperator
Examples
>>> qo = QubitOperator.from_string("(1.0, X0 Y1), (0.1j, Y0 X1), (0.5 + 0.2j, Z0 Z1)") >>> print(qo.antihermitian_part()) (0.1j, Y0 X1), (0.2j, Z0 Z1) >>> a = Symbol('a', real=True) >>> b = Symbol('b', imaginary=True) >>> c = Symbol('c') >>> p_str_a = QubitOperatorString.from_string("X0 Y1") >>> p_str_b = QubitOperatorString.from_string("Y0 X1") >>> p_str_c = QubitOperatorString.from_string("Z0 Z1") >>> qo = QubitOperator({p_str_a: a, p_str_b: b, p_str_c: c}) >>> print(qo.antihermitian_part()) (b, Y0 X1), (1.0*I*im(c), Z0 Z1)
- approx_equal_to(other, abs_tol=1e-10)
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=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.
- as_scalar(abs_tol=None)
If the operator is a sum of identity terms or zero, return the sum of the coefficients, otherwise return
None
.Note that this does not perform combination of terms and will return zero only if all coefficients are zero.
- Parameters:
abs_tol (
float
, default:None
) – Tolerance for checking if coefficients are zero. Set toNone
to test using a standard
:param python
==
comparison.:
- commutator(other_operator, abs_tol=None)
Calculate the commutator with another operator.
Computes commutator. Small terms in the result may be discarded.
- Parameters:
other_operator (
QubitOperator
) – The otherQubitOperator
.abs_tol (
Optional
[float
], default:None
) – Threshold below which terms are discarded. Set to a negative value to skip.
- Returns:
QubitOperator
– The commutator.
- commutes_with(other_operator, abs_tol=1e-10)
Calculates whether operator commutes with another
QubitOperator
, within a tolerance.If both operators are single Pauli strings, we use tket. Otherwise, it calculates the whole commutator and checks if it is zero.
- Parameters:
other_operator (
QubitOperator
) – The otherQubitOperator
.abs_tol (
float
, default:1e-10
) – Threshold below which terms are deemed negligible.
- Returns:
bool
–True
if operators commute, within tolerance, otherwiseFalse
.
- compress(abs_tol=1e-10, symbol_sub_type=CompressSymbolSubType.NONE)
Adapted from
pytket.QubitPauliOperator
to account for non-sympy coefficients.- Parameters:
abs_tol (
float
, default:1e-10
) – The threshold below which to remove values.symbol_sub_type (
CompressSymbolSubType
, 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.
- Return type:
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]\).
- dagger()
Return the Hermitian conjugate of
QubitOperator
.- Return type:
- df()
Returns a Pandas DataFrame object of the dictionary.
- Return type:
DataFrame
- dot_state(state, qubits=None)
Calculate the result of operating on a given qubit state.
Can accept right-hand state as a
QubitState
,QubitStateString
or anumpy.ndarray
. In the former two cases, we maintain a symbolic representation of both operator and state, and each Pauli is implemented in sequence. Resultant states are returned asQubitState
. This should support sympy parametrised states and operators, but the use of parametrised states and operators is untested. In this case, the optional qubits parameter is ignored.For a
numpy.ndarray
, we delegate to pytket’sQubitPauliOperator.dot_state()
method - this should be faster for dense states, but slower for sparse ones. Here, a register of qubits may be specified in thequbits
parameter to determine the meaning of the indices of the provided state vector. From the pytket documentation:When
qubits
is an explicitlist
, the qubits are ordered withqubits[0]
as the most significant qubit for indexing into state.If
None
, qubits sequentially indexed from 0 in the default register and ordered by ILO-BE soQubit(0)
is the most significant.
- Parameters:
state (
Union
[QubitState
,QubitStateString
,ndarray
]) – Input qubit state to operated on.qubits (
Optional
[List
[Qubit
]], default:None
) – For ndarray input, determines sequencing of qubits in the state, if not mapped to the default register. Ignored for other input types.
- Returns:
Union
[QubitState
,ndarray
] – Output state.
- eigenspectrum(hamming_weight=None, nroots=None, threshold=1e-5, check_hermitian=False, check_hermitian_atol=1e-10)
Returns the eigenspectrum of a Hermitian operator, optionally filtered by a given Hamming weight.
More precisely, if
hamming_weight
is provided, only those eigenvalues whose eigenstates’ computational components have coefficients larger thanthreshold
and match the provided Hamming weight will be returned.If argument
nroots
is provided, an iterative sparse matrix diagonalisation procedure is invoked. Otherwise, the whole dense matrix is diagonalised.Notes
If this operator results from a Jordan-Wigner fermion-qubit encoding, filtering by Hamming weight corresponds to particle conservation. The operator is assumed to be Hermitian.
Warning
This method scales exponentially. Use only for testing on small systems.
- Parameters:
hamming_weight (
Optional
[int
], default:None
) – Hamming weight for filtering the roots.nroots (
Optional
[int
], default:None
) – How many roots to calculate (invokes iterative diagonalisation).threshold (
float
, default:1e-5
) – State coefficient threshold for checking Hamming weight.check_hermitian (
bool
, default:False
) – Whether to check the hermiticity of the operator. Usesis_hermitian()
.check_hermitian_atol (
float
, default:1e-10
) – Absolute tolerance for hermiticity check. Passed tois_hermitian()
.
- Returns:
ndarray
– Array of (filtered) eigenvalues.
- ensure_hermitian(tolerance=1e-10)
Eliminate all insignificant imaginary parts of numeric coefficients.
- Raises:
ValueError – imaginary symbolic, or significant imaginary numeric coefficient.
- Parameters:
tolerance (
float
, default:1e-10
) – Threshold determining whether a numerical imag coefficient is significant.- Returns:
QubitOperator
– This instance.
- evalf(*args, **kwargs)
Evaluates symbolic expressions stored in
dict
values and replaces them with the results.
- exponentiate_commuting_operator(additional_exponent=1.0, check_commuting=True)
Exponentiate a
QubitOperator
where all terms commute, returning as a product of operators.As all terms are mutually commuting, exponentiation reduces to a product of exponentials of individual terms (i.e. \(e^{\sum_i{P_i}} = \prod_i{e^{P_i}}\)). Each individual exponential can further be expanded trigonometrically. While storing these as a product is efficient, expanding the product will result in an exponential number of terms, and thus this method returns the result in factorised form, as a
QubitOperatorList
.- Parameters:
- Returns:
QubitOperatorList
– The exponentiated operator in factorised form.- Raises:
ValueError – commutativity checking is performed and the operator is not a commuting set of terms.
- exponentiate_single_term(additional_exponent=1.0, coeff_cutoff=1e-14)
Exponentiates a single weighted Pauli string through trigonometric expansion.
This will except if the operator contains more than one term. It will attempt to maintain single term if rotation is sufficiently close to an integer multiple of \(pi/2\). Set
coeff_cutoff
toNone
to disable this behaviour.- Parameters:
additional_exponent (
complex
, default:1.0
) – Optional additional factor in exponent.coeff_cutoff (
Optional
[float
], default:1e-14
) – If a Pauli string is weighted by an integer multiple of \(pi/2\) and exponentiated, the resulting expansion will have a single Pauli term (as opposed to two). If this parameter is notNone
, it will be used to determine a threshold for cutting off negligible terms in the trigonometric expansion to avoid floating point errors resulting in illusory growth in the number of terms. Set toNone
to disable this behaviour.
- Returns:
QubitOperator
– The exponentiated operator.- Raises:
ValueError – the operator is not a single term.
- 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_QubitPauliOperator(qop, unsympify_coefficients=True)
Generate an instance of this class from a tket
QubitPauliOperator
.Component
QubitPauliString
s will be converted toQubitOperatorString
s. By default, coefficients without free symbols will be converted to float (if real) or complex (otherwise). To disable this, setunsympify_coefficients = False
. For finer grained control over unsympification, generate withunsympify_coefficients = False
and unsympify after generation. Seeunsympify()
for further details.- Parameters:
qop (
QubitPauliOperator
) – TheQubitPauliOperator
to be converted.unsympify_coefficients (
bool
, default:True
) – Whether to cast coefficents to standard python float/complex. Set toFalse
to disable.
- Returns:
The converted operator.
- classmethod from_list(pauli_list)
Construct a QubitPauliOperator from a serializable JSON list format, as returned by QubitPauliOperator.to_list()
- classmethod from_string(input_string)
Constructs a child class instance from a string.
- Parameters:
input_string (
str
) – String in the formatcoeff1 [(coeff1_1, term1_1), ..., (coeff1_n, term1_n)], ..., coeffn [(coeffn_1, termn_1), ...]
.- Returns:
Child class object.
- get(key, default)
Get the coefficient value of the provided Pauli string.
- Parameters:
key (
QubitPauliString
)
- hermitian_factorisation()
Returns a
tuple
of the real and imaginary parts of the originalQubitOperator
.For example, both P and Q from \(O = P + iQ\).
In case the original
QubitOperator
object contains symbolic coefficients that do not have an associated type, those will be cast into both the real and imaginaryExpr
types and assigned to both objects (imaginary component will be multiplied by \(-I\) in order to return its real part).- Returns:
Tuple
[QubitOperator
,QubitOperator
] – Real and imaginary parts of the qubit operator.
Examples
>>> qo = QubitOperator.from_string("(1.0, X0 Y1), (0.1j, Y0 X1), (0.5 + 0.2j, Z0 Z1)") >>> re_qo, im_qo = qo.hermitian_factorisation() >>> print(re_qo) (1.0, X0 Y1), (0.5, Z0 Z1) >>> print(im_qo) (0.1, Y0 X1), (0.2, Z0 Z1) >>> a = Symbol('a', real=True) >>> b = Symbol('b', imaginary=True) >>> c = Symbol('c') >>> p_str_a = QubitOperatorString.from_string("X0 Y1") >>> p_str_b = QubitOperatorString.from_string("Y0 X1") >>> p_str_c = QubitOperatorString.from_string("Z0 Z1") >>> qo = QubitOperator({p_str_a: a, p_str_b: b, p_str_c: c}) >>> re_qo, im_qo = qo.hermitian_factorisation() >>> print(re_qo) (a, X0 Y1), (re(c), Z0 Z1) >>> print(im_qo) (-I*b, Y0 X1), (im(c), Z0 Z1)
- hermitian_part()
Return the Hermitian (all real-coefficient terms) part of the original
QubitOperator
.In case the original
QubitOperator
object contains symbolic coefficients that do not have an associated type, those will be cast to the realExpr
type. :rtype:QubitOperator
Examples
>>> qo = QubitOperator.from_string("(1.0, X0 Y1), (0.1j, Y0 X1), (0.5 + 0.2j, Z0 Z1)") >>> print(qo.hermitian_part()) (1.0, X0 Y1), (0.5, Z0 Z1) >>> a = Symbol('a', real=True) >>> b = Symbol('b', imaginary=True) >>> c = Symbol('c') >>> p_str_a = QubitOperatorString.from_string("X0 Y1") >>> p_str_b = QubitOperatorString.from_string("Y0 X1") >>> p_str_c = QubitOperatorString.from_string("Z0 Z1") >>> qo = QubitOperator({p_str_a: a, p_str_b: b, p_str_c: c}) >>> print(qo.hermitian_part()) (a, X0 Y1), (re(c), Z0 Z1)
- classmethod identity()
Return an identity operator. :rtype:
QubitOperator
Examples
>>> print(QubitOperator.identity()) (1.0, )
- 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_antihermitian(tolerance=1e-10)
Check if operator is anti-Hermitian (purely imaginary coefficients).
Check is performed by looking for symbolic or significant numeric real part in at least one coefficient
- 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_commuting_operator()
Returns
True
if every term in operator commutes with every other term, otherwiseFalse
.- Return type:
- is_hermitian(tolerance=1e-10)
Check if operator is Hermitian.
Check is performed by looking for symbolic or significant numeric imaginary part in at least one coefficient
- static is_hermitian_coeff(coeff, tolerance=1e-10)
Determine whether the given coefficient can be present in a Hermitian
QubitOperator
.
- is_normalized(order=2, abs_tol=1e-10)
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=1e-10)
Returns
True
if other is parallel with this (i.e. a scalar multiple of this), otherwiseFalse
.
- is_self_inverse(abs_tol=1e-10)
Check if operator is its own inverse.
- is_symmetry_of(operator)
Check if operator is symmetry of given operator.
Checks by determining if operator commutes with all terms of other operator.
True
if it commutes,False
otherwise.- Parameters:
operator (
QubitOperator
) – Operator to compare to.- Returns:
bool
–True
if this is a symmetry ofoperator
, otherwiseFalse
.
- is_unit_1norm(abs_tol=1e-10)
Returns True if operator has unit 1-norm, else False.
- is_unit_2norm(abs_tol=1e-10)
Returns True if operator has unit 1-norm, else False.
- is_unit_norm(order=2, abs_tol=1e-10)
Returns True if operator has unit p-norm, else False.
- Parameters:
- Raises:
ValueError – Coefficients contain free symbols.
- Return type:
- is_unitary(abs_tol=1e-10)
Check if operator is unitary.
Checking is performed by multiplying the operator by its Hermitian conjugate and comparing against the identity.
- Parameters:
abs_tol (default:
1e-10
) – Tolerance threshold for comparison with identity.- Returns:
bool
–True
if unitary,False
otherwise.
- static key_from_str(key_str)
Returns a
QubitOperatorString
instance initialised from the input string.- Parameters:
key_str (
str
) – Input python string.- Returns:
QubitOperatorString
– Operator string initialised from input.
- list_class
alias of
QubitOperatorList
- 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 normalised coefficients.
- pad(register_qubits=None, zero_to_max=False)
Modify
QubitOperator
in-place by replacing implicit identities with explicit identities.By default, this will assume a minimal register - i.e. the register contains only qubits acted on by any term in the
QubitOperator
. A specific register of qubits may be provided by setting theregister_qubits
parameter. This must contain all qubits acted on by theQubitOperator
. Alternatively,zero_to_max
may be set toTrue
in order to assume that the qubit register is indexed on \([0, N)\), where \(N\) is the highest integer indexed qubit in the originalQubitOperator
. These modes of operation are incompatible and this method will except ifzero_to_max
is set toTrue
andregister_qubits
is provided. Seepadded()
for a non-in-place version of this method.- Parameters:
- Raises:
PaddingIncompatibleArgumentsError – If register_qubits has been provided while
zero_to_max
is set toTrue
.PaddingInferenceError – If
zero_to_max
is set toTrue
and maximum qubit index cannot be inferred, for instance by non-integer labelled qubits.PaddingInvalidRegisterError – If
QubitOperator
acts on qubits not in provided register.
- Return type:
-
>>> qs = QubitOperator("X0") + QubitOperator("X1") >>> qs.pad() >>> print(qs) (1.0, X0 I1), (1.0, I0 X1)
>>> qs = QubitOperator("X0") >>> qs.pad([Qubit(0),Qubit(1)]) >>> print(qs) (1.0, X0 I1)
>>> qs = QubitOperator("X1") >>> print(qs.padded(zero_to_max=True)) (1.0, I0 X1)
- padded(register_qubits=None, zero_to_max=False)
Return a copy of the
QubitOperator
with implicit identities replaced by explicit identities.By default, this will assume a minimal register - i.e. the register contains only qubits acted on by any term in the
QubitOperator
. A specific register of qubits may be provided by setting theregister_qubits
parameter. This must contain all qubits acted on by theQubitOperator
. Alternatively,zero_to_max
may be set toTrue
in order to assume that the qubit register is indexed on \([0, N)\), where \(N\) is the highest integer indexed qubit in the originalQubitOperator
. These modes of operation are incompatible and this method will except ifzero_to_max
is set toTrue
andregister_qubits
is provided. Seepad()
for an in-place version of this method.- Parameters:
- Raises:
PaddingIncompatibleArgumentsError – If
register_qubits
has been provided whilezero_to_max
is set toTrue
.PaddingInferenceError – If
zero_to_max
is set toTrue
and maximum qubit index cannot be inferred, for instance by non-integer labelled qubits.PaddingInvalidRegisterError – If
QubitOperator
acts on qubits not in provided register.
- Returns:
QubitOperator
– ModifiedQubitOperator
.
Examples
>>> qs = QubitOperator("X0") + QubitOperator("X1") >>> qs_padded = qs.padded() >>> print(qs_padded) (1.0, X0 I1), (1.0, I0 X1)
>>> qs = QubitOperator("X0") >>> qs_padded = qs.padded([Qubit(0),Qubit(1)]) >>> print(qs_padded) (1.0, X0 I1)
>>> qs = QubitOperator("X1") >>> qs_padded = qs.padded(zero_to_max=True) >>> print(qs_padded) (1.0, I0 X1)
- property pauli_strings: List[QubitOperatorString]
Return the Pauli strings within the operator sum as a list.
- qubitwise_anticommutes_with(other_operator)
Calculates whether two single-term QubitOperators qubit-wise anticommute.
Two Pauli strings qubit-wise anticommute if every Pauli acting on a given qubit anticommutes with the Pauli acting on the same qubit in the other string. This necessitates that the Paulis are different, and both non-identity, for every qubit.
This method is currently not defined for
QubitOperator
objects consisting of multiple terms.- Parameters:
other_operator (
QubitOperator
) – The other single-termQubitOperator
.- Returns:
bool
–True
if the operators qubit-wise anticommute, otherwiseFalse
.- Raises:
ValueError – either operator consists of more than a single term.
- qubitwise_commutes_with(other_operator)
Calculates whether two single-term
QubitOperator
s qubit-wise commute.Two Pauli strings qubit-wise commute if every Pauli acting on a given qubit commutes with the Pauli acting on the same qubit in the other string. This necessitates that either the Paulis are the same, or that at least one is an identity.
This method is currently not defined for
QubitOperator
s consisting of multiple terms.- Parameters:
other_operator (
QubitOperator
) – The other single-termQubitOperator
.- Returns:
bool
–True
if the operators qubit-wise commute, otherwiseFalse
.- Raises:
ValueError – either operator consists of more than a single term.
- 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
- 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.
- state_expectation(state, *args, **kwargs)
Calculate expectation value of operator with input state.
Can accept right-hand state as a
QubitState
or anumpy.ndarray
. In the first case, we maintain a symbolic representation of both operator and state, and each Pauli is implemented in sequence. This should support sympy parametrised states and operators, but the use of parametrised states and operators is untested. For anumpy.ndarray
, we delegate to pytket’sQubitPauliOperator.dot_state()
method and return anumpy.ndarray
- this should be faster for dense states, but slower for sparse ones.- Parameters:
state (
Union
[QubitState
,ndarray
]) – The state to be acted upon.*args – Additional arguments passed to
pytket.utils.operators.QubitPauliOperator.state_expectation()
.**kwargs – Additional keyword arguments passed to
pytket.utils.operators.QubitPauliOperator.state_expectation()
.
- Returns:
complex
– Expectation value ofQubitOperator
.
- subs(symbol_map)
Substitution for symbolic expressions.
- Parameters:
symbol_map (
Union
[SymbolDict
,dict
[Union
[str
,Symbol
],Union
[float
,complex
,Expr
,None
]]]) – A map from sympy symbols to sympy expressions, floating-point or complex values.- Returns:
QubitOperator
– A newQubitOperator
object with symbols substituted.
- symbol_substitution(symbol_map=None)
Substitutes free symbols for numerical values according to a map.
- symmetry_sector(state)
Find the symmetry sector that a qubit state is in by direct expectation value calculation.
- Parameters:
state (
QubitState
) – Input qubit state.
Warning
Validity is not checked and providing symmetry-broken states may lead to odd results.
Danger
Due to direct expectation value calculation, this may scale exponentially in the general case, although it should be okay for sparse states and operators e.g. \(\mathbb{Z}_2\) symmetries on number states.
- sympify(*args, **kwargs)
Sympifies dictionary values.
Replaces values with their corresponding symbolic expressions.
- Parameters:
- Returns:
LinearDictCombiner
– Updated instance ofLinearDictCombiner
.- Raises:
RuntimeError – Sympification fails.
- symplectic_representation(qubits=None)
Generate the symplectic representation of the operator.
This is a binary \((M\times 2N)\) matrix where \(M\) is the number of terms and \(N\) is the number of qubits. In the leftmost half of the matrix, the element indexed by
[i,j]
isTrue
where qubitj
is acted on by an \(X\) or a \(Y\) in termi
, and otherwise isFalse
. In the rightmost half, element indexed by[i,j]
isTrue
where qubitj-num_qubits
is acted on by a \(Y\) or a \(Z\) in termi
, and otherwise isFalse
.Notes
If qubits is not specified, a minimal register will be assumed and columns will be assigned to qubits in ascending numerical order by index.
- Parameters:
qubits (
Optional
[List
[Qubit
]], default:None
) – A register of qubits. If not provided, a minimal register is assumed.- Returns:
ndarray
– The symplectic form of this operator- Raises:
ValueError – operator contains qubits which are not in the provided qubits argument.
- to_QubitPauliOperator()
Converts this object to a tket
QubitPauliOperator
.Component
QubitOperatorString
s will be converted to tketQubitPauliString
s. Note that coefficients will implicitly be converted to sympy objects in accordance with theQubitPauliOperator
API.- Returns:
The converted operator.
- to_latex(imaginary_unit='\\\\text{i}', **kwargs)
Generate a LaTeX representation of the operator.
- Parameters:
imaginary_unit (
str
, default:r"\\text{i}"
) – Symbol to use for the imaginary unit.**kwargs – Keyword arguments passed to the
to_latex()
method of component operator strings (FermionOperatorString
orQubitOperatorString
).
- Returns:
str
– LaTeX compilable equation string.
Examples
>>> from inquanto.operators import FermionOperator >>> from sympy import sympify >>> c = sympify("c") >>> fo = FermionOperator([(-c, "F1 F2^"), (c**2, "F1^"), (c, "F0 F5 F3^")]) >>> print(fo.to_latex()) - c a_{1} a_{2}^{\dagger} + c^{2} a_{1}^{\dagger} + c a_{0} a_{5} a_{3}^{\dagger} >>> fo = FermionOperator([(1.0, "F0^ F1^ F3^"), (-1.0j, "F3 F1 F0")]) >>> print(fo.to_latex()) a_{0}^{\dagger} a_{1}^{\dagger} a_{3}^{\dagger} -\text{i} a_{3} a_{1} a_{0} >>> from sympy import sqrt >>> fo = FermionOperator([(sqrt(2), "F0^ F1"), (0.5-8j, "F5 F5^"), (2j, "F1^ F1^")]) >>> print(fo.to_latex(imaginary_unit=r"\text{j}", operator_symbol="f")) \sqrt{2} f_{0}^{\dagger} f_{1} + (0.5-8.0\text{j}) f_{5} f_{5}^{\dagger} + 2.0\text{j} f_{1}^{\dagger} f_{1}^{\dagger}
>>> from inquanto.operators import QubitOperator, QubitOperatorString >>> qos1 = QubitOperatorString.from_string("X1 Y2 Z3") >>> qos2 = QubitOperatorString.from_string("Z0 Y1 X4") >>> qos3 = QubitOperatorString.from_list([(("a", [0]), "I"), (("b", [1]), "Z"), (("c", [2]), "Z")]) >>> qo = QubitOperator({qos1: -1.0, qos2: 3+4j, qos3: c}) >>> print(qo.to_latex()) - X_{1} Y_{2} Z_{3} + (3.0+ 4.0\text{i}) Z_{0} Y_{1} X_{4} + c I_{0} Z_{1} Z_{2} >>> qo = QubitOperator({qos3: 3j}) >>> print(qo.to_latex(imaginary_unit="j", show_labels=True)) 3.0j I^{\text{a}}_{0} Z^{\text{b}}_{1} Z^{\text{c}}_{2}
- to_list()
- Generate a list serialized representation of QubitPauliOperator,
suitable for writing to JSON.
- Returns:
JSON serializable list of dictionaries.
- Return type:
List[Dict[str, Any]]
- to_sparse_matrix(qubits=None)
Represents the sparse operator as a dense operator under the ordering scheme specified by
qubits
, and generates the corresponding matrix.When
qubits
is an explicit list, the qubits are ordered withqubits[0]
as the most significant qubit for indexing into the matrix.If
None
, then no padding qubits are introduced and we use the ILO-BE convention, e.g.Qubit("a", 0)
is more significant thanQubit("a", 1)
orQubit("b")
.Giving a number specifies the number of qubits to use in the final operator, treated as sequentially indexed from 0 in the default register (padding with identities as necessary) and ordered by ILO-BE so
Qubit(0)
is the most significant.
- Parameters:
qubits (Union[List[Qubit], int, None], optional) – Sequencing of qubits in the matrix, either as an explicit list, number of qubits to pad to, or infer from the operator. Defaults to None
- Returns:
A sparse matrix representation of the operator.
- Return type:
csc_matrix
- toeplitz_decomposition()
Returns a tuple of the Hermitian and anti-Hermitian parts of the original
QubitOperator
.In case the original
QubitOperator
object contains symbolic coefficients that do not have an associated type, those will be cast into both the real and imaginaryExpr
types and assigned to both objects.- Returns:
Tuple
[QubitOperator
] – Hermitian and anti-Hermitian parts of operator.
Examples
>>> qo = QubitOperator.from_string("(1.0, X0 Y1), (0.1j, Y0 X1), (0.5 + 0.2j, Z0 Z1)") >>> herm_qo, antiherm_qo = qo.toeplitz_decomposition() >>> print(herm_qo) (1.0, X0 Y1), (0.5, Z0 Z1) >>> print(antiherm_qo) (0.1j, Y0 X1), (0.2j, Z0 Z1) >>> a = Symbol('a', real=True) >>> b = Symbol('b', imaginary=True) >>> c = Symbol('c') >>> p_str_a = QubitOperatorString.from_string("X0 Y1") >>> p_str_b = QubitOperatorString.from_string("Y0 X1") >>> p_str_c = QubitOperatorString.from_string("Z0 Z1") >>> qo = QubitOperator({p_str_a: a, p_str_b: b, p_str_c: c}) >>> herm_qo, antiherm_qo = qo.toeplitz_decomposition() >>> print(herm_qo) (a, X0 Y1), (re(c), Z0 Z1) >>> print(antiherm_qo) (1.0*b, Y0 X1), (1.0*I*im(c), Z0 Z1)
- totally_commuting_decomposition(abs_tol=1e-10)
Decomposes into two separate operators, one including the totally commuting terms and the other including all other terms.
This will return two
QubitOperator
s. The first is comprised of all terms which commute with all other terms, the second comprised of terms which do not. An emptyQubitOperator
will be returned if either of these sets is empty.- Parameters:
abs_tol (
float
, default:1e-10
) – Tolerance threshold used for determining commutativity - seecommutator()
for details.- Returns:
Tuple
[QubitOperator
,QubitOperator
] – The totally commuting operator, and the remainder operator.
- trotterize(trotter_number=1, trotter_order=1, constant=1.0, coefficients_location=TrotterizeCoefficientsLocation.OUTER)
Trotterizes the operator, treating the operator as an exponent.
- Assuming that this operator is an exponent, this will generate an instance with each element corresponding to a
single exponent in the Trotter product of exponentials.
- Parameters:
trotter_number (
int
, default:1
) – The number of time-slices in the Trotter approximation.trotter_order (
int
, default:1
) – The order of the Trotter-Suzuki approximation being used. Currently, this supports values1
(i.e. \(AB\)) and2
(i.e. \(A/2\,B/2\,B/2\,A/2\))constant (
Union
[float
,complex
], default:1.0
) – An additional constant factor to multiply each exponent by, which may be useful when, for example, constructing a time evolution operator.coefficients_location (
TrotterizeCoefficientsLocation
, default:TrotterizeCoefficientsLocation.OUTER
) – By default, the coefficient of each term in the input operator is multiplied by the Trotter factor and stored in the outer coefficient of the returned instance, with the coefficient of each innerOperator
set to 1. This behaviour can be controlled with this argument - set to"outer"
for default behaviour. On the other hand, setting this parameter to"inner"
will store all scalars in the innerOperator
coefficient, with the outer coefficients of the returned instance set to 1. Setting this parameter to"mixed"
will store the Trotter factor in the outer coefficients of the returned instance, with the inner coefficients of each term left untouched. See examples for a comparison.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – A Trotterized form of the exponential product, where each element is an individual exponent.
Examples
>>> from inquanto.operators import QubitOperator >>> op1 = QubitOperator("X0 Y1 Z3", 4.6) + QubitOperator("Z1 Z2 Z3 Z5", -5.6j) >>> trotter_operator = op1.trotterize(trotter_number=2) >>> print(trotter_operator) 2.3 [(1.0, X0 Y1 Z3)], -2.8j [(1.0, Z1 Z2 Z3 Z5)], 2.3 [(1.0, X0 Y1 Z3)], -2.8j [(1.0, Z1 Z2 Z3 Z5)] >>> from inquanto.operators import QubitOperator >>> op1 = QubitOperator("X0 Y1 Z3", 4.6) + QubitOperator("Z1 Z2 Z3 Z5", -5.6j) >>> trotter_operator = op1.trotterize(trotter_number=2,coefficients_location="inner") >>> print(trotter_operator) 1.0 [(2.3, X0 Y1 Z3)], 1.0 [(-2.8j, Z1 Z2 Z3 Z5)], 1.0 [(2.3, X0 Y1 Z3)], 1.0 [(-2.8j, Z1 Z2 Z3 Z5)] >>> from inquanto.operators import QubitOperator >>> op1 = QubitOperator("X0 Y1 Z3", 4.6) + QubitOperator("Z1 Z2 Z3 Z5", -5.6j) >>> trotter_operator = op1.trotterize(trotter_number=2,coefficients_location="mixed") >>> print(trotter_operator) 0.5 [(4.6, X0 Y1 Z3)], 0.5 [(-5.6j, Z1 Z2 Z3 Z5)], 0.5 [(4.6, X0 Y1 Z3)], 0.5 [(-5.6j, Z1 Z2 Z3 Z5)]
- class SymmetryOperatorPauliFactorised(data=None, coeff=1.0)
Bases:
QubitOperatorList
,SymmetryOperator
Stores a factorised form of qubit symmetry operators.
Our symmetry operators may be an exponentiated sum of Pauli operators. Expanding this out as a single
SymmetryOperatorPauli
may blow up exponentially. However, we know that many properties can be calculated without this cost - particularly when sets of terms are known to map to single Pauli strings. Here, we store the symmetry operator in factorised form - the overall symmetry operator is the product of the those contained in theoperators
member. To make calculation easier, we also enforce that the component operators must all mutually commute.- Parameters:
data (
Union
[QubitOperator
,QubitOperatorString
,List
[Tuple
[Union
[int
,float
,complex
,Expr
],QubitOperator
]]], default:None
) – Input data from which the list of qubit operators is built. SeeQubitOperator
for methods of constructing terms.coeff (
Union
[int
,float
,complex
,Expr
], default:1.0
) – Multiplicative scalar coefficient. Used only ifdata
is not of typelist
.
- class CompressScalarsBehavior(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
-
Governs compression of scalars method behaviour.
- ALL = 'all'
Combine all coefficients possible, simplifying inner terms.
- ONLY_IDENTITIES_AND_ZERO = 'simple'
Only compress based on terms which are a scalar multiple of the identity operator, or zero.
- OUTER = 'outer'
Combine all “outer” coefficients (coefficients stored directly in the top-level OperatorList) into one.
- capitalize()
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
- casefold()
Return a version of the string suitable for caseless comparisons.
- center(width, fillchar=' ', /)
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
- count(sub[, start[, end]]) int
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
- encode(encoding='utf-8', errors='strict')
Encode the string using the codec registered for encoding.
- encoding
The encoding in which to encode the string.
- errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(suffix[, start[, end]]) bool
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
- expandtabs(tabsize=8)
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(*args, **kwargs) str
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).
- format_map(mapping) str
Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).
- index(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- isalnum()
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
- isalpha()
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
- isascii()
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
- isdecimal()
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
- isdigit()
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
- isidentifier()
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.
- islower()
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
- isnumeric()
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.
- isprintable()
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in repr() or if it is empty.
- isspace()
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
- istitle()
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
- isupper()
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
- join(iterable, /)
Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
- ljust(width, fillchar=' ', /)
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
- lower()
Return a copy of the string converted to lowercase.
- lstrip(chars=None, /)
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- static maketrans()
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
- partition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
- removeprefix(prefix, /)
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
- removesuffix(suffix, /)
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
- replace(old, new, count=-1, /)
Return a copy with all occurrences of substring old replaced by new.
- count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
- rfind(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- rjust(width, fillchar=' ', /)
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
- rpartition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
- rsplit(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
- rstrip(chars=None, /)
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the front of the string and works to the end.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
- splitlines(keepends=False)
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
- startswith(prefix[, start[, end]]) bool
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
- strip(chars=None, /)
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase()
Convert uppercase characters to lowercase and lowercase characters to uppercase.
- title()
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
- translate(table, /)
Replace each character in the string using the given translation table.
- table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
- upper()
Return a copy of the string converted to uppercase.
- zfill(width, /)
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
- class ExpandExponentialProductCoefficientsBehavior(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
-
Governs behaviour for expansion of exponential products of commuting operators.
- BRING_INTO_OPERATOR = 'compact'
Treat top-level coefficients of the QubitOperatorList as being outside the exponential; multiply generated component QubitOperators by them and return QubitOperatorList with unit top-level coefficients.
- IGNORE = 'ignore'
Drop top-level coefficients entirely.
- IN_EXPONENT = 'inside'
Treat top-level coefficients of the QubitOperatorList as being within the exponent.
- OUTSIDE_EXPONENT = 'outside'
Treat top-level coefficients of the QubitOperatorList as being outside the exponential; return them as top-level coefficients of the generated QubitOperatorList.
- capitalize()
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
- casefold()
Return a version of the string suitable for caseless comparisons.
- center(width, fillchar=' ', /)
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
- count(sub[, start[, end]]) int
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
- encode(encoding='utf-8', errors='strict')
Encode the string using the codec registered for encoding.
- encoding
The encoding in which to encode the string.
- errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(suffix[, start[, end]]) bool
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
- expandtabs(tabsize=8)
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(*args, **kwargs) str
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).
- format_map(mapping) str
Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).
- index(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- isalnum()
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
- isalpha()
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
- isascii()
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
- isdecimal()
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
- isdigit()
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
- isidentifier()
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.
- islower()
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
- isnumeric()
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.
- isprintable()
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in repr() or if it is empty.
- isspace()
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
- istitle()
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
- isupper()
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
- join(iterable, /)
Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
- ljust(width, fillchar=' ', /)
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
- lower()
Return a copy of the string converted to lowercase.
- lstrip(chars=None, /)
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- static maketrans()
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
- partition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
- removeprefix(prefix, /)
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
- removesuffix(suffix, /)
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
- replace(old, new, count=-1, /)
Return a copy with all occurrences of substring old replaced by new.
- count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
- rfind(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- rjust(width, fillchar=' ', /)
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
- rpartition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
- rsplit(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
- rstrip(chars=None, /)
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the front of the string and works to the end.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
- splitlines(keepends=False)
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
- startswith(prefix[, start[, end]]) bool
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
- strip(chars=None, /)
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase()
Convert uppercase characters to lowercase and lowercase characters to uppercase.
- title()
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
- translate(table, /)
Replace each character in the string using the given translation table.
- table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
- upper()
Return a copy of the string converted to uppercase.
- zfill(width, /)
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
- class FactoryCoefficientsLocation(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
-
Determines where the
from_Operator()
method places coefficients.- INNER = 'inner'
Coefficients are left within the component operators.
- OUTER = 'outer'
Coefficients are moved to be directly stored at the top-level of the OperatorList.
- capitalize()
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
- casefold()
Return a version of the string suitable for caseless comparisons.
- center(width, fillchar=' ', /)
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
- count(sub[, start[, end]]) int
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
- encode(encoding='utf-8', errors='strict')
Encode the string using the codec registered for encoding.
- encoding
The encoding in which to encode the string.
- errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(suffix[, start[, end]]) bool
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
- expandtabs(tabsize=8)
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(*args, **kwargs) str
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).
- format_map(mapping) str
Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).
- index(sub[, start[, end]]) int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- isalnum()
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
- isalpha()
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
- isascii()
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
- isdecimal()
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
- isdigit()
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
- isidentifier()
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.
- islower()
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
- isnumeric()
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.
- isprintable()
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in repr() or if it is empty.
- isspace()
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
- istitle()
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
- isupper()
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
- join(iterable, /)
Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
- ljust(width, fillchar=' ', /)
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
- lower()
Return a copy of the string converted to lowercase.
- lstrip(chars=None, /)
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- static maketrans()
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
- partition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
- removeprefix(prefix, /)
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
- removesuffix(suffix, /)
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
- replace(old, new, count=-1, /)
Return a copy with all occurrences of substring old replaced by new.
- count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
- rfind(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(sub[, start[, end]]) int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- rjust(width, fillchar=' ', /)
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
- rpartition(sep, /)
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
- rsplit(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
- rstrip(chars=None, /)
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(sep=None, maxsplit=-1)
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the front of the string and works to the end.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
- splitlines(keepends=False)
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
- startswith(prefix[, start[, end]]) bool
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
- strip(chars=None, /)
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase()
Convert uppercase characters to lowercase and lowercase characters to uppercase.
- title()
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
- translate(table, /)
Replace each character in the string using the given translation table.
- table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
- upper()
Return a copy of the string converted to uppercase.
- zfill(width, /)
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
- property all_nontrivial_qubits: set[Qubit]
Returns a set of all qubits acted upon by the operators in this QubitOperatorList nontrivially (i.e. with an X,Y or Z).
- property all_qubits: Set[Qubit]
Returns a set of all qubits included in any operator in the QubitOperatorList.
- build_subset(indices)
Builds a subset of the class based on a list of indices passed by a user.
- Parameters:
indices (
List
[int
]) – Indices of the items which are selected to for the subset as a newQubitOperatorList
instance.- Raises:
ValueError – the number of requested indices is larger than the number of elements in this instance.
- Returns:
QubitOperatorList
– Subset of terms of the initial object.
- collapse_as_linear_combination(ignore_outer_coefficients=False)
Treating this instance as a linear combination, return it in the form of an
Operator
.By default, each term is multiplied by its corresponding scalar coefficient, then all such multiplied terms are summed to yield a single
Operator
. The first step may be skipped (i.e. the scalar coefficients associated with each constituentOperator
may be ignored) by settingignore_outer_coefficients
toTrue
.
- collapse_as_product(reverse=False, ignore_outer_coefficients=False)
Treating this instqnce as a product of separate terms, return the full product as an
Operator
.By default, each
Operator
in theOperatorList
is multiplied by its corresponding coefficient, and the product is taken sequentially with the leftmost term given by the first element of theOperatorList
. This behaviour can be reversed with thereverse
parameter - if set toTrue
, the leftmost term will be given by the last element ofOperatorList
.If
ignore_outer_coefficients
is set toTrue
, the first step (the multiplication ofOperator
terms by their corresponding coefficients) is skipped - i.e. the “outer” coefficients stored in theOperatorList
are ignored.Danger
In the general case, the number of terms in the expansion will blow up exponentially (and thus the runtime of this method will also blow up exponentially).
- Parameters:
- Returns:
TypeVar
(OperatorT
, bound= Operator) – The product of each component operator.
- compatibility_matrix(abs_tol=1e-10)
Returns the compatibility matrix of the operator list.
This matrix is the adjacency matrix of the compatibility graph of the
OperatorList
. It is a boolean \((N\times N) matrix where :math:`N\) is the number of operators in theOperatorList
. Element indexed by[n,m]
isTrue
if operators indexed byn
andm
commute, otherwiseFalse
.- Parameters:
abs_tol (
float
, default:1e-10
) – Tolerance threshold used for determining commutativity - seeQubitOperator.commutator()
for details.- Returns:
ndarray
– The compatibility matrix of the operator list.
- compress_scalars_as_product(abs_tol=1e-12, inner_coefficient=False, coefficients_to_compress=CompressScalarsBehavior.ONLY_IDENTITIES_AND_ZERO)
Treating the
OperatorList
as a product, compress identity terms or resolve to zero if possible.To do this, we iterate through the (coefficient, operator) pairs in the
OperatorList
. If any coefficient or operator is zero, then return an emptyOperatorList
, as the product will be zero. If the iteration operator is an identity, it will be treated as a scalar multiplier, itself multiplied by its associated coefficient, with the operator itself removed from theOperatorList
. These multipliers are multiplied together and – if they do not equate to 1 – are prepended to theOperatorList
as a separate identity term.By default, (coefficient, operator) pairs which are not identity or zero will be ignored. This behaviour may be controlled with the
coefficients_to_compress
parameter. This can be set to"outer"
to include all"outer"
coefficients of the (coefficient, operator) pairs in the prepended identity term. It can also be set to"all"
to additionally bring coefficients within the non-identity operators into the prepended identity term – i.e. for operators where all the “inner” coefficients are equal. See examples for a comparison.The prepended identity term will, by default, store the multiplied scalar factor in the “outer” coefficient of the (coefficient, operator) pair. The
inner_coefficient
parameter may be set toTrue
to instead store it within the operator.Note
Term simplification is not performed on component operators. It is possible that a component operator will resolve on simplification to the identity or zero. This method will not catch these occurrences.
- Parameters:
abs_tol (
float
, default:1e-12
) – Numerical threshold for comparison of numbers to 0 and 1. Set toNone
to use exact identity.inner_coefficient (
bool
, default:False
) – Set toTrue
to store generated scalar factors within the identity term, as described above.coefficients_to_compress (
CompressScalarsBehavior
, default:CompressScalarsBehavior.ONLY_IDENTITIES_AND_ZERO
) – Controls which scalar factors will be combined, as described above.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – TheOperatorList
with identity and zero terms combined, as described above.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0", 2) + QubitOperator("Z1", 2) >>> op2 = 3 * QubitOperator.identity() >>> qol = QubitOperatorList([(5, op1), (7, op2)]) >>> result = qol.compress_scalars_as_product() >>> print(result) 21.0 [(1.0, )], 5 [(2, X0), (2.0, Z1)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0", 2) + QubitOperator("Z1", 2) >>> op2 = 3 * QubitOperator.identity() >>> qol = QubitOperatorList([(5, op1), (7, op2)]) >>> result = qol.compress_scalars_as_product(inner_coefficient=True) >>> print(result) 1 [(21.0, )], 5 [(2, X0), (2.0, Z1)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0", 2) + QubitOperator("Z1", 2) >>> op2 = 3 * QubitOperator.identity() >>> qol = QubitOperatorList([(5, op1), (7, op2)]) >>> result = qol.compress_scalars_as_product(coefficients_to_compress="outer") >>> print(result) 105.0 [(1.0, )], 1.0 [(2, X0), (2.0, Z1)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0", 2) + QubitOperator("Z1", 2) >>> op2 = 3 * QubitOperator.identity() >>> qol = QubitOperatorList([(5, op1), (7, op2)]) >>> result = qol.compress_scalars_as_product(coefficients_to_compress="all") >>> print(result) 210.0 [(1.0, )], 1.0 [(1.0, X0), (1.0, Z1)]
- compute_jacobian(symbols, as_sympy_sparse=False)
Generate symbolic sparse Jacobian Matrix.
If the number of terms in the operator list is \(N\) and the number of symbols in the symbols
list
is \(M\) then the resultant matrix has a shape \((N, M) and :math:`J_{i,j} = \frac{\partial c_i}{\partial \theta_j}\)- Parameters:
- Returns:
Union
[List
,ImmutableSparseMatrix
] – Jacobian Matrix inlist
oftuple
s of the form(i, j, J_ij)
(this format is referred as a row-sorted list of non-zero elements of the matrix.)
Examples
>>> op0 = QubitOperator("X0 Y2 Z3", 4.6) >>> op1 = QubitOperator(((0, "X"), (1, "Y"), (3, "Z")), 0.1 + 2.0j) >>> op2 = QubitOperator([(0, "X"), (1, "Z"), (3, "Z")], -1.3) >>> qs = QubitOperatorString.from_string("X0 Y1 Y3") >>> op3 = QubitOperator(qs, 0.8) >>> qs0 = QubitOperatorString.from_string("X0 Y1 Z3 X4") >>> qs1 = QubitOperatorString.from_tuple([(0, Pauli.Y), (1, Pauli.X)]) >>> dictionary = {qs0: 2.1, qs1: -1.7j} >>> op4 = QubitOperator(dictionary)
>>> a, b, c = sympify("a,b,c") >>> trotter_operator = QubitOperatorList([(a**3, op1), (2, op2), (b, op3), (c, op4)]) >>> print(trotter_operator) a**3 [(0.1+2j, X0 Y1 Z3)], 2 [(-1.3, X0 Z1 Z3)], b [(0.8, X0 Y1 Y3)], c [(2.1, X0 Y1 Z3 X4), (-1.7j, Y0 X1)]
>>> jacobian_matrix = trotter_operator.compute_jacobian([a, b]) >>> print(jacobian_matrix) [(0, 0, 3*a**2), (2, 1, 1)]
>>> jacobian_matrix = trotter_operator.compute_jacobian([a, b], as_sympy_sparse=True) >>> print(jacobian_matrix) Matrix([[3*a**2, 0], [0, 0], [0, 1], [0, 0]])
- copy()
Returns a deep copy of this instance.
- Return type:
LinearListCombiner
- df()
Returns a pandas
DataFrame
object of the dictionary.
- dot_state_as_linear_combination(state, qubits=None)
Operate upon a state acting as a linear combination of the component operators.
Associated scalar constants are treated as scalar multiplier of their respective QubitOperator terms. This method can accept right-hand state as a
QubitState
,QubitStateString
or anumpy.ndarray
. In the former two cases, we maintain a symbolic representation of both operator and state, and each Pauli is implemented in sequence. Resultant states are returned asQubitState
. In this case, the optional qubits parameter is ignored.For a
numpy.ndarray
, we delegate to pytket’sQubitPauliOperator.dot_state()
method - this should be faster for dense states, but slower for sparse ones. Here, a register of qubits may be specified in thequbits
parameter to determine the meaning of the indices of the provided state vector. From the pytket documentation:When
qubits
is an explicit list, the qubits are ordered withqubits[0]
as the most significant qubit for indexing into state.If
None
, qubits sequentially indexed from 0 in the default register and ordered by ILO-BE soQubit(0)
is the most significant.
- Parameters:
state (
Union
[QubitState
,QubitStateString
,ndarray
]) – Input qubit state to operated on.qubits (
Optional
[List
[Qubit
]], default:None
) – For ndarray input, determines sequencing of qubits in the state, if not mapped to the default register. Ignored for other input types.
- Returns:
Union
[QubitState
,ndarray
] – Output state.
- dot_state_as_product(state, reverse=False, qubits=None)
Operate upon a state with each component operator in sequence, starting from operator indexed 0.
This will apply each operator in sequence, starting from the top of the list - i.e. the top of the list is on the right hand side when acting on a ket. Ordering can be controlled with the
reverse
parameter. Associated scalar constants are treated as scalar multipliers.The right-hand state ket can be accepted as a
QubitState
,QubitStateString
or andarray
. In the former two cases, we maintain a symbolic representation of both operator and state, and each Pauli is implemented in sequence. Resultant states are returned asQubitState
. In this case, thequbits
parameter is ignored.For
ndarray
s, we delegate to pytket’sQubitPauliOperatorString.dot_state()
method - this should be faster for dense states, but slower for sparse ones. Here, a register of qubits may be specified in thequbits
parameter to determine the meaning of the indices of the provided state vector. From the pytket documentation:When
qubits
is an explicit list, the qubits are ordered withqubits[0]
as the most significant qubit for indexing into state.If
None
, qubits sequentially indexed from 0 in the default register and ordered by ILO-BE soQubit(0)
is the most significant.
Danger
In the general case, this will blow up exponentially.
- Parameters:
state (
Union
[QubitState
,QubitStateString
,ndarray
]) – The state to be acted upon.reverse (
bool
, default:False
) – Set toTrue
to reverse order of operations applied (i.e. treat the 0th indexed operator as the leftmost operator).
- Returns:
Union
[QubitState
,ndarray
] – The state yielded from acting on input state in the type as described above.
- equality_matrix(abs_tol=1e-10)
Returns the equality matrix of the operator list.
The equality matrix is a boolean \((N\times N)\) matrix where \(N\) is the number of operators in the
OperatorList
. Element indexed by[n,m]
isTrue
if operators indexed byn
andm
are equal, otherwiseFalse
.- Parameters:
abs_tol (
Optional
[float
], default:1e-10
) – Threshold of comparing numeric values. Set toNone
to test for exact equivalence.- Returns:
ndarray
– The equality matrix of theQubitOperatorList
.
- evalf(*args, **kwargs)
Numerically evaluates symbolic expressions stored in the left and right values of list items and replaces them with the results.
- expand_exponential_product_commuting_operators(expansion_coefficients_behavior=ExpandExponentialProductCoefficientsBehavior.IN_EXPONENT, additional_exponent=1.0, check_commuting=True, combine_scalars=True)
Trigonometrically expand a
QubitOperatorList
representing a product of exponentials of operators with mutually commuting terms.Given a
QubitOperatorList
, this method interprets it as a product of exponentials of the component operators. This means that for aQubitOperatorList
consisting of terms (\(c_i\),:math:hat{O}_i), it is interpreted as \(\prod_i{e^{c_i \hat{O}_i}}\). Component operators must consist of terms which all mutually commute.Each component operator is first expanded as its own exponential product (as they consist of terms which all mutually commute, \(e^{A+B} = e^A e^B\)). Each of the individual exponentiated terms are trigonometrically expanded. These are then concatenated to return a
QubitOperatorList
with the desired form.Notes
Typically this may be used upon an operator generated by Trotterization methods to yield a computable form of the exponential product. While this method scales polynomially, expansion of the resulting operator or calculating its action on a state will typically be exponentially costly.
By default, this method will combine constant scalar multiplicative factors (obtained by, for instance, \(pi\) rotations) into one identity term prepended to the generated
QubitOperatorList
. This behaviour can be disabled by setting combine_scalars toFalse
. For more detail, and for control over the process of combining constant factors, seecompress_scalars_as_product()
.- Parameters:
expansion_coefficients_behavior (
ExpandExponentialProductCoefficientsBehavior
, default:ExpandExponentialProductCoefficientsBehavior.IN_EXPONENT
) – By default, it will be assumed that the “outer” coefficients associated with each component operator are within the exponent, as per the above formula. This may be set to “outside” to instead assume that they are scalar multiples of the exponential itself, rather than the exponent (i.e. \(\prod_i{c_i e^{\hat{O}_i}}\)). In this case, the coefficients will be returned as the outer coefficients of the returned QubitOperatorList, as input. Set to “compact” to assume similar structure to “outside”, but returning coefficients within the componentQubitOperators
. Set to “ignore” to drop the ‘outer’ coefficients entirely. See examples for a comparison.additional_exponent (
complex
, default:1.0
) – Optional additional factor in each exponent.check_commuting (default:
True
) – Set toFalse
to skip checking whether all terms in each component operator commute.combine_scalars (default:
True
) – Set toFalse
to disable combination of identity and zero terms.
- Returns:
QubitOperatorList
– The trigonometrically expanded form of the inputQubitOperatorList
.
Examples
>>> import sympy >>> op= QubitOperator("X0", -1.j * sympy.Symbol('x')) >>> qol = QubitOperatorList([(2, op)]) >>> result = qol.expand_exponential_product_commuting_operators() >>> print(result) 1 [(1.0*cos(2.0*x), ), (-1.0*I*sin(2.0*x), X0)] >>> import sympy >>> op = QubitOperator("X0", -1.j * sympy.Symbol('x')) >>> qol = QubitOperatorList([(2, op)]) >>> result = qol.expand_exponential_product_commuting_operators(expansion_coefficients_behavior="outside") >>> print(result) 2 [(1.0*cos(1.0*x), ), (-1.0*I*sin(1.0*x), X0)] >>> import sympy >>> op = QubitOperator("X0", -1.j * sympy.Symbol('x')) >>> qol = QubitOperatorList([(2, op)]) >>> result = qol.expand_exponential_product_commuting_operators(expansion_coefficients_behavior="ignore") >>> print(result) 1 [(1.0*cos(1.0*x), ), (-1.0*I*sin(1.0*x), X0)] >>> import sympy >>> op = QubitOperator("X0", -1.j * sympy.Symbol('x')) >>> qol = QubitOperatorList([(2, op)]) >>> result = qol.expand_exponential_product_commuting_operators(expansion_coefficients_behavior="compact") >>> print(result) 1.0 [(2.0*cos(1.0*x), ), (-2.0*I*sin(1.0*x), X0)]
- free_symbols_ordered()
Returns the free symbols in the coefficients, ordered alphabetically.
- Returns:
SymbolSet
– Ordered set of symbols.
- classmethod from_Operator(input, additional_coefficient=1.0, coefficients_location=FactoryCoefficientsLocation.INNER)
Converts an
Operator
to anOperatorList
with terms in arbitrary order.Each term in the
Operator
is split into a separate componentOperator
in theOperatorList
. The resulting location of each scalar coefficient in the inputOperator
can be controlled with thecoefficients_location
parameter. Setting this to"inner"
will leave coefficients stored as part of the component operators, a value of"outer"
will move the coefficients to the “outer” level.- Parameters:
input (
Operator
) – The input operator to split into anOperatorList
.additional_coefficient (
Union
[int
,float
,complex
,Expr
], default:1.0
) – An additional factor to include in the “outer” coefficients of the generatedOperatorList
.coefficients_location (
FactoryCoefficientsLocation
, default:FactoryCoefficientsLocation.INNER
) – The destination of the coefficients of the input operator, as described above.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – AnOperatorList
as described above.- Raises:
ValueError – On invalid input to the
coefficients_location
parameter.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op = QubitOperator("X0", 2.) + QubitOperator("Z1", 2.) >>> qol = QubitOperatorList.from_Operator(op) >>> print(qol) 1.0 [(2.0, X0)], 1.0 [(2.0, Z1)] >>> op = QubitOperator("X0", 2.) + QubitOperator("Z1", 2.) >>> qol = QubitOperatorList.from_Operator(op,coefficients_location='outer') >>> print(qol) 2.0 [(1.0, X0)], 2.0 [(1.0, Z1)]
- classmethod from_list(ops, symbol_format='term{}')
Converts a list of
QubitOperator
s to aQubitOperatorList
.Each
QubitOperator
in the list will be a separate entry in the generatedQubitOperatorList
. Fresh symbols will be generated to represent the “outer” coefficients of the generatedQubitOperatorList
.- Parameters:
ops (
List
[QubitOperator
]) –QubitOperator
s which will comprise the terms of the generatedQubitOperatorList
.symbol_format (default:
r"term{}"
) – A raw string containing one positional substitution (in which a numerical index will be placed), used to generate each symbolic coefficient.
- Returns:
QubitOperatorList
– Terms corresponding to the inputQubitOperator
s, and coefficients as newly generated symbols.
- classmethod from_string(input_string)
Constructs a child class instance from a string.
- incompatibility_matrix(abs_tol=1e-10)
Returns the incompatibility matrix of the operator list.
This matrix is the adjacency matrix of the incompatibility graph of the
OperatorList
. It is a boolean \((N\times N) matrix where :math:`N\) is the number of operators in theOperatorList
. Element indexed by[n,m]
isFalse
if operators indexed byn
andm
commute, otherwiseTrue
.- Parameters:
abs_tol (
float
, default:1e-10
) – Tolerance threshold used for determining commutativity - seeQubitOperator.commutator()
for details.- Returns:
ndarray
– The incompatibility matrix of the operator list.
- is_symmetry_of(operator)
Check if operator is symmetry of given operator.
Checks by determining if operator commutes with all terms of other operator.
True
if it commutes,False
otherwise.- Parameters:
operator (
QubitOperator
) – Operator to compare to.- Returns:
bool
–True
if this is a symmetry ofoperator
, otherwiseFalse
.
Danger
This calls
to_symmetry_operator_pauli()
. For standard chemical purposes using \(\mathbb{Z}_2\) symmetries this should be ok, but may scale exponentially when in advanced usage.
- make_hashable()
Return a hashable representation of the object.
- Returns:
str
– A string representation of this instance.
- map(mapping)
Updates right values of items in-place, using a mapping function provided.
- operator_class
alias of
QubitOperator
- parallelity_matrix(abs_tol=1e-10)
Returns the “parallelity matrix” of the operator list.
This matrix is a boolean \((N\times N)\) matrix where \(N\) is the number of operators in the
OperatorList
. Element indexed by[n,m]
isTrue
if operators indexed byn
andm
are parallel - i.e. they are a scalar multiples of each other, otherwiseFalse
.
- qubitwise_compatibility_matrix()
Returns the qubit-wise compatibility matrix of the operator list.
This matrix is the adjacency matrix of the qubit-wise compatibility graph of the
OperatorList
. It is a boolean \((N\times N)\) matrix where \(N\) is the number of operators in theOperatorList
. Element indexed by[n,m]
isTrue
if operators indexed byn
andm
qubit-wise commute, otherwiseFalse
. SeeQubitOperator.qubitwise_commutes_with()
for further details on qubit-wise commutativity.Note that individual
QubitOperator
objects within theOperatorList
must be comprised of single terms for this to be well-defined.- Returns:
ndarray
– The qubit-wise compatibility matrix of the operator list.
- qubitwise_incompatibility_matrix()
Returns the qubit-wise incompatibility matrix of the operator list.
This matrix is the adjacency matrix of the qubit-wise incompatibility graph of the
OperatorList
. It is a boolean \((N\times N) matrix where :math:`N\) is the number of operators in theOperatorList
.Element indexed by
[n,m]
isFalse
if operators indexed byn
andm
qubit-wise commute, otherwiseTrue
. SeeQubitOperator.qubitwise_commutes_with()
for further details on qubit-wise commutativity.Note that individual
QubitOperator
s within theOperatorList
must be comprised of single terms for this to be well-defined.Returns: The qubit-wise incompatibility matrix of the operator list.
- Return type:
ndarray
- reduce_exponents_by_commutation(abs_tol=1e-10)
Given a
QubitOperatorList
representing a product of exponentials, combine terms by commutation.Given a
QubitOperatorList
, this method interprets it as a product of exponentials of the component operators. This means that for aQubitOperatorList
consisting of terms (\(c_i\),:math:hat{O}_i), it is interpreted as \(\prod_i{e^{c_i \hat{O}_i}}\). This method attempts to combine terms which are scalar multiples of one another. Each term is commuted backwards through theQubitOperatorList
until it reaches an operator with which it does not commute with. If it encounters an operator which is a scalar multiple of the term, then the terms are combined. Otherwise, the term is left unchanged.- Parameters:
abs_tol (
float
, default:1e-10
) – Tolerance threshold used for determining commutativity - seeQubitOperator.commutator()
for details.- Returns:
QubitOperatorList
– A reduced form of theQubitOperatorList
as described above.
- retrotterize(new_trotter_number, initial_trotter_number=1, new_trotter_order=1, initial_trotter_order=1, constant=1.0, inner_coefficients=False)
Retrotterize an expression given a
OperatorList
representing a product of exponentials.This method assumes that
self
represents a product of exponentials, with each constituentOperator
corresponding to the exponentiated term of a single exponential in a product. Scalar factors within theOperatorList
are treated as scalar multipliers within each exponent.The
OperatorList
is first untrotterized using the providedinitial_trotter_number
andinitial_trotter_order
, then subsequently Trotterized using the providednew_trotter_number
andnew_trotter_order
. The returnedOperatorList
corresponds to the generated product of exponentials, in a similar manner to the originalOperatorList
.- Parameters:
new_trotter_number (
int
) – The desired number of Trotter steps in the final Trotter-Suzuki expansion.initial_trotter_number (
int
, default:1
) – The number of Trotter steps in the original Trotter-Suzuki expansion.new_trotter_order (
int
, default:1
) – The desired order of the final Trotter-Suzuki expansion. Currently, only a first order (\(ABABAB...\)) or second order (\(ABBAABBA...\)) expansion is supported.initial_trotter_order (
int
, default:1
) – The order of the original Trotter-Suzuki expansion used. Currently, only a first order (\(ABABAB...\)) expansion is supported.constant (
Union
[float
,complex
], default:1.0
) – An additional constant multiplier in the exponent.inner_coefficients (
bool
, default:False
) – By default, generated scalar factors in each exponent are stored in the coefficients of the generatedOperatorList
, with the coefficient of each innerOperator
unchanged. Set this toTrue
to instead store all scalar factors as coefficients in eachOperator
, with the outer coefficients of theOperatorList
left unchanged. See examples for a comparison.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) –:- The exponential product retrotterized with the provided new Trotter number and order. Each element is an
individual exponent.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1./2.,op1),(1./2.,op2),(1./2.,op1),(1./2.,op2)]) >>> retrotterised = qol.retrotterize(new_trotter_number=4,initial_trotter_number=2) >>> print(retrotterised) 0.25 [(1.0, X0 X1)], 0.25 [(1.0, Z0)], 0.25 [(1.0, X0 X1)], 0.25 [(1.0, Z0)], 0.25 [(1.0, X0 X1)], 0.25 [(1.0, Z0)], 0.25 [(1.0, X0 X1)], 0.25 [(1.0, Z0)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1./2.,op1),(1./2.,op2),(1./2.,op1),(1./2.,op2)]) >>> retrotterised = qol.retrotterize(new_trotter_number=4,initial_trotter_number=2,inner_coefficients=True) >>> print(retrotterised) 0.5 [(0.5, X0 X1)], 0.5 [(0.5, Z0)], 0.5 [(0.5, X0 X1)], 0.5 [(0.5, Z0)], 0.5 [(0.5, X0 X1)], 0.5 [(0.5, Z0)], 0.5 [(0.5, X0 X1)], 0.5 [(0.5, Z0)]
- reversed_order()
Reverses internal
list
order and returns it as a new object.n.b. the constructor’s
data
argument expects (coeff, operator) ordering of the elements if it is passed as alist
, butself._list
is stored in (operator, coeff) ordering- Return type:
- simplify(*args, **kwargs)
Simplifies expressions stored in left and right values of list items.
- split_totally_commuting_set(abs_tol=1e-10)
For a
QubitOperatorList
, separate it into a totally commuting part and a remainder.This will return two
QubitOperatorList
instances - the first comprised of all the componentQubitOperator
s which commute with all other terms, the second comprised of all other terms. An emptyQubitOperatorList
will be returned if either of these sets is empty.- Parameters:
abs_tol (
float
, default:1e-10
) – Tolerance threshold used for determining commutativity - seeQubitOperator.commutator()
for details.- Returns:
A pair of
QubitOperatorList
s - the first representing the totally commuting set, the second representing the rest of the operator.
- sublist(sublist_indices)
Returns a new instance containing a subset of the terms in the original object.
- Parameters:
sublist_indices (
list
[int
]) – Indices of elements in this instance selected to constitute a new object.- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – A sublist of this instance.- Raises:
ValueError – If
sublist_indices
contains indices not contained in this instance, or if this instanceis empty. –
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 Y1 Z3", 4.6) >>> op2 = QubitOperator("Z0", -1.6j) >>> op3 = QubitOperator("Z1 Z2 Z3 Z5", -5.6j) >>> long_operator = QubitOperatorList([(1, op1), (1, op2), (1, op3)]) >>> short_operator = long_operator.sublist([0, 2]) >>> print(short_operator) 1 [(4.6, X0 Y1 Z3)], 1 [(-5.6j, Z1 Z2 Z3 Z5)]
- 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
) – Maps symbol-representing keys to the value the symbol should be substituted for.- Returns:
LinearListCombiner
– This instance with symbols key symbols replaced by their values.
- symmetry_sector(state)
Find the symmetry sector that a qubit state is in by direct expectation value calculation.
As all terms commute, we take the product of their individual expectation values. For certain symmetry operators (e.g. parity operators) this should be polynomially hard.
- Parameters:
state (
QubitState
) – Input qubit state.- Returns:
int
– The symmetry sector of the state (i.e. the expectation value).
Danger
Due to direct expectation value calculation, this may scale exponentially in the general case, although it should be okay for sparse states and operators e.g. \(\mathbb{Z}_2\) symmetries on number states.
- sympify(*args, **kwargs)
Sympifies left and right values of list items.
Replaces left and right values with their corresponding symbolic expressions.
- Parameters:
- Returns:
LinearListCombiner
– Updated instance ofLinearListCombiner
.- Raises:
RuntimeError – Sympification fails.
- to_sparse_matrices(qubits=None)
Returns a list of sparse matrices representing each element of the
QubitOperatorList
.Outer coefficients are treated by multiplying their corresponding
QubitOperator
s. Otherwise, this method acts largely as a wrapper forQubitOperator.to_sparse_matrix()
, which derives from the base pytketQubitPauliOperator.to_sparse_matrix()
method. The qubits parameter specifies the ordering scheme for qubits. Note that if no explicit qubits are provided, we use the set of all qubits included in any operator in theQubitOperatorList
(i.e.self.all_qubits
), ordered ILO-BE as per pytket. From the pytket docs:When
qubits
is an explicit list, the qubits are ordered withqubits[0]
as the most significant qubit for indexing into the matrix.If
None
, then no padding qubits are introduced and we use the ILO-BE convention, e.g.Qubit("a",0)
is more significant thanQubit("a",1)
orQubit("b")
.Giving a number specifies the number of qubits to use in the final operator, treated as sequentially indexed from 0 in the default register (padding with identities as necessary) and ordered by ILO-BE so
Qubit(0)
is the most significant.
- to_symmetry_operator_pauli()
Convert to a
SymmetryOperatorPauli
. :rtype:SymmetryOperatorPauli
Warning
For standard chemical purposes using \(\mathbb{Z}_2\) symmetries this should be OK, but may scale exponentially when in advanced usage.
- trotterize_as_linear_combination(trotter_number, trotter_order=1, constant=1.0, inner_coefficients=False)
Trotterize an exponent linear combination of Operators.
This method assumes that
self
represents the exponential of a linear combination ofOperator
objects, each corresponding to a term in this linear combination. Trotterization is performed at the level of theseOperator
instances. TheOperator
objects contained within the returnedOperatorList
correspond to exponents within the Trotter sequence.- Parameters:
trotter_number (
int
) – The number of Trotter steps in the Trotter-Suzuki expansion.trotter_order (
int
, default:1
) – The order of the Trotter-Suzuki approximation to be used. The first- and the second-order options are supported.constant (
Union
[float
,complex
], default:1.0
) – An additional constant multiplier in the exponent.inner_coefficients (
bool
, default:False
) – By default, generated scalar factors in each exponent are stored in the coefficients of the generatedOperatorList
, with the coefficient of each innerOperator
unchanged. Set this toTrue
to instead store all scalar factors as coefficients in eachOperator
, with the outer coefficients of theOperatorList
left unchanged. See examples for a comparison.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – A Trotterized form of the exponential product, where each element is an individual exponent.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1.,op1),(1.,op2)]) >>> result = qol.trotterize_as_linear_combination(2) >>> print(result) 0.5 [(1.0, X0 X1)], 0.5 [(1.0, Z0)], 0.5 [(1.0, X0 X1)], 0.5 [(1.0, Z0)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1.,op1),(1.,op2)]) >>> result = qol.trotterize_as_linear_combination(2,inner_coefficients=True) >>> print(result) 1.0 [(0.5, X0 X1)], 1.0 [(0.5, Z0)], 1.0 [(0.5, X0 X1)], 1.0 [(0.5, Z0)]
- 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 (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:
LinearListCombiner
– Updated instance ofLinearListCombiner
.- Raises:
TypeError – Unsympification fails.
- untrotterize(trotter_number, trotter_order=1)
Reverse a Trotter-Suzuki expansion given a product of exponentials as an
OperatorList
.This method assumes that the
OperatorList
represents a product of exponentials, with eachOperator
in the list corresponding to an exponent of a single exponential in the product. Scalar factors within theOperatorList
are treated as scalar multipliers within each exponent. AnOperator
corresponding to the exponent of a single, untrotterized exponential is returned.- Parameters:
- Returns:
TypeVar
(OperatorT
, bound= Operator) – The exponent of the untrotterised operator.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1./2.,op1),(1./2.,op2),(1./2.,op1),(1./2.,op2)]) >>> untrotterised = qol.untrotterize(2) >>> print(untrotterised) (1.0, X0 X1), (1.0, Z0)
- untrotterize_partitioned(trotter_number, trotter_order=1, inner_coefficients=False)
Reverse a Trotter-Suzuki expansion given a product of exponentials as an
OperatorList
, maintaining separation of exponents.This method assumes that
self
represents a product of exponentials, with each constituentOperator
corresponding to the exponentiated term of a single exponential within a product. Scalar factors within thisOperatorList
are treated as scalar multipliers within each exponent. AOperatorList
is returned wherein each term represents a single term in the exponent of the single, untrotterized exponential.- Parameters:
trotter_number (
int
) – The number of Trotter steps within the Trotter expansion to be reversed.trotter_order (
int
, default:1
) – The order of the Trotter-Suzuki expansion used. Currently, only a first order (\(ABABAB...\)) expansion is supported.inner_coefficients (
bool
, default:False
) – By default, generated scalar factors in each exponent are stored in the coefficients of the generatedOperatorList
, with the coefficient of each innerOperator
unchanged. Set this toTrue
to instead store all scalar factors as coefficients in eachOperator
, with the outer coefficients of theOperatorList
left unchanged. See examples for a comparison.
- Returns:
TypeVar
(OperatorListT
, bound= OperatorList) – The terms in the exponent of the untrotterised operator as aOperatorList
.- Raises:
ValueError – If the provided Trotter number is not compatible with the
OperatorList
.
Examples
>>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1./2.,op1),(1./2.,op2),(1./2.,op1),(1./2.,op2)]) >>> untrotterised = qol.untrotterize_partitioned(2) >>> print(untrotterised) 1.0 [(1.0, X0 X1)], 1.0 [(1.0, Z0)] >>> from inquanto.operators import QubitOperator,QubitOperatorList >>> op1 = QubitOperator("X0 X1", 1.) >>> op2 = QubitOperator("Z0",1.) >>> qol = QubitOperatorList([(1./2.,op1),(1./2.,op2),(1./2.,op1),(1./2.,op2)]) >>> untrotterised = qol.untrotterize_partitioned(2,inner_coefficients=True) >>> print(untrotterised) 0.5 [(2.0, X0 X1)], 0.5 [(2.0, Z0)]
- class UnrestrictedOneBodyRDM(rdm1_aa, rdm1_bb)
Bases:
OneBodyRDM
One-body reduced density matrix in a spin unrestricted representation.
- Parameters:
rdm1_aa (
ndarray
) – Reduced one-body density matrix for the alpha spin channel. \(\text{1RDM}_{ij}^{\alpha} = \langle a_{i,\alpha}^\dagger a_{j,\alpha}\rangle\)rdm1_bb (
ndarray
) – Reduced one-body density matrix for the beta spin channel. \(\text{1RDM}_{ij}^{\beta} = \langle a_{i,\beta}^\dagger a_{j,\beta}\rangle\)
- copy()
Performs a deep copy of object.
- Return type:
RDM
- get_block(mask)
Return a new RDM spanning a subset of the original RDM’s orbitals.
All orbitals not specified in
mask
are ignored.- Parameters:
mask (
ndarray
) – Indices of orbitals to retain.- Returns:
UnrestrictedOneBodyRDM
– New, smaller RDM with only the target orbitals.
- classmethod load_h5(name)
Loads RDM object from .h5 file.
- mean_field_rdm2()
Calculate the mean-field two-body RDM object.
- Returns:
UnrestrictedTwoBodyRDM
– Two body RDM object.
- rotate(rotation_aa, rotation_bb=None)
Rotate the density matrix to a new basis.
- Parameters:
rotation_aa (
ndarray
) – Alpha rotation matrix as 2D array.rotation_bb (
Optional
[ndarray
], default:None
) – Beta rotation matrix as 2D array, if unspecified is set equal torotation_aa
.
- Returns:
UnrestrictedOneBodyRDM
– RDM after rotation.
- save_h5(name)
Dumps RDM object to .h5 file.
- set_block(mask, rdm)
Set the RDM entries for a specified set of orbitals.
- Parameters:
mask (
ndarray
) – Indices of orbitals to be edited.rdm (
UnrestrictedOneBodyRDM
) – RDM object to replace target orbitals.
- Returns:
UnrestrictedOneBodyRDM
– Updated RDM object with target orbitals overwritten.
- class UnrestrictedTwoBodyRDM(rdm2_aaaa, rdm2_bbbb, rdm2_aabb, rdm2_bbaa)
Bases:
RDM
Two-body reduced density matrix in a spin unrestricted representation.
The arguments are two-body reduced density matrices (2-RDM) for spatial orbitals in the aaaa, bbbb, aabb, bbaa spin channels, where a and b stand for alpha and beta.
- Parameters:
rdm2_aaaa (
ndarray
) – 2-RDM for spatial orbitals in the aaaa spin channels as a 4D array. \(\text{2RDM}_{ijkl}^{\alpha\alpha} = \langle a_{i,\alpha}^\dagger a_{k, \alpha}^\dagger a_{l, \alpha} a_{j, \alpha}\rangle\)rdm2_bbbb (
ndarray
) – 2-RDM for spatial orbitals in the bbbb spin channels as a 4D array. \(\text{2RDM}_{ijkl}^{\beta\beta} = \langle a_{i,\beta}^\dagger a_{k, \beta}^\dagger a_{l, \beta} a_{j, \beta}\rangle\)rdm2_aabb (
ndarray
) – 2-RDM for spatial orbitals in the aabb spin channels as a 4D array. \(\text{2RDM}_{ijkl}^{\alpha\beta} = \langle a_{i,\alpha}^\dagger a_{k, \beta}^\dagger a_{l, \beta} a_{j, \alpha}\rangle\)rdm2_bbaa (
ndarray
) – 2-RDM for spatial orbitals in the bbaa spin channels as a 4D array. \(\text{2RDM}_{ijkl}^{\beta\alpha} = \langle a_{i,\beta}^\dagger a_{k, \alpha}^\dagger a_{l, \alpha} a_{j, \beta}\rangle\)
- copy()
Performs a deep copy of object.
- Return type:
RDM
- classmethod load_h5(name)
Loads RDM object from .h5 file.
- rotate(rotation_aa, rotation_bb)
Rotate the density matrix to a new basis.
- Parameters:
rotation_aa (
ndarray
) – Alpha rotation matrix as 2D array.rotation_bb (
ndarray
) – Beta rotation matrix as 2D array.
- Returns:
UnrestrictedTwoBodyRDM
– RDM after rotation.