inquanto.operators

InQuanto representation of quantum operators.

class ChemistryRestrictedIntegralOperator(constant, one_body, two_body, dtype=None)

Bases: BaseChemistryIntegralOperator

Handles a (restricted-orbital) chemistry integral operator.

Stores constant, one- and two-body spatial integral values following chemistry notation, two_body[p, q, r, s] = \((pq|rs)\).

Parameters:
  • constant (float) – Constant energy term, electron independent.

  • one_body (ndarray) – One-body integrals.

  • two_body (ndarray) – Two-body electron repulsion integrals (ERI).

TOLERANCE = 1e-08

Internal tolerance used when iterating over terms. Terms with magnitude smaller than this are not returned by items().

approx_equal(other, rtol=1.0e-5, atol=1.0e-8, equal_nan=False)

Test for approximate equality with another instance of this class by comparing integral arrays.

Arguments are passed directly to numpy.allclose() for equality comparison - see numpy documentation for further details.

Parameters:
  • other (ChemistryRestrictedIntegralOperator) – The other operator to compare for approximate equality.

  • rtol (float, default: 1.0e-5) – The relative tolerance parameter, as defined by numpy.allclose().

  • atol (float, default: 1.0e-8) – The absolute tolerance parameter, as defined by numpy.allclose().

  • equal_nan (default: False) – Whether to compare NaN’s as equal, as defined by numpy.allclose().

Returns:

boolTrue if other instance is approximately equal to this one, otherwise False.

astype(dtype)

Returns a copy of the current integral operator, cast to a new dtype.

Parameters:

dtype (Any) – The dtype to cast into.

Returns:

ChemistryRestrictedIntegralOperator – New integral operator with components cast to dtype.

copy()

Performs a deep copy of object.

Return type:

BaseChemistryIntegralOperator

df()

Returns a pandas.DataFrame object showing all terms in the operator.

Return type:

DataFrame

double_factorize(tol1=-1.0, tol2=None, method=DecompositionMethod.EIG, diagonalize_one_body=True, diagonalize_one_body_offset=True, combine_one_body_terms=True)

Double factorizes the two-electron integrals and returns the Hamiltonian in diagonal form.

The Hamiltonian can be written as \(\hat{H} = H_0 + \hat{H}_1 + \hat{S} + \hat{V}\) where \(\hat{S}+\hat{V}\) is the Coulomb interaction. \(V = \frac{1}{2}\sum_{ijkl} (ij|kl) a_i^\dagger a_j a_k^\dagger a_l\) is a reordered two-body operator and \(\hat{S}\) is a one-body offset term given by \(\hat{S} = \sum_{ij} s_{ij} a_i^\dagger a_j\) where \(s_{ij} = -\frac{1}{2}\sum_k (ik|kj)\). \(H_0\) and \(\hat{H}_1\) are the constant and one-electron terms respectively.

The first level of factorization decomposes the electron repulsion integrals tensor into the form: \((pq|rs)=\sum_t^{N_\gamma} V_{pq}^t \gamma^t V_{rs}^t\). This may be performed using an eigenvalue decomposition (method='eig'), or a pivoted, incomplete Cholesky decomposition (method="cho") (see J. Chem. Phys. 118, 9481–9484 (2003) and J. Chem. Phys. 139, 134105 (2013)). The second factorization is diagonalization of the \(V_{pq}^t\) matrix for each t: \(V_{pq}^t = \sum_u^{N_\lambda^t} U_{pu}^t \lambda_u^t U_{qu}^t\).

At the first factorization stage, truncation depends on the decomposition method. With "eig", truncation is performed by discarding eigenvalues, starting from the smallest in magnitude, until the sum of those discarded magnitudes exceeds the threshold tol1. With "cho", the decomposition is constructed iteratively until the error is less than tol1. At the second factorization level, truncation is always performed by discarding low-magnitude eigenvalues.

One-body-like terms are consolidated and diagonalized by default: \(\tilde{h}_{pq} = h_{pq} + s_{pq} = \sum_r W_{pr} \omega_r W_{qr}\). One-body diagonalization is not truncated.

Warning

This is not intended for reduction of classical memory usage, only for truncating the two-body terms of the Hamiltonian for quantum simulation.

Parameters:
  • tol1 (float, default: -1.0) – Truncation threshold for first diagonalization of ERI matrix. If negative, no truncation is performed.

  • tol2 (Optional[float], default: None) – Truncation threshold for second diagonalization of ERI matrix. If None, same as tol1. If negative, no truncation is performed.

  • method (Union[DecompositionMethod, str], default: DecompositionMethod.EIG) – Decomposition method used for the first level of factorization. "eig" for an eigenvalue decomposition, "cho" for a pivoted, incomplete Cholesky decomposition.

  • diagonalize_one_body (bool, default: True) – Whether to diagonalize the physical one-body integrals \(h_{pq}\).

  • diagonalize_one_body_offset (bool, default: True) – Whether to diagonalize the one-body offset integrals \(s_{pq}\)

  • combine_one_body_terms (bool, default: True) – Whether to consolidate the one-body and one-body offset integrals into effective one-body integrals. Requires diagonalize_one_body == diagonalize_one_body_offset.

Returns:

DoubleFactorizedHamiltonian – Hamiltonian operator storing two-body integrals in double factorized form and, optionally, diagonalized one-body integrals.

property dtype: dtype

Returns numpy data type of the two-body integral terms.

effective_potential(rdm1)

Calculates the effective Coulombic potential for a given 1-RDM.

Parameters:

rdm1 (RestrictedOneBodyRDM) – Restricted, one-body reduced density matrix object.

Returns:

ndarray – Effective potential matrix.

effective_potential_spin(rdm1)

Calculates the contribution to the effective Coulomb potential due to a spin imbalance.

This is defined as the contribution to the effective potential matrix from the difference of the alpha and beta 1-RDMs .

Parameters:

rdm1 (RestrictedOneBodyRDM) – Restricted, one-body reduced density matrix object.

Returns:

ndarray – Effective potential matrix.

energy(rdm1, rdm2=None)

Calculate total energy based on the one- and two-body reduced density matrices.

If rdm2 is not given, this method returns the mean-field energy.

Parameters:
Returns:

float – Total energy.

energy_electron_mean_field(rdm1)

Calculates the electronic energy in the mean-field approximation.

Parameters:

rdm1 (RestrictedOneBodyRDM) – Restricted, one-body reduced density matrix object.

Returns:

Tuple[float, float] – The mean-field electronic energy (one-body + two-body), and the mean-field Coulomb contribution (two-body only).

classmethod from_FermionOperator(operator, dtype=float)

Convert a two-body fermionic operator to restricted-orbital integral operator.

The one-body terms are stored in a matrix, _one_body[p, q], and the two-body terms are stored in a tensor, _two_body[p, q, r, s].

Parameters:
  • operator (FermionOperator) – Input fermionic operator.

  • dtype (default: float) – Desired term value dtype.

Returns:

ChemistryRestrictedIntegralOperator – The converted operator.

Warning

This converter assumes that operator represents a spin-restricted operator.

static from_fcidump(filename)

Generate a ChemistryRestrictedIntegralOperator object from an FCIDUMP file.

FCIDUMP files typically contain information regarding the molecular orbital integrals, number of orbitals, number of electrons, spin and spatial symmetry. Only the symmetry information is discarded by this method.

Parameters:

filename (str) – The FCIDUMP filename.

Returns:

Tuple[ChemistryRestrictedIntegralOperator, int, int, int] – A tuple containing the operator generated from the FCIDUMP file, the number of orbitals in the system, the number of electrons in the system, and the spin multiplicity of the system.

property imag: ChemistryRestrictedIntegralOperator

Extract the imaginary part of the integral operator.

Returns:

New integral operator object with only the imaginary parts of all elements remaining.

items(yield_constant=True, yield_one_body=True, yield_two_body=True)

Generates the constant, one- and two-body operator terms contained in the operator object.

