from qiskit.circuit import *

qreg, creg = QuantumRegister(5, "q"), ClassicalRegister(2, "c")

body = QuantumCircuit(3, 1)
loop_parameter = Parameter("foo")
indexset = range(0, 10, 2)

body.rx(loop_parameter, [0, 1, 2])

circuit = QuantumCircuit(qreg, creg)
circuit.for_loop(indexset, loop_parameter, body, [1, 2, 3], [1])
print(circuit.draw())

from qiskit.qasm3 import dumps
print(dumps(circuit))

from qiskit.transpiler.passes import UnrollForLoops
circuit_unroll = UnrollForLoops()(circuit)

print(dumps(circuit_unroll))
circuit_unroll.draw()

print(dumps(UnrollForLoops(max_target_depth=4)(circuit)))

from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager

pass_manager = generate_preset_pass_manager(1)
pass_manager.run(circuit).draw()

pass_manager.pre_optimization.append(UnrollForLoops())
pass_manager.run(circuit).draw()

# skip when continue and break
import math
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, 1)

with qc.for_loop(range(5)) as i:
    qc.rx(i * math.pi/4, 0)
    qc.cx(0, 1)
    qc.measure(0, 0)
    qc.break_loop().c_if(0, True)
print(dumps(qc))

print(dumps(UnrollForLoops()(qc)))

