PennyLaneAI / pennylane

PennyLane is a cross-platform Python library for quantum computing, quantum machine learning, and quantum chemistry. Train a quantum computer the same way as a neural network.
https://pennylane.ai
Apache License 2.0
2.2k stars 573 forks source link

Improve drawing of Hamiltonians #1519

Open mariaschuld opened 2 years ago

mariaschuld commented 2 years ago

Since Hamiltonians are now observables with differentiable coefficients, drawing a circuit with a Hamiltonian looks as follows:

coeffs = [1.0, 1.0, 1.0]
observables1 = [qml.PauliZ(0), qml.PauliY(0), qml.PauliZ(2)]
H1 = qml.Hamiltonian(coeffs, observables1)

@qml.qnode(dev)
def circuit1():
    return qml.expval(H1)
>>> qml.draw(circuit1)()
 0: ──╭┤ ⟨Hamiltonian(1, 1, 1)⟩
 2: ──╰┤ ⟨Hamiltonian(1, 1, 1)⟩ 

However, information about the observables is not shown. Instead we could use the solution of how arbitrary unitaries get printed below the circuit:

 0: ──H──╭┤ ⟨Ham⟩
 2: ─────╰┤ ⟨Ham⟩

Ham = 2 X0 + 3 Z0 Z1

This would require an update in qml.circuit_drawer.representation_resolver which mimics the behaviour of QubitUnitary.

Useful info: The Hamiltonian class defines a __str__() method which prints an abbreviated string such as Hamiltonian(terms=2, wires=[0,1]) and a __repr__() method for the full information. The latter is probably what we want here.

albi3ro commented 1 year ago

Hamiltonian coefficients are now shown only when there is less than three coefficients:

0: ───┤ ╭<𝓗(1.00,1.00,1.00)>
1: ───┤ ├<𝓗(1.00,1.00,1.00)>
2: ───┤ ╰<𝓗(1.00,1.00,1.00)>

For greater than 3, only a simple 𝓗 is displayed.

0: ───┤ ╭<𝓗>
1: ───┤ ├<𝓗>
2: ───┤ ├<𝓗>
3: ───┤ ╰<𝓗>

We could cache the hamiltonian and display it below similar to how we handle matrices, but I think this is currently sufficient.

How the Hamiltonian is displayed is now the responsibility of the label method.