Parameters:
  • yield_constant (bool, default: True) – Whether to generate a constant term.

  • yield_one_body (bool, default: True) – Whether to generate one-body terms.

  • yield_two_body (bool, default: True) – Whether to generate two-body terms.

Yields:

Next requested FermionOperatorString and constant/integral value.

Return type:

Generator[Tuple[FermionOperatorString, float], None, None]

classmethod load_h5(name)

Loads operator object from .h5 file.

Parameters:

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

Returns:

BaseChemistryIntegralOperator – Loaded integral operator object.

norm(*args, **kwargs)

Calculates the norm of the integral operator.

Sums the norm of the constant, one-body and two-body parts using numpy.linalg.norm().

Parameters:
  • *args – Additional arguments passed to numpy.linalg.norm().

  • **kwargs – Additional keyword arguments passed to numpy.linalg.norm().

Returns:

float – Norm of this instance.

print_table()

Prints operator terms in a table format.

Return type:

None

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 the to_FermionOperator() method, before mapping to a QubitOperator using the provided mapping scheme. Please see the documentation for to_FermionOperator() for finer grained control over operator generation.

Parameters:
Returns:

QubitOperator – Mapped QubitOperator object.

property real: ChemistryRestrictedIntegralOperator

Extract the real part of the integral operator.

Returns:

New integral operator object with only the real parts of all elements remaining.

rotate(rotation, check_unitary=True, check_unitary_atol=1e-15)

Performs an in-place unitary rotation of the chemistry integrals.

Parameters:
  • rotation (ndarray) – Unitary rotation matrix.

  • check_unitary (bool, default: True) – Whether to perform the check for unitarity of the rotation matrix.

  • check_unitary_atol (float, default: 1e-15) – Absolute tolerance of unitarity check.

Returns:

ChemistryRestrictedIntegralOperator – This instance after rotation.

save_h5(name)

Dumps operator object to .h5 file.

Parameters:

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

Return type:

None

to_FermionOperator(yield_constant=True, yield_one_body=True, yield_two_body=True)

Converts chemistry integral operator to FermionOperator.

Parameters:
  • yield_constant (bool, default: True) – Whether to include a constant term.

  • yield_one_body (bool, default: True) – Whether to include one-body terms.

  • yield_two_body (bool, default: True) – Whether to include two-body terms.

Returns:

FermionOperator – Integral operator in general fermionic operator form.

to_compact_integral_operator(symmetry)

Converts two-body integrals into compact form.

Compacts the two-body integrals into a CompactTwoBodyIntegrals object.

Parameters:

symmetry (Union[int, str]) – Target symmetry. Four-fold symmetry (4, "4" or "s4") or eight-fold symmetry (8, "8" or "s8") are supported.

Returns:

ChemistryRestrictedIntegralOperatorCompact – Equivalent integral operator with two-body integrals stored in compact form.

two_body_iijj()

Returns pair-diagonal elements of two-body integrals, \((ii|jj)\) in chemist notation.

Returns:

ndarray – 2D array of pair-diagonal two body-integrals.

class ChemistryRestrictedIntegralOperatorCompact(constant, one_body, two_body, dtype=None)

Bases: BaseChemistryIntegralOperator

Handles a (restricted-orbital) chemistry integral operator, with integrals stored in a compact form.

Stores constant, one- and two-body spatial integral values following chemistry notation, i.e. two_body[p, q, r, s] = \((pq|rs)\). Two-body integrals are stored as a CompactTwoBodyIntegralsS4 or CompactTwoBodyIntegralsS8 object rather than a numpy.ndarray, which reduces memory load, at the expense of some operations taking longer.

Parameters:
TOLERANCE = 1e-08

Internal tolerance used when iterating over terms. Terms with magnitude smaller than this are not returned by items().

approx_equal(other, rtol=1.0e-5, atol=1.0e-8, equal_nan=False)

Test for approximate equality with another instance of this class by comparing integral arrays.

Arguments are passed directly to numpy.allclose() for equality comparison - see numpy documentation for further details.

Parameters:
  • other (ChemistryRestrictedIntegralOperatorCompact) – The other operator to compare for approximate equality.

  • rtol (float, default: 1.0e-5) – The relative tolerance parameter, as defined by numpy.allclose().

  • atol (float, default: 1.0e-8) – The absolute tolerance parameter, as defined by numpy.allclose().

  • equal_nan (bool, default: False) – Whether to compare NaN’s as equal, as defined by numpy.allclose().

Returns:

boolTrue if other instance is approximately equal to this, otherwise False.

astype(dtype)

Returns a copy of the current integral operator, cast to a new dtype.

Parameters:

dtype (Any) – The dtype to cast into.

Returns:

ChemistryRestrictedIntegralOperatorCompact – New integral operator with components cast to dtype.

copy()

Performs a deep copy of object.

Return type:

BaseChemistryIntegralOperator

df()

Returns a pandas.DataFrame object showing all terms in the operator.

Return type:

DataFrame

double_factorize(tol1=-1.0, tol2=None, method=DecompositionMethod.EIG, diagonalize_one_body=True, diagonalize_one_body_offset=True, combine_one_body_terms=True)

Double factorizes the two-electron integrals and returns the Hamiltonian in diagonal form.

The Hamiltonian can be written as \(\hat{H} = H_0 + \hat{H}_1 + \hat{S} + \hat{V}\) where \(\hat{S}+\hat{V}\) is the Coulomb interaction. \(V = \frac{1}{2}\sum_{ijkl} (ij|kl) a_i^\dagger a_j a_k^\dagger a_l\) is a reordered two-body operator and \(\hat{S}\) is a one-body offset term given by \(\hat{S} = \sum_{ij} s_{ij} a_i^\dagger a_j\) where \(s_{ij} = -\frac{1}{2}\sum_k (ik|kj)\). \(H_0\) and \(\hat{H}_1\) are the constant and one-electron terms respectively.

The first level of factorization decomposes the electron repulsion integrals tensor into the form: \((pq|rs)=\sum_t^{N_\gamma} V_{pq}^t \gamma^t V_{rs}^t\). This may be performed using an eigenvalue decomposition (method='eig'), or a pivoted, incomplete Cholesky decomposition (method="cho") (see J. Chem. Phys. 118, 9481–9484 (2003) and J. Chem. Phys. 139, 134105 (2013)). The second factorization is diagonalization of the \(V_{pq}^t\) matrix for each t: \(V_{pq}^t = \sum_u^{N_\lambda^t} U_{pu}^t \lambda_u^t U_{qu}^t\).

At the first factorization stage, truncation depends on the decomposition method. With "eig", truncation is performed by discarding eigenvalues, starting from the smallest in magnitude, until the sum of those discarded magnitudes exceeds the threshold tol1. With "cho", the decomposition is constructed iteratively until the error is less than tol1. At the second factorization level, truncation is always performed by discarding low-magnitude eigenvalues.

One-body-like terms are consolidated and diagonalized by default: \(\tilde{h}_{pq} = h_{pq} + s_{pq} = \sum_r W_{pr} \omega_r W_{qr}\). One-body diagonalization is not truncated.

Warning

This is not intended for reduction of classical memory usage, only for truncating the two-body terms of the Hamiltonian for quantum simulation.

Parameters:
  • tol1 (float, default: -1.0) – Truncation threshold for first diagonalization of ERI matrix. If negative, no truncation is performed.

  • tol2 (Optional[float], default: None) – Truncation threshold for second diagonalization of ERI matrix. If None, same as tol1. If negative, no truncation is performed.

  • method (Union[DecompositionMethod, str], default: DecompositionMethod.EIG) – Decomposition method used for the first level of factorization. "eig" for an eigenvalue decomposition, "cho" for a pivoted, incomplete Cholesky decomposition.

  • diagonalize_one_body (bool, default: True) – Whether to diagonalize the physical one-body integrals \(h_{pq}\).

  • diagonalize_one_body_offset (bool, default: True) – Whether to diagonalize the one-body offset integrals \(s_{pq}\)

  • combine_one_body_terms (bool, default: True) – Whether to consolidate the one-body and one-body offset integrals into effective one-body integrals. Requires diagonalize_one_body == diagonalize_one_body_offset.

