inquanto.operators¶
InQuanto representation of quantum operators.
 class ChemistryRestrictedIntegralOperator(constant, one_body, two_body, dtype=None)¶
Bases:
BaseChemistryIntegralOperator
Handles a (restrictedorbital) chemistry integral operator.
Stores constant, one and twobody spatial integral values following chemistry notation,
two_body[p, q, r, s]
= \((pqrs)\). Parameters:
constant (
float
) – Constant energy term, electron independent.one_body (
ndarray
) – Onebody integrals.two_body (
ndarray
) – Twobody electron repulsion integrals (ERI).
 TOLERANCE = 1e08¶
Internal tolerance used when iterating over terms. Terms with magnitude smaller than this are not returned by
items()
.
 approx_equal(other, rtol=1.0e5, atol=1.0e8, 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.0e5
) – The relative tolerance parameter, as defined bynumpy.allclose()
.atol (
float
, default:1.0e8
) – 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 twoelectron 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} (ijkl) a_i^\dagger a_j a_k^\dagger a_l\) is a reordered twobody operator and \(\hat{S}\) is a onebody offset term given by \(\hat{S} = \sum_{ij} s_{ij} a_i^\dagger a_j\) where \(s_{ij} = \frac{1}{2}\sum_k (ikkj)\). \(H_0\) and \(\hat{H}_1\) are the constant and oneelectron terms respectively.
The first level of factorization decomposes the electron repulsion integrals tensor into the form: \((pqrs)=\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 lowmagnitude eigenvalues.Onebodylike terms are consolidated and diagonalized by default: \(\tilde{h}_{pq} = h_{pq} + s_{pq} = \sum_r W_{pr} \omega_r W_{qr}\). Onebody diagonalization is not truncated.
Warning
This is not intended for reduction of classical memory usage, only for truncating the twobody 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 onebody integrals \(h_{pq}\).diagonalize_one_body_offset (
bool
, default:True
) – Whether to diagonalize the onebody offset integrals \(s_{pq}\)combine_one_body_terms (
bool
, default:True
) – Whether to consolidate the onebody and onebody offset integrals into effective onebody integrals. Requiresdiagonalize_one_body == diagonalize_one_body_offset
.
 Returns:
DoubleFactorizedHamiltonian
– Hamiltonian operator storing twobody integrals in double factorized form and, optionally, diagonalized onebody integrals.
 property dtype: dtype¶
Returns numpy data type of the twobody integral terms.
 effective_potential(rdm1)¶
Calculates the effective Coulombic potential for a given 1RDM.
 Parameters:
rdm1 (
RestrictedOneBodyRDM
) – Restricted, onebody 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 1RDMs .
 Parameters:
rdm1 (
RestrictedOneBodyRDM
) – Restricted, onebody reduced density matrix object. Returns:
ndarray
– Effective potential matrix.
 energy(rdm1, rdm2=None)¶
Calculate total energy based on the one and twobody reduced density matrices.
If
rdm2
is not given, this method returns the meanfield energy. Parameters:
rdm1 (
RestrictedOneBodyRDM
) – Restricted, onebody reduced density matrix object.rdm2 (
Optional
[RestrictedTwoBodyRDM
], default:None
) – Restricted, twobody reduced density matrix object.
 Returns:
float
– Total energy.
 energy_electron_mean_field(rdm1)¶
Calculates the electronic energy in the meanfield approximation.
 Parameters:
rdm1 (
RestrictedOneBodyRDM
) – Restricted, onebody reduced density matrix object. Returns:
Tuple
[float
,float
] – The meanfield electronic energy (onebody + twobody), and the meanfield Coulomb contribution (twobody only).
 classmethod from_FermionOperator(operator, dtype=float)¶
Convert a twobody fermionic operator to restrictedorbital integral operator.
The onebody terms are stored in a matrix,
_one_body[p, q]
, and the twobody 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 spinrestricted 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 twobody 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, onebody and twobody 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=1e15)¶
Performs an inplace 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 twobody integrals into compact form.
Compacts the twobody integrals into a
CompactTwoBodyIntegrals
object. Parameters:
symmetry (
Union
[int
,str
]) – Target symmetry. Fourfold symmetry (4
,"4"
or"s4"
) or eightfold symmetry (8
,"8"
or"s8"
) are supported. Returns:
ChemistryRestrictedIntegralOperatorCompact
– Equivalent integral operator with twobody integrals stored in compact form.
 two_body_iijj()¶
