Skip to content

Logical mvp

append_measurements_and_annotations

append_measurements_and_annotations(
    mt: Method,
    m2dets: list[list[int]] | None,
    m2obs: list[list[int]] | None,
) -> None

Append terminal measurement, detector, and observable IR statements to a squin kernel.

The method is mutated in-place.

Parameters:

Name Type Description Default
mt Method

A squin ir.Method whose body returns None.

required
m2dets list[list[int]] | None

Binary matrix of shape (num_total_meas, num_detectors). Each column defines a detector by its non-zero row indices.

required
m2obs list[list[int]] | None

Binary matrix of shape (num_total_meas, num_observables). Each column defines an observable by its non-zero row indices.

required
Source code in .venv/lib/python3.12/site-packages/bloqade/lanes/logical_mvp.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
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
def append_measurements_and_annotations(
    mt: ir.Method,
    m2dets: list[list[int]] | None,
    m2obs: list[list[int]] | None,
) -> None:
    """Append terminal measurement, detector, and observable IR statements to a squin kernel.

    The method is mutated in-place.

    Args:
        mt: A squin ``ir.Method`` whose body returns ``None``.
        m2dets: Binary matrix of shape ``(num_total_meas, num_detectors)``.
            Each column defines a detector by its non-zero row indices.
        m2obs: Binary matrix of shape ``(num_total_meas, num_observables)``.
            Each column defines an observable by its non-zero row indices.
    """

    if m2dets is None and m2obs is None:
        raise ValueError("At least one of m2dets or m2obs must be provided")

    qubit_ssas = _find_qubit_ssas(mt)
    num_qubits = len(qubit_ssas)
    if num_qubits == 0:
        raise ValueError("No qubit allocations found in the kernel")

    m2 = m2dets if m2dets is not None else m2obs
    assert m2 is not None
    num_total_meas = len(m2)
    meas_per_qubit = num_total_meas // num_qubits
    assert (
        meas_per_qubit * num_qubits == num_total_meas
    ), "Incompatible shape of m2dets or m2obs"

    return_stmt = _find_return_stmt(mt)

    # insert TerminalLogicalMeasurement if not present
    terminal_measurement = next(
        (
            s
            for s in mt.callable_region.walk()
            if isinstance(s, TerminalLogicalMeasurement)
        ),
        None,
    )
    if terminal_measurement is not None:
        term_meas = terminal_measurement
    else:
        qlist_stmt = _insert_before(ilist.New(qubit_ssas), return_stmt)
        term_meas = _insert_before(
            TerminalLogicalMeasurement(qlist_stmt.result), return_stmt
        )

    @cache
    def _get_logical_measurement(q_idx: int) -> ir.SSAValue:
        (idx := py.Constant(q_idx)).insert_before(return_stmt)
        (getitem := py.GetItem(term_meas.result, idx.result)).insert_before(return_stmt)
        return getitem.result

    @cache
    def _get_physical_measurement(q_idx: int, m_idx: int) -> ir.SSAValue:
        (idx := py.Constant(m_idx)).insert_before(return_stmt)
        (
            getitem := py.GetItem(_get_logical_measurement(q_idx), idx.result)
        ).insert_before(return_stmt)
        return getitem.result

    # insert detectors
    if m2dets is not None:
        for j in range(len(m2dets[0])):
            indices = [i for i, row in enumerate(m2dets) if row[j]]
            meas_ssas = [
                _get_physical_measurement(*divmod(idx, meas_per_qubit))
                for idx in indices
            ]
            meas_list = _insert_before(ilist.New(meas_ssas), return_stmt)

            coord_0 = _insert_before(py.Constant(0.0), return_stmt)
            coord_1 = _insert_before(py.Constant(float(j)), return_stmt)
            coords = _insert_before(
                ilist.New([coord_0.result, coord_1.result]), return_stmt
            )

            _insert_before(SetDetector(meas_list.result, coords.result), return_stmt)

    # insert observables
    if m2obs is not None:
        for j in range(len(m2obs[0])):
            indices = [i for i, row in enumerate(m2obs) if row[j]]
            meas_ssas = [
                _get_physical_measurement(*divmod(idx, meas_per_qubit))
                for idx in indices
            ]
            meas_list = _insert_before(ilist.New(meas_ssas), return_stmt)
            _insert_before(SetObservable(meas_list.result), return_stmt)

