BQSKit / bqskit

Berkeley Quantum Synthesis Toolkit
Other
106 stars 31 forks source link

Is it possible to get the QASM string representation of a BQSKit circuit? #214

Closed jagandecapri closed 5 months ago

jagandecapri commented 5 months ago

Hi,

Is it possible to get the QASM string representation of a BQSKit circuit?

mtweiden commented 5 months ago

Hi Jagatheesan,

You can save circuits using Circuit.save('file_name.qasm'). Here's an example:

from bqskit import Circuit
from bqskit.ir.gates import CNOTGate

circuit = Circuit(2)
circuit.append_gate(CNOTGate(), (0, 1))

circuit.save('circuit.qasm')
jagandecapri commented 5 months ago

Hi @mtweiden ,

Thank you for your response and sorry if my question was not clear. I am looking for a way to get the QASM string from a BQSKit circuit saved into a variable like here.

jagandecapri commented 5 months ago

I think I found the function that I am looking for at Circuit.to I'm calling it as circuit.to('qasm') and it seems to return the string of the circuit in QASM representation. Is this correct?

[Update]

I tested out reading a small QASM 2.0 file which contains a Controlled-U1 gate and converting to QASM string again using the code below:

QASM file - test_circuit.qasm

OPENQASM 2.0;
include "qelib1.inc";

qreg q[2];
cu1(0) q[0], q[1];

Code for testing

from bqskit import Circuit
circuit = Circuit.from_file('qasm/test_circuit.qasm')
circuit.to('qasm')

However, I'm getting the error AttributeError: 'ControlledGate' object has no attribute '_qasm_name'.

edyounis commented 5 months ago

Yes, the circuit.to method will return the qasm as a str the way you have called it.

Thanks for reporting this bug. We should always be able to save a qasm file that we read. This happens because the cu1 gets internally converted to a ControlledGate(U1Gate) and the ControlledGate doesn't support qasm encoding, unlike the specialized controlled gates, e.g. CXGate().

jagandecapri commented 5 months ago

Hi @edyounis , noted. I tried to see if I can do a workaround by converting the BQSKit to Qiskit and then use the circuit.qasm() method from Qiskit but I end up with the same error AttributeError: 'ControlledGate' object has no attribute '_qasm_name' when executing qc = bqskit_to_qiskit(circuit) as following (in Jupyter notebook):

from bqskit import Circuit
from bqskit.ext import bqskit_to_qiskit
circuit = Circuit.from_file('qasm/test_circuit.qasm')
qc = bqskit_to_qiskit(circuit)
qc.qasm()

If you know any workaround for this issue, please kindly let me know. It seems to me that I cannot have "non-specialised" controlled gates in the BQSKit circuit and convert the resulting circuit to QASM.

edyounis commented 5 months ago

There is really no low-effort workaround here, but @mtweiden put up a PR that we will get merged in shortly.