bloqade-circuit 0.4.4__py3-none-any.whl → 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of bloqade-circuit might be problematic. Click here for more details.

Files changed (42) hide show
  1. bloqade/cirq_utils/__init__.py +7 -0
  2. bloqade/cirq_utils/lineprog.py +295 -0
  3. bloqade/cirq_utils/parallelize.py +400 -0
  4. bloqade/pyqrack/squin/op.py +7 -2
  5. bloqade/pyqrack/squin/runtime.py +4 -2
  6. bloqade/qasm2/dialects/expr/stmts.py +2 -20
  7. bloqade/qasm2/parse/lowering.py +1 -0
  8. bloqade/qasm2/passes/parallel.py +18 -0
  9. bloqade/qasm2/rewrite/__init__.py +1 -0
  10. bloqade/qasm2/rewrite/parallel_to_glob.py +82 -0
  11. bloqade/squin/__init__.py +1 -0
  12. bloqade/squin/_typeinfer.py +20 -0
  13. bloqade/squin/analysis/nsites/impls.py +6 -1
  14. bloqade/squin/cirq/__init__.py +74 -9
  15. bloqade/squin/cirq/emit/noise.py +49 -0
  16. bloqade/squin/cirq/emit/runtime.py +9 -1
  17. bloqade/squin/cirq/lowering.py +46 -27
  18. bloqade/squin/noise/_wrapper.py +9 -2
  19. bloqade/squin/noise/rewrite.py +3 -3
  20. bloqade/squin/op/__init__.py +1 -0
  21. bloqade/squin/op/_wrapper.py +4 -0
  22. bloqade/squin/op/stmts.py +20 -2
  23. bloqade/squin/qubit.py +8 -5
  24. bloqade/squin/rewrite/__init__.py +1 -0
  25. bloqade/squin/rewrite/canonicalize.py +60 -0
  26. bloqade/squin/rewrite/desugar.py +52 -5
  27. bloqade/squin/types.py +8 -0
  28. bloqade/squin/wire.py +91 -5
  29. bloqade/stim/__init__.py +1 -0
  30. bloqade/stim/_wrappers.py +4 -0
  31. bloqade/stim/dialects/noise/emit.py +1 -0
  32. bloqade/stim/dialects/noise/stmts.py +5 -0
  33. bloqade/stim/passes/squin_to_stim.py +16 -1
  34. bloqade/stim/rewrite/__init__.py +1 -0
  35. bloqade/stim/rewrite/qubit_to_stim.py +10 -6
  36. bloqade/stim/rewrite/squin_noise.py +120 -0
  37. bloqade/stim/rewrite/util.py +44 -9
  38. bloqade/stim/rewrite/wire_to_stim.py +8 -3
  39. {bloqade_circuit-0.4.4.dist-info → bloqade_circuit-0.5.0.dist-info}/METADATA +4 -2
  40. {bloqade_circuit-0.4.4.dist-info → bloqade_circuit-0.5.0.dist-info}/RECORD +42 -33
  41. {bloqade_circuit-0.4.4.dist-info → bloqade_circuit-0.5.0.dist-info}/WHEEL +0 -0
  42. {bloqade_circuit-0.4.4.dist-info → bloqade_circuit-0.5.0.dist-info}/licenses/LICENSE +0 -0
bloqade/squin/op/stmts.py CHANGED
@@ -98,6 +98,15 @@ class ConstantUnitary(ConstantOp):
98
98
 
99
99
  @statement(dialect=dialect)
100
100
  class U3(PrimitiveOp):
101
+ """
102
+ The rotation operator U3(theta, phi, lam).
103
+ Note that we use the convention from the QASM2 specification, namely
104
+
105
+ $$
106
+ U_3(\theta, \phi, \lambda) = R_z(\phi) R_y(\theta) R_z(\lambda)
107
+ $$
108
+ """
109
+
101
110
  traits = frozenset({ir.Pure(), lowering.FromPythonCall(), Unitary(), FixedSites(1)})
102
111
  theta: ir.SSAValue = info.argument(types.Float)
