Skip to content

Index

Notebook-focused Gemini decoding helpers.

ConfidenceDecoder

Bases: ABC


              flowchart TD
              bloqade.gemini.decoding.ConfidenceDecoder[ConfidenceDecoder]

              

              click bloqade.gemini.decoding.ConfidenceDecoder href "" "bloqade.gemini.decoding.ConfidenceDecoder"
            

Decoder interface for a correction plus a scalar confidence score.

decode_with_confidence abstractmethod

decode_with_confidence(
    detector_bits: NDArray[bool_],
) -> tuple[npt.NDArray[np.bool_], np.float64]

Decode one detector syndrome and return a confidence score.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/confidence.py
84
85
86
87
88
89
@abstractmethod
def decode_with_confidence(
    self,
    detector_bits: npt.NDArray[np.bool_],
) -> tuple[npt.NDArray[np.bool_], np.float64]:
    """Decode one detector syndrome and return a confidence score."""

GurobiDecoderWithConfidence

GurobiDecoderWithConfidence(*args: Any, **kwargs: Any)

Bases: GurobiDecoder, ConfidenceDecoder


              flowchart TD
              bloqade.gemini.decoding.GurobiDecoderWithConfidence[GurobiDecoderWithConfidence]
              bloqade.gemini.decoding.confidence.GurobiDecoder[GurobiDecoder]
              bloqade.gemini.decoding.confidence.ConfidenceDecoder[ConfidenceDecoder]

                              bloqade.gemini.decoding.confidence.GurobiDecoder --> bloqade.gemini.decoding.GurobiDecoderWithConfidence
                
                bloqade.gemini.decoding.confidence.ConfidenceDecoder --> bloqade.gemini.decoding.GurobiDecoderWithConfidence
                


              click bloqade.gemini.decoding.GurobiDecoderWithConfidence href "" "bloqade.gemini.decoding.GurobiDecoderWithConfidence"
              click bloqade.gemini.decoding.confidence.GurobiDecoder href "" "bloqade.gemini.decoding.confidence.GurobiDecoder"
              click bloqade.gemini.decoding.confidence.ConfidenceDecoder href "" "bloqade.gemini.decoding.confidence.ConfidenceDecoder"
            

Gurobi MLE decoder with logical-gap confidence.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/confidence.py
32
33
def __init__(self, *args: Any, **kwargs: Any) -> None:
    raise ImportError(_GUROBI_MISSING_MSG)

decode

decode(
    detector_bits: NDArray[bool_],
    verbose: bool = False,
    return_weights: bool = False,
) -> (
    npt.NDArray[np.bool_]
    | tuple[npt.NDArray[np.bool_], np.ndarray]
)

Decode detector bits after validating the detector-shot width.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/confidence.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def decode(
    self,
    detector_bits: npt.NDArray[np.bool_],
    verbose: bool = False,
    return_weights: bool = False,
) -> npt.NDArray[np.bool_] | tuple[npt.NDArray[np.bool_], np.ndarray]:
    """Decode detector bits after validating the detector-shot width."""

    validated_bits = _validate_detector_bits(
        detector_bits,
        self.num_detectors,
        allow_batch=True,
        method_name="decode",
    )
    return super().decode(
        validated_bits,
        verbose=verbose,
        return_weights=return_weights,
    )

decode_with_confidence

decode_with_confidence(
    detector_bits: NDArray[bool_],
) -> tuple[npt.NDArray[np.bool_], np.float64]

Decode a single shot and return the logical-gap confidence.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/confidence.py
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
def decode_with_confidence(
    self,
    detector_bits: npt.NDArray[np.bool_],
) -> tuple[npt.NDArray[np.bool_], np.float64]:
    """Decode a single shot and return the logical-gap confidence."""

    validated_bits = _validate_detector_bits(
        detector_bits,
        self.num_detectors,
        allow_batch=False,
        method_name="decode_with_confidence",
    )
    decoded_obs, logical_gap = self._decode_with_logical_gap(validated_bits)
    logical_gap_arr = np.asarray(logical_gap, dtype=np.float64).reshape(-1)
    return decoded_obs.astype(np.bool_), np.float64(logical_gap_arr[0])

PostSelectionExperiment

PostSelectionExperiment(
    nonclifford_prefix: Method[..., None],
    clifford_circuit: Method[..., None],
    tomography_circuits: Mapping[str, Method[..., None]],
    decoder: type[ConfidenceDecoder],
    decoder_init_args: Mapping[str, object] | None = None,
)

A "wizard" class that orchestrates the steps of running a experiment to do tomography which obtains samples from the hardware and runs decoding with postselection on your ancilla qubits.

It defines methods for creating noisy tomography circuits, creating decoders from the detector error models from those tomography circuits, sampling from the hardware, and doing some analysis based on the confidence associated with each shot.

Attributes:

Name Type Description
nonclifford_prefix Method[..., None]

