Example: importing and exporting circuits¶
A circuit does not have to start life in Python: it may come from an OpenQASM file, a Quirk link or a JSON document another program saved. This example walks through all three formats, both ways.
OpenQASM 2.0¶
vq.qasm writes the circuit and vq.circuit_from_qasm reads it. The importer
needs no ply and no other dependency:
import vqubit as vq
q0, q1 = vq.LineQubit.range(2)
circuit = vq.Circuit(vq.H(q0), vq.CNOT(q0, q1), vq.measure(q0, q1, key="m"))
print(vq.qasm(circuit))
// Generated by vqubit
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg m[2];
h q[0];
cx q[0],q[1];
measure q[0] -> m[0];
measure q[1] -> m[1];
And back:
You can write the QASM by hand too. The importer understands the whole qelib1
set (h, x, y, z, s, sdg, t, tdg, rx, ry, rz, cx, cy,
cz, ch, swap, ccx, cswap, id, u1, u2, u3), pi expressions,
custom gate definitions, reset, barrier and if(c==N) conditions:
hand_written = """OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
h q[0];
cx q[0],q[1];
measure q[0] -> c[0];
measure q[1] -> c[1];
"""
imported = vq.circuit_from_qasm(hand_written)
print(imported)
print(vq.Simulator(seed=3).run(imported, repetitions=4).measurements)
The two measurements come out correlated: this is the Bell state.
Quirk¶
https://algassert.com/quirk#circuit=eyJjb2xzIjpbWyJIIiwxXSxbIlx1MjAyMiIsIlgiXSxbIk1lYXN1cmUiLCJNZWFzdXJlIl1dLCJxdWJpdHMiOlsicTAiLCJxMSJdfQ
q0: ───H───@───M───
│ │
q1: ───────X───M───
The link encodes Quirk's JSON in base64; you can open it in a browser to see the
circuit. vq.quirk_json_to_circuit takes the JSON directly if that is what you
have.
JSON¶
The JSON format is Cirq's, so it works to exchange circuits with other programs (and with Cirq itself, if you have it installed):
To hand a circuit to Cirq and back, use the optional bridge:
import importlib.util
if importlib.util.find_spec("cirq") is not None:
cirq_circuit = vq.to_cirq(circuit) # a cirq.Circuit
back = vq.from_cirq(cirq_circuit) # back to vqubit
What you have learned¶
- QASM is the most portable exchange format, and vqubit's importer has no dependencies.
- Quirk is for sharing a circuit as a web link.
- JSON is Cirq's format: it keeps types, parameters and measurements, and it
is the basis of the
to_cirq/from_cirqbridge.
The details of each format are in Serialization.