compile_squin_to_move

compile_squin_to_move(
    mt: Method,
    transversal_rewrite: bool = False,
    no_raise: bool = True,
    layout_heuristic: LayoutHeuristicABC | None = None,
    insert_return_moves: bool = True,
)

Compile a squin kernel to the move dialect.

Parameters:

Name Type Description Default
mt Method

The squin kernel to compile.

required
transversal_rewrite bool

Whether to apply transversal rewrite rules. Defaults to False.

False
no_raise bool

Whether to suppress exceptions during compilation. Defaults to True.

True
layout_heuristic LayoutHeuristicABC | None

Layout heuristic for atom placement. Defaults to None (uses LogicalLayoutHeuristic).

None
insert_return_moves bool

Whether to insert return moves at the end of the program. Defaults to True.

True

Returns:

Type Description

ir.Method: The compiled move dialect method.

Source code in .venv/lib/python3.12/site-packages/bloqade/lanes/logical_mvp.py
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
def compile_squin_to_move(
    mt: ir.Method,
    transversal_rewrite: bool = False,
    no_raise: bool = True,
    layout_heuristic: LayoutHeuristicABC | None = None,
    insert_return_moves: bool = True,
):
    """Compile a squin kernel to the move dialect.

    Args:
        mt (ir.Method): The squin kernel to compile.
        transversal_rewrite (bool, optional): Whether to apply transversal rewrite rules. Defaults to False.
        no_raise (bool, optional): Whether to suppress exceptions during compilation. Defaults to True.
        layout_heuristic (LayoutHeuristicABC | None, optional): Layout heuristic for atom
            placement. Defaults to ``None`` (uses ``LogicalLayoutHeuristic``).
        insert_return_moves (bool, optional): Whether to insert return moves at the end
            of the program. Defaults to True.

    Returns:
        ir.Method: The compiled move dialect method.

    """

    if layout_heuristic is None:
        layout_heuristic = logical_layout.LogicalLayoutHeuristic()

    mt = squin_to_move(
        mt,
        layout_heuristic=layout_heuristic,
        placement_strategy=LogicalPlacementStrategyNoHome(),
        insert_return_moves=insert_return_moves,
        no_raise=no_raise,
        logical_initialize=True,
    )
    if transversal_rewrite:
        mt = transversal_rewrites(mt)

    return mt

compile_squin_to_move_and_visualize

compile_squin_to_move_and_visualize(
    mt: Method,
    interactive: bool = True,
    transversal_rewrite: bool = False,
    animated: bool = False,
    no_raise: bool = True,
    layout_heuristic: LayoutHeuristicABC | None = None,
)

Compile a squin kernel to moves and visualize the program.

Parameters:

Name Type Description Default
mt Method

The squin kernel to compile.

required
interactive bool

Whether to display the visualization interactively. Defaults to True.

True
transversal_rewrite bool

Whether to apply transversal rewrite rules. Defaults to False.

False
animated bool

Whether to use animated visualization for displaying moves. Defaults to False.

False
no_raise bool

Whether to suppress exceptions during compilation. Defaults to True.

True
layout_heuristic LayoutHeuristicABC | None

Layout heuristic for atom placement. Defaults to None (uses LogicalLayoutHeuristic).