Returns:

DoubleFactorizedHamiltonian – Hamiltonian operator storing two-body integrals in double factorized form and, optionally, diagonalized one-body integrals.

property dtype: dtype

Returns numpy data type of the two-body integral terms.

effective_potential(rdm1)

Calculates the effective Coulombic potential for a given 1-RDM.

Parameters:

rdm1 (RestrictedOneBodyRDM) – Restricted, one-body reduced density matrix object.

Returns:

ndarray – Effective potential matrix.

effective_potential_spin(rdm1)

Calculates the contribution to the effective Coulomb potential due to a spin imbalance.

This is defined as the contribution to the effective potential matrix from the difference of the alpha and beta 1-RDMs.

Parameters:

rdm1 (RestrictedOneBodyRDM) – Restricted, one-body reduced density matrix object.

Returns:

ndarray – Effective potential matrix.

energy(rdm1, rdm2=None)

Calculate total energy based on the one- and two-body reduced density matrices.

If rdm2 is not given, this method returns the mean-field energy.

Parameters:
Returns:

float – Total energy.

energy_electron_mean_field(rdm1)

Calculates the electronic energy in the mean-field approximation.

Parameters:

rdm1 (RestrictedOneBodyRDM) – Restricted, one-body reduced density matrix object.

Returns:

Tuple[float, float] – The mean-field electronic energy (one-body + two-body), and the mean-field Coulomb contribution (two-body only).

classmethod from_FermionOperator(operator, dtype=float, symmetry='s4')

Convert a 2-body fermionic operator to compact, restricted-orbital integral operator.

The one-body terms are stored in a matrix, _one_body[p, q], and the two-body terms are stored in a CompactTwoBodyIntegrals object, _two_body[p, q, r, s]

Parameters:
  • operator (FermionOperator) – Input fermion operator.

  • dtype (default: float) – Desired term value dtype.

  • symmetry (Union[str, int], default: "s4") – Target symmetry. Four-fold symmetry (4, "4" or "s4") or eight-fold symmetry (8, "8" or "s8") are supported.

Returns:

Output integral operator.

Warning

Currently, this converter assumes all the terms in the integral operator are represented by the aabb and bbaa blocks of fermion operator terms, and they are supposed to overwrite the (contracted) aaaa and bbbb terms - it might give faulty results if this is not the case.

property imag

Extract the imaginary part of the integral operator.

Returns:

New integral operator object with only the imaginary parts of all elements remaining.

items(yield_constant=True, yield_one_body=True, yield_two_body=True)

Generates the constant, one- and two-body operator terms contained in the operator object.

Parameters:
  • yield_constant (bool, default: True) – Whether to generate a constant term.

  • yield_one_body (bool, default: True) – Whether to generate one-body terms.

  • yield_two_body (bool, default: True) – Whether to generate two-body terms.

Yields:

Next requested FermionOperatorString and constant/integral value.

Return type:

Generator[Tuple[FermionOperatorString, float], None, None]

classmethod load_h5(name)

Loads operator object from .h5 file.

Parameters:

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

Returns:

BaseChemistryIntegralOperator – Loaded integral operator object.

norm()

Calculates the Frobenius norm of the integral operator.

Sums the norm of the constant, one-body and two-body parts.

Returns:

Norm of integral operator.

print_table()

Prints operator terms in a table format.

Return type:

None

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 the to_FermionOperator() method, before mapping to a QubitOperator using the provided mapping scheme. Please see the documentation for to_FermionOperator() for finer grained control over operator generation.

Parameters:
Returns:

QubitOperator – Mapped QubitOperator object.

property real

Extract the real part of the integral operator.

Returns:

New integral operator object with only the real parts of all elements remaining.

rotate(rotation, check_unitary=True, check_unitary_atol=1e-15)

Performs an in-place unitary rotation of the chemistry integrals.

Rotation must be real-valued (orthogonal) for compact integrals.

Raises:

ValueError – If dimensions of rotation matrix are not compatible with integrals.

Parameters:
  • rotation (ndarray) – Real, unitary rotation matrix.

  • check_unitary (bool, default: True) – Whether to perform the check for unitarity of the rotation matrix.

  • check_unitary_atol (float, default: 1e-15) – Absolute tolerance of unitarity check.

Returns:

ChemistryRestrictedIntegralOperatorCompact – This instance after rotation.

save_h5(name)

Dumps operator object to .h5 file.

Parameters:

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

Return type:

None

to_FermionOperator(yield_constant=True, yield_one_body=True, yield_two_body=True)

Converts chemistry integral operator to FermionOperator.

Parameters:
  • yield_constant (bool, default: True) – Whether to include a constant term.

  • yield_one_body (bool, default: True) – Whether to include one-body terms.

  • yield_two_body (bool, default: True) – Whether to include two-body terms.

Returns:

FermionOperator – Integral operator in general fermionic operator form.

to_uncompacted_integral_operator()

Convert to a ChemistryRestrictedIntegralOperator object.

Unpacks the compact two-body integrals into a four-dimensional numpy.ndarray.

Returns:

Equivalent integral operator object with un-compacted integrals.

two_body_iijj()

Returns pair-diagonal elements of two-body integrals, \((ii|jj)\) in chemist’s notation.

Returns:

2D array of pair-diagonal two body-integrals.

class ChemistryUnrestrictedIntegralOperator(constant, one_body_aa, one_body_bb, two_body_aaaa, two_body_bbbb, two_body_aabb, two_body_bbaa)

Bases: BaseChemistryIntegralOperator

Handles a (unrestricted-orbital) chemistry integral operator.

Stores constant, one- and two-body spatial integral values following chemist notation, i.e. two_body[p, q, r, s] = \((pq|rs)\)

Parameters:
  • constant (float) – Constant energy term, electron independent.

  • one_body_aa (ndarray) – One-body integrals for the alpha (a) spin channel.

  • one_body_bb (ndarray) – One-body integrals for the beta (b) spin channel.

  • two_body_aaaa (ndarray) – Two-body electron repulsion integrals (ERI) with spatial orbitals in the aaaa spin channels respectively.

  • two_body_bbbb (ndarray) – ERI with spatial orbitals in the bbbb spin channels.

  • two_body_aabb (ndarray) – ERI with spatial orbitals in the aabb spin channels.

  • two_body_bbaa (ndarray) – ERI with spatial orbitals in the bbaa spin channels.

TOLERANCE = 1e-08

Internal tolerance used when iterating over terms. Terms with magnitude smaller than this are not returned by items().

approx_equal(other, rtol=1.0e-5, atol=1.0e-8, equal_nan=False)

Test for approximate equality with another instance of this class by comparing integral arrays.

Arguments are passed directly to numpy.allclose() for equality comparison - see numpy documentation for further details.

Parameters:
  • other (ChemistryUnrestrictedIntegralOperator) – The other operator to compare for approximate equality.

  • rtol (float, default: 1.0e-5) – The relative tolerance parameter, as defined by numpy.allclose().

  • atol (float, default: 1.0e-8) – The absolute tolerance parameter, as defined by numpy.allclose().

  • equal_nan (bool, default: False) – Whether to compare NaN’s as equal, as defined by numpy.allclose().

Returns:

boolTrue if other instance is approximately equal to this one, otherwise False.

copy()

Performs a deep copy of object.

Return type:

BaseChemistryIntegralOperator

df()

Returns a pandas.DataFrame object showing all terms in the operator.

Return type:

DataFrame

double_factorize(tol1=-1.0, tol2=None, method=DecompositionMethod.EIG, diagonalize_one_body=True, diagonalize_one_body_offset=True, combine_one_body_terms=True)

Double factorizes the two-electron integrals and returns the Hamiltonian in diagonal form.

