Skip to content

Commit a3109a7

Browse files
authored
pauli_sum_collector.estimate_energy() should return float when energy.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.
1 parent 0d8bf31 commit a3109a7

File tree

2 files changed

+7
-3
lines changed

2 files changed

+7
-3
lines changed

cirq-core/cirq/work/pauli_sum_collector.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,9 +92,9 @@ def estimated_energy(self) -> Union[float, complex]:
9292
if a + b:
9393
energy += coef * (a - b) / (a + b)
9494
energy = complex(energy)
95+
energy += self._identity_offset
9596
if energy.imag == 0:
9697
energy = energy.real
97-
energy += self._identity_offset
9898
return energy
9999

100100

cirq-core/cirq/work/pauli_sum_collector_test.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,16 @@ async def test_pauli_string_sample_collector():
2222
a, b = cirq.LineQubit.range(2)
2323
p = cirq.PauliSumCollector(
2424
circuit=cirq.Circuit(cirq.H(a), cirq.CNOT(a, b), cirq.X(a), cirq.Z(b)),
25-
observable=cirq.X(a) * cirq.X(b) - 16 * cirq.Y(a) * cirq.Y(b) + 4 * cirq.Z(a) * cirq.Z(b),
25+
observable=(1 + 0j) * cirq.X(a) * cirq.X(b)
26+
- 16 * cirq.Y(a) * cirq.Y(b)
27+
+ 4 * cirq.Z(a) * cirq.Z(b)
28+
+ (1 - 0j),
2629
samples_per_term=100,
2730
)
2831
completion = p.collect_async(sampler=cirq.Simulator())
2932
assert await completion is None
30-
assert p.estimated_energy() == 11
33+
energy = p.estimated_energy()
34+
assert isinstance(energy, float) and energy == 12
3135

3236

3337
@pytest.mark.asyncio

0 commit comments

Comments
 (0)