Returns pairdiagonal elements of twobody integrals, \((iijj)\) in chemist notation.
 Returns:
ndarray
– 2D array of pairdiagonal two bodyintegrals.
 class ChemistryRestrictedIntegralOperatorCompact(constant, one_body, two_body, dtype=None)¶
Bases:
BaseChemistryIntegralOperator
Handles a (restrictedorbital) chemistry integral operator, with integrals stored in a compact form.
Stores constant, one and twobody spatial integral values following chemistry notation, i.e.
two_body[p, q, r, s]
= \((pqrs)\). Twobody 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
) – Onebody energy integrals.two_body (
Union
[CompactTwoBodyIntegralsS4
,CompactTwoBodyIntegralsS8
]) – Twobody electron repulsion integrals (ERI).
 TOLERANCE = 1e08¶
Internal tolerance used when iterating over terms. Terms with magnitude smaller than this are not returned by
items()
.
 approx_equal(other, rtol=1.0e5, atol=1.0e8, 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.0e5
) – The relative tolerance parameter, as defined bynumpy.allclose()
.atol (
float
, default:1.0e8
) – 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 twoelectron 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} (ijkl) a_i^\dagger a_j a_k^\dagger a_l\) is a reordered twobody operator and \(\hat{S}\) is a onebody offset term given by \(\hat{S} = \sum_{ij} s_{ij} a_i^\dagger a_j\) where \(s_{ij} = \frac{1}{2}\sum_k (ikkj)\). \(H_0\) and \(\hat{H}_1\) are the constant and oneelectron terms respectively.
The first level of factorization decomposes the electron repulsion integrals tensor into the form: \((pqrs)=\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 lowmagnitude eigenvalues.Onebodylike terms are consolidated and diagonalized by default: \(\tilde{h}_{pq} = h_{pq} + s_{pq} = \sum_r W_{pr} \omega_r W_{qr}\). Onebody diagonalization is not truncated.
Warning
This is not intended for reduction of classical memory usage, only for truncating the twobody 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 onebody integrals \(h_{pq}\).diagonalize_one_body_offset (
bool
, default:True
) – Whether to diagonalize the onebody offset integrals \(s_{pq}\)combine_one_body_terms (
bool
, default:True
) – Whether to consolidate the onebody and onebody offset integrals into effective onebody integrals. Requiresdiagonalize_one_body == diagonalize_one_body_offset
.
 Returns:
DoubleFactorizedHamiltonian
– Hamiltonian operator storing twobody integrals in double factorized form and, optionally, diagonalized onebody integrals.
 property dtype: dtype¶
Returns numpy data type of the twobody integral terms.
 effective_potential(rdm1)¶
Calculates the effective Coulombic potential for a given 1RDM.
 Parameters:
rdm1 (
RestrictedOneBodyRDM
) – Restricted, onebody 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 1RDMs.
 Parameters:
rdm1 (
RestrictedOneBodyRDM
) – Restricted, onebody reduced density matrix object. Returns:
ndarray
– Effective potential matrix.
 energy(rdm1, rdm2=None)¶
Calculate total energy based on the one and twobody reduced density matrices.
If
rdm2
is not given, this method returns the meanfield energy. Parameters:
rdm1 (
RestrictedOneBodyRDM
) – Restricted, onebody reduced density matrix object.rdm2 (
Optional
[RestrictedTwoBodyRDM
], default:None
) – Restricted, twobody reduced density matrix object.
 Returns:
float
– Total energy.
 energy_electron_mean_field(rdm1)¶
Calculates the electronic energy in the meanfield approximation.
 Parameters:
rdm1 (
RestrictedOneBodyRDM
) – Restricted, onebody reduced density matrix object. Returns:
Tuple
[float
,float
] – The meanfield electronic energy (onebody + twobody), and the meanfield Coulomb contribution (twobody only).
 classmethod from_FermionOperator(operator, dtype=float, symmetry='s4')¶
Convert a 2body fermionic operator to compact, restrictedorbital integral operator.
The onebody terms are stored in a matrix,
_one_body[p, q]
, and the twobody 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. Fourfold symmetry (4
,"4"
or"s4"
) or eightfold 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 twobody 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, onebody and twobody 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=1e15)¶
Performs an inplace unitary rotation of the chemistry integrals.
Rotation must be realvalued (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 twobody integrals into a fourdimensional
numpy.ndarray
. Returns:
Equivalent integral operator object with uncompacted integrals.
 two_body_iijj()¶
Returns pairdiagonal elements of twobody integrals, \((iijj)\) in chemist’s notation.
 Returns:
2D array of pairdiagonal two bodyintegrals.
 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 (unrestrictedorbital) chemistry integral operator.
Stores constant, one and twobody spatial integral values following chemist notation, i.e.
two_body[p, q, r, s]
= \((pqrs)\) Parameters:
constant (
float
) – Constant energy term, electron independent.one_body_aa (
ndarray
) – Onebody integrals for the alpha (a) spin channel.one_body_bb (
ndarray
) – Onebody integrals for the beta (b) spin channel.two_body_aaaa (
ndarray
) – Twobody 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 = 1e08¶
Internal tolerance used when iterating over terms. Terms with magnitude smaller than this are not returned by
items()
.
 approx_equal(other, rtol=1.0e5, atol=1.0e8, 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.0e5
) – The relative tolerance parameter, as defined bynumpy.allclose()
.atol (
float
, default:1.0e8
) – 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 twoelectron 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} (ijkl) a_i^\dagger a_j a_k^\dagger a_l\) is a reordered twobody operator and \(\hat{S}\) is a onebody offset term given by \(\hat{S} = \sum_{ij} s_{ij} a_i^\dagger a_j\) where \(s_{ij} = \frac{1}{2}\sum_k (ikkj)\). \(H_0\) and \(\hat{H}_1\) are the constant and oneelectron terms respectively.
The first level of factorization decomposes the electron repulsion integrals tensor into the form: \((pqrs)=\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 lowmagnitude eigenvalues.Onebodylike terms are consolidated and diagonalized by default: \(\tilde{h}_{pq} = h_{pq} + s_{pq} = \sum_r W_{pr} \omega_r W_{qr}\). Onebody diagonalization is not truncated.
Warning
This is not intended for reduction of classical memory usage, only for truncating the twobody 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 onebody integrals \(h_{pq}\).diagonalize_one_body_offset (
bool
, default:True
) – Whether to diagonalize the onebody offset integrals \(s_{pq}\)combine_one_body_terms (
bool
, default:True
) – Whether to consolidate the onebody and onebody offset integrals into effective onebody integrals. Requiresdiagonalize_one_body == diagonalize_one_body_offset
.
 Returns:
DoubleFactorizedHamiltonian
– Hamiltonian operator storing twobody integrals in double factorized form and, optionally, diagonalized onebody integrals.
 effective_potential(rdm1)¶
Calculates the effective Coulombic potential for a given 1RDM.
 Parameters:
rdm1 (
UnrestrictedOneBodyRDM
) – Unrestricted, onebody 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 twobody reduced density matrices.
If
rdm2
is not given, this method returns the meanfield energy. Parameters:
rdm1 (
UnrestrictedOneBodyRDM
) – Unrestricted, onebody reduced density matrix object.rdm2 (
Optional
[UnrestrictedTwoBodyRDM
], default:None
) – Unrestricted, twobody reduced density matrix object.
 Returns:
float
– Total energy.
 energy_electron_mean_field(rdm1)¶
Calculates the electronic energy in the meanfield approximation.
 Parameters:
rdm1 (
UnrestrictedOneBodyRDM
) – Unrestricted, onebody reduced density matrix object. Returns:
Tuple
[float
,float
] – The meanfield electronic energy (onebody + twobody), and the meanfield Coulomb contribution (twobody only).
 classmethod from_FermionOperator(operator)¶
Convert a 2body fermionic operator to unrestrictedorbital integral operator.
The onebody terms are stored in matrices,
_one_body_aa[p, q]
and_one_body_bb
, and the twobody 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 samespin (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 twobody 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=1e15)¶
Performs an inplace 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:1e15
) – 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 twobody integrals into compact form.
Compacts the twobody integrals into a
CompactTwoBodyIntegrals
object. Parameters:
symmetry (
Union
[int
,str
]) – Target symmetry. Fourfold symmetry (4
,"4"
or"s4"
) or eightfold symmetry (8
,"8"
or"s8"
) are supported. Returns:
ChemistryUnrestrictedIntegralOperatorCompact
– Equivalent integral operator with twobody 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 (unrestrictedorbital) chemistry integral operator, with integrals stored in a compact form.
Stores constant, one and twobody spatial integral values following chemistry notation, i.e.
two_body[p, q, r, s]
= \((pqrs)\). Twobody 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
) – Onebody energy integrals for the alpha (a) spin channel.one_body_bb (
ndarray
) – Onebody energy integrals for the beta (b) spin channel.two_body_aaaa (
Union
[CompactTwoBodyIntegralsS4
,CompactTwoBodyIntegralsS8
]) – Twobody 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 = 1e08¶
Internal tolerance used when iterating over terms. Terms with magnitude smaller than this are not returned by
items()
.
 approx_equal(other, rtol=1.0e5, atol=1.0e8, 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.0e5
) – The relative tolerance parameter, as defined bynumpy.allclose()
.atol (
float
, default:1.0e8
) – 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 twoelectron 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} (ijkl) a_i^\dagger a_j a_k^\dagger a_l\) is a reordered twobody operator and \(\hat{S}\) is a onebody offset term given by \(\hat{S} = \sum_{ij} s_{ij} a_i^\dagger a_j\) where \(s_{ij} = \frac{1}{2}\sum_k (ikkj)\). \(H_0\) and \(\hat{H}_1\) are the constant and oneelectron terms respectively.
The first level of factorization decomposes the electron repulsion integrals tensor into the form: \((pqrs)=\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 lowmagnitude eigenvalues.Onebodylike terms are consolidated and diagonalized by default: \(\tilde{h}_{pq} = h_{pq} + s_{pq} = \sum_r W_{pr} \omega_r W_{qr}\). Onebody diagonalization is not truncated.
Warning
This is not intended for reduction of classical memory usage, only for truncating the twobody 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 onebody integrals \(h_{pq}\).diagonalize_one_body_offset (
bool
, default:True
) – Whether to diagonalize the onebody offset integrals \(s_{pq}\)combine_one_body_terms (
bool
, default:True
) – Whether to consolidate the onebody and onebody offset integrals into effective onebody integrals. Requiresdiagonalize_one_body == diagonalize_one_body_offset
.
 Returns:
DoubleFactorizedHamiltonian
– Hamiltonian operator storing twobody integrals in double factorized form and, optionally, diagonalized onebody integrals.
 effective_potential(rdm1)¶
Calculates the effective Coulombic potential for a given 1RDM.
 Parameters:
rdm1 (
UnrestrictedOneBodyRDM
) – Unrestricted, onebody 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 twobody reduced density matrices.
If
rdm2
is not given, this method returns the meanfield energy. Parameters:
rdm1 (
UnrestrictedOneBodyRDM
) – Unrestricted, onebody reduced density matrix object.rdm2 (
Optional
[UnrestrictedTwoBodyRDM
], default:None
) – Unrestricted, twobody reduced density matrix object.
 Returns:
float
– Total energy.
 energy_electron_mean_field(rdm1)¶
Calculates the electronic energy in the meanfield approximation.
 Parameters:
rdm1 (
UnrestrictedOneBodyRDM
) – Unrestricted, onebody reduced density matrix object. Returns:
Tuple
[float
,float
] – The meanfield electronic energy (onebody + twobody), and the meanfield Coulomb contribution (twobody only).
 classmethod from_FermionOperator(operator, symmetry='s4')¶
Convert a 2body fermionic operator to unrestrictedorbital integral operator.
The onebody terms are stored in matrices,
_one_body_aa[p, q]
and_one_body_bb
, and the twobody 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. Fourfold symmetry (4
,"4"
or"s4"
) or eightfold symmetry (8
,"8"
or"s8"
) are supported.
 Returns:
ChemistryUnrestrictedIntegralOperatorCompact
– Output integral operator.
Warning
The samespin (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 twobody 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=1e15)¶
Performs an inplace unitary rotation of the chemistry integrals.
Each spin block is rotated separately. Rotation must be realvalued (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:1e15
) – 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 twobody integrals into a fourdimensional
numpy.ndarray
. Returns:
ChemistryUnrestrictedIntegralOperator
– Equivalent integral operator object with uncompacted integrals.
 class CompactTwoBodyIntegralsS4(compact_array)¶
Bases:
BaseCompactTwoBodyIntegrals
Stores a twobody integral tensor in
s4
symmetry reduced form.Allows simple, 4indexed
[i,j,k,l]
arraylike access through index transformation. Parameters:
compact_array (
ndarray
) – Twobody integrals in a fourfold symmetryreduced 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.0e5, atol=1.0e8, equal_nan=False)¶
Tests whether the input ERI tensor has fourfold (
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.0e5, atol=1.0e8, equal_nan=False)¶
Builds a compact integrals object from an uncompacted array of two body integrals (a rank4 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.0e5
) – Relative tolerance on symmetry checks.atol (
float
, default:1.0e8
) – 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 twobody 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 twobody 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 twobody 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 twobody 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 twobody integrals tensor.
 Return type:
 class CompactTwoBodyIntegralsS8(compact_array)¶