The Hamiltonian can be written as \(\hat{H} = H_0 + \hat{H}_1 + \hat{S} + \hat{V}\) where \(\hat{S}+\hat{V}\) is the Coulomb interaction. \(V = \frac{1}{2}\sum_{ijkl} (ij|kl) a_i^\dagger a_j a_k^\dagger a_l\) is a reordered two-body operator and \(\hat{S}\) is a one-body offset term given by \(\hat{S} = \sum_{ij} s_{ij} a_i^\dagger a_j\) where \(s_{ij} = -\frac{1}{2}\sum_k (ik|kj)\). \(H_0\) and \(\hat{H}_1\) are the constant and one-electron terms respectively.

The first level of factorization decomposes the electron repulsion integrals tensor into the form: \((pq|rs)=\sum_t^{N_\gamma} V_{pq}^t \gamma^t V_{rs}^t\). This may be performed using an eigenvalue decomposition (method='eig'), or a pivoted, incomplete Cholesky decomposition (method="cho") (see J. Chem. Phys. 118, 9481–9484 (2003) and J. Chem. Phys. 139, 134105 (2013)). The second factorization is diagonalization of the \(V_{pq}^t\) matrix for each t: \(V_{pq}^t = \sum_u^{N_\lambda^t} U_{pu}^t \lambda_u^t U_{qu}^t\).

At the first factorization stage, truncation depends on the decomposition method. With "eig", truncation is performed by discarding eigenvalues, starting from the smallest in magnitude, until the sum of those discarded magnitudes exceeds the threshold tol1. With "cho", the decomposition is constructed iteratively until the error is less than tol1. At the second factorization level, truncation is always performed by discarding low-magnitude eigenvalues.

One-body-like terms are consolidated and diagonalized by default: \(\tilde{h}_{pq} = h_{pq} + s_{pq} = \sum_r W_{pr} \omega_r W_{qr}\). One-body diagonalization is not truncated.

Warning

This is not intended for reduction of classical memory usage, only for truncating the two-body terms of the Hamiltonian for quantum simulation.

Parameters:
  • tol1 (float, default: -1.0) – Truncation threshold for first diagonalization of ERI matrix. If negative, no truncation is performed.

  • tol2 (Optional[float], default: None) – Truncation threshold for second diagonalization of ERI matrix. If None, same as tol1. If negative, no truncation is performed.

  • method (Union[DecompositionMethod, str], default: DecompositionMethod.EIG) – Decomposition method used for the first level of factorization. "eig" for an eigenvalue decomposition, "cho" for a pivoted, incomplete Cholesky decomposition.

  • diagonalize_one_body (bool, default: True) – Whether to diagonalize the physical one-body integrals \(h_{pq}\).

  • diagonalize_one_body_offset (bool, default: True) – Whether to diagonalize the one-body offset integrals \(s_{pq}\)

  • combine_one_body_terms (bool, default: True) – Whether to consolidate the one-body and one-body offset integrals into effective one-body integrals. Requires diagonalize_one_body == diagonalize_one_body_offset.

Returns:

DoubleFactorizedHamiltonian – Hamiltonian operator storing two-body integrals in double factorized form and, optionally, diagonalized one-body integrals.

effective_potential(rdm1)

Calculates the effective Coulombic potential for a given 1-RDM.

Parameters:

rdm1 (UnrestrictedOneBodyRDM) – Unrestricted, one-body reduced density matrix.

Returns:

List[ndarray] – Effective potentials for the alpha and beta spin channels.

energy(rdm1, rdm2=None)

Calculate total energy based on the one- and two-body reduced density matrices.

If rdm2 is not given, this method returns the mean-field energy.

Parameters:
Returns:

float – Total energy.

energy_electron_mean_field(rdm1)

Calculates the electronic energy in the mean-field approximation.

Parameters:

rdm1 (UnrestrictedOneBodyRDM) – Unrestricted, one-body reduced density matrix object.

Returns:

Tuple[float, float] – The mean-field electronic energy (one-body + two-body), and the mean-field Coulomb contribution (two-body only).

classmethod from_FermionOperator(operator)

Convert a 2-body fermionic operator to unrestricted-orbital integral operator.

The one-body terms are stored in matrices, _one_body_aa[p, q] and _one_body_bb, and the two-body terms are stored in tensors, _two_body_aaaa[p, q, r, s], _two_body_bbbb[...], _two_body_aabb[...] and _two_body_bbaa[...].

Parameters:

operator (FermionOperator) – Input fermion operator.

Returns:

ChemistryUnrestrictedIntegralOperator – The converted operator.

Warning

The same-spin (aaaa and bbbb) blocks returned are contracted - this is fine for use in quantum chemistry calculations with density matrices having unit elements (e.g. Slater determinants) - for other purposes one should be careful.

items(yield_constant=True, yield_one_body=True, yield_two_body=True)

Generates the constant, one- and two-body operator terms contained in the operator object.

Parameters:
  • yield_constant (bool, default: True) – Whether to generate a constant term.

  • yield_one_body (bool, default: True) – Whether to generate one-body terms.

  • yield_two_body (bool, default: True) – Whether to generate two-body terms.

Yields:

Next requested FermionOperatorString and constant/integral value.

Return type:

Generator[Tuple[FermionOperatorString, float], None, None]

classmethod load_h5(name)

Loads operator object from .h5 file.

Parameters:

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

Returns:

BaseChemistryIntegralOperator – Loaded integral operator object.

print_table()

Prints operator terms in a table format.

Return type:

None

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 the to_FermionOperator() method, before mapping to a QubitOperator using the provided mapping scheme. Please see the documentation for to_FermionOperator() for finer grained control over operator generation.

Parameters:
Returns:

QubitOperator – Mapped QubitOperator object.

rotate(rotation_aa, rotation_bb, check_unitary=True, check_unitary_atol=1e-15)

Performs an in-place unitary rotation of the chemistry integrals.

Each spin block is rotated separately.

Parameters:
  • rotation_aa (ndarray) – Unitary rotation matrix for the alpha spin block.

  • rotation_bb (ndarray) – Unitary rotation matrix for the beta spin block.

  • check_unitary (bool, default: True) – Whether to perform the check for unitarity of the rotation matrices.

  • check_unitary_atol (float, default: 1e-15) – Absolute tolerance of unitarity checks.

Returns:

ChemistryUnrestrictedIntegralOperator – This instance after rotation.

save_h5(name)

Dumps operator object to .h5 file.

Parameters:

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

Return type:

None

to_FermionOperator(yield_constant=True, yield_one_body=True, yield_two_body=True)

Converts chemistry integral operator to FermionOperator.

Parameters:
  • yield_constant (bool, default: True) – Whether to include a constant term.

  • yield_one_body (bool, default: True) – Whether to include one-body terms.

  • yield_two_body (bool, default: True) – Whether to include two-body terms.

Returns:

FermionOperator – Integral operator in general fermionic operator form.

to_compact_integral_operator(symmetry)

Converts two-body integrals into compact form.

Compacts the two-body integrals into a CompactTwoBodyIntegrals object.

Parameters:

symmetry (Union[int, str]) – Target symmetry. Four-fold symmetry (4, "4" or "s4") or eight-fold symmetry (8, "8" or "s8") are supported.

Returns:

ChemistryUnrestrictedIntegralOperatorCompact – Equivalent integral operator with two-body integrals stored in compact form.

class ChemistryUnrestrictedIntegralOperatorCompact(constant, one_body_aa, one_body_bb, two_body_aaaa, two_body_bbbb, two_body_aabb, two_body_bbaa, dtype=None)

Bases: BaseChemistryIntegralOperator

Handles a (unrestricted-orbital) chemistry integral operator, with integrals stored in a compact form.

Stores constant, one- and two-body spatial integral values following chemistry notation, i.e. two_body[p, q, r, s] = \((pq|rs)\). Two-body integrals are stored as a CompactTwoBodyIntegralsS4 or CompactTwoBodyIntegralsS8 object rather than a numpy.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 the two_body_aaaa input. The aabb and bbaa integral tensors are incompatible with s8 symmetry.