None
Source code in .venv/lib/python3.12/site-packages/bloqade/lanes/logical_mvp.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def compile_squin_to_move_and_visualize(
    mt: ir.Method,
    interactive: bool = True,
    transversal_rewrite: bool = False,
    animated: bool = False,
    no_raise: bool = True,
    layout_heuristic: LayoutHeuristicABC | None = None,
):
    """Compile a squin kernel to moves and visualize the program.

    Args:
        mt (ir.Method): The squin kernel to compile.
        interactive (bool, optional): Whether to display the visualization interactively. Defaults to True.
        transversal_rewrite (bool, optional): Whether to apply transversal rewrite rules. Defaults to False.
        animated (bool, optional): Whether to use animated visualization for displaying moves. Defaults to False.
        no_raise (bool, optional): Whether to suppress exceptions during compilation. Defaults to True.
        layout_heuristic (LayoutHeuristicABC | None, optional): Layout heuristic for atom
            placement. Defaults to ``None`` (uses ``LogicalLayoutHeuristic``).

    """
    # Compile to move dialect
    mt = compile_squin_to_move(
        mt,
        transversal_rewrite,
        no_raise=no_raise,
        layout_heuristic=layout_heuristic,
    )
    if transversal_rewrite:
        arch_spec = generate_arch_hypercube(4)
        marker = "o"
    else:
        arch_spec = logical.get_arch_spec()
        marker = "s"

    if animated:
        visualize.animated_debugger(
            mt, arch_spec, interactive=interactive, atom_marker=marker
        )
    else:
        visualize.debugger(mt, arch_spec, interactive=interactive, atom_marker=marker)

compile_task

compile_task(
    logical_kernel: Method | Callable[..., Any],
    m2dets: list[list[int]] | None = None,
    m2obs: list[list[int]] | None = None,
)

Compile a logical kernel into physical move artifacts.

Handles CUDAQ kernel detection/conversion, squin kernel validation, squin-to-move compilation, architecture spec generation, and post-processing extraction.

Parameters:

Name Type Description Default
logical_kernel Method | Callable[..., Any]

A squin ir.Method or a CUDA-Q kernel to compile.

required
m2dets list[list[int]] | None

Binary measurement-to-detector matrix. For CUDA-Q kernels, defaults to Steane [[7,1,3]] detectors if None.

None
m2obs list[list[int]] | None

Binary measurement-to-observable matrix. For CUDA-Q kernels, defaults to Steane [[7,1,3]] observables if None.

None

Returns:

Type Description

A tuple of ``(logical_squin_kernel, physical_arch_spec,

physical_move_kernel, post_processing)``.

Source code in .venv/lib/python3.12/site-packages/bloqade/lanes/logical_mvp.py
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
def compile_task(
    logical_kernel: ir.Method | Callable[..., Any],
    m2dets: list[list[int]] | None = None,
    m2obs: list[list[int]] | None = None,
):
    """Compile a logical kernel into physical move artifacts.

    Handles CUDAQ kernel detection/conversion, squin kernel validation,
    squin-to-move compilation, architecture spec generation, and
    post-processing extraction.

    Args:
        logical_kernel: A squin ``ir.Method`` or a CUDA-Q kernel to compile.
        m2dets: Binary measurement-to-detector matrix. For CUDA-Q kernels,
            defaults to Steane [[7,1,3]] detectors if ``None``.
        m2obs: Binary measurement-to-observable matrix. For CUDA-Q kernels,
            defaults to Steane [[7,1,3]] observables if ``None``.

    Returns:
        A tuple of ``(logical_squin_kernel, physical_arch_spec,
        physical_move_kernel, post_processing)``.

    """
    if is_cudaq_kernel(logical_kernel):
        logical_squin_kernel: ir.Method = cudaq_to_squin(logical_kernel)

        if m2dets is None and m2obs is None:
            num_qubits = len(_find_qubit_ssas(logical_squin_kernel))
            m2dets = steane7_m2dets(num_qubits)
            m2obs = steane7_m2obs(num_qubits)

        append_measurements_and_annotations(logical_squin_kernel, m2dets, m2obs)
    elif isinstance(logical_kernel, ir.Method):
        logical_squin_kernel = logical_kernel
        if m2dets is not None or m2obs is not None:
            append_measurements_and_annotations(logical_squin_kernel, m2dets, m2obs)
    else:
        raise ValueError(f"Unknown kernel type {type(logical_kernel)}")

    run_squin_kernel_validation(logical_squin_kernel).raise_if_invalid()

    physical_arch_spec = generate_arch_hypercube(4)
    physical_move_kernel = compile_squin_to_move(
        logical_squin_kernel, transversal_rewrite=True
    )
    post_processing = atom.AtomInterpreter(
        physical_move_kernel.dialects, arch_spec=physical_arch_spec
    ).get_post_processing(physical_move_kernel)

    return (
        logical_squin_kernel,
        physical_arch_spec,
        physical_move_kernel,
        post_processing,
    )

