Code Documentation¶
openfermion.hamiltonians¶

class
openfermion.hamiltonians.
FermiHubbardModel
(lattice, tunneling_parameters=None, interaction_parameters=None, potential_parameters=None, magnetic_field=0.0, particle_hole_symmetry=False)¶ A general, parameterized FermiHubbard model.
The general (AKA ‘multiband’) FermiHubbard model has k degrees of freedom per site in a lattice. For a lattice with n sites, there are N = k * n spatial orbitals. Additionally, in what we call the “spinful” model each spatial orbital is associated with “up” and “down” spin orbitals, for a total of 2N spin orbitals; in the spinless model, there is only one spinorbital per site for a total of N.
For a lattice with only one type of site and edges from each site only to itself and its neighbors, the Hamiltonian for the spinful model has the form
\[\begin{split}\begin{align} H = & \sum_{a < b} t_{a, b}^{(\mathrm{onsite})} \sum_{i} \sum_{\sigma} (a^\dagger_{i, a, \sigma} a_{i, b, \sigma} + a^\dagger_{i, b, \sigma} a_{i, a, \sigma}) \\ & \sum_{a} t_{a, a}^{(\mathrm{nghbr})} \sum_{\{i, j\}} \sum_{\sigma} (a^\dagger_{i, a, \sigma} a_{j, a, \sigma} + a^\dagger_{j, a, \sigma} a_{i, a, \sigma})  \sum_{a < b} t_{a, b}^{(\mathrm{nghbr})} \sum_{(i, j)} \sum_{\sigma} (a^\dagger_{i, a, \sigma} a_{j, b, \sigma} + a^\dagger_{j, b, \sigma} a_{i, a, \sigma}) \\ &+ \sum_{a < b} U_{a, b}^{(\mathrm{onsite}, +)} \sum_{i} \sum_{\sigma} n_{i, a, \sigma} n_{i, b, \sigma} \\ &+ \sum_{a} U_{a, a}^{(\mathrm{nghbr}, +)} \sum_{\{i, j\}} \sum_{\sigma} n_{i, a, \sigma} n_{j, a, \sigma} + \sum_{a < b} U_{a, b}^{(\mathrm{nghbr}, +)} \sum_{(i, j)} \sum_{\sigma} n_{i, a, \sigma} n_{j, b, \sigma} \\ &+ \sum_{a \leq b} U_{a, b}^{(\mathrm{onsite}, )} \sum_{i} \sum_{\sigma} n_{i, a, \sigma} n_{i, b, \sigma} \\ &+ \sum_{a} U_{a, a}^{(\mathrm{nghbr}, )} \sum_{\{ i, j \}} \sum_{\sigma} n_{i, a, \sigma} n_{j, a, \sigma} + \sum_{a < b} U_{a, b}^{(\mathrm{nghbr}, )} \sum_{( i, j )} \sum_{\sigma} n_{i, a, \sigma} n_{j, b, \sigma} \\ & \sum_{a} \mu_a \sum_i \sum_{\sigma} n_{i, a, \sigma} \\ & h \sum_{i} \sum_{a} \left(n_{i, a, \uparrow}  n_{i, a, \downarrow}\right) \end{align}\end{split}\]where
 The indices \((i, j)\) and \(\{i, j\}\) run over ordered and unordered pairs, respectively of sites \(i\) and \(j\) of neighboring sites in the lattice,
 \(a\) and \(b\) index degrees of freedom on each site,
 \(\sigma \in \{\uparrow, \downarrow\}\) is the spin,
 \(t_{a, b}^{(\mathrm{onsite})}\) is the tunneling amplitude between spin orbitals on the same site,
 \(t_{a, b}^{(\mathrm{nghbr})}\) is the tunneling amplitude between spin orbitals on neighboring sites,
 \(U_{a, b}^{(\mathrm{onsite, \pm})}\) is the Coulomb potential between spin orbitals on the same site with the same (+) or different () spins,
 \(U_{a, b}^{(\mathrm{nghbr, \pm})}\) is the Coulomb potential betwen spin orbitals on neighborings sites with the same (+) or different () spins,
 \(\mu_{a}\) is the chemical potential, and
 \(h\) is the magnetic field.
One can also construct the Hamiltonian for the spinless model, which has the form
\[\begin{split}\begin{align} H = & \sum_{a < b} t_{a, b}^{(\mathrm{onsite})} \sum_{i} (a^\dagger_{i, a} a_{i, b} + a^\dagger_{i, b} a_{i, a}) \\ & \sum_{a} t_{a, a}^{(\mathrm{nghbr})} \sum_{\{i, j\}} (a^\dagger_{i, a} a_{j, a} + a^\dagger_{j, a} a_{i, a})  \sum_{a < b} t_{a, b}^{(\mathrm{nghbr})} \sum_{(i, j)} (a^\dagger_{i, a} a_{j, b} + a^\dagger_{j, b} a_{i, a}) \\ &+ \sum_{a < b} U_{a, b}^{(\mathrm{onsite})} \sum_{i} n_{i, a} n_{i, b} \\ &+ \sum_{a} U_{a, a}^{(\mathrm{nghbr})} \sum_{\{i, j\}} n_{i, a} n_{j, a} + \sum_{a < b} U_{a, b}^{(\mathrm{nghbr})} \sum_{(i, j)} n_{i, a} n_{j, b} \\ & \sum_{a} \mu_a \sum_i n_{i, a} \end{align}\end{split}\]
__init__
(lattice, tunneling_parameters=None, interaction_parameters=None, potential_parameters=None, magnetic_field=0.0, particle_hole_symmetry=False)¶ A Hubbard model defined on a lattice.
Parameters:  lattice (HubbardLattice) – The lattice on which the model is defined.
 (Iterable[Tuple[Hashable, Tuple[int, int], (interaction_parameters) – float]], optional): The tunneling parameters.
 (Iterable[Tuple[Hashable, Tuple[int, int], – float, int?]], optional): The interaction parameters.
 potential_parameters (Iterable[Tuple[int, float]], optional) – The potential parameters.
 magnetic_field (float, optional) – The magnetic field. Default is 0.
 particle_hole_symmetry – If true, each number operator \(n\) is replaced with \(n  1/2\).
Each group of parameters is specified as an iterable of tuples.
Each tunneling parameter is a tuple
(edge_type, dofs, coefficient)
.In the spinful, model, the tunneling parameter corresponds to the terms
\[t \sum_{(i, j) \in E^{(\mathrm{edge type})}} \sum_{\sigma} \left(a_{i, a, \sigma}^{\dagger} a_{j, b, \sigma} + a_{j, b, \sigma}^{\dagger} a_{i, a, \sigma}\right)\]and in the spinless model to
\[t \sum_{(i, j) \in E^{(\mathrm{edge type})}} \left(a_{i, a}^{\dagger} a_{j, b} + a_{j, b}^{\dagger} a_{i, a}\right),\]where
 \((a, b)\) is the pair of degrees
of freedom given by
dofs
;  \(E^{(\mathrm{edge type})}\) is the set of ordered pairs ofsite indices returned bylattice.site_pairs_iter(edge_type, a != b)
; and \(t\) is the
coefficient
.
Each interaction parameter is a tuple
(edge_type, dofs, coefficient, spin_pairs)
. The finalspin_pairs
element is optional, and will default toSpinPairs.ALL
. In any case, it is ignored for spinless lattices.For example, in the spinful model if dofs indicates distinct degrees of freedom then the parameter corresponds to the terms
\[\]U sum_{(i, j) in E^{(mathrm{edge type})}} sum_{(sigma, sigma’)} n_{i, a, sigma} n_{j, b, sigma’}
where
 \((a, b)\) is the pair of degrees of