Bases:
BaseCompactTwoBodyIntegrals
Stores a twobody integral tensor in
s8
symmetry reduced form.Allows simple, 4indexed
[i,j,k,l]
arraylike 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
) – Twobody integrals in an eightfold symmetryreduced 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.0e5, atol=1.0e8, equal_nan=False)¶
Tests whether the input ERI tensor has eightfold (
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.0e5, atol=1.0e8, equal_nan=False)¶
Builds a compact integrals object from an uncompacted array of two body integrals (a rank4 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.0e5
) – Relative tolerance on symmetry checks.atol (
float
, default:1.0e8
) – 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 twobody 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 twobody integrals.
 Returns:
New compact object containing only the real part of the integrals.
 rotate(u)¶
Perform a rotation of the compact twobody 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
Restrictedspin hamiltonian operator, with twobody 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} (ijkl) a_i^\dagger a_j a_k^\dagger a_l\) is a reordered twobody operator and \(\hat{S}\) is a onebody offset to the twobody operator given by \(\hat{S}=\sum_{ij}s_{ij}a_i^\dagger a_j\) where \(s_{ij} = \frac{1}{2}\sum_k (ikkj)\). \(H_0\) and \(\hat{H}_1\) are the constant and oneelectron terms respectively.
Double factorized twobody 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.
Onebodylike terms may be consolidated into a single effectiveonebody term: \(\hat{H}_1' = \hat{H}_1 + \hat{S}\). Onebody term(s) may be stored as arrays, or diagonalized. When diagonalized, onebody 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 (electronindependent) energy.one_body (
Union
[DiagonalizedOneBodyIntegrals
,ndarray
[Any
,dtype
[TypeVar
(_ScalarType_co
, bound=generic
, covariant=True)]]]) – Onebody integrals. These are the physical onebody integrals \(\hat{H}_1\) ifone_body_offset != None
, or effective onebody 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 twobody 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 onebody terms.include_one_body_offset (
bool
, default:True
) – Whether to include the onebody offset terms. Ifone_body_offset == None
, this term is omitted anyway.include_two_body (
bool
, default:True
) – Whether to include the twobody terms.square_two_body_sum (
bool
, default:True
) – Whether to square the linear combination of number operators in the twobody 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 onebody 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\) onebody matrix and \(N\times N\times N\times N\) twobody 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 twobody 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 onebody 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=1e12)¶
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, onebody integrals as a numpy array.two_body (
ndarray
[Any
,dtype
[TypeVar
(_ScalarType_co
, bound=generic
, covariant=True)]]) – The spatial orbital, twobody 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:1e12
) – 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 nonoverlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
 encode(encoding='utf8', 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 alphanumeric string, False otherwise.
A string is alphanumeric if all characters in the string are alphanumeric 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+0000U+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 titlecased string, False otherwise.
In a titlecased string, upper and titlecase 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 leftjustified 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 3tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3tuple 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 rightjustified 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 3tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3tuple 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 postoperation 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=1e10)¶
Checks for equality between this instance and another
FermionOperator
.First, dictionary equivalence is tested for. If
False
, operators are compared in normalordered form, and difference is compared toabs_tol
. Parameters:
other (
FermionOperator
) – An operator to test for equality with.abs_tol (
float
, default:1e10
) – 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=1e10)¶
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 onebody creationannihilation pair with a unit coefficient in its
dict
. Parameters:
 Returns:
The creationannihilation operator pair.
Examples
>>> print(FermionOperator.ca(2, 0)) (1.0, F2^ F0 )
 classmethod caca(a, b, c, d)¶
Return object with a single twobody creationannihilation pair with a unit coefficient in its
dict
.Ordered as creationannihilationcreationannihilation.
 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 twobody 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 twobody creationannihilation pair with a unit coefficient in its
dict
.Ordered as creationcreationannihilationannihilation.
 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 twobody 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=1e10)¶
Returns
True
if this instance commutes withother_operator
(within tolerance), otherwiseFalse
. Parameters:
other_operator (
FermionOperator
) – The other fermionic operator.abs_tol (
float
, default:1e10
) – Tolerance threshold for negligible terms in the commutator.
 Returns:
bool
–True
if operators commute (within tolerance) otherwiseFalse
.
 compress(abs_tol=1e10, symbol_sub_type=CompressSymbolSubType.NONE)¶
Combines duplicate terms, removing those with negligible coefficient.
 Parameters:
abs_tol (
float
, default:1e10
) – 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 spinorbitals, 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 noncomplex value occurs before any free symbols in thedict
values, orTrue
if no noncomplex values occur.
Warning
Returns
None
if a free symbol occurs before any noncomplex values in the coefficients.
 is_all_coeff_imag()¶
