Skip to content

Qubit to stim

SquinQubitToStim

Bases: RewriteRule

NOTE this require address analysis result to be wrapped before using this rule.

rewrite_Apply_and_Broadcast

rewrite_Apply_and_Broadcast(
    stmt: Apply | Broadcast,
) -> RewriteResult

Rewrite Apply and Broadcast nodes to their stim equivalent statements.

Source code in .venv/lib/python3.12/site-packages/bloqade/stim/rewrite/qubit_to_stim.py
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
def rewrite_Apply_and_Broadcast(
    self, stmt: qubit.Apply | qubit.Broadcast
) -> RewriteResult:
    """
    Rewrite Apply and Broadcast nodes to their stim equivalent statements.
    """

    # this is an SSAValue, need it to be the actual operator
    applied_op = stmt.operator.owner

    if isinstance(applied_op, noise.stmts.QubitLoss):
        return rewrite_QubitLoss(stmt)

    assert isinstance(applied_op, op.stmts.Operator)

    if isinstance(applied_op, op.stmts.Control):
        return rewrite_Control(stmt)

    # need to handle Control through separate means

    # check if its adjoint, assume its canonicalized so no nested adjoints.
    is_conj = False
    if isinstance(applied_op, op.stmts.Adjoint):
        if not applied_op.is_unitary:
            return RewriteResult()

        is_conj = True
        applied_op = applied_op.op.owner

    stim_1q_op = SQUIN_STIM_OP_MAPPING.get(type(applied_op))
    if stim_1q_op is None:
        return RewriteResult()

    address_attr = stmt.qubits[0].hints.get("address")

    if address_attr is None:
        return RewriteResult()

    assert isinstance(address_attr, AddressAttribute)
    qubit_idx_ssas = insert_qubit_idx_from_address(
        address=address_attr, stmt_to_insert_before=stmt
    )

    if qubit_idx_ssas is None:
        return RewriteResult()

    if isinstance(stim_1q_op, gate.stmts.Gate):
        stim_1q_stmt = stim_1q_op(targets=tuple(qubit_idx_ssas), dagger=is_conj)
    else:
        stim_1q_stmt = stim_1q_op(targets=tuple(qubit_idx_ssas))
    stmt.replace_by(stim_1q_stmt)

    return RewriteResult(has_done_something=True)