Parameters:
TOLERANCE = 1e-08

Internal tolerance used when iterating over terms. Terms with magnitude smaller than this are not returned by items().

approx_equal(other, rtol=1.0e-5, atol=1.0e-8, equal_nan=False)

Test for approximate equality with another instance of this class by comparing integral arrays.

Arguments are passed directly to numpy.allclose() for equality comparison - see numpy documentation for further details.

Parameters:
  • other (ChemistryUnrestrictedIntegralOperatorCompact) – The other operator to compare for approximate equality.

  • rtol (float, default: 1.0e-5) – The relative tolerance parameter, as defined by numpy.allclose().

  • atol (float, default: 1.0e-8) – The absolute tolerance parameter, as defined by numpy.allclose().

  • equal_nan (bool, default: False) – Whether to compare NaN’s as equal, as defined by numpy.allclose().

Returns:

boolTrue if other instance is approximately equal to this, otherwise False.

copy()

Performs a deep copy of object.

Return type:

BaseChemistryIntegralOperator

df()

Returns a pandas.DataFrame object showing all terms in the operator.

Return type:

DataFrame

double_factorize(tol1=-1.0, tol2=None, method=DecompositionMethod.EIG, diagonalize_one_body=True, diagonalize_one_body_offset=True, combine_one_body_terms=True)

Double factorizes the two-electron integrals and returns the Hamiltonian in diagonal form.

The Hamiltonian can be written as \(\hat{H} = H_0 + \hat{H}_1 + \hat{S} + \hat{V}\) where \(\hat{S}+\hat{V}\) is the Coulomb interaction. \(V = \frac{1}{2}\sum_{ijkl} (ij|kl) a_i^\dagger a_j a_k^\dagger a_l\) is a reordered two-body operator and \(\hat{S}\) is a one-body offset term given by \(\hat{S} = \sum_{ij} s_{ij} a_i^\dagger a_j\) where \(s_{ij} = -\frac{1}{2}\sum_k (ik|kj)\). \(H_0\) and \(\hat{H}_1\) are the constant and one-electron terms respectively.

The first level of factorization decomposes the electron repulsion integrals tensor into the form: \((pq|rs)=\sum_t^{N_\gamma} V_{pq}^t \gamma^t V_{rs}^t\). This may be performed using an eigenvalue decomposition (method='eig'), or a pivoted, incomplete Cholesky decomposition (method="cho") (see J. Chem. Phys. 118, 9481–9484 (2003) and J. Chem. Phys. 139, 134105 (2013)). The second factorization is diagonalization of the \(V_{pq}^t\) matrix for each t: \(V_{pq}^t = \sum_u^{N_\lambda^t} U_{pu}^t \lambda_u^t U_{qu}^t\).

At the first factorization stage, truncation depends on the decomposition method. With "eig", truncation is performed by discarding eigenvalues, starting from the smallest in magnitude, until the sum of those discarded magnitudes exceeds the threshold tol1. With "cho", the decomposition is constructed iteratively until the error is less than tol1. At the second factorization level, truncation is always performed by discarding low-magnitude eigenvalues.

One-body-like terms are consolidated and diagonalized by default: \(\tilde{h}_{pq} = h_{pq} + s_{pq} = \sum_r W_{pr} \omega_r W_{qr}\). One-body diagonalization is not truncated.

Warning

This is not intended for reduction of classical memory usage, only for truncating the two-body terms of the Hamiltonian for quantum simulation.

Parameters:
  • tol1 (float, default: -1.0) – Truncation threshold for first diagonalization of ERI matrix. If negative, no truncation is performed.

  • tol2 (Optional[float], default: None) – Truncation threshold for second diagonalization of ERI matrix. If None, same as tol1. If negative, no truncation is performed.

  • method (Union[DecompositionMethod, str], default: DecompositionMethod.EIG) – Decomposition method used for the first level of factorization. "eig" for an eigenvalue decomposition, "cho" for a pivoted, incomplete Cholesky decomposition.

  • diagonalize_one_body (bool, default: True) – Whether to diagonalize the physical one-body integrals \(h_{pq}\).

  • diagonalize_one_body_offset (bool, default: True) – Whether to diagonalize the one-body offset integrals \(s_{pq}\)

  • combine_one_body_terms (bool, default: True) – Whether to consolidate the one-body and one-body offset integrals into effective one-body integrals. Requires diagonalize_one_body == diagonalize_one_body_offset.

Returns:

DoubleFactorizedHamiltonian – Hamiltonian operator storing two-body integrals in double factorized form and, optionally, diagonalized one-body integrals.

effective_potential(rdm1)

Calculates the effective Coulombic potential for a given 1-RDM.

Parameters:

rdm1 (UnrestrictedOneBodyRDM) – Unrestricted, one-body reduced density matrix.

Returns:

List[ndarray] – Effective potentials for the alpha and beta spin channels.

energy(rdm1, rdm2=None)

Calculate total energy based on the one- and two-body reduced density matrices.

If rdm2 is not given, this method returns the mean-field energy.

Parameters:
Returns:

float – Total energy.

energy_electron_mean_field(rdm1)

Calculates the electronic energy in the mean-field approximation.

Parameters:

rdm1 (UnrestrictedOneBodyRDM) – Unrestricted, one-body reduced density matrix object.

Returns:

Tuple[float, float] – The mean-field electronic energy (one-body + two-body), and the mean-field Coulomb contribution (two-body only).

classmethod from_FermionOperator(operator, symmetry='s4')

Convert a 2-body fermionic operator to unrestricted-orbital integral operator.

The one-body terms are stored in matrices, _one_body_aa[p, q] and _one_body_bb, and the two-body terms are stored in CompactTwoBodyIntegrals objects, _two_body_aaaa[p, q, r, s], _two_body_bbbb[...], _two_body_aabb[...] and _two_body_bbaa[...].

Parameters:
  • operator (FermionOperator) – Input fermion operator.

  • symmetry (Union[str, int], default: "s4") – Target symmetry. Four-fold symmetry (4, "4" or "s4") or eight-fold symmetry (8, "8" or "s8") are supported.

Returns:

ChemistryUnrestrictedIntegralOperatorCompact – Output integral operator.

Warning

The same-spin (aaaa and bbbb) blocks returned are contracted - this is fine for use in quantum chemistry calculations with density matrices having unit elements (e.g. Slater determinants) - for other purposes one should be careful.

items(yield_constant=True, yield_one_body=True, yield_two_body=True)

Generates the constant, one- and two-body operator terms contained in the operator object.

Parameters:
  • yield_constant (bool, default: True) – Whether to generate a constant term.

  • yield_one_body (bool, default: True) – Whether to generate one-body terms.

  • yield_two_body (bool, default: True) – Whether to generate two-body terms.

Yields:

Next requested FermionOperatorString and constant/integral value.

Return type:

Generator[Tuple[FermionOperatorString, float], None, None]

classmethod load_h5(name)

Loads operator object from .h5 file.

Parameters:

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

Returns:

BaseChemistryIntegralOperator – Loaded integral operator object.

print_table()

Prints operator terms in a table format.

Return type:

None

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 the to_FermionOperator() method, before mapping to a QubitOperator using the provided mapping scheme. Please see the documentation for to_FermionOperator() for finer grained control over operator generation.

Parameters:
Returns:

QubitOperator – Mapped QubitOperator object.

rotate(rotation_aa, rotation_bb, check_unitary=True, check_unitary_atol=1e-15)

Performs an in-place unitary rotation of the chemistry integrals.

Each spin block is rotated separately. Rotation must be real-valued (orthogonal) for compact integrals.

Parameters:
  • rotation_aa (ndarray) – Real, unitary rotation matrix for the alpha spin basis.

  • rotation_bb (ndarray) – Real, unitary rotation matrix for the beta spin basis.

  • check_unitary (bool, default: True) – Whether to perform the check for unitarity of the rotation matrices.

  • check_unitary_atol (float, default: 1e-15) – Absolute tolerance of unitarity checks.