A SQuIN kernel consisting of a single layer of single-qubit gates applied to the physical qubits before the state-preparation circuit is applied.

clifford_circuit Method[..., None]

A SQuIN kernel consisting of a Clifford circuit applied to the logical qubits (after logical encoding).

tomography_circuits Method[..., None]

A mapping of basis strings to SQuIN kernels consisting of a clifford circuit applied to your logical qubits.

These kernels will be appended to your circuits in the following fashion, for each `basis_label in tomography_circuits`

nonclifford_prefix + clifford_circuit + tomography_circuits[basis_label] From these circuits in each basis, a DEM will be extracted to initialize decoders in each basis.

decoder type[ConfidenceDecoder]

A type of ConfidenceDecoder used to initialize decoders.

decoder_init_args Mapping[str, object] | None

Optional arguments that can be passed in to initialize the decoder. Defaults to None.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/experiments.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def __init__(
    self,
    nonclifford_prefix: ir.Method[..., None],
    clifford_circuit: ir.Method[..., None],
    tomography_circuits: Mapping[str, ir.Method[..., None]],
    decoder: type[ConfidenceDecoder],
    decoder_init_args: Mapping[str, object] | None = None,
):
    self.nonclifford_prefix = nonclifford_prefix
    self.clifford_circuit = clifford_circuit
    self.tomography_circuits = dict(tomography_circuits)
    self.decoder = decoder
    self.decoder_init_args = (
        {} if decoder_init_args is None else dict(decoder_init_args)
    )

    self._postselection_exp_cache = _PostSelectionExperimentCache()
    # NOTE: hardcoding this for now (I guess) to support having some
    # interface for adding noise to the circuit and compiling it down.
    # This simulator object is used for compiling down and adding noise to a circuit
    # to construct a DEM for initializing the decoder.
    self._simulator = GeminiLogicalSimulator()

analysis_f_vs_fraction

analysis_f_vs_fraction(
    *,
    target_bloch: ndarray = _DEFAULT_TARGET_BLOCH,
    threshold_points: int = 64,
    min_accepted_per_basis: int = 50
) -> PostselectionCurveData

Analyzes the shot data to produce arrays for the fidelity to some target state as a function of the fraction of total accepted shots. Produces various thresholds of accepted shots by thresholding on the confidence score associated with each shot.

Parameters:

Name Type Description Default
target_bloch ndarray

The bloch vector to which fidelity is computed. Defaults to np.array([1.0, 1.0, 1.0]) / np.sqrt(3).

_DEFAULT_TARGET_BLOCH
threshold_points int

The number of thresholds that we would like to compute. We get thresholds at evenly spaced quantiles on the array of

64
min_accepted_per_basis int

The minimum number of shots that we require per basis in order to do tomography. This is to prevent very

50

Returns:

Name Type Description
PostselectionCurveData PostselectionCurveData

The accepted fractions and point fidelities

PostselectionCurveData

for the thresholded curve.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/experiments.py
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
def analysis_f_vs_fraction(
    self,
    *,
    target_bloch: np.ndarray = _DEFAULT_TARGET_BLOCH,
    threshold_points: int = 64,
    min_accepted_per_basis: int = 50,
) -> PostselectionCurveData:
    """
    Analyzes the shot data to produce arrays for the fidelity to some target state as a function of the fraction of total accepted shots.
    Produces various thresholds of accepted shots by thresholding on the confidence score associated with each shot.

    Args:
        target_bloch (np.ndarray): The bloch vector to which fidelity is computed. Defaults to np.array([1.0, 1.0, 1.0]) / np.sqrt(3).
        threshold_points (int): The number of thresholds that we would like to compute. We get thresholds at evenly spaced quantiles on the array of
        confidence scores across all shots in each basis. Defaults to 64.
        min_accepted_per_basis (int): The minimum number of shots that we require per basis in order to do tomography. This is to prevent very
        inaccurate estimates for the tomography due to shot count in a basis being very low. Defaults to 50.

    Returns:
        PostselectionCurveData: The accepted fractions and point fidelities
        for the thresholded curve.
    """
    decoded_results = self._postselection_exp_cache.decoded_results
    actual_data = self._postselection_exp_cache.raw_results
    if decoded_results is None:
        raise RuntimeError("decode_and_postselect must be called before analysis.")
    if actual_data is None:
        raise RuntimeError("get_samples must be called before analysis.")
    basis_labels = tuple(decoded_results.keys())
    total_shots = sum(len(dataset.observables) for dataset in actual_data.values())
    # NOTE: In the current implementation, it is possible to get less than "threshold" points if many of your confidence scores end up being the same.
    # Exploring alternative implementations to identify confidence thresholds can be done in a future PR.
    threshold_curve = _evaluate_cached_threshold_curve(
        decoded_results,
        threshold_points=threshold_points,
        target_bloch=target_bloch,
        basis_labels=basis_labels,
        min_accepted_per_basis=min_accepted_per_basis,
        total_shots=total_shots,
    )
    self._postselection_exp_cache.thresholded_data = threshold_curve
    return threshold_curve