compile_to_physical_squin_noise_model

compile_to_physical_squin_noise_model(
    mt: Method,
    noise_model: LogicalNoiseModelABC | None = None,
    no_raise: bool = True,
    layout_heuristic: LayoutHeuristicABC | None = None,
) -> ir.Method

Compile a logical squin kernel to a physical squin kernel with noise channels inserted.

Parameters:

Name Type Description Default
mt Method

The logical squin method to compile.

required
noise_model LogicalNoiseModelABC | None

The logical noise model to insert during compilation. Defaults to None (uses :func:generate_logical_noise_model).

None
no_raise bool

Whether to suppress exceptions during compilation. Defaults to True.

True
layout_heuristic LayoutHeuristicABC | None

Layout heuristic for atom placement. Defaults to None (uses LogicalLayoutHeuristic).

None

Returns:

Type Description
Method

ir.Method: The compiled physical squin method with noise channels.

Source code in .venv/lib/python3.12/site-packages/bloqade/lanes/logical_mvp.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
def compile_to_physical_squin_noise_model(
    mt: ir.Method,
    noise_model: LogicalNoiseModelABC | None = None,
    no_raise: bool = True,
    layout_heuristic: LayoutHeuristicABC | None = None,
) -> ir.Method:
    """Compile a logical squin kernel to a physical squin kernel with noise channels inserted.

    Args:
        mt (ir.Method): The logical squin method to compile.
        noise_model (LogicalNoiseModelABC | None, optional): The logical noise model to insert
            during compilation. Defaults to ``None`` (uses :func:`generate_logical_noise_model`).
        no_raise (bool, optional): Whether to suppress exceptions during compilation. Defaults to True.
        layout_heuristic (LayoutHeuristicABC | None, optional): Layout heuristic for atom
            placement. Defaults to ``None`` (uses ``LogicalLayoutHeuristic``).

    Returns:
        ir.Method: The compiled physical squin method with noise channels.

    """
    if noise_model is None:
        noise_model = generate_logical_noise_model()

    move_mt = compile_squin_to_move(
        mt,
        transversal_rewrite=True,
        no_raise=no_raise,
        layout_heuristic=layout_heuristic,
    )
    transformer = MoveToSquinLogical(
        arch_spec=generate_arch_hypercube(4),
        noise_model=noise_model,
        add_noise=True,
        aggressive_unroll=False,
    )
    return transformer.emit(move_mt, no_raise=no_raise)

compile_to_stim_program

compile_to_stim_program(
    mt: Method,
    noise_model: LogicalNoiseModelABC | None = None,
    no_raise: bool = True,
    layout_heuristic: LayoutHeuristicABC | None = None,
) -> str

Compile a logical squin kernel to a Stim program string with noise channels inserted.

Parameters:

Name Type Description Default
mt Method

The logical squin method to compile.

required
noise_model NoiseModelABC | None

The noise model to insert during compilation. Defaults to None (uses :func:generate_simple_noise_model).

None
no_raise bool

Whether to suppress exceptions during compilation. Defaults to True.

True
layout_heuristic LayoutHeuristicABC | None

Layout heuristic for atom placement. Defaults to None (uses LogicalLayoutHeuristic).

None

Returns:

Name Type Description
str str