Returns:

ChemistryUnrestrictedIntegralOperatorCompact – This instance after rotation.

save_h5(name)

Dumps operator object to .h5 file.

Parameters:

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

Return type:

None

to_FermionOperator(yield_constant=True, yield_one_body=True, yield_two_body=True)

Converts chemistry integral operator to FermionOperator.

Parameters:
  • yield_constant (bool, default: True) – Whether to include a constant term.

  • yield_one_body (bool, default: True) – Whether to include one-body terms.

  • yield_two_body (bool, default: True) – Whether to include two-body terms.

Returns:

FermionOperator – Integral operator in general fermionic operator form.

to_uncompacted_integral_operator()

Convert to a ChemistryUnrestrictedIntegralOperator object.

Unpacks the compact two-body integrals into a four-dimensional numpy.ndarray.

Returns:

ChemistryUnrestrictedIntegralOperator – Equivalent integral operator object with un-compacted integrals.

class CompactTwoBodyIntegralsS4(compact_array)

Bases: BaseCompactTwoBodyIntegrals

Stores a two-body integral tensor in s4 symmetry reduced form.

Allows simple, 4-indexed [i,j,k,l] array-like access through index transformation.

Parameters:

compact_array (ndarray) – Two-body integrals in a four-fold symmetry-reduced form. A numpy.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 numpy dtype to cast into.

Returns:

CompactTwoBodyIntegralsS4 – New compact integrals object with compact array cast to the given dtype.

static check_s4_symmetry(uncompact_array, rtol=1.0e-5, atol=1.0e-8, equal_nan=False)

Tests whether the input ERI tensor has four-fold (s4) index symmetries.

Checks for symmetries under index swaps \(i \leftrightarrow j\) and \(k \leftrightarrow l\).

Parameters:
  • uncompact_array (ndarray) – Four-dimensional ERI tensor.

  • rtol (float, default: 1.0e-5) – Relative tolerance.

  • atol (float, default: 1.0e-8) – Absolute tolerance.

  • equal_nan (bool, default: False) – Whether to compare NaN’s as equal.

Returns:

boolTrue if the input array has s4 symmetry, False otherwise.

property dtype: dtype

Returns numpy data type of the compact array.

classmethod from_uncompacted_integrals(two_body, symmetry, check_symmetry=False, rtol=1.0e-5, atol=1.0e-8, equal_nan=False)

Builds a compact integrals object from an uncompacted array of two body integrals (a rank-4 tensor).

Parameters:
  • two_body (ndarray) – 4D array.

  • symmetry (Union[str, int]) – Code to specify target symmetry. Uses the same convention as pyscf. Currently supports s4 and s8 symmetry.

  • check_symmetry (bool, default: False) – Whether the input array should be checked for the requested symmetry.

  • rtol (float, default: 1.0e-5) – Relative tolerance on symmetry checks.

  • atol (float, default: 1.0e-8) – Absolute tolerance.

  • equal_nan (bool, default: False) – Whether to compare NaN values as equal.

Returns:

Union[CompactTwoBodyIntegralsS4, CompactTwoBodyIntegralsS8] – Object containing the same information as the input array in a compact form.

property imag: CompactTwoBodyIntegralsS4

Extract the imaginary part of the two-body integrals.

Returns:

New compact object containing only the imaginary part of the integrals.

static pairs(n_orb)

Yields unique index pairs, and their pair index.

Does not return multiple equivalent pairs i.e. {2, 1} will appear, but {1, 2} will not.

Parameters:

n_orb (int) – Number of orbitals over which pairs will be iterated.

Yields:

The next pair index, first orbital index, and second orbital index.

Return type:

Iterator[Tuple[int, int, int]]

property real: CompactTwoBodyIntegralsS4

Extract the real part of the two-body integrals.

Returns:

New compact object containing only the real part of the integrals.

rotate(u_ij, u_kl=None)

Perform a rotation of the compact two-body integrals.

Parameters:
  • u_ij (ndarray) – A real, orthogonal matrix of dimensions (\(n_{\text{orb}_{ij}}\), \(n_{\text{orb}_{ij}}\)). For rotating the first two indices of the two-body integrals tensor.

  • u_kl (Optional[ndarray], default: None) – A real, orthogonal matrix of dimensions (\(n_{\text{orb}_{kl}}\), \(n_{\text{orb}_{kl}}\)). For rotating the second two indices of the two-body integrals tensor.

Return type:

None

property shape: Tuple[int, int, int, int]

The shape of the corresponding rank-4 tensor.

Returns:

A tuple containing the shape \((n_p, n_q, n_r, n_s)\) of the two body tensor \((pq|rs)\).

class CompactTwoBodyIntegralsS8(compact_array)

Bases: BaseCompactTwoBodyIntegrals

Stores a two-body integral tensor in s8 symmetry reduced form.

Allows simple, 4-indexed [i,j,k,l] array-like access through index transformation.

Note

This symmetry class can only be used for ERI tensors that describe orbitals with the same spin i.e. the restricted spin ERI tensor, or the aaaa and bbbb unrestricted ERI tensors. It cannot be used for the aabb unrestricted tensor, because that block does not respect \(ij \leftrightarrow kl\) swap symmetry.

Parameters:

compact_array (ndarray) – Two-body integrals in an eight-fold symmetry-reduced form. A numpy.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 numpy dtype to cast into.

Returns:

CompactTwoBodyIntegralsS8 – New compact integrals object with compact array cast to the given dtype.

static check_s8_symmetry(uncompact_array, rtol=1.0e-5, atol=1.0e-8, equal_nan=False)

Tests whether the input ERI tensor has eight-fold (s8) index symmetries.

Checks for symmetries under index swaps \(i \leftrightarrow j\) and \(k \leftrightarrow l\), and pair index swaps \(ij \leftrightarrow kl\).

Parameters:
  • uncompact_array (ndarray) – Four-dimensional ERI tensor.

  • rtol (float, default: 1.0e-5) – Relative tolerance.

  • atol (float, default: 1.0e-8) – Absolute tolerance.

  • equal_nan (bool, default: False) – Whether to compare NaN’s as equal.

Returns:

bool – True if the input array has s8 symmetry, false otherwise.

property dtype: dtype

Returns numpy data type of the compact array.

classmethod from_uncompacted_integrals(two_body, symmetry, check_symmetry=False, rtol=1.0e-5, atol=1.0e-8, equal_nan=False)

Builds a compact integrals object from an uncompacted array of two body integrals (a rank-4 tensor).

Parameters:
  • two_body (ndarray) – 4D array.

  • symmetry (Union[str, int]) – Code to specify target symmetry. Uses the same convention as pyscf. Currently supports s4 and s8 symmetry.

  • check_symmetry (bool, default: False) – Whether the input array should be checked for the requested symmetry.

  • rtol (float, default: 1.0e-5) – Relative tolerance on symmetry checks.

  • atol (float, default: 1.0e-8) – Absolute tolerance.

  • equal_nan (bool, default: False) – Whether to compare NaN values as equal.

Returns:

Union[CompactTwoBodyIntegralsS4, CompactTwoBodyIntegralsS8] – Object containing the same information as the input array in a compact form.

property imag: CompactTwoBodyIntegralsS8

Extract the imaginary part of the two-body integrals.

Returns:

New compact object containing only the imaginary part of the integrals.

static pairs(n_orb)

Yields unique index pairs, and their pair index.

Does not return multiple equivalent pairs i.e. {2, 1} will appear, but {1, 2} will not.

Parameters:

n_orb (int) – Number of orbitals over which pairs will be iterated.

Yields:

The next pair index, first orbital index, and second orbital index.

Return type:

Iterator[Tuple[int, int, int]]

property real: CompactTwoBodyIntegralsS8

Extract the real part of the two-body integrals.

Returns:

New compact object containing only the real part of the integrals.

rotate(u)

Perform a rotation of the compact two-body integrals.

Parameters:

u (ndarray) – A real, orthogonal matrix of dimensions (\(n_{\text{orb}}\), \(n_{\text{orb}}\)).

Return type:

None

property shape: Tuple[int, int, int, int]

The shape of the corresponding rank-4 tensor.

Returns:

A tuple containing the shape \((n_p, n_q, n_r, n_s)\) of the two body tensor \((pq|rs)\).

class DecompositionMethod(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

Methods for factorization of two electron integrals tensor.

CHOLESKY = 'cho'
EIG = 'eig'
class DoubleFactorizedHamiltonian(constant, one_body, one_body_offset, two_body)

Bases: object

Restricted-spin hamiltonian operator, with two-body integrals stored in double factorized form.

Stores a hamiltonian of the form \(\hat{H} = H_0 + \hat{H}_1 + \hat{S} + \hat{V}\) where \(\hat{S}+\hat{V}\) is the coulomb interaction. \(\hat{V} = \frac{1}{2}\sum_{ijkl} (ij|kl) a_i^\dagger a_j a_k^\dagger a_l\) is a reordered two-body operator and \(\hat{S}\) is a one-body offset to the two-body operator given by \(\hat{S}=\sum_{ij}s_{ij}a_i^\dagger a_j\) where \(s_{ij} = -\frac{1}{2}\sum_k (ik|kj)\). \(H_0\) and \(\hat{H}_1\) are the constant and one-electron terms respectively.

Double factorized two-body operator has the form: \(V = (1/2)\sum_t^{N_\gamma} R(U_t) A_t R(U_t)^\dagger\) where \(A_t = \gamma^t\left( \sum_u^{N_\lambda^t} \lambda_u^t a_u^\dagger a_u \right)^2\) and \(R(U_t)\) is a basis rotation operator.

One-body-like terms may be consolidated into a single effective-one-body term: \(\hat{H}_1' = \hat{H}_1 + \hat{S}\). One-body term(s) may be stored as arrays, or diagonalized. When diagonalized, one-body terms are given by: \(\hat{H}_1 = R(W)\left( \sum_i^N \omega_i a_i^\dagger a_i\right) R(W)^\dagger\).

Parameters:
  • constant (float) – Constant (electron-independent) energy.

  • one_body (Union[DiagonalizedOneBodyIntegrals, ndarray[Any, dtype[TypeVar(_ScalarType_co, bound= generic, covariant=True)]]]) – One-body integrals. These are the physical one-body integrals \(\hat{H}_1\) if one_body_offset != None, or effective one-body integrals \(\hat{H}_1'\) if one_body_offset == None.

  • one_body_offset (Union[DiagonalizedOneBodyIntegrals, ndarray[Any, dtype[TypeVar(_ScalarType_co, bound= generic, covariant=True)]], None]) – Contracted ERI tensor \(s_{ij}\). If None, they are assumed to be part of one_body.

  • two_body (DoubleFactorizedTwoBodyIntegrals) – Double factorized two-body integrals.

items(include_constant=True, include_one_body=True, include_one_body_offset=True, include_two_body=True, square_two_body_sum=True)

Iterate through all fermion operators alongside accompanying rotation matrices.

Parameters:
  • include_constant (bool, default: True) – Whether to include the constant energy term.

  • include_one_body (bool, default: True) – Whether to include the physical/effective one-body terms.

  • include_one_body_offset (bool, default: True) – Whether to include the one-body offset terms. If one_body_offset == None, this term is omitted anyway.

  • include_two_body (bool, default: True) – Whether to include the two-body terms.

  • square_two_body_sum (bool, default: True) – Whether to square the linear combination of number operators in the two-body term.

Yields:

Fermion operators terms, corresponding rotation matrices.

Return type:

Iterator[Tuple[FermionOperator, ndarray[Any, dtype[float]]]]

class FCIDumpRestricted

Bases: object

This class reads FCIDUMP files and facilitates transformations to native InQuanto objects.

Symmetry information is not extracted from the FCIDUMP files. To be used in InQuanto, symmetry information should be passed by the user to the relevant space object. The vanilla information is, however, stored in the specification attribute, so a user can map from FCIDUMP integer values to irrep labels using their own code.

Notes

Currently this functionality is tested against pyscf, psi4 and nwchem FCIDUMP files for restricted systems only. User experience may differ when using this with files generated by packages not listed here.

Parameters:

filename – The name of the FCIDUMP file to be handled by the object.

get_system_specification()

Read the system specification block of the FCIDUMP file and process the contents into a dictionary.

Parameters:

filename – The name of the FCIDUMP file.

Returns:

Dict – A dictionary where each key is a named element of the system specification block.

load(filename)

Load the contents of the FCIDUMP file in one IO operation.

This method populates the constant, one_body_list, and two_body_list attributes.

Parameters:

filename (str) – The filename of the file to be read.

Return type:

None

one_body_to_array()

Unpack the one-body data into a \(N\times N\) matrix, where \(N\) is the number of spatial orbitals.

Elements which are permutationally equivalent to those in the FCIDUMP file are filled with the appropriate value.

Returns:

ndarray[Any, dtype[TypeVar(_ScalarType_co, bound= generic, covariant=True)]] – The one-electron integrals as a matrix, as read from the FCIDUMP file.

to_ChemistryRestrictedIntegralOperator()

Generate a ChemistryRestrictedIntegralOperator object from the provided file.

The integrals from the file are unpacked and distributed into the full \(N\times N\) one-body matrix and \(N\times N\times N\times N\) two-body tensor, where \(N\) is the number of spatial orbitals.

Parameters:

filename – The name of the FCIDUMP file.

Returns:

ChemistryRestrictedIntegralOperator – A ChemistryRestrictedIntegralOperator object corresponding to the integrals contained in the FCIDUMP file represented by this instance.

to_arrays()

Transform the one- and two-body data into their unpacked array forms.

Chemist notation is followed, and permutationally equivalent elements to those in the FCIDUMP file are filled.

Returns:

Tuple[ndarray[Any, dtype[TypeVar(_ScalarType_co, bound= generic, covariant=True)]], ndarray[Any, dtype[TypeVar(_ScalarType_co, bound= generic, covariant=True)]]] – The one- and two-body integral arrays as a tuple.

two_body_to_tensor()

Unpack the one-body data into an \(N\times N\times N\times N\) tensor, where \(N\) is the number of spatial orbitals.

Elements which are permutationally equivalent to those in the FCIDUMP file are filled with the appropriate value.

Returns:

ndarray[Any, dtype[TypeVar(_ScalarType_co, bound= generic, covariant=True)]] – The two-electron integrals as a tensor, as read from the FCIDUMP file.

write(filename, constant, one_body, two_body, norb, nelec, multiplicity, orbsym=None, isym=None, tolerance=1e-12)

Write an FCIDUMP file corresponding to the provided constant, one body and two body quantities.

Parameters:
  • filename (str) – The name of the file to write the FCIDUMP to.

  • constant (float) – The constant term of the Hamiltonian.

  • one_body (ndarray[Any, dtype[TypeVar(_ScalarType_co, bound= generic, covariant=True)]]) – The spatial orbital, one-body integrals as a numpy array.

  • two_body (ndarray[Any, dtype[TypeVar(_ScalarType_co, bound= generic, covariant=True)]]) – The spatial orbital, two-body integrals as a numpy array.

  • norb (int) – The number of spatial orbitals in the system.

  • nelec (int) – The number of electrons in the system.

  • multiplicity (int) – The spin multiplicity of the system.

  • orbsym (Optional[List[int]], default: None) – The integer value of the irreps of the spatial orbitals.

  • isym (Optional[int], default: None) – The integer value of the point group.

  • tolerance (float, default: 1e-12) – Write integrals to the file with a value greater than this number.

Return type:

None

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 being FermionOperatorString objects (terms) and values being the corresponding term coefficients. This can be directly instantiated with a tuple, a list of tuples, or a dict.

See examples below, and the documentation for the from_tuple() and from_list() methods for further detail.

Parameters:

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)

Bases: str, Enum

Determines where coefficients will be stored upon performing Trotterization.

INNER = 'inner'

All coefficients will be stored in the “inner” coefficients, within the component QubitOperators in the Trotterized result.

MIXED = 'mixed'

The Trotter step factor will be stored in the “outer” coefficients, whereas the original coefficients of the original Operator will remain in the component Operators.

OUTER = 'outer'

All coefficients will be stored in the “outer” coefficients, the coefficients stored directly in the generated OperatorList.

capitalize()

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

casefold()

Return a version of the string suitable for caseless comparisons.

center(width, fillchar=' ', /)

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

count(sub[, start[, end]]) int

Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

encode(encoding='utf-8', errors='strict')

Encode the string using the codec registered for encoding.

encoding

The encoding in which to encode the string.

errors

The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

endswith(suffix[, start[, end]]) bool

Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.

expandtabs(tabsize=8)

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find(sub[, start[, end]]) int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

format(*args, **kwargs) str

Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).

format_map(mapping) str

Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).