analysis_visualization

analysis_visualization(
    min_accepted_fraction: float = 0.04,
    title: str | None = None,
)

Plots the curve of the fidelity vs. accepted fraction, with a cutoff of min_accepted_fraction as well as a supplied title.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/experiments.py
493
494
495
496
497
498
499
500
501
502
503
504
505
def analysis_visualization(
    self, min_accepted_fraction: float = 0.04, title: str | None = None
):
    """Plots the curve of the fidelity vs. accepted fraction, with a cutoff of min_accepted_fraction as well as a supplied title."""
    if self._postselection_exp_cache.thresholded_data is None:
        raise RuntimeError(
            "analysis_f_vs_fraction must be called before visualization."
        )
    return _plot_decoder_curves(
        {"decoder": self._postselection_exp_cache.thresholded_data},
        min_accepted_fraction=min_accepted_fraction,
        title=title,
    )

decode_and_postselect

decode_and_postselect(
    postselection_condition: ndarray,
    progress_label: str | bool = False,
) -> dict[str, _DecodedPostselectionResult]

With the resulting shot data from the hardware samples, runs the following steps: 1. Decoding and correction on the ancilla qubits 2. Filtering shots whose corrected ancilla observable is a valid pattern in postselection_condition 3. Out of these filtered shots, decode and correct the output qubit 4. Returns the corrected observables as well as the confidence score associated with each observable.

Parameters:

Name Type Description Default
postselection_condition ndarray

A 2D numpy array of shape (num_conditions, num_ancillae) representing the valid ancilla patterns to postselect on. Example: If postselection_condition = np.array([[1, 0, 1, 1]]), then we will only accept shots where the first ancilla is 1, the second ancilla is 0, the third ancilla is 1, and the fourth ancilla is 1 after those ancilla have been corrected by the decoder.

required
progress_label str | bool

If False, no progress bar is displayed. If True, the decoder class name is used as the progress-bar label. If a string, that string is used as the progress-bar label. Defaults to False.

False

Returns:

Type Description
dict[str, _DecodedPostselectionResult]

dict[str, _DecodedPostselectionResult]: A dictionary that maps each basis to postselected observables and confidence scores per shot.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/experiments.py
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
def decode_and_postselect(
    self,
    postselection_condition: np.ndarray,
    progress_label: str | bool = False,
) -> dict[str, _DecodedPostselectionResult]:
    """
    With the resulting shot data from the hardware samples, runs the following steps:
    1. Decoding and correction on the ancilla qubits
    2. Filtering shots whose corrected ancilla observable is a valid pattern in postselection_condition
    3. Out of these filtered shots, decode and correct the output qubit
    4. Returns the corrected observables as well as the confidence score associated with each observable.

    Args:
        postselection_condition (np.ndarray): A 2D numpy array of shape (num_conditions, num_ancillae) representing the valid ancilla patterns to postselect on.
            Example: If postselection_condition = np.array([[1, 0, 1, 1]]), then we will only accept shots where the first ancilla is 1, the second ancilla is 0, the third ancilla is 1, and the fourth ancilla is 1
            after those ancilla have been corrected by the decoder.
        progress_label (str | bool): If False, no progress bar is displayed. If True,
            the decoder class name is used as the progress-bar label. If a string, that
            string is used as the progress-bar label. Defaults to False.

    Returns:
        dict[str, _DecodedPostselectionResult]: A dictionary that maps each basis to postselected observables and confidence scores per shot.
    """
    actual_data = self._postselection_exp_cache.raw_results
    decoder_map = self._postselection_exp_cache.decoders_with_confidence
    if actual_data is None:
        raise RuntimeError("get_samples must be called before decoding.")
    if decoder_map is None:
        raise RuntimeError("initialize_decoders must be called before decoding.")
    targets = np.asarray(postselection_condition, dtype=np.uint8)
    if targets.ndim != 2:
        raise ValueError("postselection_condition must be a 2D array.")
    basis_labels = list(decoder_map.keys())
    decoded_results = _build_generic_threshold_tables(
        actual_data,
        decoder_map,
        targets=targets,
        basis_labels=basis_labels,
        progress_label=(
            self.decoder.__name__ if progress_label is True else progress_label
        ),
    )
    self._postselection_exp_cache.decoded_results = decoded_results
    return decoded_results

dem_circuits

dem_circuits() -> dict[str, tsim_backend.Circuit]

Constructs TSIM circuits annotated with error channels for each basis from the tomography kernels, which will later be used to construct detector error models.

Note: this function depends on .kernels() being invoked. Note: in the implementation of this function, to obtain a noiseless reference observable to later construct a DEM, we take our whole circuit, strip away the noise, and prepend it to our circuit so that the noiseless behavior is U^dagU = I.