103
112
  phi: ir.SSAValue = info.argument(types.Float)
@@ -110,7 +119,7 @@ class PhaseOp(PrimitiveOp):
110
119
  A phase operator.
111
120
 
112
121
  $$
113
- PhaseOp(theta) = e^{i \theta} I
122
+ PhaseOp(\theta) = e^{i \theta} I
114
123
  $$
115
124
  """
116
125
 
@@ -124,7 +133,7 @@ class ShiftOp(PrimitiveOp):
124
133
  A phase shift operator.
125
134
 
126
135
  $$
127
- Shift(theta) = \\begin{bmatrix} 1 & 0 \\\\ 0 & e^{i \\theta} \\end{bmatrix}
136
+ Shift(\theta) = \\begin{bmatrix} 1 & 0 \\\\ 0 & e^{i \\theta} \\end{bmatrix}
128
137
  $$
129
138
  """
130
139
 
@@ -141,6 +150,15 @@ class Reset(PrimitiveOp):
141
150
  traits = frozenset({ir.Pure(), lowering.FromPythonCall(), FixedSites(1)})
142
151
 
143
152
 
153
+ @statement(dialect=dialect)
154
+ class ResetToOne(PrimitiveOp):
155
+ """
156
+ Reset qubits to the one state. Mainly needed to accommodate cirq's GeneralizedAmplitudeDampingChannel
157
+ """
158
+
159
+ traits = frozenset({ir.Pure(), lowering.FromPythonCall(), FixedSites(1)})
160
+
161
+
144
162
  @statement
145
163
  class CliffordOp(ConstantUnitary):
146
164
  pass
bloqade/squin/qubit.py CHANGED
@@ -17,6 +17,7 @@ from kirin.lowering import wraps
17
17
  from bloqade.types import Qubit, QubitType
18
18
  from bloqade.squin.op.types import Op, OpType
19
19
 
20
+ from .types import MeasurementResult, MeasurementResultType
20
21
  from .lowering import ApplyAnyCallLowering
21
22
 
22
23
  dialect = ir.Dialect("squin.qubit")
@@ -65,8 +66,8 @@ class MeasureQubit(ir.Statement):
65
66
  name = "measure.qubit"
66
67
 
67
68
  traits = frozenset({lowering.FromPythonCall()})
68
- qubit: ir.SSAValue = info.argument(ilist.IListType[QubitType])
69
- result: ir.ResultValue = info.result(ilist.IListType[types.Bool])
69
+ qubit: ir.SSAValue = info.argument(QubitType)
70
+ result: ir.ResultValue = info.result(MeasurementResultType)
70
71
 
71
72
 
72
73
  @statement(dialect=dialect)
@@ -75,7 +76,7 @@ class MeasureQubitList(ir.Statement):
75
76
 
76
77
  traits = frozenset({lowering.FromPythonCall()})
77
78
  qubits: ir.SSAValue = info.argument(ilist.IListType[QubitType])
78
- result: ir.ResultValue = info.result(ilist.IListType[types.Bool])
79
+ result: ir.ResultValue = info.result(ilist.IListType[MeasurementResultType])
79
80
 
80
81
 
81
82
  # NOTE: no dependent types in Python, so we have to mark it Any...
@@ -131,9 +132,11 @@ def apply(operator: Op, *qubits) -> None: ...
131
132
 
132
133
 
133
134
  @overload
134
- def measure(input: Qubit) -> bool: ...
135
+ def measure(input: Qubit) -> MeasurementResult: ...
135
136
  @overload
136
- def measure(input: ilist.IList[Qubit, Any] | list[Qubit]) -> ilist.IList[bool, Any]: ...
137
+ def measure(
138
+ input: ilist.IList[Qubit, Any] | list[Qubit],
139
+ ) -> ilist.IList[MeasurementResult, Any]: ...
137
140
 
138
141
 
139
142
  @wraps(MeasureAny)
@@ -4,4 +4,5 @@ from .wrap_analysis import (
4
4
  WrapOpSiteAnalysis as WrapOpSiteAnalysis,
5
5
  WrapAddressAnalysis as WrapAddressAnalysis,
6
6
  )
