Skip to content

Lowering

Squin dataclass

Squin(circuit: Circuit)

Bases: LoweringABC[Circuit]


              flowchart TD
              bloqade.cirq_utils.lowering.Squin[Squin]

              

              click bloqade.cirq_utils.lowering.Squin href "" "bloqade.cirq_utils.lowering.Squin"
            

Lower a cirq.Circuit object to a squin kernel

__post_init__

__post_init__()

Map Cirq qubits to allocation-order register indices.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
212
213
214
215
216
def __post_init__(self):
    """Map Cirq qubits to allocation-order register indices."""
    # TODO: sort by cirq ordering
    qbits = sorted(self.circuit.all_qubits())
    self.qreg_index = {qid: idx for (idx, qid) in enumerate(qbits)}

allocate_register

allocate_register(state: State[Circuit]) -> ir.SSAValue

Allocate circuit qubits in the lowerer's selected order.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
233
234
235
236
def allocate_register(self, state: lowering.State[cirq.Circuit]) -> ir.SSAValue:
    """Allocate circuit qubits in the lowerer's selected order."""
    n = state.current_frame.push(py.Constant(len(self.qreg_index)))
    return state.current_frame.push(func.Invoke((n.result,), callee=qalloc)).result

generic_visit

generic_visit(state: State[Circuit], node: CirqNode)

Reject Cirq nodes without a supported lowering method.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
288
289
290
291
292
293
294
def generic_visit(self, state: lowering.State[cirq.Circuit], node: CirqNode):
    """Reject Cirq nodes without a supported lowering method."""
    if isinstance(node, CirqNode):
        raise lowering.BuildError(
            f"Cannot lower {node.__class__.__name__} node: {node}"
        )
    raise lowering.BuildError(f"Cannot lower {node}")

lower_global

lower_global(
    state: State[Circuit], node: CirqNode
) -> lowering.LoweringABC.Result

Reject global values in Cirq circuits.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
300
301
302
303
304
def lower_global(
    self, state: lowering.State[cirq.Circuit], node: CirqNode
) -> lowering.LoweringABC.Result:
    """Reject global values in Cirq circuits."""
    raise lowering.BuildError("Literals not supported in cirq circuit")

lower_literal

lower_literal(state: State[Circuit], value) -> ir.SSAValue

Reject standalone literals in Cirq circuits.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
296
297
298
def lower_literal(self, state: lowering.State[cirq.Circuit], value) -> ir.SSAValue:
    """Reject standalone literals in Cirq circuits."""
    raise lowering.BuildError("Literals not supported in cirq circuit")

lower_qubit_getindex

lower_qubit_getindex(state: State[Circuit], qid: Qid)

Look up one Cirq qubit in the SQuIN register.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
218
219
220
221
222
223
def lower_qubit_getindex(self, state: lowering.State[cirq.Circuit], qid: cirq.Qid):
    """Look up one Cirq qubit in the SQuIN register."""
    index = self.qreg_index[qid]
    index_ssa = state.current_frame.push(py.Constant(index)).result
    qbit_getitem = state.current_frame.push(py.GetItem(self.qreg, index_ssa))
    return qbit_getitem.result

lower_qubit_getindices

lower_qubit_getindices(
    state: State[Circuit], qids: tuple[Qid, ...]
)

Collect register entries for a tuple of Cirq qubits.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
225
226
227
228
229
230
231
def lower_qubit_getindices(
    self, state: lowering.State[cirq.Circuit], qids: tuple[cirq.Qid, ...]
):
    """Collect register entries for a tuple of Cirq qubits."""
    qbits_getitem = [self.lower_qubit_getindex(state, qid) for qid in qids]
    qbits = state.current_frame.push(ilist.New(values=qbits_getitem))
    return qbits.result

run

run(
    stmt: Circuit,
    *,
    source: str | None = None,
    globals: dict[str, Any] | None = None,
    file: str | None = None,
    lineno_offset: int = 0,
    col_offset: int = 0,
    compactify: bool = True,
    register_as_argument: bool = False,
    register_argument_name: str = "q"
) -> ir.Region