Check if all coefficients have purely imaginary values.
 Returns:
bool
–False
if a noncomplex value occurs before any free symbols in thedict
values, orTrue
if no noncomplex values occur.
Warning
Returns
None
if a free symbol occurs before any nonimaginary values in the coefficients.
 is_all_coeff_real()¶
Check if all coefficients have real values.
 Returns:
bool
–False
if a nonreal value occurs before any free symbols in thedict
values, orTrue
if no nonreal values occur.
Warning
Returns
None
if a free symbol occurs before any nonreal 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=1e10)¶
Returns
True
if operator is antiHermitian (within a tolerance), elseFalse
.This explicitly calculates the Hermitian conjugate, multiplies by 1 and tests for equality. Normalordering is performed before comparison.
 Parameters:
abs_tol (
float
, default:1e10
) – Tolerance threshold for negligible terms in comparison. Returns:
bool
–True
if operator is antiHermitian, 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=1e10)¶
Returns
True
if operator is Hermitian (within a tolerance), elseFalse
.This explicitly calculates the Hermitian conjugate and tests for equality. Normalordering is performed before comparison.
 Parameters:
abs_tol (
float
, default:1e10
) – 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 normalordered 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 normalordered,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=1e10)¶
Returns True if operator has unit pnorm, else False.
 Parameters:
 Raises:
ValueError – Coefficients contain free symbols.
 Return type:
 is_parallel_with(other, abs_tol=1e10)¶
Returns
True
if other is parallel with this (i.e. a scalar multiple of this), otherwiseFalse
.
 is_self_inverse(abs_tol=1e10)¶
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. Normalordering is performed before comparison.
 Parameters:
abs_tol (
float
, default:1e10
) – Tolerance threshold for negligible terms in comparison. Returns:
bool
–True
if operator is selfinverse, 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 particlenumber 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=1e10)¶
Returns True if operator has unit 1norm, else False.
 is_unit_2norm(abs_tol=1e10)¶
Returns True if operator has unit 1norm, else False.
 is_unit_norm(order=2, abs_tol=1e10)¶
Returns True if operator has unit pnorm, else False.
 Parameters:
 Raises:
ValueError – Coefficients contain free symbols.
 Return type:
 is_unitary(abs_tol=1e10)¶
Returns True if operator is unitary (within a tolerance), False otherwise.
This explicitly calculates the Hermitian conjugate, rightmultiplies by the initial operator and tests for equality to the identity. Normalordering is performed before comparison.
 Parameters:
abs_tol (
float
, default:1e10
) – 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 pnorm of the coefficients.
 normal_ordered()¶
Returns a normalordered version of
FermionOperator
.Normalordering 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 normalordered 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 spinorbitals 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 singleterm
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:
 to_ChemistryUnrestrictedIntegralOperator()¶