7
+ from .U3_to_clifford import SquinU3ToClifford as SquinU3ToClifford
7
8
  from .remove_dangling_qubits import RemoveDeadRegister as RemoveDeadRegister
@@ -0,0 +1,60 @@
1
+ from typing import cast
2
+
3
+ from kirin import ir
4
+ from kirin.rewrite import abc
5
+ from kirin.dialects import cf
6
+
7
+ from .. import wire
8
+
9
+
10
+ class CanonicalizeWired(abc.RewriteRule):
11
+ def rewrite_Statement(self, node: ir.Statement) -> abc.RewriteResult:
12
+
13
+ if (
14
+ not isinstance(node, wire.Wired)
15
+ or len(node.qubits) != 0
16
+ or (parent_region := node.parent_region) is None
17
+ ):
18
+ return abc.RewriteResult()
19
+
20
+ parent_block = cast(ir.Block, node.parent_block)
21
+
22
+ # the body doesn't contain any quantum operations so we can safely inline the
23
+ # body into the parent block
24
+
25
+ # move all statements after `node` in the current block into another block
26
+ after_block = ir.Block()
27
+
28
+ stmt = node.next_stmt
29
+ while stmt is not None:
30
+ stmt.detach()
31
+ after_block.stmts.append(stmt)
32
+ stmt = node.next_stmt
33
+
34
+ # remap all results of the node to the arguments of the after_block
35
+ for result in node.results:
36
+ arg = after_block.args.append_from(result.type, result.name)
37
+ result.replace_by(arg)
38
+
39
+ parent_block_idx = parent_region._block_idx[parent_block]
40
+ # insert goto of parent block to the body block of the node.
41
+ parent_region.blocks.insert(parent_block_idx + 1, after_block)
42
+ # insert all blocks of the body of the node after the parent region
43
+ # making sure to convert any yield statements to jump statements to the after_block
44
+ parent_block.stmts.append(
45
+ cf.Branch(
46
+ arguments=(),
47
+ successor=node.body.blocks[0],
48
+ )
49
+ )
50
+ for block in reversed(node.body.blocks):
51
+ block.detach()
52
+ if isinstance((yield_stmt := block.last_stmt), wire.Yield):
53
+ yield_stmt.replace_by(
54
+ cf.Branch(yield_stmt.values, successor=after_block)
55
+ )
56
+
57
+ parent_region.blocks.insert(parent_block_idx + 1, block)
58
+
59
+ node.delete()
60
+ return abc.RewriteResult(has_done_something=True)
@@ -1,5 +1,5 @@
1
1
  from kirin import ir, types
2
- from kirin.dialects import ilist
2
+ from kirin.dialects import py, ilist
3
3
  from kirin.rewrite.abc import RewriteRule, RewriteResult
4
4
 