Lower a Cirq circuit into a Kirin region.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
def run(
    self,
    stmt: cirq.Circuit,
    *,
    source: str | None = None,
    globals: dict[str, Any] | None = None,
    file: str | None = None,
    lineno_offset: int = 0,
    col_offset: int = 0,
    compactify: bool = True,
    register_as_argument: bool = False,
    register_argument_name: str = "q",
) -> ir.Region:
    """Lower a Cirq circuit into a Kirin region."""
    state = lowering.State(
        self,
        file=file,
        lineno_offset=lineno_offset,
        col_offset=col_offset,
    )

    with state.frame([stmt], globals=globals, finalize_next=False) as frame:

        # NOTE: need a register of qubits before lowering statements
        if register_as_argument:
            # NOTE: register as argument to the kernel; we have freedom of choice for the name here
            frame.curr_block.args.append_from(
                ilist.IListType[qubit.QubitType, types.Any],
                name=register_argument_name,
            )
            self.qreg = frame.curr_block.args[0]
        else:
            self.qreg = self.allocate_register(state)

        self.visit(state, stmt)

        if compactify:
            Walk(CFGCompactify()).rewrite(frame.curr_region)

        region = frame.curr_region

    return region

visit

visit(
    state: State[Circuit], node: CirqNode
) -> lowering.Result

Dispatch a Cirq node to its lowering method.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
281
282
283
284
285
286
def visit(
    self, state: lowering.State[cirq.Circuit], node: CirqNode
) -> lowering.Result:
    """Dispatch a Cirq node to its lowering method."""
    name = node.__class__.__name__
    return getattr(self, f"visit_{name}", self.generic_visit)(state, node)

visit_AsymmetricDepolarizingChannel

visit_AsymmetricDepolarizingChannel(
    state: State[Circuit],
    node: AsymmetricDepolarizingChannel,
)

Lower one- or two-qubit asymmetric Pauli noise.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
def visit_AsymmetricDepolarizingChannel(
    self,
    state: lowering.State[cirq.Circuit],
    node: cirq.AsymmetricDepolarizingChannel,
):
    """Lower one- or two-qubit asymmetric Pauli noise."""
    nqubits = node.gate.num_qubits()
    if nqubits > 2:
        raise lowering.BuildError(
            "AsymmetricDepolarizingChannel applied to more than 2 qubits is not supported!"
        )

    if nqubits == 1:
        qubits = self.lower_qubit_getindices(state, node.qubits)
        p_x = state.current_frame.push(py.Constant(node.gate.p_x)).result
        p_y = state.current_frame.push(py.Constant(node.gate.p_y)).result
        p_z = state.current_frame.push(py.Constant(node.gate.p_z)).result
        return state.current_frame.push(
            noise.stmts.SingleQubitPauliChannel(p_x, p_y, p_z, qubits)
        )

    # NOTE: nqubits == 2
    error_probs = node.gate.error_probabilities
    probability_values = []
    p0 = None
    for key in self.two_qubit_paulis:
        p = error_probs.get(key)

        if p is None:
            if p0 is None:
                p0 = state.current_frame.push(py.Constant(0)).result
            p_ssa = p0
        else:
            p_ssa = state.current_frame.push(py.Constant(p)).result
        probability_values.append(p_ssa)

    probabilities = state.current_frame.push(
        ilist.New(values=probability_values)
    ).result

    control, target = node.qubits
    control_qarg = self.lower_qubit_getindices(state, (control,))
    target_qarg = self.lower_qubit_getindices(state, (target,))

    return state.current_frame.push(
        noise.stmts.TwoQubitPauliChannel(
            probabilities, controls=control_qarg, targets=target_qarg
        )
    )

visit_BitFlipChannel

visit_BitFlipChannel(
    state: State[Circuit], node: BitFlipChannel
)

Lower bit-flip noise to a single-qubit Pauli channel.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
677
678
679
680
681
682
683
684
685
686
687
def visit_BitFlipChannel(
    self, state: lowering.State[cirq.Circuit], node: cirq.BitFlipChannel
):
    """Lower bit-flip noise to a single-qubit Pauli channel."""
    p = node.gate.p
    p_x = state.current_frame.push(py.Constant(p)).result
    p_y = p_z = state.current_frame.push(py.Constant(0)).result
    qubits = self.lower_qubit_getindices(state, node.qubits)
    return state.current_frame.push(
        noise.stmts.SingleQubitPauliChannel(px=p_x, py=p_y, pz=p_z, qubits=qubits)
    )

visit_CCZPowGate

visit_CCZPowGate(
    state: State[Circuit], node: GateOperation
)

Lower a cirq CCZ power gate with an odd integer exponent to a CCZ gate.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
def visit_CCZPowGate(
    self, state: lowering.State[cirq.Circuit], node: cirq.GateOperation
):
    """Lower a cirq CCZ power gate with an odd integer exponent to a CCZ gate."""
    if node.gate.exponent % 2 == 0:
        return

    if node.gate.exponent % 2 != 1:
        raise lowering.BuildError("Exponents of CCZ gate are not supported!")

    control1, control2, target = node.qubits
    control1_qarg = self.lower_qubit_getindices(state, (control1,))
    control2_qarg = self.lower_qubit_getindices(state, (control2,))
    target_qarg = self.lower_qubit_getindices(state, (target,))
    return state.current_frame.push(
        gate.stmts.CCZ(
            controls1=control1_qarg,
            controls2=control2_qarg,
            targets=target_qarg,
        )
    )

