Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove hf dependency in qubit tapering #2510

Merged
merged 6 commits into from
Apr 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion doc/releases/changelog-dev.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@
This is a temporary fix that will disappear in the future.
[(#2408)](https://github.com/PennyLaneAI/pennylane/pull/2408)

* The `qml.taper` function can now be used to consistently taper any additional observables such as dipole moment,
particle number, and spin operators using the symmetries obtained from the Hamiltonian.
[(#2510)](https://github.com/PennyLaneAI/pennylane/pull/2510)

<h3>Breaking changes</h3>

Expand All @@ -43,4 +46,4 @@

This release contains contributions from (in alphabetical order):

Christian Gogolin, Christina Lee
Utkarsh Azad, Christian Gogolin, Christina Lee
2 changes: 1 addition & 1 deletion pennylane/qchem/observable_hf.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ def jordan_wigner(op):
>>> f = [0, 0]
>>> q = jordan_wigner(f)
>>> q
([(0.5+0j), (-0.5+0j)], [[], [(0, 'Z')]]) # corresponds to :math:`\frac{1}{2}(I_0 - Z_0)`
([(0.5+0j), (-0.5+0j)], [Identity(wires=[0]), PauliZ(wires=[0])]) # corresponds to :math:`\frac{1}{2}(I_0 - Z_0)`
"""
if len(op) == 1:
op = [((op[0], 1),)]
Expand Down
31 changes: 17 additions & 14 deletions pennylane/qchem/tapering.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@
import numpy
import pennylane as qml
from pennylane import numpy as np
from pennylane.qchem.observable_hf import simplify
from pennylane.hf.hamiltonian import _generate_qubit_operator
from pennylane.qchem.observable_hf import simplify, jordan_wigner
from pennylane.wires import Wires


Expand Down Expand Up @@ -395,7 +394,20 @@ def taper(h, generators, paulixops, paulix_sector):
c = anp.multiply(val, h.terms()[0])
c = qml.math.stack(c)

return simplify(qml.Hamiltonian(c, o))
tapered_ham = simplify(qml.Hamiltonian(c, o))
# If simplified Hamiltonian is missing wires, then add wires manually for consistency
obliviateandsurrender marked this conversation as resolved.
Show resolved Hide resolved
if wires_tap != list(tapered_ham.wires):
identity_op = functools.reduce(
lambda i, j: i @ j,
[
qml.Identity(wire)
for wire in Wires.unique_wires([tapered_ham.wires, Wires(wires_tap)])
],
)
tapered_ham = qml.Hamiltonian(
np.array([*tapered_ham.coeffs, 0.0]), [*tapered_ham.ops, identity_op]
)
obliviateandsurrender marked this conversation as resolved.
Show resolved Hide resolved
return tapered_ham


def optimal_sector(qubit_op, generators, active_electrons):
Expand Down Expand Up @@ -491,26 +503,17 @@ def taper_hf(generators, paulixops, paulix_sector, num_electrons, num_wires):
>>> taper_hf(generators, paulixops, paulix_sector, n_elec, n_qubits)
tensor([1, 1], requires_grad=True)
"""

pauli_map = {"I": qml.Identity, "X": qml.PauliX, "Y": qml.PauliY, "Z": qml.PauliZ}

# build the untapered Hartree Fock state
hf = np.where(np.arange(num_wires) < num_electrons, 1, 0)

# convert the HF state to a corresponding HF observable under the JW transform
fermop_terms = []
for idx, bit in enumerate(hf):
if bit:
op_coeffs, op_str = _generate_qubit_operator([idx])
op_terms = []
for term in op_str:
op_term = pauli_map[term[0][1]](term[0][0])
for tm in term[1:]:
op_term @= pauli_map[tm[1]](tm[0])
op_terms.append(op_term)
op_coeffs, op_terms = jordan_wigner([idx])
op_term = qml.Hamiltonian(np.array(op_coeffs), op_terms)
else:
op_term = qml.Hamiltonian([1], [qml.Identity(idx)])
op_term = qml.Hamiltonian([1.0], [qml.Identity(idx)])
fermop_terms.append(op_term)

ferm_op = functools.reduce(lambda i, j: _observable_mult(i, j), fermop_terms)
Expand Down
39 changes: 22 additions & 17 deletions tests/qchem/hf_tests/test_tapering.py
Original file line number Diff line number Diff line change
Expand Up @@ -589,17 +589,15 @@ def test_transform_hf(generators, paulixops, paulix_sector, num_electrons, num_w
),
],
)
def test_hf_energy(symbols, geometry, charge):
r"""Test that HF energy obtained from the tapered Hamiltonian and tapered Hartree Fock state
is consistent."""
def test_taper_obs(symbols, geometry, charge):
r"""Test that the expectation values of tapered observables with respect to the
tapered Hartree-Fock state (:math:`\langle HF|obs|HF \rangle`) are consistent."""
mol = qml.qchem.Molecule(symbols, geometry, charge)
hamiltonian = qml.qchem.diff_hamiltonian(mol)(geometry)
hf_state = np.where(np.arange(len(hamiltonian.wires)) < mol.n_electrons, 1, 0)
generators = qml.symmetry_generators(hamiltonian)
paulixops = qml.paulix_ops(generators, len(hamiltonian.wires))
paulix_sector = optimal_sector(hamiltonian, generators, mol.n_electrons)

hamiltonian_tapered = qml.taper(hamiltonian, generators, paulixops, paulix_sector)
hf_state_tapered = taper_hf(
generators, paulixops, paulix_sector, mol.n_electrons, len(hamiltonian.wires)
)
Expand All @@ -612,15 +610,22 @@ def test_hf_energy(symbols, geometry, charge):
lambda i, j: np.kron(i, j), [l if s else o for s in hf_state_tapered]
)

energy = (
scipy.sparse.coo_matrix(state)
@ qml.utils.sparse_hamiltonian(hamiltonian)
@ scipy.sparse.coo_matrix(state).T
).toarray()
energy_tapered = (
scipy.sparse.coo_matrix(state_tapered)
@ qml.utils.sparse_hamiltonian(hamiltonian_tapered)
@ scipy.sparse.coo_matrix(state_tapered).T
).toarray()

assert np.isclose(energy, energy_tapered)
observables = [
hamiltonian,
qml.qchem.particle_number(len(hamiltonian.wires)),
qml.qchem.spin2(mol.n_electrons, len(hamiltonian.wires)),
qml.qchem.spinz(len(hamiltonian.wires)),
]
for observable in observables:
tapered_obs = qml.taper(observable, generators, paulixops, paulix_sector)
obs_val = (
scipy.sparse.coo_matrix(state)
@ qml.utils.sparse_hamiltonian(observable)
@ scipy.sparse.coo_matrix(state).T
).toarray()
obs_val_tapered = (
scipy.sparse.coo_matrix(state_tapered)
@ qml.utils.sparse_hamiltonian(tapered_obs)
@ scipy.sparse.coo_matrix(state_tapered).T
).toarray()
assert np.isclose(obs_val, obs_val_tapered)