The compiled Stim program as a string.

Source code in .venv/lib/python3.12/site-packages/bloqade/lanes/logical_mvp.py
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
def compile_to_stim_program(
    mt: ir.Method,
    noise_model: LogicalNoiseModelABC | None = None,
    no_raise: bool = True,
    layout_heuristic: LayoutHeuristicABC | None = None,
) -> str:
    """Compile a logical squin kernel to a Stim program string with noise channels inserted.

    Args:
        mt (ir.Method): The logical squin method to compile.
        noise_model (NoiseModelABC | None, optional): The noise model to insert during
            compilation. Defaults to ``None`` (uses :func:`generate_simple_noise_model`).
        no_raise (bool, optional): Whether to suppress exceptions during compilation. Defaults to True.
        layout_heuristic (LayoutHeuristicABC | None, optional): Layout heuristic for atom
            placement. Defaults to ``None`` (uses ``LogicalLayoutHeuristic``).

    Returns:
        str: The compiled Stim program as a string.

    """
    noise_kernel = compile_to_physical_squin_noise_model(
        mt,
        noise_model,
        no_raise=no_raise,
        layout_heuristic=layout_heuristic,
    )
    RemoveReturn().rewrite(noise_kernel.code)
    noise_kernel = squin_to_stim(noise_kernel)
    buf = io.StringIO()
    emit = EmitStimMain(dialects=noise_kernel.dialects, io=buf)
    emit.initialize()
    emit.run(node=noise_kernel)
    return buf.getvalue().strip()

run_squin_kernel_validation

run_squin_kernel_validation(mt: Method)

Run validation checks on a Squin kernel method.

Parameters:

Name Type Description Default
mt Method

The Squin kernel method to validate.

required

Returns:

Name Type Description
ValidationResult

A validation result object containing the validation errors, if they exist

Note: To trigger an error run run_squin_kernel_validation(mt).raise_if_invalid().

Source code in .venv/lib/python3.12/site-packages/bloqade/lanes/logical_mvp.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def run_squin_kernel_validation(mt: ir.Method):
    """
    Run validation checks on a Squin kernel method.

    Args:
        mt (ir.Method): The Squin kernel method to validate.

    Returns:
        ValidationResult: A validation result object containing the
            validation errors, if they exist

    Note: To trigger an error run `run_squin_kernel_validation(mt).raise_if_invalid()`.

    """
    validator = ValidationSuite(
        [
            GeminiLogicalValidation,
            GeminiTerminalMeasurementValidation,
            FlatKernelNoCloningValidation,
        ]
    )
    return validator.validate(mt)

transversal_rewrites

transversal_rewrites(mt: Method)

Apply transversal rewrite rules to a squin method.

Expands logical operations into their transversal (physical qubit) equivalents using the Steane [[7,1,3]] transversal map. The method is rewritten in place.

Parameters:

Name Type Description Default
mt Method

The squin method to rewrite.

required

Returns:

Type Description

ir.Method: The rewritten method (same object, mutated in place).

Source code in .venv/lib/python3.12/site-packages/bloqade/lanes/logical_mvp.py
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
def transversal_rewrites(mt: ir.Method):
    """Apply transversal rewrite rules to a squin method.

    Expands logical operations into their transversal (physical qubit) equivalents
    using the Steane [[7,1,3]] transversal map. The method is rewritten in place.

    Args:
        mt (ir.Method): The squin method to rewrite.

    Returns:
        ir.Method: The rewritten method (same object, mutated in place).

    """

    rewrite.Walk(
        rewrite.Chain(
            transversal.RewriteLocations(logical.steane7_transversal_map),
            transversal.RewriteLogicalInitialize(logical.steane7_transversal_map),
            transversal.RewriteMoves(logical.steane7_transversal_map),
            transversal.RewriteGetItem(logical.steane7_transversal_map),
            transversal.RewriteLogicalToPhysicalConversion(),
        )
    ).rewrite(mt.code)

    return mt