visit_CXPowGate

visit_CXPowGate(state: State[Circuit], node: GateOperation)

Lower an odd CX power, rejecting unsupported exponents.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
def visit_CXPowGate(
    self, state: lowering.State[cirq.Circuit], node: cirq.GateOperation
):
    """Lower an odd CX power, rejecting unsupported exponents."""
    if node.gate.exponent % 2 == 0:
        return

    if node.gate.exponent % 2 != 1:
        raise lowering.BuildError("Exponents of CX gate are not supported!")

    control, target = node.qubits
    control_qarg = self.lower_qubit_getindices(state, (control,))
    target_qarg = self.lower_qubit_getindices(state, (target,))
    return state.current_frame.push(
        gate.stmts.CX(controls=control_qarg, targets=target_qarg)
    )

visit_CZPowGate

visit_CZPowGate(state: State[Circuit], node: GateOperation)

Lower an odd CZ power, rejecting unsupported exponents.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
def visit_CZPowGate(
    self, state: lowering.State[cirq.Circuit], node: cirq.GateOperation
):
    """Lower an odd CZ power, rejecting unsupported exponents."""
    if node.gate.exponent % 2 == 0:
        return

    if node.gate.exponent % 2 != 1:
        raise lowering.BuildError("Exponents of CZ gate are not supported!")

    control, target = node.qubits
    control_qarg = self.lower_qubit_getindices(state, (control,))
    target_qarg = self.lower_qubit_getindices(state, (target,))
    return state.current_frame.push(
        gate.stmts.CZ(controls=control_qarg, targets=target_qarg)
    )

visit_Circuit

visit_Circuit(
    state: State[Circuit], node: Circuit | FrozenCircuit
) -> lowering.Result

Lower the moments of a circuit in order.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
306
307
308
309
310
311
312
313
def visit_Circuit(
    self,
    state: lowering.State[cirq.Circuit],
    node: cirq.Circuit | cirq.FrozenCircuit,
) -> lowering.Result:
    """Lower the moments of a circuit in order."""
    for moment in node:
        self.visit_Moment(state, moment)

visit_CircuitOperation

visit_CircuitOperation(
    state: State[Circuit], node: CircuitOperation
)

Lower a circuit operation with a supported repetition count.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
def visit_CircuitOperation(
    self, state: lowering.State[cirq.Circuit], node: cirq.CircuitOperation
):
    """Lower a circuit operation with a supported repetition count."""
    reps = node.repetitions

    if not isinstance(reps, int):
        raise lowering.BuildError(
            f"Cannot lower CircuitOperation with non-integer repetitions: {node}"
        )

    if reps > 1:
        raise lowering.BuildError(
            "Repetitions of circuit operatiosn not yet supported"
        )

    return self.visit(state, node.circuit)

visit_ClassicallyControlledOperation

visit_ClassicallyControlledOperation(
    state: State[Circuit],
    node: ClassicallyControlledOperation,
)

Lower a classically controlled operation to conditional IR.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
def visit_ClassicallyControlledOperation(
    self,
    state: lowering.State[cirq.Circuit],
    node: cirq.ClassicallyControlledOperation,
):
    """Lower a classically controlled operation to conditional IR."""
    conditions: list[ir.SSAValue] = []
    for outcome in node.classical_controls:
        key = outcome.key
        if isinstance(key, cirq.MeasurementKey):
            key = key.name
        measurement_outcome = state.current_frame.defs[key]

        if measurement_outcome.type.is_subseteq(ilist.IListType):
            # NOTE: there is currently no convenient ilist.any method, so we need to use foldl
            # with a simple function that just does an or

            def bool_op_or(x: bool, y: bool) -> bool:
                return x or y

            f_code = state.current_frame.push(
                lowering.Python(self.dialects).python_function(bool_op_or)
            )
            fn = ir.Method(
                mod=None,
                py_func=bool_op_or,
                sym_name="bool_op_or",
                arg_names=[],
                dialects=self.dialects,
                code=f_code,
            )
            f_const = state.current_frame.push(py.constant.Constant(fn))
            init_val = state.current_frame.push(py.Constant(False)).result
            condition = state.current_frame.push(
                ilist.Foldl(f_const.result, measurement_outcome, init=init_val)
            ).result
        else:
            condition = measurement_outcome

        conditions.append(condition)

    if len(conditions) == 1:
        condition = conditions[0]
    else:
        condition = state.current_frame.push(
            py.boolop.And(conditions[0], conditions[1])
        ).result
        for next_cond in conditions[2:]:
            condition = state.current_frame.push(
                py.boolop.And(condition, next_cond)
            ).result

    then_stmt = self.visit(state, node.without_classical_controls())

    assert isinstance(
        then_stmt, ir.Statement
    ), f"Expected operation of classically controlled node {node} to be lowered to a statement, got type {type(then_stmt)}. \
    Please report this issue!"

    # NOTE: remove stmt from parent block
    then_stmt.detach()
    then_body = ir.Block((then_stmt,))
    then_body.args.append_from(types.Bool, name="cond")
    then_body.stmts.append(scf.Yield())

    else_body = ir.Block(())
    else_body.args.append_from(types.Bool, name="cond")
    else_body.stmts.append(scf.Yield())

    return state.current_frame.push(
        scf.IfElse(condition, then_body=then_body, else_body=else_body)
    )