freedom given by
dofs
;  \(E^{(\mathrm{edge type})}\) is the set of ordered pairs ofsite indices returned bylattice.site_pairs_iter(edge_type)
;\(U\) is the
coefficient
; and \((\sigma, \sigma')\) runs over
 all four possible pairs of spins
if spin_pairs == SpinPairs.ALL,  \(\{(\uparrow, \downarrow), (\downarrow, \uparrow)\}\) if spin_pairs == SpinPairs.DIFF, and  \(\{(\uparrow, \uparrow), (\downarrow, \downarrow)\}' if 'spin_pairs == SpinPairs.SAME\).
Each potential parameter is a tuple
(dof, coefficient)
. For example, in the spinful model, it corresponds to the terms\[\mu \sum_{i} \sum_{\sigma} n_{i, a, \sigma},\]where
 \(i\) runs over the sites of the lattice;
 \(a\) is the degree of freedom
dof
; and  \(\mu\) is the
coefficient
.
In the spinless model, the magnetic field is ignored.

class
openfermion.hamiltonians.
HartreeFockFunctional
(*, one_body_integrals: numpy.ndarray, two_body_integrals: numpy.ndarray, overlap: numpy.ndarray, n_electrons: int, model='rhf', nuclear_repulsion: Optional[float] = 0.0, initial_orbitals: Union[None, Callable] = None)¶ Implementation of the objective function code for Restricted HartreeFock
The object transforms a variety of input types into the appropriate output. It does this by analyzing the type and size of the input based on its knowledge of each type.

__init__
(*, one_body_integrals: numpy.ndarray, two_body_integrals: numpy.ndarray, overlap: numpy.ndarray, n_electrons: int, model='rhf', nuclear_repulsion: Optional[float] = 0.0, initial_orbitals: Union[None, Callable] = None)¶ Initialize functional
Parameters:  one_body_integrals – integrals in the atomic orbital basis for the onebody potential.
 two_body_integrals – integrals in the atomic obrital basis for the twobody potential ordered according to phi_{p}(r1)^{*}phi_{q}^{*}(r2) x phi_{r}(r2)phi_{s}(r1)
 overlap – overlap integrals in the atomic orbital basis
 n_electrons – number of electrons total
 model – Optional flag for performing restricted, unrestricted, or generalized hartreefock.
 nuclear_repulsion – Optional nuclear repulsion term. Energy is shifted by this amount. default is 0.
 initial_orbitals – Method for producing the initial orbitals from the atomic orbitals. Default is defining the core orbitals.

energy_from_rhf_opdm
(opdm_aa: numpy.ndarray) → float¶ Compute the energy given a spinup opdm
Parameters: opdm_aa – spinup opdm. Should be an n x n matrix where n is the number of spatial orbitals Returns: RHF energy

rdms_from_rhf_opdm
(opdm_aa: numpy.ndarray) → openfermion.ops.representations.interaction_rdm.InteractionRDM¶ Generate spinorbital InteractionRDM object from the alphaspin opdm.
Parameters: opdm_aa – single spin sector of the 1particle denstiy matrix Returns: InteractionRDM object for full spinorbital 1RDM and 2RDM

rhf_global_gradient
(params: numpy.ndarray, alpha_opdm: numpy.ndarray)¶ Compute rhf global gradient
Parameters:  params – rhfparameters for rotation matrix.
 alpha_opdm – 1RDM corresponding to results of basis rotation parameterized by `params’.
Returns: gradient vector the same size as the input `params’


openfermion.hamiltonians.
bose_hubbard
(x_dimension, y_dimension, tunneling, interaction, chemical_potential=0.0, dipole=0.0, periodic=True)¶ Return symbolic representation of a BoseHubbard Hamiltonian.
In this model, bosons move around on a lattice, and the energy of the model depends on where the bosons are.
The lattice is described by a 2D grid, with dimensions x_dimension x y_dimension. It is also possible to specify if the grid has periodic boundary conditions or not.
The Hamiltonian for the BoseHubbard model has the form
\[H =  t \sum_{\langle i, j \rangle} (b_i^\dagger b_j + b_j^\dagger b_i) + V \sum_{\langle i, j \rangle} b_i^\dagger b_i b_j^\dagger b_j + \frac{U}{2} \sum_i b_i^\dagger b_i (b_i^\dagger b_i  1)  \mu \sum_i b_i^\dagger b_i.\]where
 The indices \(\langle i, j \rangle\) run over pairs \(i\) and \(j\) of nodes that are connected to each other in the grid
 \(t\) is the tunneling amplitude
 \(U\) is the onsite interaction potential
 \(\mu\) is the chemical potential
 \(V\) is the dipole or nearestneighbour interaction potential
Parameters:  x_dimension (int) – The width of the grid.
 y_dimension (int) – The height of the grid.
 tunneling (float) – The tunneling amplitude \(t\).
 interaction (float) – The attractive local interaction strength \(U\).
 chemical_potential (float, optional) – The chemical potential \(\mu\) at each site. Default value is 0.
 periodic (bool, optional) – If True, add periodic boundary conditions. Default is True.
 dipole (float) – The attractive dipole interaction strength \(V\).
Returns: bose_hubbard_model – An instance of the BosonOperator class.

openfermion.hamiltonians.
dual_basis_external_potential
(grid, geometry, spinless, non_periodic=False, period_cutoff=None)¶ Return the external potential in the dual basis of arXiv:1706.00023.
 The external potential resulting from electrons interacting with nuclei
 in the plane wave dual basis. Note that a cos term is used which is strictly only equivalent under aliasing in odd grids, and amounts to the addition of an extra term to make the diagonals real on even grids. This approximation is not expected to be significant and allows for use of even and odd grids on an even footing.
Parameters:  grid (Grid) – The discretization to use.
 geometry – A list of tuples giving the coordinates of each atom. example is [(‘H’, (0, 0, 0)), (‘H’, (0, 0, 0.7414))]. Distances in atomic units. Use atomic symbols to specify atoms.
 spinless (bool) – Whether to use the spinless model or not.
 non_periodic (bool) – If the system is nonperiodic, default to False.
 period_cutoff (float) – Period cutoff, default to grid.volume_scale() ** (1. / grid.dimensions)
Returns: FermionOperator – The dual basis operator.

openfermion.hamiltonians.
dual_basis_jellium_model
(grid, spinless=False, kinetic=True, potential=True, include_constant=False, non_periodic=False, period_cutoff=None)¶ Return jellium Hamiltonian in the dual basis of arXiv:1706.00023
Parameters:  grid (Grid) – The discretization to use.
 spinless (bool) – Whether to use the spinless model or not.
 kinetic (bool) – Whether to include kinetic terms.
 potential (bool) – Whether to include potential terms.
 include_constant (bool) – Whether to include the Madelung constant. Note constant is unsupported for nonuniform, noncubic cells with ions.
 non_periodic (bool) – If the system is nonperiodic, default to False.
 period_cutoff (float) – Period cutoff, default to grid.volume_scale() ** (1. / grid.dimensions).
Returns: operator (FermionOperator)

openfermion.hamiltonians.
dual_basis_kinetic
(grid, spinless=False)¶ Return the kinetic operator in the dual basis of arXiv:1706.00023.
Parameters:  grid (Grid) – The discretization to use.
 spinless (bool) – Whether to use the spinless model or not.
Returns: operator (FermionOperator)

openfermion.hamiltonians.
dual_basis_potential
(grid, spinless=False, non_periodic=False, period_cutoff=None)¶ Return the potential operator in the dual basis of arXiv:1706.00023
Parameters:  grid (Grid) – The discretization to use.
 spinless (bool) – Whether to use the spinless model or not.
 non_periodic (bool) – If the system is nonperiodic, default to False.
 period_cutoff (float) – Period cutoff, default to grid.volume_scale() ** (1. / grid.dimensions).
Returns: operator (FermionOperator)

openfermion.hamiltonians.
fermi_hubbard
(x_dimension, y_dimension, tunneling, coulomb, chemical_potential=0.0, magnetic_field=0.0, periodic=True, spinless=False, particle_hole_symmetry=False)¶ Return symbolic representation of a FermiHubbard Hamiltonian.
The idea of this model is that some fermions move around on a grid and the energy of the model depends on where the fermions are. The Hamiltonians of this model live on a grid of dimensions x_dimension x y_dimension. The grid can have periodic boundary conditions or not. In the standard FermiHubbard model (which we call the “spinful” model), there is room for an “up” fermion and a “down” fermion at each site on the grid. In this model, there are a total of 2N spinorbitals, where N = x_dimension * y_dimension is the number of sites. In the spinless model, there is only one spinorbital per site for a total of N.
The Hamiltonian for the spinful model has the form
\[\begin{split}\begin{align} H = & t \sum_{\langle i,j \rangle} \sum_{\sigma} (a^\dagger_{i, \sigma} a_{j, \sigma} + a^\dagger_{j, \sigma} a_{i, \sigma}) + U \sum_{i} a^\dagger_{i, \uparrow} a_{i, \uparrow} a^\dagger_{i, \downarrow} a_{i, \downarrow} \\ & \mu \sum_i \sum_{\sigma} a^\dagger_{i, \sigma} a_{i, \sigma}  h \sum_i (a^\dagger_{i, \uparrow} a_{i, \uparrow}  a^\dagger_{i, \downarrow} a_{i, \downarrow}) \end{align}\end{split}\]where
 The indices \(\langle i, j \rangle\) run over pairs \(i\) and \(j\) of sites that are connected to each other in the grid
 \(\sigma \in \{\uparrow, \downarrow\}\) is the spin
 \(t\) is the tunneling amplitude
 \(U\) is the Coulomb potential
 \(\mu\) is the chemical potential
 \(h\) is the magnetic field
One can also construct the Hamiltonian for the spinless model, which has the form
\[H =  t \sum_{\langle i, j \rangle} (a^\dagger_i a_j + a^\dagger_j a_i) + U \sum_{\langle i, j \rangle} a^\dagger_i a_i a^\dagger_j a_j  \mu \sum_i a_i^\dagger a_i.\]Parameters:  x_dimension (int) – The width of the grid.
 y_dimension (int) – The height of the grid.
 tunneling (float) – The tunneling amplitude \(t\).
 coulomb (float) – The attractive local interaction strength \(U\).
 chemical_potential (float, optional) – The chemical potential \(\mu\) at each site. Default value is 0.
 magnetic_field (float, optional) – The magnetic field \(h\) at each site. Default value is 0. Ignored for the spinless case.
 periodic (bool, optional) – If True, add periodic boundary conditions. Default is True.
 spinless (bool, optional) – If True, return a spinless FermiHubbard model. Default is False.
 particle_hole_symmetry (bool, optional) –
If False, the repulsion term corresponds to:
\[U \sum_{k=1}^{N1} a_k^\dagger a_k a_{k+1}^\dagger a_{k+1}\]If True, the repulsion term is replaced by:
\[U \sum_{k=1}^{N1} (a_k^\dagger a_k  \frac12) (a_{k+1}^\dagger a_{k+1}  \frac12)\]which is unchanged under a particlehole transformation. Default is False
Returns: hubbard_model – An instance of the FermionOperator class.

openfermion.hamiltonians.
get_matrix_of_eigs
(w: numpy.ndarray) → numpy.ndarray¶ Transform the eigenvalues into a matrix corresponding to summing the adjoint rep.
Parameters: w – eigenvalues of Cmatrix Returns: new array of transformed eigenvalues

openfermion.hamiltonians.
hartree_fock_state_jellium
(grid, n_electrons, spinless=True, plane_wave=False)¶ Give the HartreeFock state of jellium.
Parameters:  grid (Grid) – The discretization to use.
 n_electrons (int) – Number of electrons in the system.
 spinless (bool) – Whether to use the spinless model or not.
 plane_wave (bool) – Whether to return the HartreeFock state in the plane wave (True) or dual basis (False).
Notes
The jellium model is built up by filling the lowestenergy singleparticle states in the planewave Hamiltonian until n_electrons states are filled.

openfermion.hamiltonians.
hypercube_grid_with_given_wigner_seitz_radius_and_filling
(dimension, grid_length, wigner_seitz_radius, filling_fraction=0.5, spinless=True)¶ Return a Grid with the same number of orbitals along each dimension with the specified WignerSeitz radius.
Parameters:  dimension (int) – The number of spatial dimensions.
 grid_length (int) – The number of orbitals along each dimension.
 wigner_seitz_radius (float) – The WignerSeitz radius per particle, in Bohr.
 filling_fraction (float) – The average spinorbital occupation. Specifies the number of particles (rounding down).
 spinless (boolean) – Whether to give the system without or with spin.

openfermion.hamiltonians.
jellium_model
(grid, spinless=False, plane_wave=True, include_constant=False, e_cutoff=None, non_periodic=False, period_cutoff=None)¶ Return jellium Hamiltonian as FermionOperator class.
Parameters:  grid (openfermion.utils.Grid) – The discretization to use.
 spinless (bool) – Whether to use the spinless model or not.
 plane_wave (bool) – Whether to return in momentum space (True) or position space (False).
 include_constant (bool) – Whether to include the Madelung constant. Note constant is unsupported for nonuniform, noncubic cells with ions.
 e_cutoff (float) – Energy cutoff.
 non_periodic (bool) – If the system is nonperiodic, default to False.
 period_cutoff (float) – Period cutoff, default to grid.volume_scale() ** (1. / grid.dimensions).
Returns: FermionOperator – The Hamiltonian of the model.

openfermion.hamiltonians.
jordan_wigner_dual_basis_hamiltonian
(grid, geometry=None, spinless=False, include_constant=False)¶ Return the dual basis Hamiltonian as QubitOperator.
Parameters:  grid (Grid) – The discretization to use.
 geometry – A list of tuples giving the coordinates of each atom. example is [(‘H’, (0, 0, 0)), (‘H’, (0, 0, 0.7414))]. Distances in atomic units. Use atomic symbols to specify atoms.
 spinless (bool) – Whether to use the spinless model or not.
 include_constant (bool) – Whether to include the Madelung constant.
Returns: hamiltonian (QubitOperator)

openfermion.hamiltonians.
jordan_wigner_dual_basis_jellium
(grid, spinless=False, include_constant=False)¶ Return the jellium Hamiltonian as QubitOperator in the dual basis.
Parameters:  grid (Grid) – The discretization to use.
 spinless (bool) – Whether to use the spinless model or not.
 include_constant (bool) – Whether to include the Madelung constant. Note constant is unsupported for nonuniform, noncubic cells with ions.
Returns: hamiltonian (QubitOperator)

openfermion.hamiltonians.
majorana_operator
(term=None, coefficient=1.0)¶ Initialize a Majorana operator.
Parameters:  term (tuple or string) –
The first element of the tuple indicates the mode on which the Majorana operator acts, starting from zero. The second element of the tuple is an integer, either 0 or 1, indicating which type of Majorana operator it is:
Type 0: \(a^\dagger_p + a_p\)Type 1: \(i (a^\dagger_p  a_p)\)
where the \(a^\dagger_p\) and \(a_p\) are the usual fermionic ladder operators. Alternatively, one can provide a string such as ‘c2’, which is a Type 0 operator on mode 2, or ‘d3’, which is a Type 1 operator on mode 3. Default will result in the zero operator.
 coefficient (complex or float, optional) – The coefficient of the term. Default value is 1.0.
Returns: FermionOperator
 term (tuple or string) –

openfermion.hamiltonians.
mean_field_dwave
(x_dimension, y_dimension, tunneling, sc_gap, chemical_potential=0.0, periodic=True)¶ Return symbolic representation of a BCS meanfield dwave Hamiltonian.
The Hamiltonians of this model live on a grid of dimensions x_dimension x y_dimension. The grid can have periodic boundary conditions or not. Each site on the grid can have an “up” fermion and a “down” fermion. Therefore, there are a total of 2N spinorbitals, where N = x_dimension * y_dimension is the number of sites.
The Hamiltonian for this model has the form
\[\begin{split}\begin{align} H = & t \sum_{\langle i,j \rangle} \sum_\sigma (a^\dagger_{i, \sigma} a_{j, \sigma} + a^\dagger_{j, \sigma} a_{i, \sigma})  \mu \sum_i \sum_{\sigma} a^\dagger_{i, \sigma} a_{i, \sigma} \\ & \sum_{\langle i,j \rangle} \Delta_{ij} (a^\dagger_{i, \uparrow} a^\dagger_{j, \downarrow}  a^\dagger_{i, \downarrow} a^\dagger_{j, \uparrow} + a_{j, \downarrow} a_{i, \uparrow}  a_{j, \uparrow} a_{i, \downarrow}) \end{align}\end{split}\]where
 The indices \(\langle i, j \rangle\) run over pairs \(i\) and \(j\) of sites that are connected to each other in the grid
 \(\sigma \in \{\uparrow, \downarrow\}\) is the spin
 \(t\) is the tunneling amplitude
 \(\Delta_{ij}\) is equal to \(+\Delta/2\) for horizontal edges and \(\Delta/2\) for vertical edges, where \(\Delta\) is the superconducting gap.
 \(\mu\) is the chemical potential
Parameters:  x_dimension (int) – The width of the grid.
 y_dimension (int) – The height of the grid.
 tunneling (float) – The tunneling amplitude \(t\).
 sc_gap (float) – The superconducting gap \(\Delta\)
 chemical_potential (float, optional) – The chemical potential \(\mu\) at each site. Default value is 0.
 periodic (bool, optional) – If True, add periodic boundary conditions. Default is True.
Returns: mean_field_dwave_model – An instance of the FermionOperator class.

openfermion.hamiltonians.
number_operator
(n_modes, mode=None, coefficient=1.0, parity=1)¶ Return a fermionic or bosonic number operator.
Parameters:  n_modes (int) – The number of modes in the system.
 mode (int, optional) – The mode on which to return the number operator. If None, return total number operator on all sites.
 coefficient (float) – The coefficient of the term.
 parity (int) – Returns the fermionic number operator if parity=1 (default), and returns the bosonic number operator if parity=1.
Returns: operator (BosonOperator or FermionOperator)

openfermion.hamiltonians.
plane_wave_external_potential
(grid, geometry, spinless, e_cutoff=None, non_periodic=False, period_cutoff=None)¶ Return the external potential operator in plane wave basis.
 The external potential resulting from electrons interacting with nuclei.
 It is defined here as the Fourier transform of the dual basis Hamiltonian such that is spectrally equivalent in the case of both even and odd grids. Otherwise, the two differ in the case of even grids.
Parameters:  grid (Grid) – The discretization to use.
 geometry – A list of tuples giving the coordinates of each atom. example is [(‘H’, (0, 0, 0)), (‘H’, (0, 0, 0.7414))]. Distances in atomic units. Use atomic symbols to specify atoms.
 spinless – Bool, whether to use the spinless model or not.
 e_cutoff (float) – Energy cutoff.
 non_periodic (bool) – If the system is nonperiodic, default to False.
 period_cutoff (float) – Period cutoff, default to grid.volume_scale() ** (1. / grid.dimensions)
Returns: FermionOperator – The plane wave operator.

openfermion.hamiltonians.
plane_wave_hamiltonian
(grid, geometry=None, spinless=False, plane_wave=True, include_constant=False, e_cutoff=None, non_periodic=False, period_cutoff=None)¶ Returns Hamiltonian as FermionOperator class.
Parameters:  grid (Grid) – The discretization to use.
 geometry – A list of tuples giving the coordinates of each atom. example is [(‘H’, (0, 0, 0)), (‘H’, (0, 0, 0.7414))]. Distances in atomic units. Use atomic symbols to specify atoms.
 spinless (bool) – Whether to use the spinless model or not.
 plane_wave (bool) – Whether to return in plane wave basis (True) or plane wave dual basis (False).
 include_constant (bool) – Whether to include the Madelung constant.
 e_cutoff (float) – Energy cutoff.
 non_periodic (bool) – If the system is nonperiodic, default to False.
 period_cutoff (float) – Period cutoff, default to grid.volume_scale() ** (1. / grid.dimensions)
Returns: FermionOperator – The hamiltonian.

openfermion.hamiltonians.
plane_wave_kinetic
(grid, spinless=False, e_cutoff=None)¶ Return the kinetic energy operator in the plane wave basis.
Parameters:  grid (openfermion.utils.Grid) – The discretization to use.
 spinless (bool) – Whether to use the spinless model or not.
 e_cutoff (float) – Energy cutoff.
Returns: FermionOperator – The kinetic momentum operator.

openfermion.hamiltonians.
plane_wave_potential
(grid, spinless=False, e_cutoff=None, non_periodic=False, period_cutoff=None)¶ Return the ee potential operator in the plane wave basis.
Parameters:  grid (Grid) – The discretization to use.
 spinless (bool) – Whether to use the spinless model or not.
 e_cutoff (float) – Energy cutoff.
 non_periodic (bool) – If the system is nonperiodic, default to False.
 period_cutoff (float) – Period cutoff, default to grid.volume_scale() ** (1. / grid.dimensions).
Returns: operator (FermionOperator)

openfermion.hamiltonians.
rhf_minimization
(rhf_object: openfermion.hamiltonians.hartree_fock.HartreeFockFunctional, method: Optional[str] = 'CG', initial_guess: Union[None, numpy.ndarray] = None, verbose: Optional[bool] = True, sp_options: Union[None, Dict[KT, VT]] = None) → scipy.optimize.optimize.OptimizeResult¶ Perform HartreeFock energy minimization
Parameters:  rhf_object – An instantiation of the HartreeFockFunctional
 method – (optional) scipy optimization method
 initial_guess – (optional) initial rhf parameter vector. If None zero vector is used.
 verbose – (optional) turn on printing. This is passed to the scipy ‘disp’ option.
 sp_options –
Returns: scipy.optimize result object

openfermion.hamiltonians.
rhf_params_to_matrix
(parameters: numpy.ndarray, num_orbitals: int, occ: Union[None, List[int]] = None, virt: Union[None, List[int]] = None) → numpy.ndarray¶ For restricted HartreeFock we have nocc * nvirt parameters. These are provided as a list that is ordered by (virtuals) imes (occupied).
For example, for H4 we have 2 orbitals occupied and 2 virtuals
occupied = [0, 1] virtuals = [2, 3]
 parameters = [(v_{0}, o_{0}), (v_{0}, o_{1}), (v_{1}, o_{0}), (v_{1}, o_{1})]
 = [(2, 0), (2, 1), (3, 0), (3, 1)]
You can think of the tuples of elements of the upper right triangle of the antihermitian matrix that specifies the c_{b, i} coefficients.
coefficient matrix [[ c_{0, 0}, c_{1, 0}, c_{2, 0}, c_{3, 0}],
[ c_{1, 0}, c_{1, 1}, c_{2, 1}, c_{3, 1}], [ c_{2, 0}, c_{2, 1}, c_{2, 2}, c_{3, 2}], [ c_{3, 0}, c_{3, 1}, c_{3, 2}, c_{3, 3}]]Since we are working with only nonredundant operators we know c_{i, i} = 0 and any c_{i, j} where i and j are both in occupied or both in virtual = 0.
Parameters:  parameters – array of parameters for kappa matrix
 num_orbitals – total number of spatial orbitals
 occ – (Optional) indices for doubly occupied sector
 virt – (Optional) indices for virtual sector
Returns: np.ndarray kappa matrix

openfermion.hamiltonians.
s_plus_operator
(n_spatial_orbitals)¶ Return the s+ operator.
\[\begin{align} S^{+} = \sum_{i=1}^{n} a_{i, \alpha}^{\dagger}a_{i, \beta} \end{align}\]Parameters: n_spatial_orbitals – number of spatial orbitals (n_qubits + 1 // 2). Returns: operator (FermionOperator) – corresponding to the s+ operator over n_spatial_orbitals. Note
The indexing convention used is that even indices correspond to spinup (alpha) modes and odd indices correspond to spindown (beta) modes.

openfermion.hamiltonians.
s_squared_operator
(n_spatial_orbitals)¶ Return the s^{2} operator.
\[\begin{align} S^{2} = S^{} S^{+} + S^{z}( S^{z} + 1) \end{align}\]Parameters: n_spatial_orbitals – number of spatial orbitals (n_qubits + 1 // 2). Returns: operator (FermionOperator) – corresponding to the s+ operator over n_spatial_orbitals. Note
The indexing convention used is that even indices correspond to spinup (alpha) modes and odd indices correspond to spindown (beta) modes.

openfermion.hamiltonians.
sx_operator
(n_spatial_orbitals)¶ Return the sx operator.
\[\begin{align} S^{x} = \frac{1}{2}\sum_{i = 1}^{n}(S^{+} + S^{}) \end{align}\]Parameters: n_spatial_orbitals – number of spatial orbitals (n_qubits // 2). Returns: operator (FermionOperator) – corresponding to the sx operator over n_spatial_orbitals. Note
The indexing convention used is that even indices correspond to spinup (alpha) modes and odd indices correspond to spindown (beta) modes.

openfermion.hamiltonians.
sy_operator
(n_spatial_orbitals)¶ Return the sy operator.
\[\begin{align} S^{y} = \frac{i}{2}\sum_{i = 1}^{n}(S^{+}  S^{}) \end{align}\]Parameters: n_spatial_orbitals – number of spatial orbitals (n_qubits // 2). Returns: operator (FermionOperator) – corresponding to the sx operator over n_spatial_orbitals. Note
The indexing convention used is that even indices correspond to spinup (alpha) modes and odd indices correspond to spindown (beta) modes.

openfermion.hamiltonians.
sz_operator
(n_spatial_orbitals)¶ Return the sz operator.
\[\begin{align} S^{z} = \frac{1}{2}\sum_{i = 1}^{n}(n_{i, \alpha}  n_{i, \beta}) \end{align}\]Parameters: n_spatial_orbitals – number of spatial orbitals (n_qubits // 2). Returns: operator (FermionOperator) – corresponding to the sz operator over n_spatial_orbitals. Note
The indexing convention used is that even indices correspond to spinup (alpha) modes and odd indices correspond to spindown (beta) modes.

openfermion.hamiltonians.
wigner_seitz_length_scale
(wigner_seitz_radius, n_particles, dimension)¶ Function to give length_scale associated with WignerSeitz radius.
Parameters:  wigner_seitz_radius (float) – The radius per particle in atomic units.
 n_particles (int) – The number of particles in the simulation cell.
 dimension (int) – The dimension of the system.
Returns: length_scale (float) – The length scale for the simulation.
Raises: ValueError
– System dimension must be a positive integer.
openfermion.measurements¶

openfermion.measurements.
apply_constraints
(operator, n_fermions)¶ Function to use linear programming to apply constraints.
Parameters:  operator (FermionOperator) – FermionOperator with only 1 and 2body terms that we wish to vectorize.
 n_fermions (int) – The number of particles in the simulation.
Returns: modified_operator(FermionOperator) –
 The operator with reduced norm
that has been modified with equality constraints.

openfermion.measurements.
binary_partition_iterator
(qubit_list, num_iterations=None)¶ Generator for a list of 2partitions of N qubits such that all pairs of qubits are split in at least one partition, This follows a variation on ArXiv:1908.0562  instead of explicitly partitioning the list based on the binary indices of the qubits, we repeatedly divide the list in two and then zip it back together.
Parameters:  qubit_list (list) – list of qubits to be partitioned
 num_iterations (int or None) – number of iterations to perform. If None, will be set to ceil(log2(len(qubit_list)))
Returns: partition(iterator of tuples of lists) – the required partitioning

openfermion.measurements.
constraint_matrix
(n_orbitals, n_fermions)¶ Function to generate matrix of constraints.
Parameters:  n_orbitals (int) – The number of orbitals in the simulation.
 n_fermions (int) – The number of particles in the simulation.
Returns: constraint_matrix(scipy.sparse.coo_matrix) – The matrix of constraints.

openfermion.measurements.
get_interaction_rdm
(qubit_operator, n_qubits=None)¶ Build an InteractionRDM from measured qubit operators.
Returns: An InteractionRDM object.

openfermion.measurements.
linearize_term
(term, n_orbitals)¶ Function to return integer index of term indices.
Parameters:  term (tuple) – The term indices of a one or twobody FermionOperator.
 n_orbitals (int) – The number of orbitals in the simulation.
Returns: index(int) – The index of the term.

openfermion.measurements.
one_body_fermion_constraints
(n_orbitals, n_fermions)¶ Generates onebody positivity constraints on fermionic RDMs.
The specific constraints implemented are known positivity constraints on the onefermion reduced density matrices. Constraints are generated in the form of FermionOperators whose expectation value is known to be zero for any NRepresentable state. Generators are used for efficiency.Parameters:  n_orbitals (int) – number of spinorbitals on which operators act.
 n_fermions (int) – number of fermions in the system.
Yields: Constraint is a FermionOperator with zero expectation value.

openfermion.measurements.
partition_iterator
(qubit_list, partition_size, num_iterations=None)¶ Generator for a list of kpartitions of N qubits such that all sets of k qubits are perfectly split in at least one partition, following ArXiv:1908.05628
Parameters:  qubit_list (list) – list of qubits to be partitioned
 partition_size (int) – the number of sets in the partition.
 num_iterations (int or None) – the number of iterations in the outer iterator. If None, set to ceil(log2(len(qubit_list)))
Returns: partition(iterator of tuples of lists) – the required partitioning

openfermion.measurements.
pauli_string_iterator
(num_qubits, max_word_size=2)¶ Generates a set of Pauli strings such that each word of k Pauli operators lies in at least one string.
Parameters:  num_qubits (int) – number of qubits in string
 max_word_size (int) – maximum required word
Returns: pauli_string(iterator of strings) –
 iterator
over Pauli strings

openfermion.measurements.
prony
(signal)¶ Estimates amplitudes and phases of a sparse signal using Prony’s method.
Singleancilla quantum phase estimation returns a signal g(k)=sum (aj*exp(i*k*phij)), where aj and phij are the amplitudes and corresponding eigenvalues of the unitary whose phases we wish to estimate. When more than one amplitude is involved, Prony’s method provides a simple estimation tool, which achieves nearHeisenberglimited scaling (error scaling as N^{1/2}K^{3/2}).
Parameters: signal (1d complex array) – the signal to fit Returns: amplitudes(list of complex values) – the amplitudes a_i, in descending order by their complex magnitude phases(list of complex values): the complex frequencies gamma_i, correlated with amplitudes.

openfermion.measurements.
two_body_fermion_constraints
(n_orbitals, n_fermions)¶ Generates twobody positivity constraints on fermionic RDMs.
The specific constraints implemented are known positivity constraints on the twofermion reduced density matrices. Constraints are generated in the form of FermionOperators whose expectation value is known to be zero for any NRepresentable state. Generators are used for efficiency.Parameters:  n_orbitals (int) – number of spinorbitals on which operators act.
 n_fermions (int) – number of fermions in the system.
Yields: Constraint is a FermionOperator with zero expectation value.

openfermion.measurements.
unlinearize_term
(index, n_orbitals)¶ Function to return integer index of term indices.
Parameters:  index (int) – The index of the term.
 n_orbitals (int) – The number of orbitals in the simulation.
Returns: term(tuple) – The term indices of a one or twobody FermionOperator.
openfermion.ops¶
This module should contain objects that describe the algebra of various operators and representations which can be thought of as abstract instances that serve as storage of the operators. The abstract instance objects derive from the PolynomialTensor. Here we differentiate between generic storage objects and particular instantiations.

class
openfermion.ops.
BinaryCode
(encoding, decoding)¶ Bases:
object
The BinaryCode class provides a representation of an encodingdecoding pair for binary vectors of different lengths, where the decoding is allowed to be nonlinear.
As the occupation number of fermionic mode is effectively binary, a lengthN vector (v) of binary number can be utilized to describe a configuration of a manybody fermionic state on N modes. An nqubit product state configuration w0> w1> w2> … wn1>, on the other hand is described by a lengthn binary vector w=(w0, w1, …, wn1). To map a subset of NOrbital Fermion states to nqubit states we define a binary code, which consists of a (here: linear) encoding (e) and a (nonlinear) decoding (d), such that for every v from that subset, w = e(v) is a lengthn binary vector with d(w) = v. This can be used to save qubits given a Hamiltonian that dictates such a subset, otherwise n=N.
Two binary codes (e,d) and (e’,d’) can construct a third code (e”,d”) by two possible operations:
Concatenation: (e”,d”) = (e,d) * (e’,d’) which means e”: v” > e’( e(v”) ) and d”: w” > d( d’(w”) ) where n” = n’ and N” = N, with n = N’ as necessary condition.
Appendage: (e”,d”) = (e,d) + (e’,d’) which means e”: (v + v’) > e(v) + e’(v’) and d”: (w + w’) > d(w) + d’( w’) where the addition is to be understood as appending two vectors together, so N” = N’ + N and n” = n + n’.
Appending codes is particularly useful when considering segment codes or segmented transforms.
A BinaryCodeinstance is initialized by BinaryCode(A,d), given the encoding (e) as n x N array or matrixlike nested lists A, such that e(v) = (A v) mod 2. The decoding d is an array or a list input of length N, which has entries either of type BinaryPolynomial, or of valid type for an input of the BinaryPolynomialconstructor.
The signs + and *, += and *= are overloaded to implement concatenation and appendage on BinaryCodeobjects.
 NOTE: multiplication of a BinaryCode with an integer yields a
 multiple appending of the same code, the multiplication with another BinaryCode their concatenation.

decoder
¶ list of BinaryPolynomial: Outputs the decoding functions as components.
Type: list

encoder
¶ Outputs A, the linear matrix that implements the encoding function.
Type: scipy.sparse.csc_matrix

n_modes
¶ Outputs the number of modes.
Type: int

n_qubits
¶ Outputs the number of qubits.
Type: int

__init__
(encoding, decoding)¶ Initialization of a binary code.
Parameters:  encoding (np.ndarray or list) – nested lists or binary 2Darray
 decoding (array or list) – list of BinaryPolynomial (list or str).
Raises: TypeError
– nonlist, array like encoding or decoding, unsuitable BinaryPolynomial generators,BinaryCodeError
– in case of decoder/encoder size mismatch or decoder size, qubits indexed mismatch

exception
openfermion.ops.
BinaryCodeError
¶ Bases:
Exception

class
openfermion.ops.
BinaryPolynomial
(term=None)¶ Bases:
object
The BinaryPolynomial class provides an analytic representation of nonlinear binary functions. An instance of this class describes a term of binary variables (variables of the values {0,1}, indexed by integers like w0, w1, w2 and so on) that is considered to be evaluated modulo 2. This implies the following set of rules:
the binary addition w1 + w1 = 0, binary multiplication w2 * w2 = w2 and power rule w3 ^ 0 = 1, where raising to every other integer power than zero reproduces w3.
Of course, we can also add a nontrivial constant, which is 1. Due to these binary rules, every function available will be a multinomial like e.g.
1 + w1 w2 + w0 w1 .
These binary functions are used for nonlinear binary codes in order to decompress qubit bases back into fermion bases. In that instance, one BinaryPolynomial object characterizes the occupation of single orbital given a multiqubit state in configuration w0> w1> w2> … .
For initialization, the preferred data types is either a string of the multinomial, where each variable and constant is to be well separated by a whitespace, or in its native form of tuples, 1 + w1 w2 + w0 w1 is represented as [(_SYMBOLIC_ONE,),(1,2),(0,1)]
 After initialization,BinaryPolynomial terms can be manipulated with the
 overloaded signs +, * and ^, according to the binary rules mentioned.
Example
bin_fun = BinaryPolynomial('1 + w1 w2 + w0 w1') # Equivalently bin_fun = BinaryPolynomial(1) + BinaryPolynomial([(1,2),(0,1)]) # Equivalently bin_fun = BinaryPolynomial([(_SYMBOLIC_ONE,),(1,2),(0,1)])

terms
¶ a list of tuples. Each tuple represents a summand of the BinaryPolynomial term and each summand can contain multiple tuples representing the factors.
Type: list

__init__
(term=None)¶ Initialize the BinaryPolynomial based on term
Parameters: term (str, list, tuple) – used for initializing a BinaryPolynomial Raises: ValueError
– when term is not a string,list or tuple

enumerate_qubits
()¶ Enumerates all qubits indexed in a given BinaryPolynomial.
Returns (list): a list of qubits

evaluate
(binary_list)¶ Evaluates a BinaryPolynomial
Parameters: binary_list (list, array, str) – a list of binary values corresponding each binary variable (in order of their indices) in the expression Returns (int, 0 or 1): result of the evaluation
Raises: BinaryPolynomialError
– Length of list provided must match the number of qubits indexed in BinaryPolynomial

classmethod
identity
()¶ Returns: multiplicative_identity (BinaryPolynomial) – A symbolic operator u with the property that u*x = x*u = x for all operators x of the same class.

shift
(const)¶ Shift all qubit indices by a given constant.
Parameters: const (int) – the constant to shift the indices by Raises: TypeError
– const must be integer

classmethod
zero
()¶ Returns: additive_identity (BinaryPolynomial) – A symbolic operator o with the property that o+x = x+o = x for all operators x of the same class.

exception
openfermion.ops.
BinaryPolynomialError
¶ Bases:
Exception

class
openfermion.ops.
BosonOperator
(term=None, coefficient=1.0)¶ Bases:
openfermion.ops.operators.symbolic_operator.SymbolicOperator
BosonOperator stores a sum of products of bosonic ladder operators.
In OpenFermion, we describe bosonic ladder operators using the shorthand: ‘i^’ = b^dagger_i ‘j’ = b_j where [‘i’, ‘j^’] = delta_ij is the commutator.
One can multiply together these bosonic ladder operators to obtain a bosonic term. For instance, ‘2^ 1’ is a bosonic term which creates at mode 2 and destroys at mode 1. The BosonicOperator class also stores a coefficient for the term, e.g. ‘3.17 * 2^ 1’.
The BosonOperator class is designed (in general) to store sums of these terms. For instance, an instance of BosonOperator might represent 3.17 2^ 1  66.2 * 8^ 7 6^ 2 The Bosonic Operator class overloads operations for manipulation of these objects by the user.
BosonOperator is a subclass of SymbolicOperator. Importantly, it has attributes set as follows:
actions = (1, 0) action_strings = ('^', '') action_before_index = False different_indices_commute = True
See the documentation of SymbolicOperator for more details.
Example
H = (BosonOperator('0^ 3', .5) + .5 * BosonOperator('3^ 0')) # Equivalently H2 = BosonOperator('0^ 3', 0.5) H2 += BosonOperator('3^ 0', 0.5)
Note
Adding BosonOperator is faster using += (as this is done by inplace addition). Specifying the coefficient during initialization is faster than multiplying a BosonOperator with a scalar.

action_before_index
¶ Whether action comes before index in string representations.

action_strings
¶ The string representations of the allowed actions.

actions
¶ The allowed actions.

different_indices_commute
¶ Whether factors acting on different indices commute.

is_boson_preserving
()¶ Query whether the term preserves particle number.
This is equivalent to requiring the same number of raising and lowering operators in each term.

is_normal_ordered
()¶ Return whether or not term is in normal order.
In our convention, ladder operators come first. Note that unlike the Fermion operator, due to the commutation of ladder operators with different indices, the BosonOperator sorts ladder operators by index.


class
openfermion.ops.
DiagonalCoulombHamiltonian
(one_body, two_body, constant=0.0)¶ Bases:
object
Class for storing Hamiltonians of the form
\[\sum_{p, q} T_{pq} a^\dagger_p a_q + \sum_{p, q} V_{pq} a^\dagger_p a_p a^\dagger_q a_q + \text{constant}\]where
 \(T\) is a Hermitian matrix.
 \(V\) is a real symmetric matrix.

one_body
¶ The Hermitian matrix \(T\).
Type: ndarray

two_body
¶ The real symmetric matrix \(V\).
Type: ndarray

constant
¶ The constant.
Type: float

__init__
(one_body, two_body, constant=0.0)¶ Initialize self. See help(type(self)) for accurate signature.

class
openfermion.ops.
FermionOperator
(term=None, coefficient=1.0)¶ Bases:
openfermion.ops.operators.symbolic_operator.SymbolicOperator
FermionOperator stores a sum of products of fermionic ladder operators.
In OpenFermion, we describe fermionic ladder operators using the shorthand: ‘q^’ = a^dagger_q ‘q’ = a_q where {‘p^’, ‘q’} = delta_pq
One can multiply together these fermionic ladder operators to obtain a fermionic term. For instance, ‘2^ 1’ is a fermion term which creates at orbital 2 and destroys at orbital 1. The FermionOperator class also stores a coefficient for the term, e.g. ‘3.17 * 2^ 1’.
The FermionOperator class is designed (in general) to store sums of these terms. For instance, an instance of FermionOperator might represent 3.17 2^ 1  66.2 * 8^ 7 6^ 2 The Fermion Operator class overloads operations for manipulation of these objects by the user.
FermionOperator is a subclass of SymbolicOperator. Importantly, it has attributes set as follows:
actions = (1, 0) action_strings = ('^', '') action_before_index = False different_indices_commute = False
See the documentation of SymbolicOperator for more details.
Example
ham = (FermionOperator('0^ 3', .5) + .5 * FermionOperator('3^ 0')) # Equivalently ham2 = FermionOperator('0^ 3', 0.5) ham2 += FermionOperator('3^ 0', 0.5)
Note
Adding FermionOperators is faster using += (as this is done by inplace addition). Specifying the coefficient during initialization is faster than multiplying a FermionOperator with a scalar.

action_before_index
¶ Whether action comes before index in string representations.

action_strings
¶ The string representations of the allowed actions.

actions
¶ The allowed actions.

different_indices_commute
¶ Whether factors acting on different indices commute.

is_normal_ordered
()¶ Return whether or not term is in normal order.
In our convention, normal ordering implies terms are ordered from highest tensor factor (on left) to lowest (on right). Also, ladder operators come first.

is_two_body_number_conserving
(check_spin_symmetry=False)¶ Query whether operator has correct form to be from a molecule.
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) – Whether to check if operator conserves spin.


class
openfermion.ops.
InteractionOperator
(constant, one_body_tensor, two_body_tensor)¶ Bases:
openfermion.ops.representations.polynomial_tensor.PolynomialTensor
Class for storing ‘interaction operators’ which are defined to be fermionic operators consisting of onebody and twobody terms which conserve particle number and spin. The most common examples of data that will use this structure are molecular Hamiltonians. In principle, everything stored in this class could also be represented using the more general FermionOperator class. However, this class is able to exploit specific properties of how fermions interact to enable more numerically efficient manipulation of the data. Note that the operators stored in this class take the form:
\[constant + \sum_{p, q} h_{p, q} a^\dagger_p a_q + \sum_{p, q, r, s} h_{p, q, r, s} a^\dagger_p a^\dagger_q a_r a_s.\]
one_body_tensor
¶ The coefficients of the onebody terms

(:math:`h_{p, q}`). This is an n_qubits x n_qubits

numpy array of floats.

two_body_tensor
¶ The coefficients of the twobody terms (\(h_{p, q, r, s}\)). This is an n_qubits x n_qubits x n_qubits x n_qubits numpy array of floats.

__init__
(constant, one_body_tensor, two_body_tensor)¶ Initialize the InteractionOperator class.
Parameters:  constant – A constant term in the operator given as a float. For instance, the nuclear repulsion energy.
 one_body_tensor –
 The coefficients of the onebody terms
 (\(h_{p,q}\)).
This is an n_qubits x n_qubits numpy array of floats.
 two_body_tensor – The coefficients of the twobody terms (\(h_{p, q, r, s}\)). This is an n_qubits x n_qubits x n_qubits x n_qubits numpy array of floats.

one_body_tensor
The value of the onebody tensor.

two_body_tensor
The value of the twobody tensor.

unique_iter
(complex_valued=False)¶ Iterate all terms that are not in the same symmetry group.
 Four point symmetry:
 pq = qp.
 pqrs = srqp = qpsr = rspq.
 Eight point symmetry:
 pq = qp.
 pqrs = rqps = psrq = srqp = qpsr = rspq = spqr = qrsp.
Parameters: complex_valued (bool) – Whether the operator has complex coefficients. Yields: tuple[int]


exception
openfermion.ops.
InteractionOperatorError
¶ Bases:
Exception

class
openfermion.ops.
InteractionRDM
(one_body_tensor, two_body_tensor)¶ Bases:
openfermion.ops.representations.polynomial_tensor.PolynomialTensor
Class for storing 1 and 2body reduced density matrices.

one_body_tensor
¶ The expectation values <a^dagger_p a_q>.

two_body_tensor
¶ The expectation values <a^dagger_p a^dagger_q a_r a_s>.

__init__
(one_body_tensor, two_body_tensor)¶ Initialize the InteractionRDM class.
Parameters:  one_body_tensor – Expectation values <a^dagger_p a_q>.
 two_body_tensor – Expectation values <a^dagger_p a^dagger_q a_r a_s>.

expectation
(operator)¶ Return expectation value of an InteractionRDM with an operator.
Parameters: operator – A QubitOperator or InteractionOperator. Returns: float – Expectation value Raises: InteractionRDMError
– Invalid operator provided.

get_qubit_expectations
(qubit_operator)¶ Return expectations of QubitOperator in new QubitOperator.
Parameters: qubit_operator – QubitOperator instance to be evaluated on this InteractionRDM. Returns: QubitOperator – QubitOperator with coefficients corresponding to expectation values of those operators. Raises: InteractionRDMError
– Observable not contained in 1RDM or 2RDM.

one_body_tensor
The value of the onebody tensor.

two_body_tensor
The value of the twobody tensor.


exception
openfermion.ops.
InteractionRDMError
¶ Bases:
Exception

class
openfermion.ops.
IsingOperator
(term=None, coefficient=1.0)¶ Bases:
openfermion.ops.operators.symbolic_operator.SymbolicOperator
The IsingOperator class provides an analytic representation of an Isingtype Hamiltonian, i.e. a sum of product of Zs.
IsingOperator is a subclass of SymbolicOperator. Importantly, it has attributes set as follows:
actions = (‘Z’) action_strings = (‘Z’) action_before_index = True different_indices_commute = TrueSee the documentation of SymbolicOperator for more details.

action_before_index
¶ Whether action comes before index in string representations.

action_strings
¶ The string representations of the allowed actions.

actions
¶ The allowed actions.

different_indices_commute
¶ Whether factors acting on different indices commute.


class
openfermion.ops.
MajoranaOperator
(term=None, coefficient=1.0)¶ Bases:
object
A linear combination of products of Majorana operators.
A system of N fermionic modes can be described using 2N Majorana operators \(\gamma_1, \ldots, \gamma_{2N}\) as an alternative to using N fermionic annihilation operators. The algebra of Majorana operators amounts to the relation
\[\{\gamma_i, \gamma_j\} = \gamma_i \gamma_j + \gamma_j \gamma_i = 2 \delta_{ij}\]Note that this implies \(\gamma_i^2 = 1\).
The MajoranaOperator class stores a linear combination of products of Majorana operators. Each product is represented as a tuple of integers representing the indices of the operators. As an example, MajoranaOperator((2, 3, 5), 1.5) initializes an operator with a single term which represents the operator \(1.5 \gamma_2 \gamma_3 \gamma_5\). MajoranaOperators can be added, subtracted, multiplied, and divided by scalars. They can be compared for approximate numerical equality using ==.

terms
¶ A dictionary from term, represented by a tuple of integers,

to the coefficient of the term in the linear combination.

__init__
(term=None, coefficient=1.0)¶ Initialize a MajoranaOperator with a single term.
Parameters:  term (Tuple[int]) – The indices of a Majorana operator term to start off with
 coefficient (complex) – The coefficient of the term
Returns: MajoranaOperator

commutes_with
(other)¶ Test commutation with another MajoranaOperator

static
from_dict
(terms)¶ Initialize a MajoranaOperator from a terms dictionary.
WARNING: The given dictionary is not validated whatsoever. It’s up to you to ensure that it is properly formed.
Parameters: terms – A dictionary from Majorana term to coefficient

with_basis_rotated_by
(transformation_matrix)¶ Change to a basis of new Majorana operators.
The input to this method is a real orthogonal matrix \(O\). It returns a new MajoranaOperator which is equivalent to the old one but rewritten in terms of a new basis of Majorana operators. Let the original Majorana operators be denoted by \(\gamma_i\) and the new operators be denoted by \(\tilde{\gamma_i}\). Then they are related by the equation
\[\tilde{\gamma_i} = \sum_j O_{ij} \gamma_j.\]Parameters: transformation_matrix – A real orthogonal matrix representing the basis transformation. Returns: The rotated operator.


class
openfermion.ops.
PolynomialTensor
(n_body_tensors)¶ Bases:
object
Class for storing tensor representations of operators that correspond with multilinear polynomials in the fermionic ladder operators. For instance, in a quadratic Hamiltonian (degree 2 polynomial) which conserves particle number, there are only terms of the form a^dagger_p a_q, and the coefficients can be stored in an n_qubits x n_qubits matrix. Higher order terms would be described with tensors of higher dimension. Note that each tensor must have an even number of dimensions, since parity is conserved. Much of the functionality of this class is redudant with FermionOperator but enables much more efficient numerical computations in many cases, such as basis rotations.

n_qubits
¶ The number of sites on which the tensor acts.
Type: int

n_body_tensors
¶ A dictionary storing the tensors describing nbody interactions. The keys are tuples that indicate the type of tensor. For instance, n_body_tensors[(1, 0)] would be an (n_qubits x n_qubits) numpy array, and it could represent the coefficients of terms of the form a^dagger_i a_j, whereas n_body_tensors[(0, 1)] would be an array of the same shape, but instead representing terms of the form a_i a^dagger_j.
Type: dict

__init__
(n_body_tensors)¶ Initialize the PolynomialTensor class.
Parameters: n_body_tensors (dict) – A dictionary storing the tensors describing nbody interactions.

constant
¶ The value of the constant term.

projected_n_body_tensors
(selection, exact=False)¶ Keep only selected elements.
Parameters:  selection (Union[int, Iterable[int]) – If int, keeps terms with at most (exactly, if exact is True) that many unique indices. If iterable, keeps only terms containing (all of, if exact is True) the specified indices.
 exact (bool) – Whether or not the selection is strict.

rotate_basis
(rotation_matrix)¶ Rotate the orbital basis of the PolynomialTensor.
Parameters: rotation_matrix – A square numpy array or matrix having dimensions of n_qubits by n_qubits. Assumed to be real and invertible.


exception
openfermion.ops.
PolynomialTensorError
¶ Bases:
Exception

class
openfermion.ops.
QuadOperator
(term=None, coefficient=1.0)¶ Bases:
openfermion.ops.operators.symbolic_operator.SymbolicOperator
QuadOperator stores a sum of products of canonical quadrature operators.
They are defined in terms of the bosonic ladder operators: q = sqrt{hbar/2}(b+b^) p = isqrt{hbar/2}(bb^) where hbar is a constant appearing in the commutator of q and p: [q, p] = i hbar
In OpenFermion, we describe the canonical quadrature operators acting on quantum modes ‘i’ and ‘j’ using the shorthand: ‘qi’ = q_i ‘pj’ = p_j where [‘qi’, ‘pj’] = i hbar delta_ij is the commutator.
The QuadOperator class is designed (in general) to store sums of these terms. For instance, an instance of QuadOperator might represent
H = 0.5 * QuadOperator('q0 p5') + 0.3 * QuadOperator('q0')
Note for a QuadOperator to be a Hamiltonian which is a hermitian operator, the coefficients of all terms must be real.
QuadOperator is a subclass of SymbolicOperator. Importantly, it has attributes set as follows:
actions = ('q', 'p') action_strings = ('q', 'p') action_before_index = True different_indices_commute = True
See the documentation of SymbolicOperator for more details.
Example
H = (QuadOperator('p0 q3', 0.5) + 0.6 * QuadOperator('p3 q0')) # Equivalently H2 = QuadOperator('p0 q3', 0.5) H2 += QuadOperator('p3 q0', 0.6)
Note
Adding QuadOperator is faster using += (as this is done by inplace addition). Specifying the coefficient during initialization is faster than multiplying a QuadOperator with a scalar.

action_before_index
¶ Whether action comes before index in string representations.

action_strings
¶ The string representations of the allowed actions.

actions
¶ The allowed actions.

different_indices_commute
¶ Whether factors acting on different indices commute.

is_gaussian
()¶ Query whether the term is quadratic or lower in the quadrature operators.

is_normal_ordered
()¶ Return whether or not term is in normal order.
In our convention, q operators come first. Note that unlike the Fermion operator, due to the commutation of quadrature operators with different indices, the QuadOperator sorts quadrature operators by index.


class
openfermion.ops.
QuadraticHamiltonian
(hermitian_part, antisymmetric_part=None, constant=0.0, chemical_potential=0.0)¶ Bases:
openfermion.ops.representations.polynomial_tensor.PolynomialTensor
Class for storing Hamiltonians that are quadratic in the fermionic ladder operators. The operators stored in this class take the form
\[\sum_{p, q} (M_{pq}  \mu \delta_{pq}) a^\dagger_p a_q + \frac12 \sum_{p, q} (\Delta_{pq} a^\dagger_p a^\dagger_q + \text{h.c.}) + \text{constant}\]where
 \(M\) is a Hermitian n_qubits x n_qubits matrix.
 \(\Delta\) is an antisymmetric n_qubits x n_qubits matrix.
 \(\mu\) is a real number representing the chemical potential.
 \(\delta_{pq}\) is the Kronecker delta symbol.
We separate the chemical potential \(\mu\) from \(M\) so that we can use it to adjust the expectation value of the total number of particles.

chemical_potential
¶ The chemical potential \(\mu\).
Type: float

__init__
(hermitian_part, antisymmetric_part=None, constant=0.0, chemical_potential=0.0)¶ Initialize the QuadraticHamiltonian class.
Parameters:  hermitian_part (ndarray) – The matrix \(M\), which represents the coefficients of the particlenumberconserving terms. This is an n_qubits x n_qubits numpy array of complex numbers.
 antisymmetric_part (ndarray) – The matrix \(\Delta\), which represents the coefficients of the nonparticlenumberconserving terms. This is an n_qubits x n_qubits numpy array of complex numbers.
 constant (float, optional) – A constant term in the operator.
 chemical_potential (float, optional) – The chemical potential \(\mu\).

add_chemical_potential
(chemical_potential)¶ Increase (or decrease) the chemical potential by some value.

antisymmetric_part
¶ The antisymmetric part.

combined_hermitian_part
¶ The Hermitian part including the chemical potential.

conserves_particle_number
¶ Whether this Hamiltonian conserves particle number.

diagonalizing_bogoliubov_transform
(spin_sector=None)¶ Compute the unitary that diagonalizes a quadratic Hamiltonian.
Any quadratic Hamiltonian can be rewritten in the form
\[\sum_{j} \varepsilon_j b^\dagger_j b_j + \text{constant},\]where the \(b^\dagger_j\) are a new set fermionic creation operators that satisfy the canonical anticommutation relations. The new creation operators are linear combinations of the original ladder operators. In the most general case, creation and annihilation operators are mixed together:
\[\begin{split}\begin{pmatrix} b^\dagger_1 \\ \vdots \\ b^\dagger_N \\ \end{pmatrix} = W \begin{pmatrix} a^\dagger_1 \\ \vdots \\ a^\dagger_N \\ a_1 \\ \vdots \\ a_N \end{pmatrix},\end{split}\]where \(W\) is an \(N \times (2N)\) matrix. However, if the Hamiltonian conserves particle number then creation operators don’t need to be mixed with annihilation operators and \(W\) only needs to be an \(N \times N\) matrix:
\[\begin{split}\begin{pmatrix} b^\dagger_1 \\ \vdots \\ b^\dagger_N \\ \end{pmatrix} = W \begin{pmatrix} a^\dagger_1 \\ \vdots \\ a^\dagger_N \\ \end{pmatrix},\end{split}\]This method returns the matrix \(W\).
Parameters: spin_sector (optional str) – An optional integer specifying a spin sector to restrict to: 0 for spinup and 1 for spindown. Should only be specified if the Hamiltonian includes a spin degree of freedom and spinup modes do not interact with spindown modes. If specified, the modes are assumed to be ordered so that spinup orbitals come before spindown orbitals. Returns:  orbital_energies(ndarray)
 A onedimensional array containing the \(\varepsilon_j\)
 diagonalizing_unitary (ndarray):
 A matrix representing the transformation \(W\) of the fermionic ladder operators. If the Hamiltonian conserves particle number then this is \(N \times N\); otherwise it is \(N \times 2N\). If spin sector is specified, then N here represents the number of spatial orbitals rather than spin orbitals.
 constant(float)
 The constant

diagonalizing_circuit
()¶ Get a circuit for a unitary that diagonalizes this Hamiltonian
This circuit performs the transformation to a basis in which the Hamiltonian takes the diagonal form
\[\sum_{j} \varepsilon_j b^\dagger_j b_j + \text{constant}.\]Returns: circuit_description (list[tuple]) – A list of operations describing the circuit. Each operation is a tuple of objects describing elementary operations that can be performed in parallel. Each elementary operation is either the string ‘pht’ indicating a particlehole transformation on the last fermionic mode, or a tuple of the form \((i, j, \theta, \varphi)\), indicating a Givens rotation of modes \(i\) and \(j\) by angles \(\theta\) and \(\varphi\).

ground_energy
()¶ Return the ground energy.

hermitian_part
¶ The Hermitian part not including the chemical potential.

majorana_form
()¶ Return the Majorana represention of the Hamiltonian.
Any quadratic Hamiltonian can be written in the form
\[\frac{i}{2} \sum_{j, k} A_{jk} f_j f_k + \text{constant}\]where the \(f_i\) are normalized Majorana fermion operators:
\[ \begin{align}\begin{aligned}f_j = \frac{1}{\sqrt{2}} (a^\dagger_j + a_j)\\f_{j + N} = \frac{i}{\sqrt{2}} (a^\dagger_j  a_j)\end{aligned}\end{align} \]and \(A\) is a (2 * n_qubits) x (2 * n_qubits) real antisymmetric matrix. This function returns the matrix \(A\) and the constant.

orbital_energies
(non_negative=False)¶ Return the orbital energies.
Any quadratic Hamiltonian is unitarily equivalent to a Hamiltonian of the form
\[\sum_{j} \varepsilon_j b^\dagger_j b_j + \text{constant}.\]We call the \(\varepsilon_j\) the orbital energies. The eigenvalues of the Hamiltonian are sums of subsets of the orbital energies (up to the additive constant).
Parameters: non_negative (bool) – If True, always return a list of orbital energies that are nonnegative. This option is ignored if the Hamiltonian does not conserve particle number, in which case the returned orbital energies are always nonnegative. Returns:  orbital_energies(ndarray) – A onedimensional array containing the \(\varepsilon_j\)
 constant(float) – The constant

exception
openfermion.ops.
QuadraticHamiltonianError
¶ Bases:
Exception

class
openfermion.ops.
QubitOperator
(term=None, coefficient=1.0)¶ Bases:
openfermion.ops.operators.symbolic_operator.SymbolicOperator
A sum of terms acting on qubits, e.g., 0.5 * ‘X0 X5’ + 0.3 * ‘Z1 Z2’.
A term is an operator acting on n qubits and can be represented as:
coefficient * local_operator[0] x … x local_operator[n1]
where x is the tensor product. A local operator is a Pauli operator (‘I’, ‘X’, ‘Y’, or ‘Z’) which acts on one qubit. In math notation a term is, for example, 0.5 * ‘X0 X5’, which means that a Pauli X operator acts on qubit 0 and 5, while the identity operator acts on all other qubits.
A QubitOperator represents a sum of terms acting on qubits and overloads operations for easy manipulation of these objects by the user.
Note for a QubitOperator to be a Hamiltonian which is a hermitian operator, the coefficients of all terms must be real.
hamiltonian = 0.5 * QubitOperator('X0 X5') + 0.3 * QubitOperator('Z0')
QubitOperator is a subclass of SymbolicOperator. Importantly, it has attributes set as follows:
actions = ('X', 'Y', 'Z') action_strings = ('X', 'Y', 'Z') action_before_index = True different_indices_commute = True
See the documentation of SymbolicOperator for more details.
Example
ham = ((QubitOperator('X0 Y3', 0.5) + 0.6 * QubitOperator('X0 Y3'))) # Equivalently ham2 = QubitOperator('X0 Y3', 0.5) ham2 += 0.6 * QubitOperator('X0 Y3')
Note
Adding QubitOperators is faster using += (as this is done by inplace addition). Specifying the coefficient during initialization is faster than multiplying a QubitOperator with a scalar.

action_before_index
¶ Whether action comes before index in string representations.

action_strings
¶ The string representations of the allowed actions.

actions
¶ The allowed actions.

different_indices_commute
¶ Whether factors acting on different indices commute.

renormalize
()¶ Fix the trace norm of an operator to 1


class
openfermion.ops.
SymbolicOperator
(term=None, coefficient=1.0)¶ Bases:
object
Base class for FermionOperator and QubitOperator.
A SymbolicOperator stores an object which represents a weighted sum of terms; each term is a product of individual factors of the form (index, action), where index is a nonnegative integer and the possible values for action are determined by the subclass. For instance, for the subclass FermionOperator, action can be 1 or 0, indicating raising or lowering, and for QubitOperator, action is from the set {‘X’, ‘Y’, ‘Z’}. The coefficients of the terms are stored in a dictionary whose keys are the terms. SymbolicOperators of the same type can be added or multiplied together.
Note
Adding SymbolicOperators is faster using += (as this is done by inplace addition). Specifying the coefficient during initialization is faster than multiplying a SymbolicOperator with a scalar.

actions
¶ A tuple of objects representing the possible actions. e.g. for FermionOperator, this is (1, 0).
Type: tuple

action_strings
¶ A tuple of string representations of actions. These should be in onetoone correspondence with actions and listed in the same order. e.g. for FermionOperator, this is (‘^’, ‘’).
Type: tuple

action_before_index
¶ A boolean indicating whether in string representations, the action should come before the index.
Type: bool

different_indices_commute
¶ A boolean indicating whether factors acting on different indices commute.
Type: bool

terms
¶ key (tuple of tuples): A dictionary storing the coefficients of the terms in the operator. The keys are the terms. A term is a product of individual factors; each factor is represented by a tuple of the form (index, action), and these tuples are collected into a larger tuple which represents the term as the product of its factors.
Type: dict

__init__
(term=None, coefficient=1.0)¶ Initialize self. See help(type(self)) for accurate signature.

classmethod
accumulate
(operators, start=None)¶ Sums over SymbolicOperators.

action_before_index
Whether action comes before index in string representations.
Example: For QubitOperator, the actions are (‘X’, ‘Y’, ‘Z’) and the string representations look something like ‘X0 Z2 Y3’. So the action comes before the index, and this function should return True. For FermionOperator, the string representations look like ‘0^ 1 2^ 3’. The action comes after the index, so this function should return False.

action_strings
The string representations of the allowed actions.
Returns a tuple containing string representations of the possible actions, in the same order as the actions property.

actions
The allowed actions.
Returns a tuple of objects representing the possible actions.

compress
(abs_tol=1e08)¶ Eliminates all terms with coefficients close to zero and removes small imaginary and real parts.
Parameters: abs_tol (float) – Absolute tolerance, must be at least 0.0

constant
¶ The value of the constant term.

different_indices_commute
Whether factors acting on different indices commute.

get_operator_groups
(num_groups)¶ Gets a list of operators with a few terms. :param num_groups: How many operators to get in the end. :type num_groups: int
Returns: operators([self.__class__]) –  A list of operators summing up to
 self.

get_operators
()¶ Gets a list of operators with a single term.
Returns: operators([self.__class__]) – A generator of the operators in self.

classmethod
identity
()¶ Returns: multiplicative_identity (SymbolicOperator) – A symbolic operator u with the property that u*x = x*u = x for all operators x of the same class.

induced_norm
(order=1)¶ Compute the induced pnorm of the operator.
If we represent an operator as :math: sum_{j} w_j H_j where :math: w_j are scalar coefficients then this norm is :math: left(sum_{j}  w_j ^p right)^{frac{1}{p}} where :math: `p is the order of the induced norm
Parameters: order (int) – the order of the induced norm.

many_body_order
()¶ Compute the manybody order of a SymbolicOperator.
The manybody order of a SymbolicOperator is the maximum length of a term with nonzero coefficient.
Returns: int

classmethod
zero
()¶ Returns: additive_identity (SymbolicOperator) – A symbolic operator o with the property that o+x = x+o = x for all operators x of the same class.


openfermion.ops.
double_decoding
(decoder_1, decoder_2)¶ Concatenates two decodings
Parameters:  decoder_1 (iterable) – list of BinaryPolynomial decoding of the outer code layer
 decoder_2 (iterable) – list of BinaryPolynomial decoding of the inner code layer
 Returns (list): list of BinaryPolynomial the decoding defined by
 w > decoder_1( decoder_2(w) )

openfermion.ops.
general_basis_change
(general_tensor, rotation_matrix, key)¶ Change the basis of an general interaction tensor.
 M’^{p_1p_2…p_n} = R^{p_1}_{a_1} R^{p_2}_{a_2} …
 R^{p_n}_{a_n} M^{a_1a_2…a_n} R^{p_n}_{a_n}^T … R^{p_2}_{a_2}^T R_{p_1}_{a_1}^T
where R is the rotation matrix, M is the general tensor, M’ is the transformed general tensor, and a_k and p_k are indices. The formula uses the Einstein notation (implicit sum over repeated indices).
In case R is complex, the kth R in the above formula need to be conjugated if key has a 1 in the kth place (meaning that the corresponding operator is a creation operator).
Parameters:  general_tensor – A square numpy array or matrix containing information about a general interaction tensor.
 rotation_matrix – A square numpy array or matrix having dimensions of n_qubits by n_qubits. Assumed to be unitary.
 key – A tuple indicating the type of general_tensor. Assumed to be nonempty. For example, a tensor storing coefficients of \(a^\dagger_p a_q\) would have a key of (1, 0) whereas a tensor storing coefficients of \(a^\dagger_p a_q a_r a^\dagger_s\) would have a key of (1, 0, 0, 1).
Returns: transformed_general_tensor – general_tensor in the rotated basis.

openfermion.ops.
shift_decoder
(decoder, shift_constant)¶ Shifts the indices of a decoder by a constant.
Parameters:  decoder (iterable) – list of BinaryPolynomial; the decoder
 shift_constant (int) – the qubit index that corresponds to the offset.
Returns (list): list of BinaryPolynomial shifted decoder
openfermion.transforms¶

class
openfermion.transforms.
FenwickNode
(parent, children, index=None)¶ Fenwick Tree node.

__init__
(parent, children, index=None)¶ Fenwick Tree node. Single parent and multiple children.
Parameters:  parent – FenwickNode. A parent node.
 children – List. A list of children nodes (FenwickNode). index: Int. Node label.

get_ancestors
()¶ Returns a list of ancestors of the node. Ordered from the earliest.
Returns: ancestor_list – A list of FenwickNodes.


class
openfermion.transforms.
FenwickTree
(n_qubits)¶ Recursive implementation of the Fenwick tree.
Please see Subsection B.2. of Operator Locality in Quantum Simulation of Fermionic Models (arXiv:1701.07072) for a reference to the update set (U), the parity set (P) and the children set (F) sets of the Fenwick.

__init__
(n_qubits)¶ Builds a Fenwick tree on n_qubits qubits.
Parameters: n_qubits – Int, the number of qubits in the system

get_children_set
(j)¶ Returns the set of children of jth site.
Parameters: j (int) – Fermionic site index. Returns: A list of children of j. ordered from lowest index.

get_node
(j)¶ Returns the node at j in the qubit register. Wrapper.
Parameters: j (int) – Fermionic site index. Returns: FenwickNode – the node at j.

get_parity_set
(j)¶ Returns the union of the remainder set with children set. Coincides with the parity set of Tranter et al.
Parameters: j (int) – Fermionic site index. Returns: A C union F

get_remainder_set
(j)¶ Return the set of children with indices less than j of all ancestors of j. The set C from (arXiv:1701.07072).
Parameters: j (int) – Fermionic site index. Returns: A list of children of jancestors with index less than j.

get_update_set
(j)¶ The set of all ancestors of j, (the update set U from the paper).
Parameters: j (int) – Fermionic site index. Returns: List of ancestors of j, ordered from earliest.


exception
openfermion.transforms.
StabilizerError
(message)¶ Stabilizer error class.

__init__
(message)¶ Throw custom errors connected to stabilizers.
Parameters: message (str) – custome error message string.


openfermion.transforms.
binary_code_transform
(hamiltonian, code)¶ Transforms a Hamiltonian written in fermionic basis into a Hamiltonian written in qubit basis, via a binary code.
The role of the binary code is to relate the occupation vectors (v0 v1 v2 … vN1) that span the fermionic basis, to the qubit basis, spanned by binary vectors (w0, w1, w2, …, wn1).
The binary code has to provide an analytic relation between the binary vectors (v0, v1, …, vN1) and (w0, w1, …, wn1), and possibly has the property N>n, when the Fermion basis is smaller than the fermionic Fock space. The binary_code_transform function can transform Fermion operators to qubit operators for custom and qubitsaving mappings.
Note
Logic multiqubit operators are decomposed into Paulistrings (e.g. CPhase(1,2) = 0.5 * (1 + Z1 + Z2  Z1 Z2 ) ), which might increase the number of Hamiltonian terms drastically.
Parameters:  hamiltonian (FermionOperator) – the fermionic Hamiltonian
 code (BinaryCode) – the binary code to transform the Hamiltonian
Returns (QubitOperator): the transformed Hamiltonian
Raises: TypeError
– if the hamiltonian is not a FermionOperator or code is not a BinaryCode

openfermion.transforms.
bravyi_kitaev
(operator, n_qubits=None)¶ Apply the BravyiKitaev transform.
Implementation from arXiv:quantph/0003137 and “A New Data Structure for Cumulative Frequency Tables” by Peter M. Fenwick.
Note that this implementation is equivalent to the one described in arXiv:1208.5986, and is different from the one described in arXiv:1701.07072. The one described in arXiv:1701.07072 is implemented in OpenFermion as bravyi_kitaev_tree.
Parameters:  operator (openfermion.ops.FermionOperator) – A FermionOperator to transform.
 n_qubits (intNone) – Can force the number of qubits in the resulting operator above the number that appear in the input operator.
Returns: transformed_operator – An instance of the QubitOperator class.
Raises: ValueError
– Invalid number of qubits specified.

openfermion.transforms.
bravyi_kitaev_code
(n_modes)¶ The BravyiKitaev transform as binary code. The implementation follows arXiv:1208.5986.
Parameters: n_modes (int) – number of modes Returns (BinaryCode): The BravyiKitaev BinaryCode

openfermion.transforms.
bravyi_kitaev_fast
(operator)¶ Find the Paulirepresentation of InteractionOperator for BravyiKitaev Super fast (BKSF) algorithm. Paulirepresentation of general FermionOperator is not possible in BKSF. Also, the InteractionOperator given as input must be Hermitian. In future we might provide a transformation for a restricted set of fermion operator.
Parameters: operator – Interaction Operator. Returns: transformed_operator – An instance of the QubitOperator class. Raises: TypeError
– If operator is not an InteractionOperator

openfermion.transforms.
bravyi_kitaev_fast_edge_matrix
(iop, n_qubits=None)¶ Use InteractionOperator to construct edge matrix required for the algorithm
Edge matrix contains the information about the edges between vertices. Edge matrix is required to build the operators in bravyi_kitaev_fast model.
Parameters: iop (Interaction Operator) – Returns: edge_matrix (Numpy array) –  A square numpy array containing information
 about the edges present in the model.

openfermion.transforms.
bravyi_kitaev_fast_interaction_op
(iop)¶ Transform from InteractionOperator to QubitOperator for BravyiKitaev fast algorithm.
The electronic Hamiltonian is represented in terms of creation and annihilation operators. These creation and annihilation operators could be used to define Majorana modes as follows:
c_{2i} = a_i + a^{dagger}_i, c_{2i+1} = (a_i  a^{dagger}_{i})/(1j) These Majorana modes can be used to define edge operators B_i and A_{ij}:
 B_i=c_{2i}c_{2i+1}, A_{ij}=c_{2i}c_{2j}
using these edge operators the fermionic algebra can be generated and hence all the terms in the electronic Hamiltonian can be expressed in terms of edge operators. The terms in electronic Hamiltonian can be divided into five types (arXiv 1208.5986). We can find the edge operator expression for each of those five types. For example, the excitation operator term in Hamiltonian when represented in terms of edge operators becomes:
a_i^{dagger}a_j+a_j^{dagger}a_i = (1j/2)*(A_ij*B_i+B_j*A_ij)For the sake of brevity the reader is encouraged to look up the expressions of other terms from the code below. The variables for edge operators are chosen according to the nomenclature defined above (B_i and A_ij). A detailed description of these operators and the terms of the electronic Hamiltonian are provided in (arXiv 1712.00446).
Parameters:  iop (Interaction Operator) –
 n_qubit (int) – Number of qubits
Returns: qubit_operator – An instance of the QubitOperator class.

openfermion.transforms.
bravyi_kitaev_tree
(operator, n_qubits=None)¶ Apply the “tree” BravyiKitaev transform.
Implementation from arxiv:1701.07072
Note that this implementation is different from the one described in arXiv:quantph/0003137. In particular, it gives different results when the total number of modes is not a power of 2. The one described in arXiv:quantph/0003137 is the same as the one described in arXiv:1208.5986, and it is implemented in OpenFermion under the name bravyi_kitaev.
Parameters:  operator (openfermion.ops.FermionOperator) – A FermionOperator to transform.
 n_qubits (intNone) – Can force the number of qubits in the resulting operator above the number that appear in the input operator.
Returns: transformed_operator – An instance of the QubitOperator class.
Raises: ValueError
– Invalid number of qubits specified.

openfermion.transforms.
check_commuting_stabilizers
(stabilizer_list, msg, thres=1e08)¶ Auxiliary function checking that stabilizers commute.
If two stabilizers anticommute their product will have an imaginary coefficient. This function checks the list of stabilizers (QubitOperator) and raises and error if a complex number is found in any of the coefficients.
Parameters:  stabilizer_list (list) – List of stabilizers as QubitOperators.
 msg (str) – Message for the error.
 thres – Tolerance value, set to OpenFermion tolerance by default.

openfermion.transforms.
check_no_sympy
(operator)¶ Checks whether a SymbolicOperator contains any sympy expressions, which will prevent it being converted to a PolynomialTensor or DiagonalCoulombHamiltonian
Parameters: operator (SymbolicOperator) – the operator to be tested

openfermion.transforms.
check_stabilizer_linearity
(stabilizer_list, msg)¶ Auxiliary function checking that stabilizers are linearly independent.
If two stabilizer are linearly dependent the result after some of their products will be the identity. This function checks the list of stabilizers (QubitOperator) and raises an error if the identity is found.
Parameters:  stabilizer_list (list) – List of stabilizers (QubitOperator).
 msg (str) – Message for the error.

openfermion.transforms.
checksum_code
(n_modes, odd)¶ Checksum code for either even or odd Hamming weight. The Hamming weight is defined such that it yields the total occupation number for a given basis state. A Checksum code with odd weight will encode all states with odd occupation number. This code saves one qubit: n_qubits = n_modes  1.
Parameters:  n_modes (int) – number of modes
 odd (int or bool) – 1 (True) or 0 (False), if odd, we encode all states with odd Hamming weight
Returns (BinaryCode): The checksum BinaryCode

openfermion.transforms.
chemist_ordered
(fermion_operator)¶ Puts a twobody fermion operator in chemist ordering.
The normal ordering convention for chemists is different. Rather than ordering the twobody term as physicists do, as \(a^\dagger a^\dagger a a\) the chemist ordering of the twobody term is \(a^\dagger a a^\dagger a\)
TODO: This routine can be made more efficient.
Parameters: fermion_operator (FermionOperator) – a fermion operator guarenteed to have number conserving one and twobody fermion terms only. Returns: chemist_ordered_operator (FermionOperator) –  the input operator
 ordered in the chemistry convention.
Raises: OperatorSpecificationError
– Operator is not twobody number conserving.

openfermion.transforms.
fix_single_term
(term, position, fixed_op, other_op, stabilizer)¶ Auxiliary function for term reductions.
Automatically multiplies a single term with a given stabilizer if the Pauli operator on a given qubit is of one of two specified types. This fixes a certain representation of a logical operator.
Parameters:  term (QubitOperator) – Single term to fix.
 position (int) – Index of the qubit which is to be fixed.
 fixed_op (str) – Pauli operator, which will cause a multiplication by the stabilizer when encountered at the fixed position.
 other_op (str) – Alternative Pauli operator, which will also cause the multiplication by the stabilizer.
 stabilizer (QubitOperator) – Stabilizer that is multiplied when necessary.
Returns: term (QubitOperator) – Updated term in a fiixed representation.

openfermion.transforms.
fourier_transform
(hamiltonian, grid, spinless)¶ Apply Fourier transform to change hamiltonian in plane wave basis.
\[c^\dagger_v = \sqrt{1/N} \sum_m {a^\dagger_m \exp(i k_v r_m)} c_v = \sqrt{1/N} \sum_m {a_m \exp(i k_v r_m)}\]Parameters:  hamiltonian (FermionOperator) – The hamiltonian in plane wave basis.
 grid (Grid) – The discretization to use.
 spinless (bool) – Whether to use the spinless model or not.
Returns: FermionOperator – The fouriertransformed hamiltonian.

openfermion.transforms.
freeze_orbitals
(fermion_operator, occupied, unoccupied=None, prune=True)¶ Fix some orbitals to be occupied and others unoccupied.
Removes all operators acting on the specified orbitals, and renumbers the remaining orbitals to eliminate unused indices. The sign of each term is modified according to the ladder uperator anticommutation relations in order to preserve the expectation value of the operator.
Parameters:  occupied – A list containing the indices of the orbitals that are to be assumed to be occupied.
 unoccupied – A list containing the indices of the orbitals that are to be assumed to be unoccupied.

openfermion.transforms.
get_boson_operator
(operator, hbar=1.0)¶ Convert to BosonOperator.
Parameters:  operator – QuadOperator.
 hbar (float) – the value of hbar used in the definition of the commutator [q_i, p_j] = i hbar delta_ij. By default hbar=1.
Returns: boson_operator – An instance of the BosonOperator class.

openfermion.transforms.
get_diagonal_coulomb_hamiltonian
(fermion_operator, n_qubits=None, ignore_incompatible_terms=False)¶ Convert a FermionOperator to a DiagonalCoulombHamiltonian.
Parameters:  fermion_operator (FermionOperator) – The operator to convert.
 n_qubits (int) – Optionally specify the total number of qubits in the system
 ignore_incompatible_terms (bool) – This flag determines the behavior of this method when it encounters terms that are not represented by the DiagonalCoulombHamiltonian class, namely, terms that are not quadratic and not quartic of the form a^dagger_p a_p a^dagger_q a_q. If set to True, this method will simply ignore those terms. If False, then this method will raise an error if it encounters such a term. The default setting is False.

openfermion.transforms.
get_fermion_operator
(operator)¶ Convert to FermionOperator.
Returns: fermion_operator – An instance of the FermionOperator class.

openfermion.transforms.
get_interaction_operator
(fermion_operator, n_qubits=None)¶ Convert a 2body fermionic operator to InteractionOperator.
This function should only be called on fermionic operators which consist of only a_p^dagger a_q and a_p^dagger a_q^dagger a_r a_s terms. 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].
Returns: interaction_operator – An instance of the InteractionOperator class.
Raises: TypeError
– Input must be a FermionOperator.TypeError
– FermionOperator does not map to InteractionOperator.
Warning
Even assuming that each creation or annihilation operator appears at most a constant number of times in the original operator, the runtime of this method is exponential in the number of qubits.

openfermion.transforms.
get_majorana_operator
(operator: Union[openfermion.ops.representations.polynomial_tensor.PolynomialTensor, openfermion.ops.representations.diagonal_coulomb_hamiltonian.DiagonalCoulombHamiltonian, openfermion.ops.operators.fermion_operator.FermionOperator]) → openfermion.ops.operators.majorana_operator.MajoranaOperator¶ Convert to MajoranaOperator.
Uses the convention of even + odd indexing of Majorana modes derived from a fermionic mode:
fermion annhil. c_k > ( gamma_{2k} + 1.j * gamma_{2k+1} ) / 2 fermion creation c^_k > ( gamma_{2k}  1.j * gamma_{2k+1} ) / 2Parameters: (PolynomialTensor, (operator) – DiagonalCoulombHamiltonian or FermionOperator): Operator to write as Majorana Operator. Returns: majorana_operator – An instance of the MajoranaOperator class. Raises: TypeError
– If operator is not of PolynomialTensor, DiagonalCoulombHamiltonian or FermionOperator.

openfermion.transforms.
get_molecular_data
(interaction_operator, geometry=None, basis=None, multiplicity=None, n_electrons=None, reduce_spin=True, data_directory=None)¶ Output a MolecularData object generated from an InteractionOperator
Parameters:  interaction_operator (InteractionOperator) – twobody interaction operator defining the “molecular interaction” to be simulated.
 geometry (string or list of atoms) –
 basis (string) – String denoting the basis set used to discretize the system.
 multiplicity (int) – Spin multiplicity desired in the system.
 n_electrons (int) – Number of electrons in the system
 reduce_spin (bool) – True if one wishes to perform spin reduction on integrals that are given in interaction operator. Assumes spatial (x) spin structure generically.
Returns: molecule(MolecularData) – Instance that captures the interaction_operator converted into the format that would come from an electronic structure package adorned with some metadata that may be useful.

openfermion.transforms.
get_quad_operator
(operator, hbar=1.0)¶ Convert to QuadOperator.
Parameters:  operator – BosonOperator.
 hbar (float) – the value of hbar used in the definition of the commutator [q_i, p_j] = i hbar delta_ij. By default hbar=1.
Returns: quad_operator – An instance of the QuadOperator class.

openfermion.transforms.
get_quadratic_hamiltonian
(fermion_operator, chemical_potential=0.0, n_qubits=None, ignore_incompatible_terms=False)¶ Convert a quadratic fermionic operator to QuadraticHamiltonian.
Parameters:  fermion_operator (FermionOperator) – The operator to convert.
 chemical_potential (float) – A chemical potential to include in the returned operator
 n_qubits (int) – Optionally specify the total number of qubits in the system
 ignore_incompatible_terms (bool) – This flag determines the behavior of this method when it encounters terms that are not quadratic that is, terms that are not of the form a^dagger_p a_q. If set to True, this method will simply ignore those terms. If False, then this method will raise an error if it encounters such a term. The default setting is False.
Returns: quadratic_hamiltonian – An instance of the QuadraticHamiltonian class.
Raises: TypeError
– Input must be a FermionOperator.TypeError
– FermionOperator does not map to QuadraticHamiltonian.
Warning
Even assuming that each creation or annihilation operator appears at most a constant number of times in the original operator, the runtime of this method is exponential in the number of qubits.

openfermion.transforms.
interleaved_code
(modes)¶ Linear code that reorders orbitals from evenodd to upthendown. In upthendown convention, one can append two instances of the same code ‘c’ in order to have two symmetric subcodes that are symmetric for spinup and down modes: ‘ c + c ‘. In evenodd, one can concatenate with the interleaved_code to have the same result:’ interleaved_code * (c + c)’. This code changes the order of modes from (0, 1 , 2, … , modes1 ) to (0, modes/2, 1 modes/2+1, … , modes1, modes/2  1). n_qubits = n_modes.
Args: modes (int): number of modes, must be even
Returns (BinaryCode): code that interleaves orbitals

openfermion.transforms.
inverse_fourier_transform
(hamiltonian, grid, spinless)¶ Apply inverse Fourier transform to change hamiltonian in plane wave dual basis.
\[a^\dagger_v = \sqrt{1/N} \sum_m {c^\dagger_m \exp(i k_v r_m)} a_v = \sqrt{1/N} \sum_m {c_m \exp(i k_v r_m)}\]Parameters:  hamiltonian (FermionOperator) – The hamiltonian in plane wave dual basis.
 grid (Grid) – The discretization to use.
 spinless (bool) – Whether to use the spinless model or not.
Returns: FermionOperator – The inversefouriertransformed hamiltonian.

openfermion.transforms.
jordan_wigner
(operator)¶ Apply the JordanWigner transform to a FermionOperator, InteractionOperator, or DiagonalCoulombHamiltonian to convert to a QubitOperator.
Operators are mapped as follows: a_j^dagger > Z_0 .. Z_{j1} (X_j  iY_j) / 2 a_j > Z_0 .. Z_{j1} (X_j + iY_j) / 2
Returns: transformed_operator – An instance of the QubitOperator class. Warning
The runtime of this method is exponential in the maximum locality of the original FermionOperator.
Raises: TypeError
– Operator must be a FermionOperator, DiagonalCoulombHamiltonian, or InteractionOperator.

openfermion.transforms.
jordan_wigner_code
(n_modes)¶ The JordanWigner transform as binary code.
Parameters: n_modes (int) – number of modes Returns (BinaryCode): The JordanWigner BinaryCode

openfermion.transforms.
linearize_decoder
(matrix)¶ Outputs linear decoding function from input matrix
Parameters: matrix (np.ndarray or list) – list of lists or 2D numpy array to derive the decoding function from Returns (list): list of BinaryPolynomial

openfermion.transforms.
mccoy
(mode, op_a, op_b, m, n)¶ Implement the McCoy formula on two operators of the form op_a^m op_b^n.
Parameters:  mode (int) – the mode number the two operators act on.
 op_a – the label of operator a. This can be any hashable type.
 op_b – the label of operator b. This can be any hashable type.
 m (int) – the power of operator a.
 n (int) – the power of operator b.

openfermion.transforms.
normal_ordered
(operator, hbar=1.0)¶ Compute and return the normal ordered form of a FermionOperator, BosonOperator, QuadOperator, or InteractionOperator.
Due to the canonical commutation/anticommutation relations satisfied by these operators, there are multiple forms that the same operator can take. Here, we define the normal ordered form of each operator, providing a distinct representation for distinct operators.
In our convention, normal ordering implies terms are ordered from highest tensor factor (on left) to lowest (on right). In addition:
 FermionOperators: a^dagger comes before a
 BosonOperators: b^dagger comes before b
 QuadOperators: q operators come before p operators,
Parameters:  operator – an instance of the FermionOperator, BosonOperator, QuadOperator, or InteractionOperator classes.
 hbar (float) – the value of hbar used in the definition of the commutator [q_i, p_j] = i hbar delta_ij. By default hbar=1. This argument only applies when normal ordering QuadOperators.

openfermion.transforms.
normal_ordered_ladder_term
(term, coefficient, parity=1)¶ Return a normal ordered FermionOperator or BosonOperator corresponding to single term.
Parameters:  term (list or tuple) – A sequence of tuples. The first element of each tuple is an integer indicating the mode on which a fermion ladder operator acts, starting from zero. The second element of each tuple is an integer, either 1 or 0, indicating whether creation or annihilation acts on that mode.
 coefficient (complex or float) – The coefficient of the term.
 parity (int) – parity=1 corresponds to a Fermionic term that should be ordered based on the canonical anticommutation relations. parity=1 corresponds to a Bosonic term that should be ordered based on the canonical commutation relations.
Returns: ordered_term –
 a FermionOperator or BosonOperator instance.
The normal ordered form of the input. Note that this might have more terms.
In our convention, normal ordering implies terms are ordered from highest tensor factor (on left) to lowest (on right). Also, ladder operators come first.
Warning
Even assuming that each creation or annihilation operator appears at most a constant number of times in the original term, the runtime of this method is exponential in the number of qubits.

openfermion.transforms.
normal_ordered_quad_term
(term, coefficient, hbar=1.0)¶ Return a normal ordered QuadOperator corresponding to single term.
Parameters:  term – A tuple of tuples. The first element of each tuple is an integer indicating the mode on which a boson ladder operator acts, starting from zero. The second element of each tuple is an integer, either 1 or 0, indicating whether creation or annihilation acts on that mode.
 coefficient – The coefficient of the term.
 hbar (float) – the value of hbar used in the definition of the commutator [q_i, p_j] = i hbar delta_ij. By default hbar=1.
Returns: ordered_term (QuadOperator) –
 The normal ordered form of the input.
Note that this might have more terms.
In our convention, normal ordering implies terms are ordered from highest tensor factor (on left) to lowest (on right). Also, q operators come first.

openfermion.transforms.
parity_code
(n_modes)¶ The parity transform (arXiv:1208.5986) as binary code. This code is very similar to the JordanWigner transform, but with long update strings instead of parity strings. It does not save qubits: n_qubits = n_modes.
Parameters: n_modes (int) – number of modes Returns (BinaryCode): The parity transform BinaryCode

openfermion.transforms.
project_onto_sector
(operator, qubits, sectors)¶ Remove qubit by projecting onto sector.
Takes a QubitOperator, and projects out a list of qubits, into either the +1 or 1 sector. Note  this requires knowledge of which sector we wish to project into.
Parameters:  operator – the QubitOperator to work on
 qubits – a list of indices of qubits in operator to remove
 sectors – for each qubit, whether to project into the 0 subspace (<Z>=1) or the 1 subspace (<Z>=1).
Returns: projected_operator – the resultant operator
Raises: TypeError
– operator must be a QubitOperator.TypeError
– qubits and sector must be an arraylike.ValueError
– If qubits and sectors have different length.ValueError
– If sector are not specified as 0 or 1.

openfermion.transforms.
projection_error
(operator, qubits, sectors)¶ Calculate the error from the project_onto_sector function.
Parameters:  operator – the QubitOperator to work on
 qubits – a list of indices of qubits in operator to remove
 sectors – for each qubit, whether to project into the 0 subspace (<Z>=1) or the 1 subspace (<Z>=1).
Returns: error – the trace norm of the removed term.
Raises: TypeError
– operator must be a QubitOperator.TypeError
– qubits and sector must be an arraylike.ValueError
– If qubits and sectors have different length.ValueError
– If sector are not specified as 0 or 1.

openfermion.transforms.
prune_unused_indices
(symbolic_operator)¶ Remove indices that do not appear in any terms.
Indices will be renumbered such that if an index i does not appear in any terms, then the next largest index that appears in at least one term will be renumbered to i.

openfermion.transforms.
qubit_operator_to_pauli_sum
(operator: openfermion.ops.operators.qubit_operator.QubitOperator, qubits: Optional[Sequence[cirq.ops.raw_types.Qid]] = None) → cirq.ops.linear_combinations.PauliSum¶ Convert QubitOperator to a sum of PauliString.
Parameters:  operator (QubitOperator) – operator to convert.
 qubits (List) – Optional list of qubit names. If None a list of cirq.LineQubit of length number of qubits in operator is created.
Returns: pauli_sum (PauliSum) – cirq PauliSum object.
Raises: TypeError
– if qubit_op is not a QubitOpertor.

openfermion.transforms.
reduce_number_of_terms
(operator, stabilizers, maintain_length=False, output_fixed_positions=False, manual_input=False, fixed_positions=None)¶ Reduce the number of Pauli strings of operator using stabilizers.
This function reduces the number of terms in a string by merging terms that are identical by the multiplication of stabilizers. The resulting Pauli strings maintain their length, unless specified otherwise. In the latter case, a list of indices can be passed to manually indicate the qubits to be fixed.
It is possible to reduce the number of terms in a Hamiltonian by merging Pauli strings \(H_1, \, H_2\) that are related by a stabilizer \(S\) such that \(H_1 = H_2 \cdot S\). Given a stabilizer generator \(\pm X \otimes p\) this algorithm fixes the first qubit, such that every Pauli string in the Hamiltonian acts with either \(Z\) or the identity on it. Where necessary, this is achieved by multiplications with \(\pm X \otimes p\): a string \(Y \otimes h\), for instance, is turned into \(Z \otimes (\mp ih\cdot p)\). Qubits on which a generator acts as \(Y\) (\(Z\)) are constrained to be acted on by the Hamiltonian as \(Z\) (\(X\)) or the identity. Fixing a different qubit for every stabilizer generator eliminates all redundant strings. The fixed representations are in the end reexpressed as the shortest of the original strings, \(H_1\) or \(H_2\).
Parameters:  operator (QubitOperator) – Operator of which the number of terms will be reduced.
 stabilizers (QubitOperator) – Stabilizer generators used for the reduction. Can also be passed as a list of QubitOperator.
 maintain_length (Boolean) – Option deciding whether the fixed Pauli strings are reexpressed in their original form. Set to False by default.
 output_fixed_positions (Boolean) – Option deciding whether to return the list of fixed qubit positions. Set to False by default.
 manual_input (Boolean) – Option to pass the list of fixed qubits positions manually. Set to False by default.
 fixed_positions (list) – (optional) List of fixed qubit positions. Passing a list is only effective if manual_input is True.
Returns: reduced_operator (QubitOperator) –
 Operator with reduced number of
terms.
fixed_positions (list): (optional) Fixed qubits.
Raises: TypeError
– Input terms must be QubitOperator.TypeError
– Input stabilizers must be QubitOperator or list.StabilizerError
– Trivial stabilizer (identity).StabilizerError
– Stabilizer with complex coefficient.TypeError
– List of fixed qubits required if manual input True.StabilizerError
– The number of stabilizers must be equal to the number of qubits manually fixed.StabilizerError
– All qubit positions must be different.

openfermion.transforms.
reorder
(operator, order_function, num_modes=None, reverse=False)¶ Changes the ladder operator order of the Hamiltonian based on the provided order_function per mode index.
Parameters:  operator (SymbolicOperator) – the operator that will be reordered. must be a SymbolicOperator or any type of operator that inherits from SymbolicOperator.
 order_function (func) – a function per mode that is used to map the indexing. must have arguments mode index and num_modes.
 num_modes (int) – default None. User can provide the number of modes assumed for the system. if None, the number of modes will be calculated based on the Operator.
 reverse (bool) – default False. if set to True, the mode mapping is reversed. reverse = True will not revert back to original if num_modes calculated differs from original and reverted.
Note: Every order function must take in a mode_idx and num_modes.

openfermion.transforms.
reverse_jordan_wigner
(qubit_operator, n_qubits=None)¶ Transforms a QubitOperator into a FermionOperator using the JordanWigner transform.
Operators are mapped as follows: Z_j > I  2 a^dagger_j a_j X_j > (a^dagger_j + a_j) Z_{j1} Z_{j2} .. Z_0 Y_j > i (a^dagger_j  a_j) Z_{j1} Z_{j2} .. Z_0
Parameters:  qubit_operator – the QubitOperator to be transformed.
 n_qubits – the number of qubits term acts on. If not set, defaults to the maximum qubit number acted on by term.
Returns: transformed_term – An instance of the FermionOperator class.
Raises: TypeError
– Input must be a QubitOperator.TypeError
– Invalid number of qubits specified.TypeError
– Pauli operators must be X, Y or Z.

openfermion.transforms.
rotate_qubit_by_pauli
(qop, pauli, angle)¶ Rotate qubit operator by exponential of Pauli.
Perform the rotation e^{i theta * P}Qe^{i theta * P} on a qubitoperator Q and a Pauli operator P.
Parameters:  qop – the QubitOperator to be rotated
 pauli – a single Pauli operator  a QubitOperator with a single term, and a coefficient equal to 1.
 angle – the angle to be rotated by.
Returns:  rotated_op  the rotated QubitOperator following the
above formula.
Raises: TypeError
– qop must be a QubitOperatorTypeError
– pauli must be a Pauli Operator (QubitOperator with single term and coefficient equal to 1).

openfermion.transforms.
symmetric_ordering
(operator, ignore_coeff=True, ignore_identity=True)¶ Apply the symmetric ordering to a BosonOperator or QuadOperator.
The symmetric ordering is performed by applying McCoy’s formula directly to polynomial terms of quadrature operators:
q^m p^n > (1/ 2^n) sum_{r=0}^{n} Binomial(n, r) q^r p^m q^{nr}
Note: in general, symmetric ordering is performed on a single term containing the tensor product of various operators. However, this function can also be applied to a sum of these terms, and the symmetric product is distributed over the summed terms.
In this case, Hermiticity cannot be guaranteed  as such, by default term coefficients and identity operators are ignored. However, this behavior can be modified via keyword arguments describe below if necessary.
Parameters:  operator – either a BosonOperator or QuadOperator.
 ignore_coeff (bool) – By default, the coefficients for each term are ignored; S(a q^m p^n) = S(q^m p^n), and the returned operator is always Hermitian. If set to False, then instead the coefficients are taken into account; S(q^m p^n) = a S(q^m p^n). In this case, if a is a complex coefficient, it is not guaranteed that the the returned operator will be Hermitian.
 ignore_identity (bool) – By default, identity terms are ignore; S(I) = 0. If set to False, then instead S(I) = I.
Returns: transformed_operator – an operator of the same class as in the input.
Warning
The runtime of this method is exponential in the maximum locality of the original operator.

openfermion.transforms.
symmetry_conserving_bravyi_kitaev
(fermion_hamiltonian, active_orbitals, active_fermions)¶ Returns the qubit Hamiltonian for the fermionic Hamiltonian supplied, with two qubits removed using conservation of electron spin and number, as described in arXiv:1701.08213.
Parameters:  fermion_hamiltonian – A fermionic hamiltonian obtained using OpenFermion. An instance of the FermionOperator class.
 active_orbitals – Int type object. The number of active orbitals being considered for the system.
 active_fermions – Int type object. The number of active fermions being considered for the system (note, this is less than the number of electrons in a molecule if some orbitals have been assumed filled).
Returns: qubit_hamiltonian –
 The qubit Hamiltonian corresponding to
the supplied fermionic Hamiltonian, with two qubits removed using spin symmetries.
Warning
Reorders orbitals from the default evenodd ordering to all spinup orbitals, then all spindown orbitals.
Raises:  ValueError if fermion_hamiltonian isn’t of the type
 FermionOperator, or active_orbitals isn’t an integer,
 or active_fermions isn’t an integer.
 Notes: This function reorders the spin orbitals as all spinup, then
 all spindown. It uses the OpenFermion bravyi_kitaev_tree mapping, rather than the bravyikitaev mapping. Caution advised when using with a FermiHubbard Hamiltonian; this technique correctly reduces the Hamiltonian only for the lowest energy even and odd fermion number states, not states with an arbitrary number of fermions.

openfermion.transforms.
taper_off_qubits
(operator, stabilizers, manual_input=False, fixed_positions=None, output_tapered_positions=False)¶ Remove qubits from given operator.
Qubits are removed by eliminating an equivalent number of stabilizer conditions. Which qubits that are can either be determined automatically or their positions can be set manually.
Qubits can be disregarded from the Hamiltonian when the effect of all its terms on them is rendered trivial. This algorithm employs a stabilizers like \(\pm X \otimes p\) to fix the action of every Pauli string on the first qubit to \(Z\) or the identity. A string \(X \otimes h\) would for instance be multiplied with the stabilizer to obtain \(1 \otimes (\pm h\cdot p)\) while a string \(Z \otimes h^\prime\) would pass without correction. The first qubit can subsequently be removed as it must be in the computational basis in Hamiltonian eigenstates. For stabilizers acting as \(Y\) (\(Z\)) on selected qubits, the algorithm would fix the action of every Hamiltonian string to \(Z\) (\(X\)). Updating also the list of remaining stabilizer generators, the algorithm is run iteratively.
Parameters:  operator (QubitOperator) – Operator of which qubits will be removed.
 stabilizers (QubitOperator) – Stabilizer generators for the tapering. Can also be passed as a list of QubitOperator.
 manual_input (Boolean) – Option to pass the list of fixed qubits positions manually. Set to False by default.
 fixed_positions (list) – (optional) List of fixed qubit positions. Passing a list is only effective if manual_input is True.
 output_tapered_positions (Boolean) – Option to output the positions of qubits that have been removed.
Returns: skimmed_operator (QubitOperator) – Operator with fewer qubits. removed_positions (list): (optional) List of removed qubit positions.
For the qubits to be gone in the qubit count, the remaining qubits have been moved up to those indices.

openfermion.transforms.
verstraete_cirac_2d_square
(operator, x_dimension, y_dimension, add_auxiliary_hamiltonian=True, snake=False)¶ Apply the VerstraeteCirac transform on a 2d square lattice.
Note that this transformation adds one auxiliary fermionic mode for each mode already present, and hence it doubles the number of qubits needed to represent the system.
Currently only supports even values of x_dimension and only works for spinless models.
Parameters:  operator (FermionOperator) – The operator to transform.
 x_dimension (int) – The number of columns of the grid.
 y_dimension (int) – The number of rows of the grid.
 snake (bool, optional) – Indicates whether the fermions are already ordered according to the 2d “snake” ordering. If False, we assume they are in “lexicographic” order by row and column index. Default is False.
Returns: transformed_operator – A QubitOperator.

openfermion.transforms.
vertical_edges_snake
(x_dimension, y_dimension)¶ Obtain the vertical edges in the 2d snake ordering.

openfermion.transforms.
weight_one_binary_addressing_code
(exponent)¶ Weight1 binary addressing code (arXiv:1712.07067). This highly nonlinear code works for a number of modes that is an integer power of two. It encodes all possible vectors with Hamming weight 1, which corresponds to all states with total occupation one. The amount of qubits saved here is maximal: for a given argument ‘exponent’, we find n_modes = 2 ^ exponent, n_qubits = exponent.
Note
This code is highly nonlinear and might produce a lot of terms.
Parameters: exponent (int) – exponent for the number of modes n_modes = 2 ^ exponent Returns (BinaryCode): the weight one binary addressing BinaryCode

openfermion.transforms.
weight_one_segment_code
()¶ Weight1 segment code (arXiv:1712.07067). Outputs a 3mode, 2qubit code, which encodes all the vectors (states) with Hamming weight (occupation) 0 and 1. n_qubits = 2, n_modes = 3. A linear amount of qubits can be saved appending several instances of this code.
Note
This code is highly nonlinear and might produce a lot of terms.
Returns (BinaryCode): weight one segment code

openfermion.transforms.
weight_two_segment_code
()¶ Weight2 segment code (arXiv:1712.07067). Outputs a 5mode, 4qubit code, which encodes all the vectors (states) with Hamming weight (occupation) 2 and 1. n_qubits = 4, n_modes = 5. A linear amount of qubits can be saved appending several instances of this code.
Note
This code is highly nonlinear and might produce a lot of terms.
Returns (BinaryCode): weight2 segment code

openfermion.transforms.
weyl_polynomial_quantization
(polynomial)¶ Apply the Weyl quantization to a phase space polynomial.
The Weyl quantization is performed by applying McCoy’s formula directly to a polynomial term of the form q^m p^n:
 q^m p^n >
 (1/ 2^n) sum_{r=0}^{n} Binomial(n, r) hat{q}^r hat{p}^m q^{nr}
where q and p are phase space variables, and hat{q} and hat{p} are quadrature operators.
The input is provided in the form of a string, for example
weyl_polynomial_quantization('q0^2 p0^3 q1^3')
where ‘q’ or ‘p’ is the phase space quadrature variable, the integer directly following is the mode it is with respect to, and ‘^2’ is the polynomial power.
Parameters: polynomial (str) – polynomial function of q and p of the form ‘qi^m pj^n …’ where i,j are the modes, and m, n the powers. Returns: QuadOperator – the Weyl quantization of the phase space function. Warning
The runtime of this method is exponential in the maximum locality of the original operator.
openfermion.utils¶

class
openfermion.utils.
Grid
(dimensions, length, scale)¶ A multidimension grid of points with an assigned length scale.
 This grid acts as a helper class for parallelpiped super cells. It
 tracks a mapping from indices to grid points and stores the associated reciprocal lattice with respect to the original realspace lattice. This enables calculations with nontrivial unit cells.

dimensions
¶ Number of spatial dimensions the grid occupys
Type: int

length
¶ dlength tuple specifying number of points along each dimension.
Type: tuple of ints

shifts
¶ Integer shifts in position to center grid.
Type: list of ints

scale
¶ Vectors defining the super cell being simulated, vectors are stored as columns in the matrix.
Type: ndarray

volume
¶ Total volume of the supercell parallelpiped.
Type: float

num_points
¶ Total number of points in the grid.
Type: int

reciprocal_scale
¶ Vectors defining the reciprocal lattice. The vectors are stored as the columns in the matrix.
Type: ndarray

__init__
(dimensions, length, scale)¶ Parameters:  dimensions (int) – The number of dimensions the grid lives in.
 length (int or tuple) – The number of points along each grid axis that will be taken in both reciprocal and real space. If tuple, it is read for each dimension, otherwise assumed uniform.
 scale (float or ndarray) – The total length of each grid dimension. If a float is passed, the uniform cubic unit cell is assumed. For an ndarray, dimensions independent vectors of the correct dimension must be passed. We assume column vectors define the supercell vectors.

all_points_indices
()¶ Returns: iterable[tuple[int]] – The indexcoordinate tuple of each point in the grid.

grid_indices
(qubit_id, spinless)¶ This function is the inverse of orbital_id.
Parameters:  qubit_id (int) – The tensor factor to map to grid indices.
 spinless (bool) – Whether to use the spinless model or not.
Returns: grid_indices (numpy.ndarray[int]) – The location of the qubit on the grid.

index_to_momentum_ints
(index)¶ Parameters: index (tuple) – ddimensional tuple specifying index in the grid Returns: Integer momentum vector

momentum_ints_to_index
(momentum_ints)¶ Parameters: momentum_ints (tuple) – ddimensional tuple momentum integers Returns: ddimensional tuples of indices

momentum_ints_to_value
(momentum_ints, periodic=True)¶ Parameters:  momentum_ints (tuple) – ddimensional tuple momentum integers
 periodic (bool) – Alias the momentum
Returns: ndarray containing the momentum vector.

momentum_vector
(momentum_indices, periodic=True)¶ Given grid point coordinate, return momentum vector with dimensions.
Parameters:  momentum_indices (list) – integers giving momentum indices. Allowed values are ints in [0, grid_length).
 periodic (bool) – Wrap the momentum indices according to periodicity
 Returns –
 momentum_vector: A numpy array giving the momentum vector with
 dimensions.

orbital_id
(grid_coordinates, spin=None)¶ Return the tensor factor of a orbital with given coordinates and spin.
Parameters:  grid_coordinates – List or tuple of ints giving coordinates of grid element. Acceptable to provide an int(instead of tuple or list) for 1D case.
 spin (bool) – 0 means spin down and 1 means spin up. If None, assume spinless model.
Returns: tensor_factor (int) – tensor factor associated with provided orbital label.

position_vector
(position_indices)¶ Given grid point coordinate, return position vector with dimensions.
Parameters: position_indices (intiterable[int]) – List or tuple of integers giving grid point coordinate. Allowed values are ints in [0, grid_length). Returns: position_vector (numpy.ndarray[float])

volume_scale
()¶ Returns: float – The volume of a lengthscale hypercube within the grid.

class
openfermion.utils.
HubbardSquareLattice
(x_dimension, y_dimension, n_dofs=1, spinless=False, periodic=True)¶ A square lattice for a Hubbard model.
 Valid edge types are:
 ‘onsite’
 ‘horizontal_neighbor’
 ‘vertical_neighbor’
 ‘neighbor’: union of ‘horizontal_neighbor’ and ‘vertical_neighbor’
 ‘diagonal_neighbor’

__init__
(x_dimension, y_dimension, n_dofs=1, spinless=False, periodic=True)¶ Parameters:  x_dimension (int) – The width of the grid.
 y_dimension (int) – The height of the grid.
 n_dofs (int, optional) – The number of degrees of freedom per site (and spin if applicable). Defaults is 1.
 periodic (bool, optional) – If True, add periodic boundary conditions. Default is True.
 spinless (bool, optional) – If True, return a spinless FermiHubbard model. Default is False.

delta_mag
(X, Y, by_index=False)¶ The distance between sites X and Y in each dimension.

edge_types
¶ The types of edges that a term could correspond to.
Examples include ‘onsite’, ‘neighbor’, ‘diagonal_neighbor’, etc.

n_dofs
¶ The number of degrees of freedom per site (and spin if applicable).

n_horizontal_neighbor_pairs
(ordered=True)¶ Number of horizontally neighboring (unordered) pairs of sites.

n_neighbor_pairs
(ordered=True)¶ Number of neighboring (unordered) pairs of sites.

n_sites
¶ The number of sites in the lattice.

n_vertical_neighbor_pairs
(ordered=True)¶ Number of vertically neighboring (unordered) pairs of sites.

onsite_edge_types
¶ The edge types that connect sites to themselves.

site_pairs_iter
(edge_type, ordered=True)¶ Iterable over pairs of sites corresponding to the given edge type.

spinless
¶ Whether or not the fermion has spin (False if so).

to_site_index
(site)¶ The index of a site.

class
openfermion.utils.
Spin
¶ An enumeration.

class
openfermion.utils.
SpinPairs
¶ The spin orbitals corresponding to a pair of spatial orbitals.

openfermion.utils.
amplitude_damping_channel
(density_matrix, probability, target_qubit, transpose=False)¶ Apply an amplitude damping channel
Applies an amplitude damping channel with a given probability to the target qubit in the density_matrix.
Parameters:  density_matrix (numpy.ndarray) – Density matrix of the system
 probability (float) – Probability error is applied p in [0, 1]
 target_qubit (int) – target for the channel error.
 transpose (bool) – Conjugate transpose channel operators, useful for acting on Hamiltonians in variational channel state models
Returns: new_density_matrix(numpy.ndarray) –
 Density matrix with the channel
applied.

openfermion.utils.
anticommutator
(operator_a, operator_b)¶ Compute the anticommutator of two operators.
Parameters: operator_b (operator_a,) – Operators in anticommutator. Any operators are accepted so long as implicit addition and multiplication are supported; e.g. QubitOperators, FermionOperators, BosonOperators, or Scipy sparse matrices. 2D Numpy arrays are also supported. Raises: TypeError
– operator_a and operator_b are not of the same type.

openfermion.utils.
bch_expand
(*ops, **kwargs)¶ Compute log[e^{x_1} … e^{x_N}] using the BCH formula.
This implementation is explained in arXiv:1712.01348.
Parameters:  ops – A sequence of operators of the same type for which multiplication and addition are supported. For instance, QubitOperators, FermionOperators, or Scipy sparse matrices.
 arguments (keyword) –
 order(int): The max degree of monomial with respect to X and Y
 to truncate the BCH expansions. Defaults to 6
Returns: The truncated BCH operator.
Raises: ValueError
– invalid order parameter.TypeError
– operator types are not all the same.

openfermion.utils.
commutator
(operator_a, operator_b)¶ Compute the commutator of two operators.
Parameters: operator_b (operator_a,) – Operators in commutator. Any operators are accepted so long as implicit subtraction and multiplication are supported; e.g. QubitOperators, FermionOperators, BosonOperators, or Scipy sparse matrices. 2D Numpy arrays are also supported. Raises: TypeError
– operator_a and operator_b are not of the same type.

openfermion.utils.
count_qubits
(operator)¶ Compute the minimum number of qubits on which operator acts.
Parameters: operator – FermionOperator, QubitOperator, DiagonalCoulombHamiltonian, or PolynomialTensor. Returns: num_qubits (int) – The minimum number of qubits on which operator acts. Raises: TypeError
– Operator of invalid type.

openfermion.utils.
dephasing_channel
(density_matrix, probability, target_qubit, transpose=False)¶ Apply a dephasing channel
Applies an amplitude damping channel with a given probability to the target qubit in the density_matrix.
Parameters:  density_matrix (numpy.ndarray) – Density matrix of the system
 probability (float) – Probability error is applied p in [0, 1]
 target_qubit (int) – target for the channel error.
 transpose (bool) – Conjugate transpose channel operators, useful for acting on Hamiltonians in variational channel state models
Returns: new_density_matrix (numpy.ndarray) –
 Density matrix with the channel
applied.

openfermion.utils.
depolarizing_channel
(density_matrix, probability, target_qubit, transpose=False)¶ Apply a depolarizing channel
Applies an amplitude damping channel with a given probability to the target qubit in the density_matrix.
Parameters:  density_matrix (numpy.ndarray) – Density matrix of the system
 probability (float) – Probability error is applied p in [0, 1]
 target_qubit (int/str) – target for the channel error, if given special value “all”, then a total depolarizing channel is applied.
 transpose (bool) – Dummy parameter to match signature of other channels but depolarizing channel is symmetric under conjugate transpose.
Returns: new_density_matrix (numpy.ndarray) –
 Density matrix with the channel
applied.

openfermion.utils.
double_commutator
(op1, op2, op3, indices2=None, indices3=None, is_hopping_operator2=None, is_hopping_operator3=None)¶ Return the double commutator [op1, [op2, op3]].
Parameters:  op2, op3 (op1,) – operators for the commutator. All three operators must be of the same type.
 indices3 (indices2,) – The indices op2 and op3 act on.
 is_hopping_operator2 (bool) – Whether op2 is a hopping operator.
 is_hopping_operator3 (bool) – Whether op3 is a hopping operator.
Returns: The double commutator of the given operators.

openfermion.utils.
down_index
(index)¶ Function to return downorbital index given a spatial orbital index.
Parameters: index (int) – spatial orbital index Returns: An integer representing the index of the associated spindown orbital

openfermion.utils.
get_file_path
(file_name, data_directory)¶ Compute file_path for the file that stores operator.
Parameters:  file_name – The name of the saved file.
 data_directory – Optional data directory to change from default data directory specified in config file.
Returns: file_path (string) – File path.
Raises: OperatorUtilsError
– File name is not provided.

openfermion.utils.
hermitian_conjugated
(operator)¶ Return Hermitian conjugate of operator.

openfermion.utils.
is_hermitian
(operator)¶ Test if operator is Hermitian.

openfermion.utils.
is_identity
(operator)¶ Check whether QubitOperator of FermionOperator is identity.
Parameters: operator – QubitOperator, FermionOperator, BosonOperator, or QuadOperator. Raises: TypeError
– Operator of invalid type.

openfermion.utils.
load_operator
(file_name=None, data_directory=None, plain_text=False)¶ Load FermionOperator or QubitOperator from file.
Parameters:  file_name – The name of the saved file.
 data_directory – Optional data directory to change from default data directory specified in config file.
 plain_text – Whether the input file is plain text
Returns: operator –
 The stored FermionOperator, BosonOperator,
QuadOperator, or QubitOperator
Raises: TypeError
– Operator of invalid type.

openfermion.utils.
map_one_hole_dm_to_one_pdm
(oqdm)¶ Convert a 1holeRDM to a 1RDM
Parameters: oqdm (numpy.ndarray) – The 1holeRDM as a 2index tensor. Indices follow the internal convention of oqdm[p, q] == \(a_{p}a_{q}^{\dagger}\). Returns: oqdm (numpy.ndarray) – the 1holeRDM transformed from a 1RDM.

openfermion.utils.
map_one_pdm_to_one_hole_dm
(opdm)¶ Convert a 1RDM to a 1holeRDM
Parameters: opdm (numpy.ndarray) – The 1RDM as a 2index tensor. Indices follow the internal convention of opdm[p, q] == \(a_{p}^{\dagger}a_{q}\). Returns: oqdm (numpy.ndarray) – the 1holeRDM transformed from a 1RDM.

openfermion.utils.
map_particle_hole_dm_to_one_pdm
(phdm, num_particles, num_basis_functions)¶ Map the particleholeRDM to the 1RDM
Parameters:  phdm (numpy.ndarray) – The 2particleholeRDM as a 4index tensor. Indices follow the internal convention of phdm[p, q, r, s] == \(a_{p}^{\dagger}a_{q}a_{r}^{\dagger}a_{s}\).
 num_particles – number of particles in the system.
 num_basis_functions – number of spinorbitals (usually the number of qubits)
Returns: opdm (numpy.ndarray) – the 1RDM transformed from a 1RDM.

openfermion.utils.
map_particle_hole_dm_to_two_pdm
(phdm, opdm)¶ Map the 2RDM to the particleholeRDM
Parameters:  phdm (numpy.ndarray) – The 2particleholeRDM as a 4index tensor. Indices follow the internal convention of phdm[p, q, r, s] == \(a_{p}^{\dagger}a_{q}a_{r}^{\dagger}a_{s}\).
 opdm (numpy.ndarray) – The 1RDM as a 2index tensor. Indices follow the internal convention of opdm[p, q] == \(a_{p}^{\dagger}a_{q}\).
Returns: tpdm (numpy.ndarray) – The 2RDM matrix.

openfermion.utils.
map_two_hole_dm_to_one_hole_dm
(tqdm, hole_number)¶ Map from 2holeRDM to 1holeRDM
Parameters:  tqdm (numpy.ndarray) – The 2holeRDM as a 4index tensor. Indices follow the internal convention of tqdm[p, q, r, s] == \(a_{p}a_{q}a_{r}^{\dagger}a_{s}^{\dagger}\).
 hole_number (float) – Number of holes in the system. For chemical systems this is usually the number of spin orbitals minus the number of electrons.
Returns: oqdm (numpy.ndarray) – The 1holeRDM contracted from the tqdm.

openfermion.utils.
map_two_hole_dm_to_two_pdm
(tqdm, opdm)¶ Map from the 2holeRDM to the 2RDM
Parameters:  tqdm (numpy.ndarray) – The 2holeRDM as a 4index tensor. Indices follow the internal convention of tqdm[p, q, r, s] == \(a_{p}a_{q}a_{r}^{\dagger}a_{s}^{\dagger}\).
 opdm (numpy.ndarray) – The 1RDM as a 2index tensor. Indices follow the internal convention of opdm[p, q] == \(a_{p}^{\dagger}a_{q}\).
Returns: tpdm (numpy.ndarray) – The 2RDM matrix.

openfermion.utils.
map_two_pdm_to_one_pdm
(tpdm, particle_number)¶ Contract a 2RDM to a 1RDM
Parameters:  tpdm (numpy.ndarray) – The 2RDM as a 4index tensor. Indices follow the internal convention of tpdm[p, q, r, s] == \(a_{p}^{\dagger}a_{q}^{\dagger}a_{r}a_{s}\).
 particle_number (float) – number of particles in the system
Returns: opdm (numpy.ndarray) – The 1RDM contracted from the tpdm.

openfermion.utils.
map_two_pdm_to_particle_hole_dm
(tpdm, opdm)¶ Map the 2RDM to the particleholeRDM
Parameters:  tpdm (numpy.ndarray) – The 2RDM as a 4index tensor. Indices follow the internal convention of tpdm[p, q, r, s] == \(a_{p}^{\dagger}a_{q}^{\dagger}a_{r}a_{s}\).
 opdm (numpy.ndarray) – The 1RDM as a 2index tensor. Indices follow the internal convention of opdm[p, q] == \(a_{p}^{\dagger}a_{q}\).
Returns: phdm (numpy.ndarray) – The particlehole matrix.

openfermion.utils.
map_two_pdm_to_two_hole_dm
(tpdm, opdm)¶ Map from the 2RDM to the 2holeRDM
Parameters:  tpdm (numpy.ndarray) – The 2RDM as a 4index tensor. Indices follow the internal convention of tpdm[p, q, r, s] == \(a_{p}^{\dagger}a_{q}^{\dagger}a_{r}a_{s}\).
 opdm (numpy.ndarray) – The 1RDM as a 2index tensor. Indices follow the internal convention of opdm[p, q] == \(a_{p}^{\dagger}a_{q}\).
Returns: tqdm (numpy.ndarray) – The 2hole matrix.

openfermion.utils.
save_operator
(operator, file_name=None, data_directory=None, allow_overwrite=False, plain_text=False)¶ Save FermionOperator or QubitOperator to file.
Parameters:  operator – An instance of FermionOperator, BosonOperator, or QubitOperator.
 file_name – The name of the saved file.
 data_directory – Optional data directory to change from default data directory specified in config file.
 allow_overwrite – Whether to allow files to be overwritten.
 plain_text – Whether the operator should be saved to a plaintext format for manual analysis
Raises: OperatorUtilsError
– Not saved, file already exists.TypeError
– Operator of invalid type.TypeError
– Coefficients in Operator sympy expressions.

openfermion.utils.
up_index
(index)¶ Function to return uporbital index given a spatial orbital index.
Parameters: index (int) – spatial orbital index Returns: An integer representing the index of the associated spinup orbital

openfermion.utils.
up_then_down
(mode_idx, num_modes)¶  up then down reordering, given the operator has the default evenodd
ordering. Otherwise this function will reorder indices where all even indices now come before odd indices.
 Example:
 0,1,2,3,4,5 > 0,2,4,1,3,5
The function takes in the index of the mode that will be relabeled and the total number modes.
Parameters:  mode_idx (int) – the mode index that is being reordered
 num_modes (int) – the total number of modes of the operator.
Returns (int): reordered index of the mode.