5
5
  from bloqade.squin.qubit import (
@@ -53,12 +53,59 @@ class ApplyDesugarRule(RewriteRule):
53
53
  op = node.operator
54
54
  qubits = node.qubits
55
55
 
56
- if len(qubits) == 1 and qubits[0].type.is_subseteq(ilist.IListType):
57
- # NOTE: already calling with just a single argument that is already an ilist
56
+ if len(qubits) > 1 and all(q.type.is_subseteq(QubitType) for q in qubits):
57
+ (qubits_ilist_stmt := ilist.New(qubits)).insert_before(node)
58
+ qubits_ilist = qubits_ilist_stmt.result
59
+
60
+ elif len(qubits) == 1 and qubits[0].type.is_subseteq(QubitType):
61
+ (qubits_ilist_stmt := ilist.New(qubits)).insert_before(node)
62
+ qubits_ilist = qubits_ilist_stmt.result
63
+
64
+ elif len(qubits) == 1 and qubits[0].type.is_subseteq(
65
+ ilist.IListType[QubitType, types.Any]
66
+ ):
58
67
  qubits_ilist = qubits[0]
59
- else:
60
- (qubits_ilist_stmt := ilist.New(values=qubits)).insert_before(node)
68
+
69
+ elif len(qubits) == 1:
70
+ # TODO: remove this elif clause once we're at kirin v0.18
71
+ # NOTE: this is a temporary workaround for kirin#408
72
+ # currently type inference fails here in for loops since the loop var
73
+ # is an IList for some reason
74
+
75
+ if not isinstance(qubits[0], ir.ResultValue):
76
+ return RewriteResult()
77
+
78
+ is_ilist = isinstance(qbit_stmt := qubits[0].stmt, ilist.New)
79
+ if is_ilist:
80
+ if len(qbit_stmt.values) != 1:
81
+ return RewriteResult()
82
+
83
+ if not isinstance(
84
+ qbit_getindex_result := qbit_stmt.values[0], ir.ResultValue
85
+ ):
86
+ return RewriteResult()
87
+
88
+ qbit_getindex = qbit_getindex_result.stmt
89
+ else:
90
+ qbit_getindex = qubits[0].stmt
91
+
92
+ if not isinstance(qbit_getindex, py.indexing.GetItem):
93
+ return RewriteResult()
94
+
95
+ if not qbit_getindex.obj.type.is_subseteq(
96
+ ilist.IListType[QubitType, types.Any]
97
+ ):
98
+ return RewriteResult()
99
+
100
+ if is_ilist:
101
+ values = qbit_stmt.values
102
+ else:
103
+ values = [qubits[0]]
104
+
105
+ (qubits_ilist_stmt := ilist.New(values=values)).insert_before(node)
61
106
  qubits_ilist = qubits_ilist_stmt.result
107
+ else:
108
+ return RewriteResult()
62
109
 
63
110
  stmt = Apply(operator=op, qubits=qubits_ilist)
64
111
  node.replace_by(stmt)
bloqade/squin/types.py ADDED
@@ -0,0 +1,8 @@
1
+ from kirin import types
2
+
3
+
4
+ class MeasurementResult:
5
+ pass
6
+
7
+
8
+ MeasurementResultType = types.PyClass(MeasurementResult)
bloqade/squin/wire.py CHANGED
@@ -6,12 +6,15 @@ circuits. Thus we do not define wrapping functions for the statements in this
6
6
  dialect.
7
7
  """
8
8
 
9
- from kirin import ir, types, lowering
9
+ from kirin import ir, types, lowering, exception
10
10
  from kirin.decl import info, statement
11
+ from kirin.dialects import func
11
12
  from kirin.lowering import wraps
13
+ from kirin.ir.attrs.types import TypeAttribute
12
14
 
13
15
  from bloqade.types import Qubit, QubitType
14
16
 
17
+ from .types import MeasurementResultType
15
18
  from .op.types import Op, OpType
16
19
 
17
20
  # from kirin.lowering import wraps
@@ -49,11 +52,87 @@ class Unwrap(ir.Statement):
49
52
  result: ir.ResultValue = info.result(WireType)
50
53
 
51
54
 
55
+ @statement(dialect=dialect)
56
+ class Wired(ir.Statement):
57
+ traits = frozenset()
58
+
59
+ qubits: tuple[ir.SSAValue, ...] = info.argument(QubitType)
60
+ memory_zone: str = info.attribute()
61
+ body: ir.Region = info.region(multi=True)
62
+
63
+ def __init__(
64
+ self,
65
+ body: ir.Region,
66
+ *qubits: ir.SSAValue,
67
+ memory_zone: str,
68
+ result_types: tuple[TypeAttribute, ...] | None = None,
69
+ ):
70
+ if result_types is None:
71
+ for block in body.blocks:
72
+ if isinstance(block.last_stmt, Yield):
73
+ result_types = tuple(arg.type for arg in block.last_stmt.values)
74
+ break
75
+
76
+ if result_types is None:
77
+ result_types = ()
78
+
79
+ super().__init__(
80
+ args=qubits,
81
+ args_slice={
82
+ "qubits": slice(0, None),
83
+ },
84
+ regions=[body],
85
+ attributes={
86
+ "memory_zone": ir.PyAttr(memory_zone)
87
+ }, # body of the wired statement
88
+ result_types=result_types,
89
+ )
90
+
91
+ def check(self):
92
+ entry_block = self.body.blocks[0]
93
+
94
+ if len(entry_block.args) != len(self.qubits):
95
+ raise exception.StaticCheckError(
96
+ f"Expected {len(self.qubits)} arguments, got {len(entry_block.args)}."
97
+ )
98
+ for arg in entry_block.args:
99
+ if not arg.type.is_subseteq(WireType):
100
+ raise exception.StaticCheckError(
101
+ f"Expected argument of type {WireType}, got {arg.type}."
102
+ )
103
+ for block in self.body.blocks:
104
+ last_stmt = block.last_stmt
105
+ if isinstance(last_stmt, func.Return):
106
+ raise exception.StaticCheckError(
107
+ "Return statements are not allowed in the body of a Wired statement."
108
+ )
109
+ elif isinstance(last_stmt, Yield) and len(last_stmt.values) != len(
110
+ self.results
111
+ ):
112
+ raise exception.StaticCheckError(
113
+ f"Expected {len(self.results)} return values, got {len(last_stmt.values)}."
114
+ )
115
+
116
+
117
+ @statement(dialect=dialect)
118
+ class Yield(ir.Statement):
119
+ traits = frozenset({})
120
+ values: tuple[ir.SSAValue, ...] = info.argument(WireType)
121
+
122
+ def __init__(self, *args: ir.SSAValue):
123
+ super().__init__(
124
+ args=args,
125
+ args_slice={
126
+ "values": slice(0, None),
127
+ },
128
+ )
129
+
130
+
52
131
  # In Quake, you put a wire in and get a wire out when you "apply" an operator
53
132
  # In this case though we just need to indicate that an operator is applied to list[wires]
54
133
  @statement(dialect=dialect)
55
134
  class Apply(ir.Statement): # apply(op, w1, w2, ...)
56
- traits = frozenset({lowering.FromPythonCall(), ir.Pure()})
135
+ traits = frozenset({lowering.FromPythonCall()})
57
136
  operator: ir.SSAValue = info.argument(OpType)
58
137
  inputs: tuple[ir.SSAValue, ...] = info.argument(WireType)
59
138
 
@@ -88,6 +167,13 @@ class Broadcast(ir.Statement):
88
167
  ) # custom lowering required for wrapper to work here
89
168
 
90
169
 
170
+ @statement(dialect=dialect)
171
+ class RegionMeasure(ir.Statement):
172
+ traits = frozenset({lowering.FromPythonCall(), WireTerminator()})
173
+ wire: ir.SSAValue = info.argument(WireType)
174
+ result: ir.ResultValue = info.result(MeasurementResultType)
175
+
176
+
91
177
  # NOTE: measurement cannot be pure because they will collapse the state
92
178
  # of the qubit. The state is a hidden state that is not visible to
93
179
  # the user in the wire dialect.
@@ -96,14 +182,14 @@ class Measure(ir.Statement):
96
182
  traits = frozenset({lowering.FromPythonCall(), WireTerminator()})
97
183
  wire: ir.SSAValue = info.argument(WireType)
98
184
  qubit: ir.SSAValue = info.argument(QubitType)
99
- result: ir.ResultValue = info.result(types.Int)
185
+ result: ir.ResultValue = info.result(MeasurementResultType)
100
186
 
101
187
 
102
188
  @statement(dialect=dialect)
103
- class NonDestructiveMeasure(ir.Statement):
189
+ class LossResolvingMeasure(ir.Statement):
104
190
  traits = frozenset({lowering.FromPythonCall()})
105
191
  input_wire: ir.SSAValue = info.argument(WireType)
106
- result: ir.ResultValue = info.result(types.Int)
192
+ result: ir.ResultValue = info.result(MeasurementResultType)
107
193
  out_wire: ir.ResultValue = info.result(WireType)
108
194
 
109
195
 
bloqade/stim/__init__.py CHANGED
@@ -31,6 +31,7 @@ from ._wrappers import (
31
31
  z_error as z_error,
32
32
  detector as detector,
33
33
  identity as identity,
34
+ qubit_loss as qubit_loss,
34
35
  depolarize1 as depolarize1,
35
36
  depolarize2 as depolarize2,
36
37
  pauli_string as pauli_string,
bloqade/stim/_wrappers.py CHANGED
@@ -190,3 +190,7 @@ def y_error(p: float, targets: tuple[int, ...]) -> None: ...
190
190
 
191
191
  @wraps(noise.ZError)
192
192
  def z_error(p: float, targets: tuple[int, ...]) -> None: ...
193
+
194
+
195
+ @wraps(noise.QubitLoss)
196
+ def qubit_loss(probs: tuple[float, ...], targets: tuple[int, ...]) -> None: ...
@@ -66,6 +66,7 @@ class EmitStimNoiseMethods(MethodTable):
66
66
  return ()
67
67
 
68
68
  @impl(stmts.TrivialError)
69
+ @impl(stmts.QubitLoss)
69
70
  def non_stim_error(
70
71
  self, emit: EmitStimMain, frame: EmitStrFrame, stmt: stmts.TrivialError
71
72
  ):
@@ -104,3 +104,8 @@ class TrivialCorrelatedError(NonStimCorrelatedError):
104
104
  @statement(dialect=dialect)
105
105
  class TrivialError(NonStimError):
106
106
  name = "TRIV_ERROR"
107
+
108
+
109
+ @statement(dialect=dialect)
110
+ class QubitLoss(NonStimError):
111
+ name = "loss"
@@ -8,6 +8,7 @@ from kirin.rewrite import (
8
8
  DeadCodeElimination,
9
9
  CommonSubexpressionElimination,
10
10
  )
11
+ from kirin.analysis import const
11
12
  from kirin.ir.method import Method
12
13
  from kirin.passes.abc import Pass
13
14
  from kirin.rewrite.abc import RewriteResult
@@ -16,11 +17,12 @@ from bloqade.stim.groups import main as stim_main_group
16
17
  from bloqade.stim.rewrite import (
17
18
  SquinWireToStim,
18
19
  PyConstantToStim,
20
+ SquinNoiseToStim,
19
21
  SquinQubitToStim,
20
22
  SquinMeasureToStim,
21
23
  SquinWireIdentityElimination,
22
24
  )
23
- from bloqade.squin.rewrite import RemoveDeadRegister
25
+ from bloqade.squin.rewrite import SquinU3ToClifford, RemoveDeadRegister
24
26
 
25
27
 
26
28
  @dataclass
@@ -31,10 +33,23 @@ class SquinToStim(Pass):
31
33
  # propagate constants
32
34
  rewrite_result = fold_pass(mt)
33
35
 
36
+ cp_frame, _ = const.Propagate(dialects=mt.dialects).run_analysis(mt)
37
+ cp_results = cp_frame.entries
38
+
34
39
  # Assume that address analysis and
35
40
  # wrapping has been done before this pass!
36
41
 
42
+ # Rewrite the noise statements first.
43
+ rewrite_result = (
44
+ Walk(SquinNoiseToStim(cp_results=cp_results))
45
+ .rewrite(mt.code)
46
+ .join(rewrite_result)
47
+ )
48
+
37
49
  # Wrap Rewrite + SquinToStim can happen w/ standard walk
50
+
51
+ rewrite_result = Walk(SquinU3ToClifford()).rewrite(mt.code).join(rewrite_result)
52
+
38
53
  rewrite_result = (
39
54
  Walk(
40
55
  Chain(
@@ -1,3 +1,4 @@
1
+ from .squin_noise import SquinNoiseToStim as SquinNoiseToStim
1
2
  from .wire_to_stim import SquinWireToStim as SquinWireToStim
2
3
  from .qubit_to_stim import SquinQubitToStim as SquinQubitToStim
3
4
  from .squin_measure import SquinMeasureToStim as SquinMeasureToStim
@@ -1,12 +1,13 @@
1
1
  from kirin import ir
2
2
  from kirin.rewrite.abc import RewriteRule, RewriteResult
3
3
 
4
- from bloqade.squin import op, qubit
4
+ from bloqade.squin import op, noise, qubit
5
5
  from bloqade.squin.rewrite import AddressAttribute
6
6
  from bloqade.stim.dialects import gate
7
7
  from bloqade.stim.rewrite.util import (
8
- SQUIN_STIM_GATE_MAPPING,
8
+ SQUIN_STIM_OP_MAPPING,
9
9
  rewrite_Control,
10
+ rewrite_QubitLoss,
10
11
  insert_qubit_idx_from_address,
11
12
  )
12
13
 
@@ -30,11 +31,17 @@ class SquinQubitToStim(RewriteRule):
30
31
 
31
32
  # this is an SSAValue, need it to be the actual operator
32
33
  applied_op = stmt.operator.owner
34
+
35
+ if isinstance(applied_op, noise.stmts.QubitLoss):
36
+ return rewrite_QubitLoss(stmt)
37
+
33
38
  assert isinstance(applied_op, op.stmts.Operator)
34
39
 
35
40
  if isinstance(applied_op, op.stmts.Control):
36
41
  return rewrite_Control(stmt)
37
42
 
43
+ # need to handle Control through separate means
44
+
38
45
  # check if its adjoint, assume its canonicalized so no nested adjoints.
39
46
  is_conj = False
40
47
  if isinstance(applied_op, op.stmts.Adjoint):
@@ -44,9 +51,7 @@ class SquinQubitToStim(RewriteRule):
44
51
  is_conj = True
45
52
  applied_op = applied_op.op.owner
46
53
 
47
- # need to handle Control through separate means
48
- # but we can handle X, Y, Z, H, and S here just fine
49
- stim_1q_op = SQUIN_STIM_GATE_MAPPING.get(type(applied_op))
54
+ stim_1q_op = SQUIN_STIM_OP_MAPPING.get(type(applied_op))
50
55
  if stim_1q_op is None:
51
56
  return RewriteResult()
52
57
 
@@ -55,7 +60,6 @@ class SquinQubitToStim(RewriteRule):
55
60
  if address_attr is None:
56
61
  return RewriteResult()
57
62
 
58
- # sometimes you can get a whole AddressReg...
59
63
  assert isinstance(address_attr, AddressAttribute)
60
64
  qubit_idx_ssas = insert_qubit_idx_from_address(
61
65
  address=address_attr, stmt_to_insert_before=stmt
@@ -0,0 +1,120 @@
1
+ from typing import Dict, Tuple
2
+ from dataclasses import dataclass
3
+
4
+ from kirin.ir import SSAValue, Statement
5
+ from kirin.analysis import const
6
+ from kirin.dialects import py
7
+ from kirin.rewrite.abc import RewriteRule, RewriteResult
8
+
9
+ from bloqade.squin import wire, noise as squin_noise, qubit
10
+ from bloqade.stim.dialects import noise as stim_noise
11
+ from bloqade.stim.rewrite.util import (
12
+ create_wire_passthrough,
13
+ insert_qubit_idx_after_apply,
14
+ )
15
+
16
+
17
+ @dataclass
18
+ class SquinNoiseToStim(RewriteRule):
19
+
20
+ cp_results: Dict[SSAValue, const.Result]
21
+
22
+ def rewrite_Statement(self, node: Statement) -> RewriteResult:
23
+ match node:
24
+ case qubit.Apply() | qubit.Broadcast():
25
+ return self.rewrite_Apply_and_Broadcast(node)
26
+ case _:
27
+ return RewriteResult()
28
+
29
+ def rewrite_Apply_and_Broadcast(
30
+ self, stmt: qubit.Apply | qubit.Broadcast
31
+ ) -> RewriteResult:
32
+ """Rewrite Apply and Broadcast to their stim statements."""
33
+
34
+ # this is an SSAValue, need it to be the actual operator
35
+ applied_op = stmt.operator.owner
36
+
37
+ if isinstance(applied_op, squin_noise.stmts.NoiseChannel):
38
+
39
+ qubit_idx_ssas = insert_qubit_idx_after_apply(stmt=stmt)
40
+ if qubit_idx_ssas is None:
41
+ return RewriteResult()
42
+
43
+ stim_stmt = None
44
+ if isinstance(applied_op, squin_noise.stmts.SingleQubitPauliChannel):
45
+ stim_stmt = self.rewrite_SingleQubitPauliChannel(stmt, qubit_idx_ssas)
46
+ elif isinstance(applied_op, squin_noise.stmts.TwoQubitPauliChannel):
47
+ stim_stmt = self.rewrite_TwoQubitPauliChannel(stmt, qubit_idx_ssas)
48
+
49
+ if isinstance(stmt, (wire.Apply, wire.Broadcast)):
50
+ create_wire_passthrough(stmt)
51
+
52
+ if stim_stmt is not None:
53
+ stmt.replace_by(stim_stmt)
54
+ if len(stmt.operator.owner.result.uses) == 0:
55
+ stmt.operator.owner.delete()
56
+
57
+ return RewriteResult(has_done_something=True)
58
+ return RewriteResult()
59
+
60
+ def rewrite_SingleQubitPauliChannel(
61
+ self,
62
+ stmt: qubit.Apply | qubit.Broadcast | wire.Broadcast | wire.Apply,
63
+ qubit_idx_ssas: Tuple[SSAValue],
64
+ ) -> Statement:
65
+ """Rewrite squin.noise.SingleQubitPauliChannel to stim.PauliChannel1."""
66
+
67
+ squin_channel = stmt.operator.owner
68
+ assert isinstance(squin_channel, squin_noise.stmts.SingleQubitPauliChannel)
69
+
70
+ params = self.cp_results.get(squin_channel.params).data
71
+ new_stmts = [
72
+ p_x := py.Constant(params[0]),
73
+ p_y := py.Constant(params[1]),
74
+ p_z := py.Constant(params[2]),
75
+ ]
76
+ for new_stmt in new_stmts:
77
+ new_stmt.insert_before(stmt)
78
+
79
+ stim_stmt = stim_noise.PauliChannel1(
80
+ targets=qubit_idx_ssas,
81
+ px=p_x.result,
82
+ py=p_y.result,
83
+ pz=p_z.result,
84
+ )
85
+ return stim_stmt
86
+
87
+ def rewrite_TwoQubitPauliChannel(
88
+ self,
89
+ stmt: qubit.Apply | qubit.Broadcast | wire.Broadcast | wire.Apply,
90
+ qubit_idx_ssas: Tuple[SSAValue],
91
+ ) -> Statement:
92
+ """Rewrite squin.noise.SingleQubitPauliChannel to stim.PauliChannel1."""
93
+
94
+ squin_channel = stmt.operator.owner
95
+ assert isinstance(squin_channel, squin_noise.stmts.TwoQubitPauliChannel)
96
+
97
+ params = self.cp_results.get(squin_channel.params).data
98
+ param_stmts = [py.Constant(p) for p in params]
99
+ for param_stmt in param_stmts:
100
+ param_stmt.insert_before(stmt)
101
+
102
+ stim_stmt = stim_noise.PauliChannel2(
103
+ targets=qubit_idx_ssas,
104
+ pix=param_stmts[0].result,
105
+ piy=param_stmts[1].result,
106
+ piz=param_stmts[2].result,
107
+ pxi=param_stmts[3].result,
108
+ pxx=param_stmts[4].result,
109
+ pxy=param_stmts[5].result,
110
+ pxz=param_stmts[6].result,
111
+ pyi=param_stmts[7].result,
112
+ pyx=param_stmts[8].result,
113
+ pyy=param_stmts[9].result,
114
+ pyz=param_stmts[10].result,
115
+ pzi=param_stmts[11].result,
116
+ pzx=param_stmts[12].result,
117
+ pzy=param_stmts[13].result,
118
+ pzz=param_stmts[14].result,
119
+ )
120
+ return stim_stmt