visit_ControlledOperation

visit_ControlledOperation(
    state: State[Circuit], node: ControlledOperation
)

Lower a supported controlled Pauli operation.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
def visit_ControlledOperation(
    self, state: lowering.State[cirq.Circuit], node: cirq.ControlledOperation
):
    """Lower a supported controlled Pauli operation."""
    match node.gate.sub_gate:
        case cirq.X:
            stmt = gate.stmts.CX
        case cirq.Y:
            stmt = gate.stmts.CY
        case cirq.Z:
            stmt = gate.stmts.CZ
        case _:
            raise lowering.BuildError(
                f"Cannot lowering controlled operation: {node}"
            )

    control, target = node.qubits
    control_qarg = self.lower_qubit_getindices(state, (control,))
    target_qarg = self.lower_qubit_getindices(state, (target,))
    return state.current_frame.push(stmt(control_qarg, target_qarg))

visit_DepolarizingChannel

visit_DepolarizingChannel(
    state: State[Circuit], node: DepolarizingChannel
)

Lower a depolarizing channel to SQuIN noise IR.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
689
690
691
692
693
694
695
def visit_DepolarizingChannel(
    self, state: lowering.State[cirq.Circuit], node: cirq.DepolarizingChannel
):
    """Lower a depolarizing channel to SQuIN noise IR."""
    p = state.current_frame.push(py.Constant(node.gate.p)).result
    qubits = self.lower_qubit_getindices(state, node.qubits)
    return state.current_frame.push(noise.stmts.Depolarize(p, qubits=qubits))

visit_FrozenCircuit

visit_FrozenCircuit(
    state: State[Circuit], node: FrozenCircuit
)

Lower a frozen circuit using the ordinary circuit visitor.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
653
654
655
656
657
def visit_FrozenCircuit(
    self, state: lowering.State[cirq.Circuit], node: cirq.FrozenCircuit
):
    """Lower a frozen circuit using the ordinary circuit visitor."""
    return self.visit_Circuit(state, node)

visit_GateOperation

visit_GateOperation(
    state: State[Circuit], node: GateOperation
)

Decompose selected gates or dispatch by gate type.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
322
323
324
325
326
327
328
329
330
331
332
333
334
335
def visit_GateOperation(
    self, state: lowering.State[cirq.Circuit], node: cirq.GateOperation
):
    """Decompose selected gates or dispatch by gate type."""
    if isinstance(node.gate, DecomposeNode):
        # NOTE: easier to decompose these, but for that we need the qubits too,
        # so we need to do this within this method
        for subnode in cirq.decompose_once(node):
            self.visit(state, subnode)
        return

    # NOTE: just forward to the appropriate method by getting the name
    name = node.gate.__class__.__name__
    return getattr(self, f"visit_{name}", self.generic_visit)(state, node)

visit_HPowGate

visit_HPowGate(state: State[Circuit], node: HPowGate)

Lower a Hadamard power, decomposing non-Hadamard exponents.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
454
455
456
457
458
459
460
461
462
463
def visit_HPowGate(self, state: lowering.State[cirq.Circuit], node: cirq.HPowGate):
    """Lower a Hadamard power, decomposing non-Hadamard exponents."""
    qargs = self.lower_qubit_getindices(state, node.qubits)

    if node.gate.exponent % 2 == 1:
        return state.current_frame.push(gate.stmts.H(qargs))

    # NOTE: decompose into products of paulis for arbitrary exponents according to _decompose_ method
    for subnode in cirq.decompose_once(node):
        self.visit(state, subnode)

