Skip to content

Utils

ShotRemappingException

Bases: Exception


              flowchart TD
              bloqade.gemini.device.logical.utils.ShotRemappingException[ShotRemappingException]

              

              click bloqade.gemini.device.logical.utils.ShotRemappingException href "" "bloqade.gemini.device.logical.utils.ShotRemappingException"
            

Exception if we failed to produce a shot remapping.

aligned_detected_and_sorted_shots_for_subtasks

aligned_detected_and_sorted_shots_for_subtasks(
    storage, shot_filter, subtasks: Sequence[dict]
) -> tuple[list[np.ndarray], list[np.ndarray]]

Return DETECTED and SORTED frames aligned shot-for-shot per subtask.

Each frame is ordered by the complete storage identity. A mismatch means that the two frames cannot safely be compared by array position.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/device/logical/utils.py
 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
def aligned_detected_and_sorted_shots_for_subtasks(
    storage,
    shot_filter,
    subtasks: Sequence[dict],
) -> tuple[list[np.ndarray], list[np.ndarray]]:
    """Return DETECTED and SORTED frames aligned shot-for-shot per subtask.

    Each frame is ordered by the complete storage identity. A mismatch means
    that the two frames cannot safely be compared by array position.
    """
    detected_results = []
    sorted_results = []

    for subtask in subtasks:
        subtask_index = subtask["subtask_index"]
        detected_rows = _shots_for_subtask_frame(
            storage, shot_filter, subtask_index, "DETECTED"
        )
        sorted_rows = _shots_for_subtask_frame(
            storage, shot_filter, subtask_index, "SORTED"
        )

        detected_keys = tuple(map(_shot_identity, detected_rows))
        sorted_keys = tuple(map(_shot_identity, sorted_rows))
        if detected_keys != sorted_keys:
            detected_only = sorted(set(detected_keys) - set(sorted_keys))
            sorted_only = sorted(set(sorted_keys) - set(detected_keys))
            raise ValueError(
                "DETECTED and SORTED frames are not aligned for "
                f"subtask_index={subtask_index}: "
                f"missing SORTED={detected_only}, missing DETECTED={sorted_only}."
            )

        detected_results.append(
            np.asarray([row.bitstring for row in detected_rows], dtype=bool)
        )
        sorted_results.append(
            np.asarray([row.bitstring for row in sorted_rows], dtype=bool)
        )

    return detected_results, sorted_results

get_slm_mapping_postprocessing

get_slm_mapping_postprocessing(
    sim_kernel: Method[..., RetType],
) -> tuple[
    Callable[..., Any], atom.PostProcessing[RetType]
]

Create a result postprocessor for full Zone-0 SLM shots.

Result post-processing is two steps, and this returns both::

physical_bitstring = [frame_data[i] for i in shot_remapping]
user_output = post_processing.emit_return([physical_bitstring])

The returned post-processing object comes from :func:~bloqade.gemini.post_processing.build_post_processing, which abstract-interprets the user's kernel once to reconstruct its return value and every detector and observable annotation.

Warning

This reconstructs the physical measurement mapping by compiling the stored logical kernel with the locally installed Bloqade Lanes compiler and Gemini architecture. The result is valid only when they match the compiler and architecture used to execute the remote task. The exact remote physical compilation artifact is not currently stored with the result.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/device/logical/utils.py
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def get_slm_mapping_postprocessing(
    sim_kernel: ir.Method[..., RetType],
) -> tuple[Callable[..., Any], atom.PostProcessing[RetType]]:
    """Create a result postprocessor for full Zone-0 SLM shots.

    Result post-processing is two steps, and this returns both::

        physical_bitstring = [frame_data[i] for i in shot_remapping]
        user_output = post_processing.emit_return([physical_bitstring])

    The returned post-processing object comes from
    :func:`~bloqade.gemini.post_processing.build_post_processing`, which
    abstract-interprets the *user's* kernel once to reconstruct its return
    value and every detector and observable annotation.

    Warning:
        This reconstructs the physical measurement mapping by compiling the
        stored logical kernel with the locally installed Bloqade Lanes compiler
        and Gemini architecture. The result is valid only when they match the
        compiler and architecture used to execute the remote task. The exact
        remote physical compilation artifact is not currently stored with the
        result.
    """

    from bloqade.gemini.post_processing import build_post_processing
    from bloqade.lanes.analysis import atom
    from bloqade.lanes.analysis.atom._shot_remapping import ShotRemappingErr
    from bloqade.lanes.arch.gemini import physical
    from bloqade.lanes.bytecode.encoding import ZoneAddress
    from bloqade.lanes.transform import LogicalPipeline

    arch_spec = physical.get_arch_spec()
    physical_move_kernel = LogicalPipeline(transversal_rewrite=True).emit(sim_kernel)
    zone0 = ZoneAddress(0)

    interpreter = atom.AtomInterpreter(
        physical_move_kernel.dialects,
        arch_spec=arch_spec,
    )
    shot_mapping = interpreter.get_shot_remapping(physical_move_kernel)
    if isinstance(shot_mapping, ShotRemappingErr):
        raise ShotRemappingException(
            f"Failed to produce shot remapping, error message: {shot_mapping.diagnostic.message}, reason: {shot_mapping.diagnostic.offending_value}"
        )
    mapping = shot_mapping.mapping
    zone0_locations = list(arch_spec.yield_zone_locations(zone0))
    # print(f"row-major SLM mapping: {mapping}")
    expected_zone0_sites = len(zone0_locations)

    post_processing = build_post_processing(sim_kernel)

    def postprocess(zone0_shots, *, invert: bool = False):
        zone0_shots = np.asarray(zone0_shots, dtype=bool)

        if zone0_shots.size == 0:
            return []
        if zone0_shots.ndim != 2:
            raise ValueError(f"Expected a 2-D array, got {zone0_shots.shape}.")
        if zone0_shots.shape[1] != expected_zone0_sites:
            raise ValueError(
                f"Expected {expected_zone0_sites} Zone-0 columns, "
                f"got {zone0_shots.shape[1]}."
            )

        measurement_shots = zone0_shots[:, mapping]

        # Enable only if the stored QLAM bit convention is opposite to the
        # simulator/post-processing convention.
        if invert:
            measurement_shots = ~measurement_shots

        return measurement_shots.tolist()

    return postprocess, post_processing

shot_results_for_subtasks

shot_results_for_subtasks(
    storage,
    shot_filter,
    subtasks: Sequence[dict],
    *,
    frame_type: str | None = None
) -> list[np.ndarray]

Return selected shot bitstrings grouped and sorted by subtask.

StorageBackend.get_shots does not promise an ordering. This helper preserves the caller-provided subtask order and sorts each subtask by its full storage identity. frame_type optionally overrides the frame type already present in shot_filter.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/device/logical/utils.py
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
def shot_results_for_subtasks(
    storage,
    shot_filter,
    subtasks: Sequence[dict],
    *,
    frame_type: str | None = None,
) -> list[np.ndarray]:
    """Return selected shot bitstrings grouped and sorted by subtask.

    ``StorageBackend.get_shots`` does not promise an ordering.  This helper
    preserves the caller-provided subtask order and sorts each subtask by its
    full storage identity. ``frame_type`` optionally overrides the frame type
    already present in ``shot_filter``.
    """
    results = []
    for subtask in subtasks:
        selected_frame = shot_filter.frame_type if frame_type is None else frame_type
        rows = _shots_for_subtask_frame(
            storage,
            shot_filter,
            subtask["subtask_index"],
            selected_frame,
        )
        results.append(np.asarray([row.bitstring for row in rows], dtype=bool))

    return results