Returns:

Type Description
dict[str, Circuit]

dict[str, tsim_backend.Circuit]: A dictionary mapping each basis label to a compiled TSIM circuit with noise channels, where the observables

dict[str, Circuit]

in noiseless simulation are all 0.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/experiments.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
def dem_circuits(self) -> dict[str, tsim_backend.Circuit]:
    """
    Constructs TSIM circuits annotated with error channels for each basis from the tomography kernels, which will later
    be used to construct detector error models.

    Note: this function depends on .kernels() being invoked.
    Note: in the implementation of this function, to obtain a noiseless reference observable to later construct a DEM,
    we take our whole circuit, strip away the noise, and prepend it to our circuit so that the noiseless behavior is U^dagU = I.

    Returns:
        dict[str, tsim_backend.Circuit]: A dictionary mapping each basis label to a compiled TSIM circuit with noise channels, where the observables
        in noiseless simulation are all 0.
    """
    dem_kernels = self._postselection_exp_cache.dem_kernels
    if dem_kernels is None:
        raise RuntimeError("kernels must be called before dem_circuits.")
    dem_simulator = GeminiLogicalSimulator(
        noise_model=self._simulator.noise_model,
        backend=TsimSimulatorBackend(),
    )
    dem_tasks = {
        basis: dem_simulator.task(kernel.similar())
        for basis, kernel in dem_kernels.items()
    }
    dem_tasks = _apply_special_tsim_circuit_strategy(dem_tasks)
    special_tsim_circuits: dict[str, tsim_backend.Circuit] = {
        basis: task.tsim_circuit for basis, task in dem_tasks.items()
    }
    self._postselection_exp_cache.dem_circuits = special_tsim_circuits
    return special_tsim_circuits

dems

dems() -> dict[str, stim.DetectorErrorModel]

Constructs detector error models from the noisy circuits in each basis. Defaults to approximating disjoint errors.

Note: this function depends on dem_circuits() being called.

Returns:

Type Description
dict[str, DetectorErrorModel]

dict[str, stim.DetectorErrorModel]: A dictionary mapping each basis label to the detector error model for the tomography

dict[str, DetectorErrorModel]

circuit in that basis.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/experiments.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
def dems(self) -> dict[str, stim.DetectorErrorModel]:
    """
    Constructs detector error models from the noisy circuits in each basis. Defaults to approximating disjoint errors.

    Note: this function depends on dem_circuits() being called.

    Returns:
        dict[str, stim.DetectorErrorModel]: A dictionary mapping each basis label to the detector error model for the tomography
        circuit in that basis.
    """
    dem_circuits = self._postselection_exp_cache.dem_circuits
    if dem_circuits is None:
        raise RuntimeError("dem_circuits must be called before dems.")
    dems = {
        basis: circ.detector_error_model(approximate_disjoint_errors=True)  # type: ignore[attr-defined]
        for basis, circ in dem_circuits.items()
    }
    self._postselection_exp_cache.dems = dems
    return dems

get_samples

get_samples(num_shots: int) -> dict[str, _BasisDataset]

For each basis, samples num_shots from the hardware. Returns the detector and observable information for each task.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/experiments.py
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
def get_samples(
    self,
    num_shots: int,
) -> dict[str, _BasisDataset]:
    """For each basis, samples num_shots from the hardware. Returns the detector and observable information for each task."""
    actual_tasks = self._postselection_exp_cache.hardware_tasks
    if actual_tasks is None:
        raise RuntimeError("make_tasks must be called before get_samples.")
    # In this implementation, we request samples for each basis in parallel, and then iteratively block
    # on X, Y, and then Z being finished.
    futures = {
        basis: task.run_async(num_shots) for basis, task in actual_tasks.items()
    }
    actual_data = {
        basis: _basis_dataset_from_task_result(future.result())
        for basis, future in futures.items()
    }
    self._postselection_exp_cache.raw_results = actual_data
    return actual_data

initialize_decoders

initialize_decoders() -> (
    dict[str, tuple[ConfidenceDecoder, BaseDecoder]]
)

Initializes the decoders for the tomography circuits in each basis from the detector error models. This function utilizes correlated decoding (https://arxiv.org/abs/2403.03272). Because of this, this function initializes two decoders: one for the decoding the ancilla qubits, and one for decoding the output qubit. The decoder that decodes the ancilla qubits decodes them jointly, taking in (num_ancillas * 3) detectors and outputting corrections for (num_ancillas) observables. This decoder does not additionally take in the output qubit's detectors for the case that the output qubit might be used later in the computation. The decoder that decodes the output qubit decodes it jointly with the ancilla qubits, taking in ((num_ancillas + 1) * 3) detectors and outputting corrections for 1 observable (on the output qubit). This function assumes that the first qubit is the output qubit, and also assumes that we are using the [[7, 1, 3]] Steane code, which has three detectors per logical qubit.

Note: this function depends on dems() being called.

Returns:

Type Description
dict[str, tuple[ConfidenceDecoder, BaseDecoder]]

dict[str, tuple[ConfidenceDecoder, BaseDecoder]]: A dictionary mapping each basis label to (factory_decoder, full_decoder), where factory_decoder

dict[str, tuple[ConfidenceDecoder, BaseDecoder]]

decodes the ancilla qubits jointly and full_decoder decodes the output qubit jointly with the information on all logical qubits.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/experiments.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
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
def initialize_decoders(self) -> dict[str, tuple[ConfidenceDecoder, BaseDecoder]]:
    """
    Initializes the decoders for the tomography circuits in each basis from the detector error models.
    This function utilizes correlated decoding (https://arxiv.org/abs/2403.03272).
    Because of this, this function initializes two decoders: one for the decoding the ancilla qubits, and one for decoding the output qubit.
    The decoder that decodes the ancilla qubits decodes them jointly, taking in (num_ancillas * 3) detectors and outputting corrections for (num_ancillas) observables.
        This decoder does not additionally take in the output qubit's detectors for the case that the output qubit might be used later in the computation.
    The decoder that decodes the output qubit decodes it jointly with the ancilla qubits, taking in ((num_ancillas + 1) * 3) detectors and outputting corrections for 1 observable (on the output qubit).
    This function assumes that the first qubit is the output qubit, and also assumes that we are using the [[7, 1, 3]] Steane code, which has three detectors per logical qubit.

    Note: this function depends on dems() being called.

    Returns:
        dict[str, tuple[ConfidenceDecoder, BaseDecoder]]: A dictionary mapping each basis label to (factory_decoder, full_decoder), where factory_decoder
        decodes the ancilla qubits jointly and full_decoder decodes the output qubit jointly with the information on all logical qubits.
    """
    dems_bases = self._postselection_exp_cache.dems
    if dems_bases is None:
        raise RuntimeError("dems must be called before initialize_decoders.")
    decoders_bases: dict[str, tuple[ConfidenceDecoder, BaseDecoder]] = {}
    # NOTE: there is a question of if we want to support multi-qubit
    # tomography in this experiment. For now, probably not; if we did, we
    # would have to specify the number of output qubits and their locations
    # and use that information to construct a custom layout.
    layout = _DEFAULT_SYNDROME_LAYOUT
    for basis_label, dem_base in dems_bases.items():
        # We subset the detector error models for the "full" and "factory" decoders to
        # extract only the detectors and observables that are used by the respective decoders.
        full_dem = _sub_detector_error_model(
            dem_base,
            detector_indices=range(dem_base.num_detectors),
            observable_indices=range(layout.output_observable_count),
        )
        factory_dem = _sub_detector_error_model(
            dem_base,
            detector_indices=range(
                layout.output_detector_count, dem_base.num_detectors
            ),
            observable_indices=range(
                layout.output_observable_count,
                dem_base.num_observables,
            ),
        )
        # NOTE: We are initializing the factory and full decoders twice. For the TableDecoder, this means that we are sampling two times for each basis
        # to build the 2 decoders. It might be more efficient if, from the same sampled data, we constructed the factory and full decoders (so we just
        # have to sample once per basis). But, the current TableDecoder does not support that API (as we assume that training happens during
        # initialization of the TableDecoder).
        # TODO: this is because the current API does NOT support decoder(dem, **kwargs) for the constructor so we have to
        # do a cast. We would want to decide on the decoder __init__ API to be able to avoid such a cast (e.g., to have **kwargs in the __init__ function
        # in the abstract class)
        # The reason why the factory decoder is a ConfidenceDecoder is that technically, we only need confidence scores when decoding the ancilla qubits.
        decoder_constructor = cast(Callable[..., ConfidenceDecoder], self.decoder)
        full_decoder = cast(
            BaseDecoder,
            decoder_constructor(full_dem, **self.decoder_init_args),
        )
        factory_decoder = decoder_constructor(factory_dem, **self.decoder_init_args)
        decoders_bases[basis_label] = (factory_decoder, full_decoder)
    self._postselection_exp_cache.decoders_with_confidence = decoders_bases
    return decoders_bases

kernels

kernels(
    num_logical_qubits: int = 5,
) -> dict[str, ir.Method[..., _LogicalTomographyReturn]]

Composes the nonclifford, clifford, and tomography kernels into a dictionary mapping each basis label to the respective nonclifford + clifford + tomography kernel.

Parameters:

Name Type Description Default
num_logical_qubits int

An integer corresponding to the number of logical qubits allocated in the kernels.

5

Returns:

Type Description
dict[str, Method[..., _LogicalTomographyReturn]]

dict[str, ir.Method[..., _LogicalTomographyReturn]]: A dictionary mapping the tomography basis labels to the respective kernel used for tomography.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/experiments.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
def kernels(
    self,
    num_logical_qubits: int = 5,
) -> dict[str, ir.Method[..., _LogicalTomographyReturn]]:
    """
    Composes the nonclifford, clifford, and tomography kernels into a dictionary mapping each basis label to
    the respective nonclifford + clifford + tomography kernel.

    Args:
        num_logical_qubits (int): An integer corresponding to the number of logical qubits allocated in the kernels.

    Returns:
        dict[str, ir.Method[..., _LogicalTomographyReturn]]: A dictionary mapping the tomography basis labels to the respective kernel used for tomography.
    """
    # TODO: change the name of _DecoderPrimitiveSet --> whole_circuit
    decoder_primitive_set = _DecoderPrimitiveSet(
        state_injection_circuit=self.nonclifford_prefix,
        logical_circuit=self.clifford_circuit,
    )
    dem_kernels = _build_decoder_kernel_bundle(
        decoder_primitive_set,
        num_logical_qubits,
        tomography_kernels=self.tomography_circuits,
    )
    self._postselection_exp_cache.dem_kernels = dem_kernels
    return dem_kernels

make_tasks

make_tasks(
    device: GeminiLogicalSimulator,
) -> dict[
    str,
    GeminiLogicalSimulatorTask[_LogicalTomographyReturn],
]

Prepares tasks for submission to the hardware device.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/experiments.py
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def make_tasks(
    self,
    # TODO: Ideally, we don't want to make the type of the device GeminiLogicalSimulator (this should be flexible to support the type representing
    # the hardware). However, because GeminiLogicalSimulator currently doesn't obey any interface/inheritance for a generic hardware object,
    # we can't really replace this with a more specific type without changing the design of GeminiLogicalSimulator.
    device: GeminiLogicalSimulator,
    # TODO: the return type of make_tasks of what we want to run on hardware should not be GeminiLogicalSimulatorTask. It should be
    # TaskABC[GeminiLogicalFuture]. However, currently, GeminiLogicalSimulatorTask does not inherit from the abstract "task" types in
    # bloqade-core.
) -> dict[str, GeminiLogicalSimulatorTask[_LogicalTomographyReturn]]:
    """Prepares tasks for submission to the hardware device."""
    dem_kernels = self._postselection_exp_cache.dem_kernels
    if dem_kernels is None:
        raise RuntimeError("kernels must be called before make_tasks.")
    actual_tasks: dict[
        str, GeminiLogicalSimulatorTask[_LogicalTomographyReturn]
    ] = {
        basis: device.task(kernel.similar())
        for basis, kernel in dem_kernels.items()
    }
    self._postselection_exp_cache.hardware_tasks = actual_tasks
    return actual_tasks

tomography_result

tomography_result(
    accepted_fraction: float,
) -> TomographyResult

Returns a TomographyResult after decoding and postselection with the option to manually specify the fraction of shots accepted.

The implementation will find the minimum number of shots to accept where the fraction of accepted shots is >= accepted_fraction, sorted by highest to lowest confidence.

Parameters:

Name Type Description Default
accepted_fraction float

The fraction of shots to accept out of shots that passed postselection. Note that if accepted_fraction == 1.0, this means

required

Returns:

Name Type Description
TomographyResult TomographyResult

The resulting shots in each basis based on the accepted_fraction provided.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/experiments.py
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
def tomography_result(
    self,
    accepted_fraction: float,
) -> TomographyResult:
    """
    Returns a TomographyResult after decoding and postselection with the option to manually specify the fraction
    of shots accepted.

    The implementation will find the minimum number of shots to accept where the fraction of accepted shots is >= accepted_fraction,
    sorted by highest to lowest confidence.

    Args:
        accepted_fraction (float): The fraction of shots to accept out of shots that passed postselection. Note that if accepted_fraction == 1.0, this means
        accepting all shots that passed postselection, not all shots used to perform the experiment.

    Returns:
        TomographyResult: The resulting shots in each basis based on the accepted_fraction provided.
    """

    decoded_results = self._postselection_exp_cache.decoded_results
    if decoded_results is None:
        raise RuntimeError(
            "decode_and_postselect must be called before tomography_result."
        )

    basis_labels = tuple(decoded_results.keys())
    shots_by_basis = _shots_at_accepted_fraction(
        decoded_results,
        accepted_fraction,
        basis_labels=basis_labels,
    )
    return TomographyResult(shots_by_basis)

PostselectionCurveData dataclass

PostselectionCurveData(
    accepted_fraction: ndarray,
    fidelity: ndarray,
    point_fidelity: ndarray,
)

Point-estimate fidelity curve from thresholded postselection.

TableDecoderWithConfidence

TableDecoderWithConfidence(
    dem: DetectorErrorModel,
    *,
    num_shots: int = 10**7,
    seed: int | None = None,
    step_size: int | None = None
)

Bases: TableDecoder, ConfidenceDecoder


              flowchart TD
              bloqade.gemini.decoding.TableDecoderWithConfidence[TableDecoderWithConfidence]
              bloqade.gemini.decoding.table_decoders.TableDecoder[TableDecoder]
              bloqade.gemini.decoding.confidence.ConfidenceDecoder[ConfidenceDecoder]

                              bloqade.gemini.decoding.table_decoders.TableDecoder --> bloqade.gemini.decoding.TableDecoderWithConfidence
                
                bloqade.gemini.decoding.confidence.ConfidenceDecoder --> bloqade.gemini.decoding.TableDecoderWithConfidence
                


              click bloqade.gemini.decoding.TableDecoderWithConfidence href "" "bloqade.gemini.decoding.TableDecoderWithConfidence"
              click bloqade.gemini.decoding.table_decoders.TableDecoder href "" "bloqade.gemini.decoding.table_decoders.TableDecoder"
              click bloqade.gemini.decoding.confidence.ConfidenceDecoder href "" "bloqade.gemini.decoding.confidence.ConfidenceDecoder"
            

Dense table decoder with empirical per-syndrome confidence.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/table_decoders.py
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
def __init__(
    self,
    dem: stim.DetectorErrorModel,
    *,
    num_shots: int = 10**7,
    seed: int | None = None,
    step_size: int | None = None,
) -> None:
    data_len = dem.num_detectors + dem.num_observables
    if data_len > 64:
        raise ValueError(
            f"Total data length {data_len} (detectors + observables) "
            "exceeds 64 bits and cannot be packed into int64."
        )

    counts_table = np.zeros(2**data_len, dtype=_COUNT_DTYPE)

    super().__init__(dem=dem, det_obs_counts=counts_table)
    self._det_obs_counts = _as_uint32_count_table(self._det_obs_counts)
    self._correction_confidence: np.ndarray | None = None

    if data_len == 0:
        self._det_obs_counts[0] = max(1, min(int(num_shots), _COUNT_MAX))
        return
    self._train_from_dem(num_shots=num_shots, seed=seed, step_size=step_size)

decode

decode(detector_bits: ndarray) -> np.ndarray

Decode detector bits after validating the detector-shot width.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/table_decoders.py
154
155
156
157
158
159
160
161
162
163
def decode(self, detector_bits: np.ndarray) -> np.ndarray:
    """Decode detector bits after validating the detector-shot width."""

    validated_bits = _validate_detector_bits(
        detector_bits,
        self.num_detectors,
        allow_batch=True,
        method_name="decode",
    )
    return super().decode(validated_bits)

decode_with_confidence

decode_with_confidence(
    detector_bits: ndarray,
) -> tuple[np.ndarray, np.float64]

Decode one detector syndrome and return its empirical confidence.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/table_decoders.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
def decode_with_confidence(
    self,
    detector_bits: np.ndarray,
) -> tuple[np.ndarray, np.float64]:
    """Decode one detector syndrome and return its empirical confidence."""

    validated_bits = _validate_detector_bits(
        detector_bits,
        self.num_detectors,
        allow_batch=False,
        method_name="decode_with_confidence",
    )
    correction = np.asarray(self.decode(validated_bits), dtype=np.bool_)
    assert self._correction_confidence is not None
    packed = int(
        pack_boolean_array(
            np.asarray(validated_bits, dtype=np.uint8).reshape(1, -1)
        )[0]
    )
    return correction, np.float64(self._correction_confidence[packed])

TomographyResult dataclass

TomographyResult(shots_by_basis: Mapping[str, ndarray])

Point-estimate single-qubit tomography result.

Parameters:

Name Type Description Default
shots_by_basis Mapping[str, ndarray]

A mapping of each basis to an array of shots (0/1's) in each basis.

required
Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/tomography.py
 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
def __init__(
    self,
    shots_by_basis: Mapping[str, np.ndarray],
) -> None:
    """
    Create a tomography result by computing the density matrix from the shots per basis.

    Args:
        shots_by_basis (Mapping[str, np.ndarray]): A mapping of each basis to an array of shots (0/1's) in each basis.
    """
    zero_counts: dict[str, int] = {}
    one_counts: dict[str, int] = {}
    totals: dict[str, int] = {}
    bloch: dict[str, float] = {}
    for basis in shots_by_basis:
        shots = np.asarray(shots_by_basis[basis], dtype=np.uint8)
        if shots.ndim != 2 or shots.shape[1] != 1:
            raise ValueError(
                "TomographyResult expects each basis to have shape (shots, 1)."
            )
        zero_counts[basis] = int(np.count_nonzero(shots[:, 0] == 0))
        one_counts[basis] = int(np.count_nonzero(shots[:, 0] == 1))
        totals[basis] = max(zero_counts[basis] + one_counts[basis], 1)
        bloch[basis] = (zero_counts[basis] - one_counts[basis]) / totals[basis]

    object.__setattr__(self, "density_matrix", _density_matrix_from_bloch(bloch))

fidelity_bloch

fidelity_bloch(
    target_bloch: ndarray | Sequence[float],
    tol: float = 1e-10,
) -> float

Return the fidelity to a target state from its Bloch vector.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/tomography.py
108
109
110
111
112
113
114
115
116
117
118
def fidelity_bloch(
    self,
    target_bloch: np.ndarray | Sequence[float],
    tol: float = 1e-10,
) -> float:
    """Return the fidelity to a target state from its Bloch vector."""

    target_density_matrix = _density_matrix_from_bloch(
        _validate_single_qubit_bloch_vector(target_bloch, tol=tol)
    )
    return _single_qubit_fidelity(self.density_matrix, target_density_matrix)

empty_logical_circuit

empty_logical_circuit() -> ir.Method[..., None]

Return a no-op logical Squin kernel for injected-state tomography.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/experiments.py
88
89
90
91
92
93
94
95
96
97
def empty_logical_circuit() -> ir.Method[..., None]:
    """Return a no-op logical Squin kernel for injected-state tomography."""

    from bloqade import squin

    @squin.kernel
    def empty_logical(reg):
        return

    return empty_logical

magic_state_dist_steane

magic_state_dist_steane(
    *,
    theta_offset: float = 0.0,
    phi_offset: float = 0.0,
    lam_offset: float = 0.0
) -> tuple[ir.Method[..., None], ir.Method[..., None]]

Returns the nonclifford prefix circuit and clifford logical circuit used for magic state distillation. Note that the kernels take in the qubit register 'reg' as input. This means that the kernels are technically agnostic to the number of input qubits.

Parameters:

Name Type Description Default
theta_offset float

An optional offset to theta to manually introduce rotation error in the nonclifford prefix. Defaults to 0.0.

0.0
phi_offset float

An optional offset to phi to manually introduce rotation error in the nonclifford prefix. Defaults to 0.0.

0.0
lan_offset float

An optional offset to lam to manually introduce rotation error in the nonclifford prefix. Defaults to 0.0.

required

Returns:

Type Description
tuple[Method[..., None], Method[..., None]]

tuple[ir.Method[..., None], ir.Method[..., None]]: The (nonclifford_prefix, logical_circuit) pair.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/experiments.py
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
def magic_state_dist_steane(
    *,
    theta_offset: float = 0.0,
    phi_offset: float = 0.0,
    lam_offset: float = 0.0,
) -> tuple[ir.Method[..., None], ir.Method[..., None]]:
    """
    Returns the nonclifford prefix circuit and clifford logical circuit
    used for magic state distillation. Note that the kernels take in the qubit register 'reg' as input.
    This means that the kernels are technically agnostic to the number of input qubits.

    Args:
        theta_offset (float): An optional offset to theta to manually introduce rotation error in the nonclifford prefix. Defaults to 0.0.
        phi_offset (float): An optional offset to phi to manually introduce rotation error in the nonclifford prefix. Defaults to 0.0.
        lan_offset (float): An optional offset to lam to manually introduce rotation error in the nonclifford prefix. Defaults to 0.0.

    Returns:
        tuple[ir.Method[..., None], ir.Method[..., None]]: The (nonclifford_prefix, logical_circuit) pair.
    """
    ideal_theta = math.acos(1 / math.sqrt(3))
    ideal_phi = 0.25 * math.pi
    ideal_lam = 0.0

    theta = ideal_theta + theta_offset
    phi = ideal_phi + phi_offset
    lam = ideal_lam + lam_offset

    primitive_set = _build_msd_primitives(theta, phi, lam)

    return primitive_set.state_injection_circuit, primitive_set.logical_circuit

single_qubit_state_tomography

single_qubit_state_tomography() -> (
    dict[str, ir.Method[..., None]]
)

Returns X, Y, and Z basis kernels used to perform single-qubit tomography. Note that the kernels take in the register as the input.

Returns:

Type Description
dict[str, Method[..., None]]

dict[str, ir.Method[..., None]]: A dictionary mapping "X", "Y", and "Z" to the respective tomography kernels.

Source code in .venv/lib/python3.12/site-packages/bloqade/gemini/decoding/experiments.py
76
77
78
79
80
81
82
83
84
85
def single_qubit_state_tomography() -> dict[str, ir.Method[..., None]]:
    """
    Returns X, Y, and Z basis kernels used to perform single-qubit tomography. Note that the kernels take in the register as the input.

    Returns:
        dict[str, ir.Method[..., None]]: A dictionary mapping "X", "Y", and "Z" to the respective tomography kernels.
    """
    # return a list?
    # should return (X, Y, Z) in order, but can check this.
    return _build_tomography_primitives(output_qubit=0)