visit_MeasurementGate

visit_MeasurementGate(
    state: State[Circuit], node: GateOperation
) -> ir.Statement

Lower a Cirq measurement and bind its result key.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
416
417
418
419
420
421
422
423
424
425
426
427
428
429
def visit_MeasurementGate(
    self, state: lowering.State[cirq.Circuit], node: cirq.GateOperation
) -> ir.Statement:
    """Lower a Cirq measurement and bind its result key."""
    qubits = self.lower_qubit_getindices(state, node.qubits)
    stmt = state.current_frame.push(qubit.stmts.Measure(qubits))

    # NOTE: add for classically controlled lowering
    key = node.gate.key
    if isinstance(key, cirq.MeasurementKey):
        key = key.name
    state.current_frame.defs[key] = stmt.result

    return stmt

visit_Moment

visit_Moment(
    state: State[Circuit], node: Moment
) -> lowering.Result

Lower each operation in a Cirq moment.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
315
316
317
318
319
320
def visit_Moment(
    self, state: lowering.State[cirq.Circuit], node: cirq.Moment
) -> lowering.Result:
    """Lower each operation in a Cirq moment."""
    for op_ in node.operations:
        self.visit(state, op_)

visit_PhasedXZGate

visit_PhasedXZGate(
    state: State[Circuit], node: GateOperation
)

Lower a phased-XZ gate with converted exponent units.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
525
526
527
528
529
530
531
532
533
534
535
536
537
def visit_PhasedXZGate(
    self, state: lowering.State[cirq.Circuit], node: cirq.GateOperation
):
    """Lower a phased-XZ gate with converted exponent units."""
    qargs = self.lower_qubit_getindices(state, node.qubits)
    x_exp = state.current_frame.push(py.Constant(node.gate.x_exponent / 2)).result
    z_exp = state.current_frame.push(py.Constant(node.gate.z_exponent / 2)).result
    axis_exp = state.current_frame.push(
        py.Constant(node.gate.axis_phase_exponent / 2)
    ).result
    return state.current_frame.push(
        gate.stmts.PhasedXZ(x_exp, z_exp, axis_exp, qargs)
    )

visit_ResetChannel

visit_ResetChannel(
    state: State[Circuit], node: ResetChannel
)

Lower a Cirq reset channel to a SQuIN reset.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
747
748
749
750
751
752
753
def visit_ResetChannel(
    self, state: lowering.State[cirq.Circuit], node: cirq.ResetChannel
):
    """Lower a Cirq reset channel to a SQuIN reset."""
    qubits = self.lower_qubit_getindices(state, node.qubits)
    stmt = qubit.stmts.Reset(qubits)
    return state.current_frame.push(stmt)

visit_Rx

visit_Rx(state: State[Circuit], node: GateOperation)

Lower a Cirq X rotation to a SQuIN X rotation.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
507
508
509
510
511
def visit_Rx(self, state: lowering.State[cirq.Circuit], node: cirq.GateOperation):
    """Lower a Cirq X rotation to a SQuIN X rotation."""
    qargs = self.lower_qubit_getindices(state, node.qubits)
    angle = state.current_frame.push(py.Constant(value=0.5 * node.gate.exponent))
    return state.current_frame.push(gate.stmts.Rx(angle.result, qargs))

visit_Ry

visit_Ry(state: State[Circuit], node: GateOperation)

Lower a Cirq Y rotation to a SQuIN Y rotation.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
513
514
515
516
517
def visit_Ry(self, state: lowering.State[cirq.Circuit], node: cirq.GateOperation):
    """Lower a Cirq Y rotation to a SQuIN Y rotation."""
    qargs = self.lower_qubit_getindices(state, node.qubits)
    angle = state.current_frame.push(py.Constant(value=0.5 * node.gate.exponent))
    return state.current_frame.push(gate.stmts.Ry(angle.result, qargs))

visit_Rz

visit_Rz(state: State[Circuit], node: GateOperation)

Lower a Cirq Z rotation to a SQuIN Z rotation.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
519
520
521
522
523
def visit_Rz(self, state: lowering.State[cirq.Circuit], node: cirq.GateOperation):
    """Lower a Cirq Z rotation to a SQuIN Z rotation."""
    qargs = self.lower_qubit_getindices(state, node.qubits)
    angle = state.current_frame.push(py.Constant(value=0.5 * node.gate.exponent))
    return state.current_frame.push(gate.stmts.Rz(angle.result, qargs))

visit_SingleQubitPauliStringGateOperation

visit_SingleQubitPauliStringGateOperation(
    state: State[Circuit],
    node: SingleQubitPauliStringGateOperation,
)

