Skip to content

Commit

Permalink
pauli_sum_collector.estimate_energy() should return float when energy…
Browse files Browse the repository at this point in the history
….imag == 0 (#4313)

For chemistry hamiltonians generated via `openfermion.qubit_operator_to_pauli_sum(qubit_hamiltonian)`, even though the pauli sum has only real terms (complex with imag == 0), using `p.estimated_energy()` returns a complex (with imag  == 0) and hence cannot be directly used with scipy optimizers which expect a flaot (eg: `Nelder-Mead`, `SLSQP` etc.)

See quantumlib/OpenFermion#732 for an example.
  • Loading branch information
tanujkhattar committed Jul 14, 2021
1 parent 0d8bf31 commit a3109a7
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
2 changes: 1 addition & 1 deletion cirq-core/cirq/work/pauli_sum_collector.py
Expand Up @@ -92,9 +92,9 @@ def estimated_energy(self) -> Union[float, complex]:
if a + b:
energy += coef * (a - b) / (a + b)
energy = complex(energy)
energy += self._identity_offset
if energy.imag == 0:
energy = energy.real
energy += self._identity_offset
return energy


Expand Down
8 changes: 6 additions & 2 deletions cirq-core/cirq/work/pauli_sum_collector_test.py
Expand Up @@ -22,12 +22,16 @@ async def test_pauli_string_sample_collector():
a, b = cirq.LineQubit.range(2)
p = cirq.PauliSumCollector(
circuit=cirq.Circuit(cirq.H(a), cirq.CNOT(a, b), cirq.X(a), cirq.Z(b)),
observable=cirq.X(a) * cirq.X(b) - 16 * cirq.Y(a) * cirq.Y(b) + 4 * cirq.Z(a) * cirq.Z(b),
observable=(1 + 0j) * cirq.X(a) * cirq.X(b)
- 16 * cirq.Y(a) * cirq.Y(b)
+ 4 * cirq.Z(a) * cirq.Z(b)
+ (1 - 0j),
samples_per_term=100,
)
completion = p.collect_async(sampler=cirq.Simulator())
assert await completion is None
assert p.estimated_energy() == 11
energy = p.estimated_energy()
assert isinstance(energy, float) and energy == 12


@pytest.mark.asyncio
Expand Down

0 comments on commit a3109a7

Please sign in to comment.