Convert fermion operator into an unrestricted integral operator.
Uses the
ChemistryUnrestrictedIntegralOperator.from_FermionOperator()
method internally. Return type:
 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.58j, "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.58.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 timeslices in the Trotter approximation.trotter_order (
int
, default:1
) – The order of the TrotterSuzuki 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=1e8, normal_ordered=True)¶
Prunes
FermionOperator
terms with coefficients below provided threshold. Parameters:
tolerance (default:
1e8
) – Threshold below which terms are removed.normal_ordered (default:
True
) – Should the operator be returned in normalordered 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 twoelementtuple
s of scalar or symbolic coefficients andFermionOperator
objects. In contrast toFermionOperator
, in this class the ordering of terms is welldefined 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 toplevel 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 nonoverlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
 encode(encoding='utf8', 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 alphanumeric string, False otherwise.
A string is alphanumeric if all characters in the string are alphanumeric 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+0000U+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 titlecased string, False otherwise.
In a titlecased string, upper and titlecase 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 leftjustified 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 3tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3tuple 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 rightjustified 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 3tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3tuple 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 toplevel 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 nonoverlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
 encode(encoding='utf8', 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 alphanumeric string, False otherwise.
A string is alphanumeric if all characters in the string are alphanumeric 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+0000U+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 titlecased string, False otherwise.
In a titlecased string, upper and titlecase 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 leftjustified 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 3tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3tuple 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 rightjustified 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 3tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3tuple 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=1e12, 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 nonidentity 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:1e12
) – 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 inplace, using a mapping function provided.
 property num_spin_orbs: int¶
Return the number of spinorbitals 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 JordanWigner 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 TrotterSuzuki expansion.initial_trotter_number (
int
, default:1
) – The number of Trotter steps in the original TrotterSuzuki expansion.new_trotter_order (
int
, default:1
) – The desired order of the final TrotterSuzuki 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 TrotterSuzuki 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 symbolrepresenting 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 TrotterSuzuki expansion.trotter_order (
int
, default:1
) – The order of the TrotterSuzuki approximation to be used. The first and the secondorder 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 TrotterSuzuki 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 TrotterSuzuki 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 TrotterSuzuki 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 postoperation 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 creationannihilation 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 particleconserving.
 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=1e15)¶
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:1e15
) – 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 GramSchmidt 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\) skewsymmetric matrix from \(n (n  1)/2\) variables.
 Parameters:
variables (
Optional
[array
], default:None
) – Variables to be mapped to a skewsymmetric 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=1e15)¶
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:1e15
) – 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 GramSchmidt 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 nonoverlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
 encode(encoding='utf8', 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 alphanumeric string, False otherwise.
A string is alphanumeric if all characters in the string are alphanumeric 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+0000U+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 titlecased string, False otherwise.
In a titlecased string, upper and titlecase 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 leftjustified 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 3tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3tuple 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 rightjustified 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 3tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3tuple 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[pytket._tket.unit_id.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=1e10)¶
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:1e10
) – Threshold below which terms are deemed negligible.
 Returns:
bool
–True
if operators anticommute, within tolerance, otherwiseFalse
.
 antihermitian_part()¶
Return the antiHermitian (all imaginarycoefficient 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=1e10)¶
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=1e10)¶
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=1e10)¶
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:1e10
) – Threshold below which terms are deemed negligible.
 Returns:
bool
–True
if operators commute, within tolerance, otherwiseFalse
.
 compress(abs_tol=1e10, symbol_sub_type=CompressSymbolSubType.NONE)¶
Adapted from
pytket.QubitPauliOperator
to account for nonsympy coefficients. Parameters:
abs_tol (
float
, default:1e10
) – 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 righthand 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 ILOBE 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=1e5, check_hermitian=False, check_hermitian_atol=1e10)¶
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 JordanWigner fermionqubit 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:1e5
) – 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:1e10
) – Absolute tolerance for hermiticity check. Passed tois_hermitian()
.
 Returns:
ndarray
– Array of (filtered) eigenvalues.
 ensure_hermitian(tolerance=1e10)¶
Eliminate all insignificant imaginary parts of numeric coefficients.
 Raises:
ValueError – imaginary symbolic, or significant imaginary numeric coefficient.
 Parameters:
tolerance (
float
, default:1e10
) – 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=1e14)¶
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:1e14
) – 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 realcoefficient 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 noncomplex value occurs before any free symbols in thedict
values, orTrue
if no noncomplex values occur.
Warning
Returns
None
if a free symbol occurs before any noncomplex values in the coefficients.
 is_all_coeff_imag()¶
Check if all coefficients have purely imaginary values.
 Returns:
bool
–False
if a noncomplex value occurs before any free symbols in thedict
values, orTrue
if no noncomplex values occur.
Warning
Returns
None
if a free symbol occurs before any nonimaginary values in the coefficients.
 is_all_coeff_real()¶
Check if all coefficients have real values.
 Returns:
bool
–False
if a nonreal value occurs before any free symbols in thedict
values, orTrue
if no nonreal values occur.
Warning
Returns
None
if a free symbol occurs before any nonreal 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=1e10)¶
Check if operator is antiHermitian (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=1e10)¶
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=1e10)¶
Determine whether the given coefficient can be present in a Hermitian
QubitOperator
.
 is_normalized(order=2, abs_tol=1e10)¶
Returns True if operator has unit pnorm, else False.
 Parameters:
 Raises:
ValueError – Coefficients contain free symbols.
 Return type:
 is_parallel_with(other, abs_tol=1e10)¶
Returns
True
if other is parallel with this (i.e. a scalar multiple of this), otherwiseFalse
.
 is_self_inverse(abs_tol=1e10)¶
Check if operator is its own inverse.
 is_unit_1norm(abs_tol=1e10)¶
Returns True if operator has unit 1norm, else False.
 is_unit_2norm(abs_tol=1e10)¶
Returns True if operator has unit 1norm, else False.
 is_unit_norm(order=2, abs_tol=1e10)¶
Returns True if operator has unit pnorm, else False.
 Parameters:
 Raises:
ValueError – Coefficients contain free symbols.
 Return type:
 is_unitary(abs_tol=1e10)¶
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:
1e10
) – 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 pnorm 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
inplace 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