Lower a single-qubit Pauli-string operation.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
def visit_SingleQubitPauliStringGateOperation(
    self,
    state: lowering.State[cirq.Circuit],
    node: cirq.SingleQubitPauliStringGateOperation,
):
    """Lower a single-qubit Pauli-string operation."""
    if isinstance(node.pauli, cirq.IdentityGate):
        # TODO: do we need an identity gate in gate?
        return

    qargs = self.lower_qubit_getindices(state, (node.qubit,))
    match node.pauli:
        case cirq.X:
            gate_stmt = gate.stmts.X
        case cirq.Y:
            gate_stmt = gate.stmts.Y
        case cirq.Z:
            gate_stmt = gate.stmts.Z
        case _:
            raise lowering.BuildError(f"Unexpected Pauli operation {node.pauli}")

    return state.current_frame.push(gate_stmt(qargs))

visit_SwapPowGate

visit_SwapPowGate(
    state: State[Circuit], node: GateOperation
)

Lower an odd SWAP power, rejecting unsupported exponents.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
595
596
597
598
599
600
601
602
603
604
605
606
607
608
def visit_SwapPowGate(
    self, state: lowering.State[cirq.Circuit], node: cirq.GateOperation
):
    """Lower an odd SWAP power, rejecting unsupported exponents."""
    if node.gate.exponent % 2 == 0:
        return

    if node.gate.exponent % 2 != 1:
        raise lowering.BuildError("Exponents of SWAP gate are not supported!")

    qubit1, qubit2 = node.qubits
    qarg1 = self.lower_qubit_getindices(state, (qubit1,))
    qarg2 = self.lower_qubit_getindices(state, (qubit2,))
    return state.current_frame.push(gate.stmts.Swap(qubits1=qarg1, qubits2=qarg2))

visit_TaggedOperation

visit_TaggedOperation(
    state: State[Circuit], node: TaggedOperation
)

Lower a tagged operation without its tags.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
337
338
339
340
341
def visit_TaggedOperation(
    self, state: lowering.State[cirq.Circuit], node: cirq.TaggedOperation
):
    """Lower a tagged operation without its tags."""
    return self.visit(state, node.untagged)

visit_XPowGate

visit_XPowGate(state: State[Circuit], node: GateOperation)

Lower an X power as X or an X rotation.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
465
466
467
468
469
470
471
472
473
474
def visit_XPowGate(
    self, state: lowering.State[cirq.Circuit], node: cirq.GateOperation
):
    """Lower an X power as X or an X rotation."""
    qargs = self.lower_qubit_getindices(state, node.qubits)
    if node.gate.exponent % 2 == 1:
        return state.current_frame.push(gate.stmts.X(qargs))

    angle = state.current_frame.push(py.Constant(0.5 * node.gate.exponent))
    return state.current_frame.push(gate.stmts.Rx(angle.result, qargs))

visit_YPowGate

visit_YPowGate(state: State[Circuit], node: GateOperation)

Lower a Y power as Y or a Y rotation.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
476
477
478
479
480
481
482
483
484
485
def visit_YPowGate(
    self, state: lowering.State[cirq.Circuit], node: cirq.GateOperation
):
    """Lower a Y power as Y or a Y rotation."""
    qargs = self.lower_qubit_getindices(state, node.qubits)
    if node.gate.exponent % 2 == 1:
        return state.current_frame.push(gate.stmts.Y(qargs))

    angle = state.current_frame.push(py.Constant(0.5 * node.gate.exponent))
    return state.current_frame.push(gate.stmts.Ry(angle.result, qargs))

visit_ZPowGate

visit_ZPowGate(state: State[Circuit], node: GateOperation)

Lower a Z power as S, T, Z, or a Z rotation.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
def visit_ZPowGate(
    self, state: lowering.State[cirq.Circuit], node: cirq.GateOperation
):
    """Lower a Z power as S, T, Z, or a Z rotation."""
    qargs = self.lower_qubit_getindices(state, node.qubits)

    if abs(node.gate.exponent) == 0.5:
        adjoint = node.gate.exponent < 0
        return state.current_frame.push(gate.stmts.S(adjoint=adjoint, qubits=qargs))

    if abs(node.gate.exponent) == 0.25:
        adjoint = node.gate.exponent < 0
        return state.current_frame.push(gate.stmts.T(adjoint=adjoint, qubits=qargs))

    if node.gate.exponent % 2 == 1:
        return state.current_frame.push(gate.stmts.Z(qubits=qargs))

    angle = state.current_frame.push(py.Constant(0.5 * node.gate.exponent))
    return state.current_frame.push(gate.stmts.Rz(angle.result, qargs))