index(sub[, start[, end]]) int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

isalnum()

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isalpha()

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isascii()

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

isdecimal()

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

isdigit()

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isidentifier()

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.

islower()

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isnumeric()

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

isprintable()

Return True if the string is printable, False otherwise.

A string is printable if all of its characters are considered printable in repr() or if it is empty.

isspace()

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

istitle()

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isupper()

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

join(iterable, /)

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

ljust(width, fillchar=' ', /)

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

lower()

Return a copy of the string converted to lowercase.

lstrip(chars=None, /)

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

static maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

partition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

removeprefix(prefix, /)

Return a str with the given prefix string removed if present.

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.

removesuffix(suffix, /)

Return a str with the given suffix string removed if present.

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.

replace(old, new, count=-1, /)

Return a copy with all occurrences of substring old replaced by new.

count

Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

rfind(sub[, start[, end]]) int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

rindex(sub[, start[, end]]) int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

rjust(width, fillchar=' ', /)

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

rpartition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

rsplit(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the end of the string and works to the front.

rstrip(chars=None, /)

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

split(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the front of the string and works to the end.

Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.

splitlines(keepends=False)

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

startswith(prefix[, start[, end]]) bool

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

strip(chars=None, /)

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

swapcase()

Convert uppercase characters to lowercase and lowercase characters to uppercase.

title()

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

translate(table, /)

Replace each character in the string using the given translation table.

table

Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper()

Return a copy of the string converted to uppercase.

zfill(width, /)

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

apply_bra(fock_state)

Performs an operation on a inquanto.states.FermionState representing a bra.

This transforms the provided inquanto.states.FermionState with the operator on the right. Conjugation on the inquanto.states.FermionState object is not performed.

Parameters:

fock_state (FermionState) – Object representing a bra.

Returns:

FermionState – A representation of the post-operation bra.

apply_ket(fock_state)

Performs an operation on a ket inquanto.states.FermionState state.

Parameters:

fock_state (FermionState) – FermionState object (ket state).

Returns:

FermionState – New ket state.

approx_equal_to(other, abs_tol=1e-10)

Checks for equality between this instance and another FermionOperator.

First, dictionary equivalence is tested for. If False, operators are compared in normal-ordered form, and difference is compared to abs_tol.

Parameters:
  • other (FermionOperator) – An operator to test for equality with.

  • abs_tol (float, default: 1e-10) – Tolerance threshold for negligible terms in comparison.

Returns:

boolTrue if this operator is equal to other, otherwise False.

Danger

This method may use the normal_ordered() method internally, which may be exponentially costly.

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

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

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

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

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

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

Return type:

bool

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 to None to test using a standard

:param python == comparison.:

Returns:

Union[float, complex, None] – The operator as a scalar if it can be represented as such, otherwise None.

classmethod ca(a, b)

Return object with a single one-body creation-annihilation pair with a unit coefficient in its dict.

Parameters:
  • a (int) – Index of fermionic mode to which a creation operator is applied.

  • b (int) – Index of fermionic mode to which an annihilation operator is applied.

Returns:

The creation-annihilation operator pair.

Examples

>>> print(FermionOperator.ca(2, 0))
(1.0, F2^ F0 )
classmethod caca(a, b, c, d)

Return object with a single two-body creation-annihilation pair with a unit coefficient in its dict.

Ordered as creation-annihilation-creation-annihilation.

Parameters:
  • a (int) – Index of fermionic mode to which the first creation operator is applied.

  • b (int) – Index of fermionic mode to which the first annihilation operator is applied.

  • c (int) – Index of fermionic mode to which the second creation operator is applied.

  • d (int) – Index of fermionic mode to which the second annihilation operator is applied.

Returns:

The composed two-body operator.

Examples

>>> print(FermionOperator.caca(2, 0, 3, 1))
(1.0, F2^ F0  F3^ F1 )
classmethod ccaa(a, b, c, d)

Return object with a single two-body creation-annihilation pair with a unit coefficient in its dict.

Ordered as creation-creation-annihilation-annihilation.

Parameters:
  • a (int) – Index of fermionic mode to which the first creation operator is applied.

  • b (int) – Index of fermionic mode to which the second creation operator is applied.

  • c (int) – Index of fermionic mode to which the first annihilation operator is applied.

  • d (int) – Index of fermionic mode to which the second annihilation operator is applied.

Returns:

The composed two-body operator.

Examples

>>> print(FermionOperator.ccaa(3, 2, 1, 0))
(1.0, F3^ F2^ F1  F0 )
clone()

Performs shallow copy of the object.

Return type:

TypeVar(SYMBOLICTYPE, bound= Symbolic)

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

Returns dictionary values.

commutator(other_operator)

Returns the commutator of this instance with other_operator.

This calculation is performed by explicit calculation through multiplication.

Parameters:

other_operator (FermionOperator) – The other fermionic operator.

Returns:

FermionOperator – The commutator.

commutes_with(other_operator, abs_tol=1e-10)

Returns True if this instance commutes with other_operator (within tolerance), otherwise False.

Parameters:
  • other_operator (FermionOperator) – The other fermionic operator.

  • abs_tol (float, default: 1e-10) – Tolerance threshold for negligible terms in the commutator.

Returns:

boolTrue if operators commute (within tolerance) otherwise False.

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

Combines duplicate terms, removing those with negligible coefficient.

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

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

Warning

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

Returns:

LinearDictCombiner – Updated instance of LinearDictCombiner.

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, )
copy()

Performs deep copy of the object.

Return type:

TypeVar(SYMBOLICTYPE, bound= Symbolic)

dagger()

Returns the Hermitian conjugate of an operator.

Return type:

FermionOperator

df()

Returns a Pandas DataFrame object of the dictionary.

Return type:

DataFrame

empty()

Checks if dictionary is empty.

Return type:

bool

evalf(*args, **kwargs)

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

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

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

Returns:

LinearDictCombiner – Updated instance of LinearDictCombiner.

free_symbols()

Returns the free symbols in the coefficient values.

free_symbols_ordered()

Returns the free symbols in the dict, ordered alphabetically.

Returns:

SymbolSet – Ordered set of symbols.

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 or None entries, whose size is equal to the number of spin-orbitals, where None indicates orbitals to be frozen and the remaining sequence of integers is expected to be continuous.

  • occupation (List[int]) – A list of 1s and 0s of the same length as index_map, indicating occupied and unoccupied orbitals.

Returns:

FermionOperator – New operator with frozen orbitals removed.

classmethod from_list(data)

Construct FermionOperator from a list of tuples.

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 the list must be a tuple containing a scalar multiplicative coefficient, followed by a FermionOperatorString or tuple (see FermionOperator.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 format coeff1 [(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 a tuple 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 index q are given by tuples (q, 0) and (q, 1) respectively. A product of single operators is given by a tuple of tuples; 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 this FermionOperator 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:

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

Warning

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

is_all_coeff_imag()

Check if all coefficients have purely imaginary values.

Returns: