1
$\begingroup$

I'd want to parse the qasm file for analyze the quantum gate consisting its qasm file.

However, Qiskit provides the attribute of the quantum circuit, quantum_circuit.data.operation which summarize the quantum gates information.

Even if it returns the gates information, but the order of the each gate is changed.

For example, the original qasm file consists like this.

h q[0];
x q[1];

It is extracted in different order into below when use the data.operation attributes.

x q[1];
h q[0];

Actually, the final result of the quantum circuit is same. But I want to parse the qasm file as the same order of original one.

Is there any qiskit API or any method?

Thanks.

$\endgroup$

2 Answers 2

3
$\begingroup$

Qiskit comes with a QasmParser; an OpenQasm 2.0 parser. It can be used directly as follows:

from qiskit.qasm.qasmparser import QasmParser
import qiskit.qasm.node as qn

filename = '/path/to/qasm_file.qasm'

with open(filename) as file:
    data = file.read()
    with QasmParser(filename) as q_parser:
        q_parser.parse_debug(False)
        program = q_parser.parse(data)
        for node in program.children:
            print(node.to_string(indent = False))
            if isinstance(node, qn.Gate):
                print(node.name)
            elif isinstance(node, qn.CustomUnitary):
                print(node.name)
            elif isinstance(node, qn.Barrier):
                print(node.children)
            elif isinstance(node, qn.Measure):
                print(node.children)
            # ... ... ...

It can also be used indirectly through Qasm.parse() method

$\endgroup$
1
  • $\begingroup$ I've exectured your code by linking my qasm file. But it's result is something different one with what I want. It returns the information list of every gate defined in qiskit I think. $\endgroup$ Commented Jan 7, 2023 at 5:55
0
$\begingroup$

I am not certain I understand your question, but I will try to answer how to read in a circuit from a qasm file, and how to get the qasm string from a Qiskit circuit object.

You can read in a qasm file (the file can be any extension) using the following command (see here):

from qiskit.circuit import QuantumCircuit
circ = QuantumCircuit.from_qasm_file(path)

Then, you can export a circuit to a qasm string:

QASM_string = circ.qasm()
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.