visit_ZZPowGate

visit_ZZPowGate(state: State[Circuit], node: GateOperation)

Lower a ZZ power directly or through a CX-Rz-CX sequence.

Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
def visit_ZZPowGate(
    self, state: lowering.State[cirq.Circuit], node: cirq.GateOperation
):
    """Lower a ZZ power directly or through a CX-Rz-CX sequence."""
    if node.gate.exponent % 2 == 0:
        return

    qubit1, qubit2 = node.qubits
    qarg1 = self.lower_qubit_getindices(state, (qubit1,))
    qarg2 = self.lower_qubit_getindices(state, (qubit2,))

    if node.gate.exponent % 2 == 1:
        state.current_frame.push(gate.stmts.Z(qarg1))
        state.current_frame.push(gate.stmts.Z(qarg2))
        return

    # NOTE: arbitrary exponent, write as CX * Rz * CX (up to global phase)
    state.current_frame.push(gate.stmts.CX(qarg1, qarg2))
    angle = state.current_frame.push(py.Constant(0.5 * node.gate.exponent))
    state.current_frame.push(gate.stmts.Rz(angle.result, qarg2))
    state.current_frame.push(gate.stmts.CX(qarg1, qarg2))

load_circuit

load_circuit(
    circuit: Circuit,
    kernel_name: str = "main",
    dialects: DialectGroup = kernel,
    register_as_argument: bool = False,
    return_register: bool = False,
    register_argument_name: str = "q",
    globals: dict[str, Any] | None = None,
    file: str | None = None,
    lineno_offset: int = 0,
    col_offset: int = 0,
    compactify: bool = True,
)

Convert a Cirq circuit into a kernel for the supplied dialect group.

A registered dialect-specific lowerer is selected when exactly one dialect in the group has one; otherwise the SQuIN lowerer is used.

Parameters:

Name Type Description Default
circuit Circuit

The circuit to load.

required

Other Parameters:

Name Type Description
kernel_name str

The name of the kernel to load. Defaults to "main".

dialects DialectGroup

Dialects and pass pipeline for the result. Defaults to squin.kernel.

register_as_argument bool

Determine whether the resulting kernel function should accept a single ilist.IList[Qubit, Any] argument that is a list of qubits used within the function. This allows you to compose kernel functions generated from circuits. Defaults to False.

return_register bool

Determine whether the resulting kernel functionr returns a single value of type ilist.IList[Qubit, Any] that is the list of qubits used in the kernel function. Useful when you want to compose multiple kernel functions generated from circuits. Defaults to False.

register_argument_name str

The name of the argument that represents the qubit register. Only used when register_as_argument=True. Defaults to "q".

globals dict[str, Any] | None

The global variables to use. Defaults to None.

file str | None

The file name for error reporting. Defaults to None.

lineno_offset int

The line number offset for error reporting. Defaults to 0.

col_offset int

The column number offset for error reporting. Defaults to 0.

compactify bool

Whether to compactify the output. Defaults to True.

Usage Examples:

# from cirq's "hello qubit" example
import cirq
from bloqade.cirq_utils import load_circuit

# Pick a qubit.
qubit = cirq.GridQubit(0, 0)

# Create a circuit.
circuit = cirq.Circuit(
    cirq.X(qubit)**0.5,  # Square root of NOT.
    cirq.measure(qubit, key='m')  # Measurement.
)

# load the circuit as squin
main = load_circuit(circuit)

# print the resulting IR
main.print()

You can also compose kernel functions generated from circuits by passing in and / or returning the respective quantum registers:

import cirq
from bloqade.cirq_utils import load_circuit
from bloqade import squin

q = cirq.LineQubit.range(2)
circuit = cirq.Circuit(cirq.H(q[0]), cirq.CX(*q))

get_entangled_qubits = load_circuit(
    circuit, return_register=True, kernel_name="get_entangled_qubits"
)
get_entangled_qubits.print()

entangle_qubits = load_circuit(
    circuit, register_as_argument=True, kernel_name="entangle_qubits"
)

@squin.kernel
def main():
    qreg = get_entangled_qubits()
    qreg2 = squin.qalloc(1)
    entangle_qubits([qreg[1], qreg2[0]])
    return squin.qubit.measure(qreg2)
Source code in .venv/lib/python3.12/site-packages/bloqade/cirq_utils/lowering.py
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
def load_circuit(
    circuit: cirq.Circuit,
    kernel_name: str = "main",
    dialects: ir.DialectGroup = kernel,
    register_as_argument: bool = False,
    return_register: bool = False,
    register_argument_name: str = "q",
    globals: dict[str, Any] | None = None,
    file: str | None = None,
    lineno_offset: int = 0,
    col_offset: int = 0,
    compactify: bool = True,
):
    """Convert a Cirq circuit into a kernel for the supplied dialect group.

    A registered dialect-specific lowerer is selected when exactly one dialect
    in the group has one; otherwise the SQuIN lowerer is used.

    Args:
        circuit (cirq.Circuit): The circuit to load.

    Keyword Args:
        kernel_name (str): The name of the kernel to load. Defaults to "main".
        dialects (ir.DialectGroup): Dialects and pass pipeline for the result.
            Defaults to `squin.kernel`.
        register_as_argument (bool): Determine whether the resulting kernel function should accept
            a single `ilist.IList[Qubit, Any]` argument that is a list of qubits used within the
            function. This allows you to compose kernel functions generated from circuits.
            Defaults to `False`.
        return_register (bool): Determine whether the resulting kernel functionr returns a
            single value of type `ilist.IList[Qubit, Any]` that is the list of qubits used
            in the kernel function. Useful when you want to compose multiple kernel functions
            generated from circuits. Defaults to `False`.
        register_argument_name (str): The name of the argument that represents the qubit register.
            Only used when `register_as_argument=True`. Defaults to "q".
        globals (dict[str, Any] | None): The global variables to use. Defaults to None.
        file (str | None): The file name for error reporting. Defaults to None.
        lineno_offset (int): The line number offset for error reporting. Defaults to 0.
        col_offset (int): The column number offset for error reporting. Defaults to 0.
        compactify (bool): Whether to compactify the output. Defaults to True.

    ## Usage Examples:

    ```python
    # from cirq's "hello qubit" example
    import cirq
    from bloqade.cirq_utils import load_circuit

    # Pick a qubit.
    qubit = cirq.GridQubit(0, 0)

    # Create a circuit.
    circuit = cirq.Circuit(
        cirq.X(qubit)**0.5,  # Square root of NOT.
        cirq.measure(qubit, key='m')  # Measurement.
    )

    # load the circuit as squin
    main = load_circuit(circuit)

    # print the resulting IR
    main.print()
    ```

    You can also compose kernel functions generated from circuits by passing in
    and / or returning the respective quantum registers:

    ```python
    import cirq
    from bloqade.cirq_utils import load_circuit
    from bloqade import squin

    q = cirq.LineQubit.range(2)
    circuit = cirq.Circuit(cirq.H(q[0]), cirq.CX(*q))

    get_entangled_qubits = load_circuit(
        circuit, return_register=True, kernel_name="get_entangled_qubits"
    )
    get_entangled_qubits.print()

    entangle_qubits = load_circuit(
        circuit, register_as_argument=True, kernel_name="entangle_qubits"
    )

    @squin.kernel
    def main():
        qreg = get_entangled_qubits()
        qreg2 = squin.qalloc(1)
        entangle_qubits([qreg[1], qreg2[0]])
        return squin.qubit.measure(qreg2)
    ```
    """

    lowerer_type = resolve_cirq_loader(dialects) or Squin
    target = lowerer_type(dialects, circuit)
    body = target.run(
        circuit,
        source=str(circuit),  # TODO: proper source string
        file=file,
        globals=globals,
        lineno_offset=lineno_offset,
        col_offset=col_offset,
        compactify=compactify,
        register_as_argument=register_as_argument,
        register_argument_name=register_argument_name,
    )

    if return_register:
        return_value = target.qreg
    else:
        return_value = func.ConstantNone()
        body.blocks[0].stmts.append(return_value)

    return_node = func.Return(value_or_stmt=return_value)
    body.blocks[0].stmts.append(return_node)

    self_arg_name = kernel_name + "_self"
    arg_names = [self_arg_name]
    if register_as_argument:
        args = (target.qreg.type,)
        arg_names.append(register_argument_name)
    else:
        args = ()

    # NOTE: add _self as argument; need to know signature before so do it after lowering
    signature = func.Signature(args, return_node.value.type)
    body.blocks[0].args.insert_from(
        0,
        types.Generic(ir.Method, types.Tuple.where(signature.inputs), signature.output),
        self_arg_name,
    )

    code = func.Function(
        sym_name=kernel_name,
        signature=signature,
        body=body,
    )

    mt = ir.Method(
        sym_name=kernel_name,
        arg_names=arg_names,
        dialects=dialects,
        code=code,
    )

    if (run_pass := dialects.run_pass) is None:
        raise ValueError("The supplied dialect group has no pass pipeline")
    run_pass(mt, typeinfer=True)

    return mt