Skip to content

Commit 9f6d5e3

Browse files
add keep_measure_order option in from_openqasm method
1 parent 5723ca6 commit 9f6d5e3

File tree

5 files changed

+68
-6
lines changed

5 files changed

+68
-6
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717

1818
- Auto unroll composite qiskit instructions when translating to tc circuit
1919

20+
- Add `keep_measure_order` bool option to `from_openqasm` methods so that the measure instruction order is kept by qiskit
21+
2022
### Fixed
2123

2224
- Fix adjoint possible bug with agnostic backend

tensorcircuit/abstractcircuit.py

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -580,21 +580,39 @@ def to_openqasm(self, **kws: Any) -> str:
580580

581581
@classmethod
582582
def from_openqasm(
583-
cls, qasmstr: str, circuit_params: Optional[Dict[str, Any]] = None
583+
cls,
584+
qasmstr: str,
585+
circuit_params: Optional[Dict[str, Any]] = None,
586+
keep_measure_order: bool = False,
584587
) -> "AbstractCircuit":
585588
from qiskit.circuit import QuantumCircuit
586589

587-
qiskit_circ = QuantumCircuit.from_qasm_str(qasmstr)
590+
if keep_measure_order is True:
591+
from .translation import qiskit_from_qasm_str_ordered_measure
592+
593+
qiskit_circ = qiskit_from_qasm_str_ordered_measure(qasmstr)
594+
else:
595+
qiskit_circ = QuantumCircuit.from_qasm_str(qasmstr)
588596
c = cls.from_qiskit(qiskit_circ, circuit_params=circuit_params)
589597
return c
590598

591599
@classmethod
592600
def from_openqasm_file(
593-
cls, file: str, circuit_params: Optional[Dict[str, Any]] = None
601+
cls,
602+
file: str,
603+
circuit_params: Optional[Dict[str, Any]] = None,
604+
keep_measure_order: bool = False,
594605
) -> "AbstractCircuit":
595606
from qiskit.circuit import QuantumCircuit
596607

597-
qiskit_circ = QuantumCircuit.from_qasm_file(file)
608+
if keep_measure_order is True:
609+
from .translation import qiskit_from_qasm_str_ordered_measure
610+
611+
with open(file) as f:
612+
qasmstr = f.read()
613+
qiskit_circ = qiskit_from_qasm_str_ordered_measure(qasmstr)
614+
else:
615+
qiskit_circ = QuantumCircuit.from_qasm_file(file)
598616
c = cls.from_qiskit(qiskit_circ, circuit_params=circuit_params)
599617
return c
600618

tensorcircuit/quantum.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1387,7 +1387,7 @@ def ps2coo_core(
13871387
return tf.SparseTensor(indices=indices, values=values, dense_shape=(s, s)) # type: ignore
13881388

13891389
except (NameError, ImportError):
1390-
logger.warning(
1390+
logger.info(
13911391
"tensorflow is not installed, and sparse Hamiltonian generation utilities are disabled"
13921392
)
13931393

tensorcircuit/translation.py

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from qiskit.extensions.exceptions import ExtensionError
1818
except ImportError:
1919
logger.warning(
20-
"Please first ``pip install -U qiskit`` to enable related functionality"
20+
"Please first ``pip install -U qiskit`` to enable related functionality in translation module"
2121
)
2222

2323
from . import gates
@@ -508,3 +508,31 @@ def eqasm2tc(
508508
getattr(c, gate_name)(*index)
509509

510510
return c
511+
512+
513+
def qiskit_from_qasm_str_ordered_measure(qasm_str: str) -> Any:
514+
"""
515+
qiskit ``from_qasm_str`` method cannot keep the order of measure as the qasm file,
516+
we provide this alternative function in case the order of measure instruction matters
517+
518+
:param qasm_str: open qasm str
519+
:type qasm_str: str
520+
:return: ``qiskit.circuit.QuantumCircuit``
521+
:rtype: Any
522+
"""
523+
measure_sequence = []
524+
qasm_instruction = []
525+
for line in qasm_str.split("\n"):
526+
if line.startswith("measure"):
527+
print(line)
528+
index = int(line.split(" ")[1][2:-1])
529+
cindex = int(line.split(" ")[3].strip(";")[2:-1])
530+
531+
measure_sequence.append((index, cindex))
532+
else:
533+
qasm_instruction.append(line)
534+
535+
qc = QuantumCircuit.from_qasm_str("\n".join(qasm_instruction))
536+
for qid, cid in measure_sequence:
537+
qc.measure(qid, cid)
538+
return qc

tests/test_circuit.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1256,3 +1256,17 @@ def test_to_openqasm():
12561256
c.to_openqasm(filename="test.qasm")
12571257
c2 = tc.Circuit.from_openqasm_file("test.qasm")
12581258
np.testing.assert_allclose(c.state(), c2.state())
1259+
1260+
1261+
def test_from_qasm_keep_measure_order():
1262+
qasm_str = """OPENQASM 2.0;
1263+
include "qelib1.inc";
1264+
qreg q[2];
1265+
creg c[2];
1266+
h q[0];
1267+
measure q[1] -> c[1];
1268+
measure q[0] -> c[0];"""
1269+
c = tc.Circuit.from_openqasm(qasm_str)
1270+
c.to_openqasm().split("\n")[-2][-3] == "1"
1271+
c = tc.Circuit.from_openqasm(qasm_str, keep_measure_order=True)
1272+
c.to_openqasm().split("\n")[-2][-3] == "0"

0 commit comments

Comments
 (0)