CQCL / pytket-qiskit

pytket-qiskit, extensions for pytket quantum SDK
Apache License 2.0
17 stars 13 forks source link

Running circuit with classical condition can cause `KeyError` #375

Open IlanIwumbwe opened 3 months ago

IlanIwumbwe commented 3 months ago

Benny and I found this by running a randomly generated circuit through the compiler.

When preparing classical registers to pass to append_tk_command_to_qiskit, there's a check here that excludes scratch registers that are used to store results of reg_eq(creg_0, 3).

However, under certain conditions, this leads to a KeyError because regname is tk_SCRATCH_BIT.

Recreate with:

main_circ = Circuit(2, 2, "main_circ")

creg_0 = main_circ.add_c_register("creg_0",2)
# Applying gates 

main_circ.add_gate(OpType.CH,[0, 1], condition = reg_eq(creg_0, 3))

main_circ.measure_all()

backend = AerBackend()
no_pass_circ = backend.get_compiled_circuit(main_circ, optimisation_level=0)
counts = backend.run_circuit(no_pass_circ).get_counts()

Results in:

KeyError: 'tk_SCRATCH_BIT'

Running the circuit above or with OpType.CH replaced by OpType.CV results in the same error.

IlanIwumbwe commented 3 months ago

Another code snippet that leads to the same error:

U3_op = Op.create(OpType.U3, [-0.09, -0.39, -0.17])
Ry_op = Op.create(OpType.Ry, [0.1])
op_map = {(0,):U3_op, (1,):Ry_op}
multiplexor = MultiplexorBox(op_map)

main_circ = Circuit(0, 2, "main_circ")

qreg_0 = main_circ.add_q_register("qreg_0",3)
creg_3 = main_circ.add_c_register("creg_3",1)

main_circ.add_gate(multiplexor,[qreg_0[1], qreg_0[2]], condition = reg_eq(creg_3, 3))

backend = AerBackend()
no_pass_circ = backend.get_compiled_circuit(main_circ, optimisation_level=2)
counts = backend.run_circuit(no_pass_circ).get_counts()
CalMacCQ commented 1 month ago

I think this is a question of giving an appropriate error message when the circuit contains classical ops which are not supported by the AerBackend.

It may also be possible to run the circuits if we can convert the reg_eq check to an equivalent qiskit operation