bragi_quantum.experiments API#

The library of calibration and characterization nodes. Every experiment is a node built from a Parameters, a Measurement, an Analysis and one or more QOI classes (see Core Concepts).

Abstractions#

The base-class families every node is assembled from.

Parameters & QOI#

pydantic model bragi_quantum.experiments.abstract.parameters.BaseParameters[source]#

Bases: BaseModel

Configuration parameters for a Calibration Node. Pydantic ensures these are validated before a node execution begins.

Every field is a single default value applied to all elements. To override a field for specific elements, populate custom_parameters with a mapping {field_name: {element_name: value}}; for_qubit / for_coupler then resolve a copy of these parameters with that element’s overrides applied (and defaults everywhere else). Values are plain data, so custom_parameters round-trips through JSON/YAML config files.

Fields:
invalid_variant_combinations: ClassVar[tuple[Mapping[str, Any], ...]] = ()#
legal_variant_combinations: ClassVar[tuple[Mapping[str, Any], ...]] = ()#
field name: str = ''#
field qubits: list[str] [Optional]#
field couplers: list[str] [Optional]#
field custom_parameters: dict[str, dict[str, Any]] [Optional]#
by_category()[source]#

Return this instance’s field values grouped by category.

Maps each category ("metadata", "data_acquisition", "analysis", and "uncategorized" if any field is unlabelled) to an {field_name: value} dict. Only non-empty categories are included.

Complements fields_by_category(), which returns field names from the class; this returns the concrete values from the instance — handy for inspecting or displaying a parameter set (e.g. in a notebook):

>>> for cat, fields in params.by_category().items():
...     print(cat, fields)
Return type:

dict[str, dict[str, Any]]

show()[source]#

Return a human-readable listing of the parameters grouped by category.

Printing the result gives a quick overview of a parameter set and which knobs are re-tunable at reanalysis (the analysis group):

>>> print(params.show())

Metadata fields (name, qubits, couplers) are populated by the orchestrator when a node actually runs; on a bare instance they are still unset and rendered as (unset) rather than '' / [].

Return type:

str

for_qubit(qubit)[source]#

Resolve these parameters for qubit (applying any per-qubit overrides).

Parameters:

qubit (str)

Return type:

BaseParameters

for_coupler(coupler)[source]#

Resolve these parameters for coupler (applying any per-coupler overrides).

Parameters:

coupler (str)

Return type:

BaseParameters

resolved_by_qubit()[source]#

Return {qubit: resolved_parameters} for every qubit in self.qubits.

Convenience for nodes building a per-qubit sample space: instead of repeating {q: self.parameters.for_qubit(q) for q in ...} in each node, call resolved = self.parameters.resolved_by_qubit() once and read resolved[q].<field>. Qubits without overrides map to self (no copy), so this is cheap.

Return type:

dict[str, BaseParameters]

resolved_by_coupler()[source]#

Return {coupler: resolved_parameters} for every coupler in self.couplers.

Coupler-node analogue of resolved_by_qubit().

Return type:

dict[str, BaseParameters]

pydantic model bragi_quantum.experiments.abstract.parameters.BaseQoi[source]#

Bases: BaseModel, ABC

Base class for Quantities of Interest (QOI). This stores the results of an experiment/analysis to be persisted back into the bragi_quantum.datalayer models.

Fields:
field is_successful: bool = False#
field timestamp: str | None = None#
property Hz_to_GHz#
abstractmethod to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, Any]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

update_model(model)[source]#

Directly injects the QOI results into a bragi_quantum.datalayer model instance (e.g., an ExtendedTransmon).

Parameters:

model (Any)

Measurement#

class bragi_quantum.experiments.abstract.measurement.SingleQubitGate(*args, **kwargs)[source]#

Bases: Protocol

A callable that constructs a single-qubit gate or schedule from a qubit name.

class bragi_quantum.experiments.abstract.measurement.BaseMeasurement(transmons, couplers={})[source]#

Bases: ABC

Parameters:
property transmons: OrderedDict[str, ExtendedTransmon]#
abstract property measure_gate_class: Measure#
abstractmethod schedule_function(**kwargs)[source]#

Build this measurement’s schedule.

Called by BaseNode.precompile() as schedule_function(**schedule_samplespace, **self.schedule_keywords) – keyword-only, with the keyword set varying per measurement (there’s no shared signature to enforce beyond that).

Return type:

TimeableSchedule

point_schedule(*args)[source]#
Return type:

TimeableSchedule

make_linear_domains(linear_setpoints, dtype)[source]#
Parameters:
Return type:

list[LinearDomain]

make_shot_indices(repetitions)[source]#
Parameters:

repetitions (int)

Return type:

LinearDomain

excite_system(to_state)[source]#

Excite all qubits to the given state (1 or 2) in parallel.

Parameters:

to_state (Literal[1, 2])

Return type:

TimeableSchedule

static calibrated_gate_level(transmon)[source]#

Highest excited state this qubit’s device model can prepare.

Calibration values are NaN until a real value has been written by a successful calibration run. Returns 0 when even the X gate (0->1) is not calibrated, 1 when the X gate is calibrated, and 2 when the 1->2 pulse is calibrated too.

Parameters:

transmon (ExtendedTransmon)

Return type:

int

calibration_points_schedule(repetitions)[source]#

Static per-state calibration block, appended by BaseNode.precompile.

Requires every qubit’s X gate (0->1) to be calibrated; returns None otherwise (no partial calibration block for a subset of qubits). The shared state range is the lowest calibrated level across all qubits: for each state i in that range, the system is reset, excited to state i (all qubits together) and measured with the coordinate CAL=i on dedicated CAL_<n> acquisition channels (CAL marks calibration data everywhere, like AR_ marks active reset). BaseNode.configure_dataset extracts these into per-qubit <qubit>_CAL data variables.

The block carries its own repetition loop register, so it runs identically regardless of the node’s sweep/loop structure and its acquisitions are hardware-averaged over repetitions.

Parameters:

repetitions (int)

Return type:

TimeableSchedule | None

reset_system(*, method)[source]#
Parameters:

method (Literal['passive', 'active'])

Return type:

TimeableSchedule

static compute_stagger_times(durations)[source]#
Parameters:

durations (list[float])

Return type:

list[float]

measure_system(*, coords, bin_mode, acq_protocol='SSBIntegrationComplex', acq_channel_prefix=None, holdoff_time=0.0, stagger=0.0, conditional_operation=None, measure_gate_class=None, acq_delay=None, pulse_amp=None, pulse_duration=None, freq=None, acq_duration=None)[source]#

Readout all qubits with configurable timing and optional conditional operations.

Qubit names are prepended to all coordinate keys before passing to the measure gate. Device override parameters, if given, are indexed per qubit by position in transmons.

Method Parameters#

coordsdict[str, list[Variable] or Variable or int or float or complex]

Coordinate labels and values attached to each acquisition. List values are indexed per qubit; scalars are broadcast to all qubits.

holdoff_timeVariable or float, optional

Idle time inserted before any measurements. By default 0.0.

staggerlist[float] or float or “trigger_network”, optional

Start times for each measurement, relative to holdoff_time. When specified as a fixed offset, then the start times are computed using compute_stagger_times(). "trigger_network" uses a fixed offset based on trigger network timing constraints. By default stagger=0.0 which corresponds to a simultaneous readout of all qubits.

conditional_operationSingleQubitGate, optional

If provided, called with each qubit name and the result is wrapped in a ConditionalOperation appended after its measurement. By default None.

measure_gate_classMeasure, optional

Override the gate class used for measurement. Defaults to measure_gate_class.

Measure gate parameters#

bin_mode“average_append” or “append”

Binning mode passed to the measure gate.

acq_protocolstr, optional

Acquisition protocol passed to the measure gate. By default "SSBIntegrationComplex".

acq_channel_prefixstr, optional

If set, the acquisition channel is set to f"{acq_channel_prefix}{qubit_idx}" instead of the default integer index. By default None.

Measure gate device override parameters#

acq_delaylist[Variable], optional

Per-qubit device override for acquisition delay.

pulse_amplist[Variable], optional

Per-qubit device override for measure pulse amplitude.

pulse_durationlist[Variable], optional

Per-qubit device override for measure pulse duration.

freqlist[Variable], optional

Per-qubit device override for readout frequency.

acq_durationlist[Variable], optional

Per-qubit device override for the acquisition duration (integration time / raw trace length).

returns:

Schedule containing the staggered measurement of all qubits.

rtype:

TimeableSchedule

Parameters:
  • coords (dict[str, list[Variable] | Variable | int | float | complex])

  • bin_mode (Literal['average_append', 'append'])

  • acq_protocol (Literal['SSBIntegrationComplex', 'Timetag', 'TimetagTrace', 'Trace', 'TriggerCount', 'ThresholdedTriggerCount', 'NumericalSeparatedWeightedIntegration', 'NumericalWeightedIntegration', 'ThresholdedAcquisition'])

  • acq_channel_prefix (str | None)

  • holdoff_time (Variable | float)

  • stagger (list[float] | float | Literal['trigger_network'])

  • conditional_operation (SingleQubitGate | None)

  • measure_gate_class (Measure | None)

  • acq_delay (list[Variable] | None)

  • pulse_amp (list[Variable] | None)

  • pulse_duration (list[Variable] | None)

  • freq (list[Variable] | None)

  • acq_duration (list[Variable] | None)

Return type:

TimeableSchedule

generic_1d_sweep(*, linear_domains, point_schedule, shot_index=None)[source]#
Parameters:
  • linear_domains (list[LinearDomain])

  • point_schedule (Callable[[list[Variable]], TimeableSchedule])

  • shot_index (Variable | None)

Return type:

TimeableSchedule

generic_2d_sweep(*, inner_linear_domains, outer_linear_domains, point_schedule, shot_index=None)[source]#
Parameters:
  • inner_linear_domains (list[LinearDomain])

  • outer_linear_domains (list[LinearDomain])

  • point_schedule (Callable[[list[Variable], list[Variable]], TimeableSchedule])

  • shot_index (Variable | None)

Return type:

TimeableSchedule

generic_1d_point(*args, **kwargs)[source]#
Return type:

TimeableSchedule

generic_2d_point(*args, **kwargs)[source]#
Return type:

TimeableSchedule

Analysis#

class bragi_quantum.experiments.abstract.analysis.Analysis(parameters, qoi_cls=None)[source]#

Bases: ABC

Unified, parameter-driven analysis for a single calibration node.

Usage:

analysis = RabiAnalysis(parameters, Rabi01QOI)
analysis.set_parameters(qubits=["q06", "q12"])      # restrict the set
results = analysis.run("data/dataset_rabi_0.hdf5")  # {element: qoi}
fig = analysis.figure("q06")                        # interactive plotly
grid = analysis.grid_figure()                       # all analysed elements
analysis.save(out_dir)                              # png + preview + pdf

run loops over parameters.qubits (or parameters.couplers when element_kind == "coupler") and analyses each element on its own worker instance, so per-element fit state is preserved for plotting. A single element can also be analysed directly with analyse_element.

Subclasses implement two hooks: compute_qoi() (populate fit/derived state from self.dataset / self.magnitudes and return the QOI) and add_traces() (draw this element’s plotly traces).

Parameters:
element_kind: str = 'qubit'#
expects_calibration_points: bool = False#
set_parameters(**overrides)[source]#

Update parameters in place (pydantic-revalidated) and return self.

Return type:

Analysis

analyse_element(dataset, element)[source]#

Slice element from dataset (Dataset or path) and fit it here.

Parameters:

element (str)

Return type:

BaseQoi

property has_calibration_points: bool#

Whether this element’s calibration points are present and complete.

Raises CalibrationPointsError if calibration points are present but expects_calibration_points is False — that combination means this analysis could use them but doesn’t declare so.

process_qubit(dataset, qubit_name)[source]#
Parameters:

qubit_name (str)

Return type:

BaseQoi

process_coupler(dataset, coupler_element)[source]#
Parameters:

coupler_element (str)

Return type:

BaseQoi

run(dataset)[source]#

Analyse the target elements; return {element: qoi}.

Targets are parameters.qubits / parameters.couplers. If that list is empty, every matching element found in dataset is analysed — so run works out-of-the-box on a raw dataset, and a subset is selected simply by setting the parameters list.

Return type:

dict[str, BaseQoi]

abstractmethod compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

BaseQoi

abstractmethod add_traces(fig, row=1, col=1)[source]#

Add this element’s plotly traces (and axis titles) to fig at (row, col).

Parameters:
Return type:

None

plot_title()[source]#

Title for this element’s (sub)plot. Override per node if desired.

Return type:

str

list_plots()[source]#

Names of the plots this analysis can render. Override for multi-plot nodes.

Return type:

list[str]

support_figures()[source]#

Extra per-element diagnostic figures as (plotly_figure, filename).

Called on each analysed element’s worker during save. Default: none. Override for nodes with 1-D projections / per-slice diagnostics.

Return type:

list[tuple[Any, str]]

figure(element=None, plot_name='main')[source]#

Return a plotly Figure for one analysed element.

Parameters:
  • element (str | None)

  • plot_name (str)

grid_figure(ncols=5)[source]#

Return a plotly grid Figure over every analysed element.

Parameters:

ncols (int)

save_png(path, *, grid=True, scale=2)[source]#

Write a PNG (grid of all elements by default) via kaleido.

Parameters:
Return type:

Path

save(out_dir)[source]#

Write this node’s figures into out_dir (call after run()).

Produces the grid {name}.png + {name}_preview.png, the per-element support figures, and — if pdf_report_path is set — merges them into the report PDF. This is the output half of the analysis; run() does the analysis and populates the per-element workers used here.

Return type:

None

Node#

class bragi_quantum.experiments.abstract.node.BaseNode(parameters, qoi_cls)[source]#

Bases: ABC

Parameters:
measurement_cls: BaseMeasurement#
analysis_cls: Analysis#
append_calibration_points: bool = False#
require_calibration_points: bool = False#
measure_node(*, execution_mode)[source]#

To be implemented by the Classes that define the Node Type: ScheduleNode or ExternalParameterNode

Parameters:

execution_mode (ExecutionMode)

Return type:

Dataset

execute()[source]#

Execute the full calibration pipeline for this node. Derives the data path from the active session’s root path, using a unique per-invocation folder so repeated runs don’t collide.

pre_measurement_operation()[source]#

To be implemented by the child measurement nodes

initial_operation()[source]#

To be implemented by the child measurement nodes. This is called before the execution of each and every iteration of the samples of the external samplespace. See coupler_spectroscopy for examples.

final_operation()[source]#

To be implemented by the child measurement nodes. This is called after ALL the iteration samples of the external samplespace have been executed. e.g. set back the dc_current to 0 in coupler_spectroscopy. See coupler_spectroscopy for examples.

precompile(schedule_samplespace)[source]#
Parameters:

schedule_samplespace (dict)

Return type:

CompiledSchedule

measure_compiled_schedule(compiled_schedule, *, execution_mode=None, measurement=(1, 1))[source]#

Execute a measurement for a node and save the resulting dataset.

Parameters:
  • compiled_schedule (CompiledSchedule) – The compiled schedule to execute.

  • execution_mode (ExecutionMode | None) – The execution mode. If None, falls back to the active session’s session_options.

  • measurement (tuple) – Tuple of (current_measurement, total_measurements).

Returns:

The dataset containing the measurement results.

Return type:

xarray.Dataset

calibrate(data_path)[source]#

Execute the calibration workflow for this node.

Parameters:

data_path (Path) – Directory where measurement results will be saved.

post_process(data_path)[source]#

Execute post-measurement analysis and generate reports.

This always runs (unless in dummy mode) to ensure plots and reports are generated.

Parameters:

data_path (Path)

configure_dataset(raw_ds)[source]#
Parameters:

raw_ds (Dataset)

Return type:

Dataset

class bragi_quantum.experiments.abstract.node.QubitNode(parameters, qoi_cls)[source]#

Bases: BaseNode, ABC

Parameters:
property transmons: dict[str, ExtendedTransmon]#

Return transmons (qubits) restricted to this node’s parameters.qubits.

class bragi_quantum.experiments.abstract.node.CouplerNode(parameters, qoi_cls)[source]#

Bases: BaseNode, ABC

Parameters:
property edges: dict[str, ExtendedCompositeSquareEdge]#

Return coupler edges restricted to this node’s parameters.couplers.

get_coupled_qubits()[source]#
Return type:

list

validate()[source]#
Return type:

None

Errors#

exception bragi_quantum.experiments.abstract.errors.ExperimentBuildingError[source]#

Bases: Exception

Raised when a node violates bragi_quantum.experiments’s build assumptions.

exception bragi_quantum.experiments.abstract.errors.ExperimentRegistryError[source]#

Bases: Exception

Raised when the bragi_quantum.experiments node registry (nodes.yaml) fails to load, or a registered variant is used in a way that violates its spec.

exception bragi_quantum.experiments.abstract.errors.ExperimentParameterError[source]#

Bases: Exception

Raised when a BaseParameters subclass violates a parameter convention/restriction introduced by bragi_quantum.experiments itself — e.g. a variant- defining field that isn’t a finite type, a metadata_field marked as variant-defining, or an instance matching a declared invalid_variant_combinations entry. Covers what would otherwise be a mix of ValueError/TypeError so all such violations share one type.

Node-type base classes#

Schedule nodes#

class bragi_quantum.experiments.nodes.schedule_node.ScheduleNode(parameters, qoi_cls)[source]#

Bases: BaseNode, ABC

A Node specialized for experiments defined entirely by pulse schedules.

This class handles the complexity of mapping experimental parameters to hardware execution, specifically addressing hardware limits: 1. Standard execution for small/simple schedules. 2. Batching for schedules exceeding QCM_RF instruction limits. 3. Outer-looping for schedules exceeding QRM_RF measurement memory limits.

property outer_schedule_dimensions: int#

Calculate the size of the outer samplespace.

The outer samplespace is used when an experiment must be split into multiple hardware executions because the number of measurement points exceeds hardware memory.

Example

self.outer_samplespace = {‘cz_amp’: {‘q1_q2’: np.array([0.1, 0.2, 0.3])}} returns 3.

Returns:

The number of iterations required in the outer loop.

Return type:

int

measure_node(*, execution_mode)[source]#

The main entry point for executing the node’s measurement.

Parameters:

execution_mode (ExecutionMode) – The mode of execution (real, dummy, or re-analyse).

Returns:

The combined dataset from the schedule measurements.

Return type:

xr.Dataset

measure_schedule_node(*, execution_mode)[source]#

Orchestrate the measurement sequence based on schedule complexity.

It branches into three paths:

  1. Simple: A single compilation and execution.

  2. Mixed/Batched: Splitting schedules that have too many pulse instructions for the QCM_RF sequencers.

  3. Outer-Looped: Splitting measurements that have too many acquisition points for the QRM_RF memory.

Returns:

The final merged experimental data.

Return type:

xr.Dataset

Parameters:

execution_mode (ExecutionMode)

class bragi_quantum.experiments.nodes.schedule_node.ScheduleQubitNode(parameters, qoi_cls, **kwargs)[source]#

Bases: ScheduleNode, QubitNode

A ScheduleNode specifically configured for single-qubit elements.

Parameters:
class bragi_quantum.experiments.nodes.schedule_node.ScheduleCouplerNode(parameters, qoi_cls, **kwargs)[source]#

Bases: ScheduleNode, CouplerNode

A ScheduleNode specifically configured for multi-qubit coupler elements.

Parameters:

External-parameter nodes#

class bragi_quantum.experiments.nodes.external_parameter_node.ExternalParameterNode(parameters, qoi_cls)[source]#

Bases: BaseNode, ABC

Abstract base class for nodes involving external hardware parameters.

These nodes are used for experiments where a parameter outside of the Quantify pulse schedule must be swept (e.g., DC currents from a DAC or magnetic fields).

Parameters:
pre_measurement_operation(reduced_ext_space)[source]#

Hook called before each hardware measurement.

Subclasses implement this to set physical hardware values (like ramping a current) before the pulse schedule executes.

Parameters:

reduced_ext_space (dict[str, Any]) – The slice of the external samplespace for the current iteration.

property external_dimensions: list[int]#

Calculates the dimensions of the external samplespace.

Supports multidimensional external sweeps. For example, if sweeping ‘dc_current’ (4 points) and ‘offset’ (3 points), it returns [4, 3].

Returns:

A list of lengths for each swept external quantity.

Return type:

List[int]

class bragi_quantum.experiments.nodes.external_parameter_node.ExternalParameterFixedScheduleNode(parameters, qoi_cls)[source]#

Bases: ExternalParameterNode

A node where the pulse schedule is constant, but hardware parameters change.

The schedule is compiled once, and then executed repeatedly for every point in the external samplespace. This is efficient for sweeps like flux-spectroscopy.

Parameters:
measure_node(*, execution_mode)[source]#

Executes the measurement loop for a fixed schedule.

Parameters:

execution_mode (ExecutionMode) – The execution mode (real, dummy, re-analyse).

Returns:

The merged dataset containing all external iterations.

Return type:

xr.Dataset

class bragi_quantum.experiments.nodes.external_parameter_node.ExternalParameterDifferentSchedulesNode(parameters, **kwargs)[source]#

Bases: ExternalParameterNode

A node where the schedule changes alongside external hardware parameters.

This is used for complex calibrations where the schedule keywords depend on the external sweep index. It includes logic to handle “active elements,” allowing different elements (like couplers) to have different numbers of sweep points.

Parameters:

parameters (BaseParameters)

measure_node(*, execution_mode)[source]#

Executes a loop where schedules are re-compiled per iteration.

Parameters:

execution_mode (ExecutionMode)

Return type:

Dataset

class bragi_quantum.experiments.nodes.external_parameter_node.ExternalParameterFixedScheduleQubitNode(parameters, **kwargs)[source]#

Bases: ExternalParameterFixedScheduleNode, QubitNode

Qubit-specific node for sweeps over external parameters with a fixed schedule.

Parameters:

parameters (BaseParameters)

class bragi_quantum.experiments.nodes.external_parameter_node.ExternalParameterDifferentSchedulesQubitNode(parameters, **kwargs)[source]#

Bases: ExternalParameterDifferentSchedulesNode, QubitNode

Qubit-specific node for sweeps over external parameters with varying schedules.

Parameters:

parameters (BaseParameters)

class bragi_quantum.experiments.nodes.external_parameter_node.ExternalParameterFixedScheduleCouplerNode(parameters, **kwargs)[source]#

Bases: ExternalParameterFixedScheduleNode, CouplerNode

Coupler-specific node for sweeps over external parameters with a fixed schedule.

Parameters:

parameters (BaseParameters)

class bragi_quantum.experiments.nodes.external_parameter_node.ExternalParameterDifferentSchedulesCouplerNode(parameters, **kwargs)[source]#

Bases: ExternalParameterDifferentSchedulesNode, CouplerNode

Coupler-specific node for sweeps over external parameters with varying schedules.

Parameters:

parameters (BaseParameters)

Readout nodes#

Resonator spectroscopy#

Node implementation for Resonator Spectroscopy.

class bragi_quantum.experiments.nodes.readout.resonator_spectroscopy.node.ResonatorSpectroscopy(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.readout.resonator_spectroscopy.parameters.ResonatorSpectroscopyBaseQOI'>)[source]#

Bases: ScheduleQubitNode

Execution node for performing Resonator Spectroscopy.

Inherits from ScheduleNode to automatically leverage ActiveSession for hardware and datastore state, injecting keywords and sample spaces into the measurement schedule.

Parameters:
measurement_cls#

alias of ResonatorSpectroscopyMeasurement

analysis_cls#

alias of ResonatorSpectroscopyAnalysis

parameters: ResonatorSpectroscopyParameters#
pydantic model bragi_quantum.experiments.nodes.readout.resonator_spectroscopy.parameters.ResonatorSpectroscopyParameters[source]#

Bases: BaseParameters

Parameters for Resonator Spectroscopy & Punchout.

Fields:
field readout_state: Literal[0, 1, 2] = 0#

Basis state the resonator is prepared to before readout.

Constraints:
  • ge = 0

  • lt = 3

field samples: int | None = 100#

Number of frequency samples.

field repetitions: int | None = 100#

Number of repetitions (averages) per frequency point.

field half_width: float | None = 1000000.0#

Half-width of the sweep window in Hz.

field sample_size_for_sliding_window_analysis: int = 200#

Frequency-point count above which a resonator sweep is treated as wide-range and routed through the sliding-window fit instead of a single fit over the full window. A wide sweep can contain more than one dip-like feature, so it needs to be localized onto one resonance first.

field slide_window_size: int = 100#

Number of frequency points in each sliding sub-window fit during the wide-range path.

field slide_window_step: int = 50#

Number of frequency points the sliding window advances between successive fit attempts.

field slide_window_min_ql: float = 7000.0#

Minimum loaded quality factor Ql a sliding-window fit must reach (in addition to the R^2 gate) to be accepted as the resonance and stop the window scan.

field slide_window_max_qe: float = 60000.0#

Maximum external quality factor Qe a sliding-window fit may have (in addition to the R^2 gate) to be accepted as the resonance and stop the window scan.

field min_r_squared: float = 0.9#

Minimum R^2 (coefficient of determination, data vs. fit) accepted for a resonator fit. R^2 doesn’t need an assumed per-point error, so its scale is fixed regardless of the qubit’s signal level.

field max_abs_theta: float = 0.25#

Maximum allowed magnitude of the fitted impedance-mismatch angle theta (radians). A fit whose theta magnitude reaches this bound indicates an implausible impedance mismatch and fails is_good_fit, regardless of R^2.

invalid_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = (mappingproxy({'readout_state': 0}), mappingproxy({'readout_state': 1}), mappingproxy({'readout_state': 2}))#
pydantic model bragi_quantum.experiments.nodes.readout.resonator_spectroscopy.parameters.ResonatorSpectroscopyBaseQOI[source]#

Bases: BaseQoi

Base Quantities of Interest for Resonator Spectroscopy.

Fields:
field fitted_frequency: float = 0.0#
field fitted_frequency_error: float | None = None#
field ql: float = 0.0#
field ql_error: float | None = None#
field qe: float = 0.0#
field qe_error: float | None = None#
field theta: float = 0.0#
field theta_error: float | None = None#
field r_squared: float = 0.0#

Coefficient of determination; gates is_good_fit.

field amplitude: float = 0.0#
field amplitude_error: float | None = None#
field minimum_frequency: float = 0.0#
field minimum_frequency_error: float | None = None#
field kappa: float = 0.0#

Linewidth fr/Ql, in Hz.

field kappa_error: float | None = None#
field propagation_delay: float = 0.0#

Cable propagation delay -phi_v/(2*pi), in seconds.

field propagation_delay_error: float | None = None#
model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.readout.resonator_spectroscopy.parameters.ResonatorSpectroscopyQOI[source]#

Bases: ResonatorSpectroscopyBaseQOI

Quantities of Interest for Resonator Spectroscopy (State 0).

Fields:

to_dict()[source]#

Convert the QOI to a dictionary representation.

Return type:

dict[str, float]

to_redis_dict()[source]#

Convert the QOI to a Redis dictionary representation.

Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.readout.resonator_spectroscopy.parameters.ResonatorSpectroscopy1QOI[source]#

Bases: ResonatorSpectroscopyBaseQOI

Quantities of Interest for Resonator Spectroscopy (State 1).

Fields:

to_dict()[source]#

Convert the QOI to a dictionary representation.

Return type:

dict[str, float]

to_redis_dict()[source]#

Convert the QOI to a Redis dictionary representation.

Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.readout.resonator_spectroscopy.parameters.ResonatorSpectroscopy2QOI[source]#

Bases: ResonatorSpectroscopyBaseQOI

Quantities of Interest for Resonator Spectroscopy (State 2).

Fields:

to_dict()[source]#

Convert the QOI to a dictionary representation.

Return type:

dict[str, float]

to_redis_dict()[source]#

Convert the QOI to a Redis dictionary representation.

Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Module containing classes that fit data from a resonator spectroscopy experiment.

One model is used here: hanger_with_delay_model (hanger_with_delay()) — the full complex hanger response (resonance dip, amplitude tilt, impedance-mismatch asymmetry, and cable propagation delay), fit directly against complex IQ data. See bragi_quantum.experiments.nodes.readout.resonator_spectroscopy.model.

Punchout (readout-amplitude calibration) reuses this exact same fit, one call per amplitude slice — a punchout trace is not a different kind of resonator sweep, so it doesn’t need a different model or a special mode flag.

class bragi_quantum.experiments.nodes.readout.resonator_spectroscopy.analysis.ResonatorSpectroscopyAnalysis(parameters, qoi_cls=None)[source]#

Bases: Analysis

Fit the data of a resonator spectroscopy experiment.

Replaces the former ResonatorSpectroscopyBaseQubitAnalysis / ResonatorSpectroscopyQubitAnalysis (per-qubit) + …NodeAnalysis (node-level). ResonatorSpectroscopy1Analysis / …2Analysis add the state-1/2 markers.

Parameters:
element_kind: str = 'qubit'#
parameters: ResonatorSpectroscopyParameters#
resonator_analysis()[source]#

Executes the fitting routine on the dataset populated by the abstract layer. Fits the complex hanger-with-delay model directly against the raw complex IQ data.

Return type:

None

create_qoi_object()[source]#

Populate the specific Quantity of Interest structure.

Return type:

ResonatorSpectroscopyBaseQOI

is_good_fit(fit_result)[source]#

Validate if the provided fit meets the quality constraints.

Gated on R^2 (r_squared(), not lmfit’s own rsquared — see that function’s docstring), used for both the final fit and the sliding-window candidate search. Without a real per-point noise estimate (no SSRO), any chi-squared threshold would depend on an assumed error scale that doesn’t track the real SNR, so chi-squared has no fixed meaning across qubits/amplitudes and isn’t tracked anywhere in this module.

Used uniformly by every caller — the plain resonator_spectroscopy node and punchout call this same check. Always called with self.fit_result in practice, which is what _fit_r_squared scores against.

Parameters:

fit_result (ModelResult)

Return type:

bool

compute_qoi()[source]#

Run the resonator fit and return the QOI.

Used as-is by every state (0/1/2) and every caller (plain resonator_spectroscopy and punchout) — they all fit the same model and gate on the same is_good_fit(), so there’s nothing left to specialize here.

Return type:

BaseQoi

plot_title()[source]#

Title for this element’s (sub)plot. Override per node if desired.

Return type:

str

add_traces(fig, row=1, col=1)[source]#

Draw the fitted model (magnitude) over the raw data (plotly).

The fit curve is drawn on the dense frequency grid (_f_dense) so it looks smooth even for narrow resonances. The black vertical line is placed at the closed-form magnitude minimum, so it always lands exactly on the dip regardless of background slope.

Parameters:
Return type:

None

support_figures()[source]#

Magnitude+phase companion figure (row_heights=[2, 1]) — the phase panel shows how the fit’s phase ramp (cable delay + hanger phase) tracks the data, which the main grid’s magnitude-only panel can’t show. Ported from tergite’s resonator_spectroscopy phase panel.

Return type:

list[tuple]

class bragi_quantum.experiments.nodes.readout.resonator_spectroscopy.analysis.ResonatorSpectroscopy1Analysis(parameters, qoi_cls=None)[source]#

Bases: ResonatorSpectroscopyAnalysis

Resonator spectroscopy specialised for state 1.

Parameters:
compute_qoi()[source]#

Run the resonator fit and return the QOI.

Used as-is by every state (0/1/2) and every caller (plain resonator_spectroscopy and punchout) — they all fit the same model and gate on the same is_good_fit(), so there’s nothing left to specialize here.

Return type:

BaseQoi

add_traces(fig, row=1, col=1)[source]#

Draw the fitted model (magnitude) over the raw data (plotly).

The fit curve is drawn on the dense frequency grid (_f_dense) so it looks smooth even for narrow resonances. The black vertical line is placed at the closed-form magnitude minimum, so it always lands exactly on the dip regardless of background slope.

Parameters:
Return type:

None

class bragi_quantum.experiments.nodes.readout.resonator_spectroscopy.analysis.ResonatorSpectroscopy2Analysis(parameters, qoi_cls=None)[source]#

Bases: ResonatorSpectroscopyAnalysis

Resonator spectroscopy specialised for state 2.

Parameters:
compute_qoi()[source]#

Run the resonator fit and return the QOI.

Used as-is by every state (0/1/2) and every caller (plain resonator_spectroscopy and punchout) — they all fit the same model and gate on the same is_good_fit(), so there’s nothing left to specialize here.

Return type:

BaseQoi

add_traces(fig, row=1, col=1)[source]#

Draw the fitted model (magnitude) over the raw data (plotly).

The fit curve is drawn on the dense frequency grid (_f_dense) so it looks smooth even for narrow resonances. The black vertical line is placed at the closed-form magnitude minimum, so it always lands exactly on the dip regardless of background slope.

Parameters:
Return type:

None

Punchout#

Node implementation for Punchout (readout amplitude) calibration.

class bragi_quantum.experiments.nodes.readout.punchout.node.Punchout(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.readout.punchout.parameters.PunchoutQOI'>)[source]#

Bases: ScheduleQubitNode

Execution node for performing Punchout.

A single node class handles the 0, 1 and 2 readout clocks (state) and both end point methods (bin_mode, see PunchoutParameters). The analysis class and QOI class are injected at construction time, mirroring the resonator spectroscopy interface used by the orchestrator.

Inherits from ScheduleNode to automatically leverage ActiveSession for hardware and datastore state, injecting keywords and sample spaces into the measurement schedule.

Parameters:
measurement_cls#

alias of PunchoutMeasurement

analysis_cls#

alias of PunchoutAnalysis

parameters: PunchoutParameters#
pydantic model bragi_quantum.experiments.nodes.readout.punchout.parameters.PunchoutParameters[source]#

Bases: BaseParameters

Parameters for Punchout (readout amplitude) calibration.

bin_mode selects the end point method the same way readout_state selects the readout clock: "average_append" hardware-averages each point and finds the end point from a shift in the fitted resonator frequency; "append" keeps every single-shot repetition instead and finds the end point from that IQ cloud’s circularity.

The readout-amplitude sweep is sampled more densely at low power, where the resonator dip moves quickly, and more coarsely at high power. The two segments are configured by crossover_amplitude and the two bin counts.

Fields:
field readout_state: Literal[0, 1, 2] = 0#

Basis state the resonator is prepared to before readout.

Constraints:
  • ge = 0

  • lt = 3

field samples: int = 200#

Number of frequency samples.

field half_width: float = 2000000.0#

Half-width of the frequency sweep window in Hz.

field min_amplitude: float = 0.015#

Minimum readout pulse amplitude.

field crossover_amplitude: float = 0.06#

Amplitude where the dense low-power segment hands over to the coarse high-power segment.

field max_amplitude: float = 0.2#

Maximum readout pulse amplitude.

field low_amplitude_bins: int = 10#

Number of samples below the crossover amplitude.

field high_amplitude_bins: int = 15#

Number of samples above the crossover amplitude.

field repetitions: int = 800#

Number of repetitions (averages) per point.

field bin_mode: Literal['average_append', 'append'] = 'average_append'#

‘average_append’ hardware-averages each point (‘repetitions’ averages) and selects the frequency-shift end point; ‘append’ keeps every single-shot repetition instead and selects the IQ-cloud-circularity end point.

field upper_threshold: float = 10000000.0#

Upward resonator-frequency shift (Hz) that ends the punchout.

field lower_threshold: float = 50000.0#

Downward resonator-frequency shift (Hz) that ends the punchout.

field amplitude_scale_factor: float = 0.8#

Fraction of the end-point amplitude used as the operating point.

field max_consecutive_missing_points: int = 3#

Maximum number of consecutive amplitudes without a valid fit before the punchout search is stopped.

field circularity_threshold: float = 0.8#

Minimum IQ-cloud circularity (ratio of the covariance eigenvalues) required to consider an amplitude still in the linear (non-discriminating) regime.

field min_r_squared: float = 0.9#

Minimum R^2 (coefficient of determination) accepted for a per-amplitude resonator fit (forwarded to ResonatorSpectroscopyParameters).

field max_abs_theta: float = 0.25#

Maximum theta magnitude (impedance-mismatch phase, rad) accepted for a per-amplitude resonator fit (forwarded to ResonatorSpectroscopyParameters).

invalid_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = (mappingproxy({'readout_state': 0, 'bin_mode': 'average_append'}), mappingproxy({'readout_state': 0, 'bin_mode': 'append'}), mappingproxy({'readout_state': 1, 'bin_mode': 'average_append'}), mappingproxy({'readout_state': 1, 'bin_mode': 'append'}), mappingproxy({'readout_state': 2, 'bin_mode': 'average_append'}), mappingproxy({'readout_state': 2, 'bin_mode': 'append'}))#
pydantic model bragi_quantum.experiments.nodes.readout.punchout.parameters.PunchoutBaseQOI[source]#

Bases: BaseQoi

Base Quantities of Interest for Punchout.

Fields:
field pulse_amp: float = 0.0#
model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.readout.punchout.parameters.PunchoutQOI[source]#

Bases: PunchoutBaseQOI

Quantities of Interest for Punchout (State 0).

Fields:

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, float]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.readout.punchout.parameters.Punchout1QOI[source]#

Bases: PunchoutBaseQOI

Quantities of Interest for Punchout (State 1).

Fields:

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, float]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.readout.punchout.parameters.Punchout2QOI[source]#

Bases: PunchoutBaseQOI

Quantities of Interest for Punchout (State 2).

Fields:

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, float]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Module containing classes that analyse data from a punchout experiment.

For each readout pulse amplitude, the swept resonator trace is fitted with the same ResonatorSpectroscopyAnalysis used by the plain resonator_spectroscopy node — a punchout amplitude slice isn’t a different kind of resonator sweep, so it doesn’t need special-cased fitting. Two end point methods are supported, selected by PunchoutParameters.bin_mode:

  • Frequency shift (bin_mode="average_append"): the amplitude at which the fitted resonator frequency starts to shift away from its low-power value marks the punchout end point, and a scaled fraction of that amplitude is returned as the operating readout amplitude.

  • Circularity (bin_mode="append"): the amplitude at which the single-shot IQ cloud at the resonator dip stops being circular (i.e. state discrimination starts to bias the resonator fit) marks the end point. This requires single-shot acquisitions (a shot_index dimension in the raw dataset).

class bragi_quantum.experiments.nodes.readout.punchout.analysis.PunchoutAnalysis(parameters, qoi_cls=None, **kwargs)[source]#

Bases: Analysis

Determine the operating readout amplitude for a qubit (unified, plotly).

Replaces the former PunchoutQubitAnalysis + PunchoutNodeAnalysis. For each readout amplitude the resonator trace is fitted (reusing ResonatorSpectroscopyAnalysis verbatim, one call per amplitude slice). Which end point method then runs — _find_endpoint_frequency_shift() or _find_endpoint_circularity() — is driven by self.parameters.bin_mode, the same way self.parameters.readout_state drives which clock the measurement targets.

Parameters:

parameters (PunchoutParameters)

element_kind: str = 'qubit'#
parameters: PunchoutParameters#
plot_title()[source]#

Title for this element’s (sub)plot. Override per node if desired.

Return type:

str

compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

BaseQoi

add_traces(fig, row=1, col=1)[source]#

2-D colour map of normalized |S21| vs (readout amplitude, frequency), with the fitted resonator frequencies and selected operating point.

Parameters:
Return type:

None

list_plots()[source]#

Names of the plots this analysis can render. Override for multi-plot nodes.

Return type:

list[str]

IQ-cloud circularity tools for the punchout node’s circularity end point (PunchoutParameters.bin_mode="append").

A cloud is the set of single-shot (I, Q) readings taken at one readout amplitude, at that amplitude’s fitted resonator dip. While the readout stays in the linear regime the cloud is round; once it starts discriminating qubit states it stretches, which also biases the resonator fit.

bragi_quantum.experiments.nodes.readout.punchout.circularity.iq_clouds_at_dip(raw_dataset, data_var, amplitude_coord, frequency_coord, amplitudes, resonator_analyses)[source]#

Return the (N, 2) single-shot IQ cloud at each amplitude’s resonator dip.

The dip is the minimum-|S21| frequency bin of that amplitude’s resonator fit (ana.min_freq_data). An entry is None where the fit failed or the shots could not be selected, so callers can skip that amplitude.

Parameters:
  • raw_dataset (Dataset)

  • data_var (str)

  • amplitude_coord (str)

  • frequency_coord (str)

  • amplitudes (list[float])

  • resonator_analyses (list)

Return type:

list[ndarray | None]

bragi_quantum.experiments.nodes.readout.punchout.circularity.compute_circularities(clouds)[source]#

Circularity of each IQ cloud: min/max covariance eigenvalue.

1.0 is a perfectly round (isotropic) cloud and 0.0 a fully elongated one; nan marks a cloud that is missing or too degenerate to fit.

Parameters:

clouds (list[ndarray | None])

Return type:

list[float]

bragi_quantum.experiments.nodes.readout.punchout.circularity.find_endpoint_by_circularity(detected_amplitudes, detected_frequencies, circularities, circularity_threshold, qubit)[source]#

Return the last (index, amplitude, frequency) before circularity drops.

Considers all amplitudes, so a transient dip in circularity (noise) does not end the search early: the end point is the highest amplitude still at or above circularity_threshold — more power is better as long as the readout stays in the linear regime. Falls back to the highest available circularity when nothing reaches the threshold, and returns (None, None, None) when no amplitude has a usable fit at all.

Parameters:
Return type:

tuple[int | None, float | None, float | None]

bragi_quantum.experiments.nodes.readout.punchout.circularity.circularity_figure(amplitudes, circularities, circularity_threshold, end_point_index)[source]#

Standalone circularity-vs-amplitude chart: the threshold line and, if an end point was found, a green star marking it.

Parameters:
bragi_quantum.experiments.nodes.readout.punchout.circularity.point_clouds_grid_figure(clouds, amplitudes, end_point_index)[source]#

One IQ-cloud scatter (with a 99% confidence ellipse) per amplitude whose resonator fit succeeded; the amplitude selected as the circularity end point is outlined in green.

Axis titles/tick labels are shown only on the grid’s outer edge — with many amplitudes, repeating them on every cell just overlaps into noise.

Parameters:

Readout frequency optimization#

Node implementation for readout-frequency optimization.

class bragi_quantum.experiments.nodes.readout.ro_frequency_optimization.node.ROTwoStateFrequencyOptimizationNode(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.readout.ro_frequency_optimization.parameters.ROTwoStateFrequencyOptimizationQOI'>)[source]#

Bases: ScheduleQubitNode

Execution node for the 2-state (|0>, |1>) readout-frequency optimization.

The prepared states are passed as a samplespace (qubit_states); the measurement derives the optimization clock from them, so no qubit_state schedule keyword is needed (it would clash with the multi-state sweep).

Parameters:
measurement_cls#

alias of ROFrequencyOptimizationMeasurement

analysis_cls#

alias of ROTwoStateFrequencyOptimizationAnalysis

parameters: ROFrequencyOptimizationParameters#
class bragi_quantum.experiments.nodes.readout.ro_frequency_optimization.node.ROThreeStateFrequencyOptimizationNode(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.readout.ro_frequency_optimization.parameters.ROThreeStateFrequencyOptimizationQOI'>)[source]#

Bases: ScheduleQubitNode

Execution node for the 3-state (|0>, |1>, |2>) readout-frequency optimization.

Parameters:
measurement_cls#

alias of ROFrequencyOptimizationMeasurement

analysis_cls#

alias of ROThreeStateFrequencyOptimizationAnalysis

parameters: ROFrequencyOptimizationParameters#
pydantic model bragi_quantum.experiments.nodes.readout.ro_frequency_optimization.parameters.ROFrequencyOptimizationParameters[source]#

Bases: BaseParameters

Parameters for readout-frequency optimization nodes.

Fields:
field samples: int | None = 100#

Number of readout-frequency samples.

field half_width: float | None = 1000000.0#

Half-width of the frequency sweep window in Hz.

field repetitions: int = 1024#

Number of repetitions (averages) per point.

invalid_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
pydantic model bragi_quantum.experiments.nodes.readout.ro_frequency_optimization.parameters.ROTwoStateFrequencyOptimizationQOI[source]#

Bases: BaseQoi

Quantities of Interest for the readout 2-state frequency optimization.

Fields:
field frequency: float = 0.0#
to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, float]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.readout.ro_frequency_optimization.parameters.ROThreeStateFrequencyOptimizationQOI[source]#

Bases: BaseQoi

Quantities of Interest for the readout 3-state frequency optimization.

Fields:
field frequency: float = 0.0#
to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, float]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Module containing classes that select the optimal readout frequency.

The resonator is probed with the qubit in each prepared state; the optimal frequency maximises the |0>/|1> IQ separation (2-state) or the area of the |0>,|1>,|2> triangle (3-state).

class bragi_quantum.experiments.nodes.readout.ro_frequency_optimization.analysis.ROTwoStateFrequencyOptimizationAnalysis(parameters, qoi_cls=None, **kwargs)[source]#

Bases: Analysis

Selects the readout frequency maximising the |0>/|1> IQ-plane separation (unified, plotly).

Replaces the former ROTwoStateFrequencyOptimizationQubitAnalysis + ROTwoStateFrequencyOptimizationNodeAnalysis.

Parameters:

qoi_cls (type[ROTwoStateFrequencyOptimizationQOI] | None)

element_kind: str = 'qubit'#
plot_title()[source]#

Title for this element’s (sub)plot. Override per node if desired.

Return type:

str

compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

BaseQoi

add_traces(fig, row=1, col=1)[source]#

|0> and |1> resonator traces on the IQ plane; the point maximising their separation is marked.

Parameters:
Return type:

None

support_figures()[source]#

|S21| magnitude and phase vs frequency for both traces, with the optimal frequency marked.

class bragi_quantum.experiments.nodes.readout.ro_frequency_optimization.analysis.ROThreeStateFrequencyOptimizationAnalysis(parameters, qoi_cls=None, **kwargs)[source]#

Bases: ROTwoStateFrequencyOptimizationAnalysis

Selects the readout frequency maximising the area of the |0>,|1>,|2> triangle in the IQ plane (unified, plotly).

Replaces the former ROThreeStateFrequencyOptimizationQubitAnalysis + ROThreeStateFrequencyOptimizationNodeAnalysis.

Parameters:

qoi_cls (type[ROThreeStateFrequencyOptimizationQOI] | None)

compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

BaseQoi

add_traces(fig, row=1, col=1)[source]#

|S21| magnitude of each state vs frequency, with the (rescaled) triangle area and its maximum overlaid — the node’s only plot.

Parameters:
Return type:

None

support_figures()[source]#

|S21| magnitude and phase vs frequency for both traces, with the optimal frequency marked.

Readout amplitude optimization#

Node implementations for readout amplitude optimisation.

Uses single-shot acquisitions (bin_mode=”append”) to build IQ clouds at each swept RO amplitude, then applies LDA to find the amplitude that maximises state-assignment fidelity.

class bragi_quantum.experiments.nodes.readout.ro_amplitude_optimization.node.ROTwoStateAmplitudeOptimizationNode(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.readout.ro_amplitude_optimization.parameters.ROTwoStateAmplitudeOptimizationQOI'>)[source]#

Bases: ScheduleQubitNode

Execution node for the 2-state (|0>, |1>) RO amplitude optimisation.

Sweeps the RO pulse amplitude around the punchout value, collecting single-shot IQ data at each point. LDA selects the amplitude that maximises assignment fidelity.

Parameters:
measurement_cls#

alias of ROAmplitudeOptimizationMeasurement

analysis_cls#

alias of ROTwoStateAmplitudeOptimizationAnalysis

parameters: ROAmplitudeOptimizationParameters#
class bragi_quantum.experiments.nodes.readout.ro_amplitude_optimization.node.ROThreeStateAmplitudeOptimizationNode(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.readout.ro_amplitude_optimization.parameters.ROThreeStateAmplitudeOptimizationQOI'>)[source]#

Bases: ScheduleQubitNode

Execution node for the 3-state (|0>, |1>, |2>) RO amplitude optimisation.

Parameters:
measurement_cls#

alias of ROAmplitudeOptimizationMeasurement

analysis_cls#

alias of ROThreeStateAmplitudeOptimizationAnalysis

parameters: ROAmplitudeOptimizationParameters#

Parameters and QOI classes for readout amplitude optimisation.

pydantic model bragi_quantum.experiments.nodes.readout.ro_amplitude_optimization.parameters.ROAmplitudeOptimizationParameters[source]#

Bases: BaseParameters

Configuration for readout amplitude optimisation nodes.

Fields:
field repetitions: int = 1024#
field amplitude_bins: int = 30#
field amplitude_lower_fraction: float = 0.25#
field amplitude_upper_fraction: float = 1.2#
invalid_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
pydantic model bragi_quantum.experiments.nodes.readout.ro_amplitude_optimization.parameters.ROTwoStateAmplitudeOptimizationQOI[source]#

Bases: BaseQoi

QOI for the 2-state (|0>, |1>) RO amplitude optimisation.

Fields:
field amplitude: float = 0.0#
field rotation: float = 0.0#
field threshold: float = 0.0#
field fidelity: float = 0.0#
field lda_coef_0: float = 0.0#
field lda_coef_1: float = 0.0#
field lda_intercept: float = 0.0#
field center_I_0: float = 0.0#
field center_Q_0: float = 0.0#
field center_I_1: float = 0.0#
field center_Q_1: float = 0.0#
to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, Any]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.readout.ro_amplitude_optimization.parameters.ROThreeStateAmplitudeOptimizationQOI[source]#

Bases: BaseQoi

QOI for the 3-state (|0>, |1>, |2>) RO amplitude optimisation.

Fields:
field amplitude: float = 0.0#
field centroid_I: float = 0.0#
field centroid_Q: float = 0.0#
field omega_01: float = 0.0#
field omega_12: float = 0.0#
field omega_20: float = 0.0#
field inv_cm_opt: str = ''#
field fidelity: float = 0.0#
to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, Any]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Analysis classes for readout amplitude optimisation.

For each swept RO amplitude, an LDA classifier is fitted to the single-shot IQ cloud (states |0> and |1>, or |0>, |1>, |2>). The optimal amplitude is the one that maximises the trace-normalised confusion-matrix diagonal (assignment fidelity).

Dataset coordinate expectations (after configure_dataset):
  • one coord whose name contains “amplitudes” → amplitude sweep axis

  • one coord whose name contains “state” → prepared qubit state

  • one coord whose name contains “shot” → individual shot index

class bragi_quantum.experiments.nodes.readout.ro_amplitude_optimization.analysis.ROAmplitudeOptimizationAnalysis(parameters, qoi_cls=None, **kwargs)[source]#

Bases: Analysis

Shared per-qubit LDA machinery for RO amplitude optimisation (unified, plotly).

Replaces the former ROAmplitudeOptimizationQubitAnalysis + RO{Two,Three}StateAmplitudeOptimizationNodeAnalysis. Subclasses (ROTwoStateAmplitudeOptimizationAnalysis / ROThreeStateAmplitudeOptimizationAnalysis) implement the state-count-specific parts of fit() and the IQ-cloud support figure.

element_kind: str = 'qubit'#
plot_title()[source]#

Title for this element’s (sub)plot. Override per node if desired.

Return type:

str

IQ(index)[source]#

Extract (N_shots, 2) IQ array for the amplitude at position index.

Parameters:

index (int)

Return type:

ndarray

run_initial_fitting()[source]#

Fit LDA for every amplitude and record fidelity + confusion matrix.

add_traces(fig, row=1, col=1)[source]#

Add this element’s plotly traces (and axis titles) to fig at (row, col).

Parameters:
Return type:

None

class bragi_quantum.experiments.nodes.readout.ro_amplitude_optimization.analysis.ROTwoStateAmplitudeOptimizationAnalysis(parameters, qoi_cls=None, **kwargs)[source]#

Bases: ROAmplitudeOptimizationAnalysis

Optimal RO amplitude for the 2-state (|0>, |1>) discrimination (unified, plotly).

Replaces the former ROTwoStateAmplitudeOptimizationQubitAnalysis + ROTwoStateAmplitudeOptimizationNodeAnalysis.

Parameters:

qoi_cls (type[ROTwoStateAmplitudeOptimizationQOI] | None)

compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

BaseQoi

support_figures()[source]#

Extra per-element diagnostic figures as (plotly_figure, filename).

Called on each analysed element’s worker during save. Default: none. Override for nodes with 1-D projections / per-slice diagnostics.

class bragi_quantum.experiments.nodes.readout.ro_amplitude_optimization.analysis.ROThreeStateAmplitudeOptimizationAnalysis(parameters, qoi_cls=None, **kwargs)[source]#

Bases: ROAmplitudeOptimizationAnalysis

Optimal RO amplitude for the 3-state (|0>, |1>, |2>) discrimination (unified, plotly).

Replaces the former ROThreeStateAmplitudeOptimizationQubitAnalysis + ROThreeStateAmplitudeOptimizationNodeAnalysis.

Parameters:

qoi_cls (type[ROThreeStateAmplitudeOptimizationQOI] | None)

compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

BaseQoi

support_figures()[source]#

Extra per-element diagnostic figures as (plotly_figure, filename).

Called on each analysed element’s worker during save. Default: none. Override for nodes with 1-D projections / per-slice diagnostics.

Readout combined optimization#

Node implementations for readout combined amplitude and frequency optimisation.

Uses single-shot acquisitions (bin_mode=”append”) to build IQ clouds at each swept RO amplitude for each RO frequency, then applies LDA to find the amplitude and frequency that maximises state-assignment fidelity.

class bragi_quantum.experiments.nodes.readout.ro_combined_optimization.node.ROTwoStateCombinedOptimizationNode(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.readout.ro_combined_optimization.parameters.ROTwoStateCombinedOptimizationQOI'>)[source]#

Bases: _AmplitudeSweepMixin, ScheduleQubitNode

Execution node for the 2-state (|0>, |1>) RO amplitude optimisation.

Sweeps the RO pulse amplitude around the punchout value, collecting single-shot IQ data at each point. LDA selects the amplitude that maximises assignment fidelity.

Parameters:
measurement_cls#

alias of ROCombinedOptimizationMeasurement

analysis_cls#

alias of ROTwoStateCombinedOptimizationAnalysis

parameters: ROCombinedOptimizationParameters#
class bragi_quantum.experiments.nodes.readout.ro_combined_optimization.node.ROThreeStateCombinedOptimizationNode(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.readout.ro_combined_optimization.parameters.ROThreeStateCombinedOptimizationQOI'>)[source]#

Bases: _AmplitudeSweepMixin, ScheduleQubitNode

Execution node for the 3-state (|0>, |1>, |2>) RO amplitude optimisation.

Parameters:
measurement_cls#

alias of ROCombinedOptimizationMeasurement

analysis_cls#

alias of ROThreeStateCombinedOptimizationAnalysis

parameters: ROCombinedOptimizationParameters#

Parameters and QOI classes for readout amplitude optimisation.

pydantic model bragi_quantum.experiments.nodes.readout.ro_combined_optimization.parameters.ROCombinedOptimizationParameters[source]#

Bases: BaseParameters

Configuration for readout amplitude optimisation nodes.

Fields:
field amplitude_bins: int = 21#

Number of amplitude samples in the sweep.

field amplitude_lower_fraction: float = 1.0#

Lower bound of the amplitude sweep as a fraction of the nominal amplitude.

field amplitude_upper_fraction: float = 1.0#

Upper bound of the amplitude sweep as a fraction of the nominal amplitude.

field frequency_samples: int = 11#

Number of readout-frequency samples.

field frequency_half_width: float = 300000.0#

Half-width of the frequency sweep window in Hz.

field repetitions: int = 1024#

Number of repetitions (averages) per point.

field min_amplitude: float = 0.015#

Minimum readout pulse amplitude.

field max_amplitude: float = 0.2#

Maximum readout pulse amplitude.

field iq_grid_row: str | None = None#

e.g. 1; 3-5; 3,4,5

field iq_grid_col: str | None = None#

e.g. 1; 3-5; 3,4,5

invalid_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
pydantic model bragi_quantum.experiments.nodes.readout.ro_combined_optimization.parameters.ROTwoStateCombinedOptimizationQOI[source]#

Bases: BaseQoi

QOI for the 2-state (|0>, |1>) RO amplitude optimisation.

Fields:
field amplitude: float = 0.0#
field frequency: float = 0.0#
field rotation: float = 0.0#
field threshold: float = 0.0#
field fidelity: float = 0.0#
field lda_coef_0: float = 0.0#
field lda_coef_1: float = 0.0#
field lda_intercept: float = 0.0#
to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, Any]

to_redis_dict()[source]#

Convert the QOI to a dictionary suitable for Redis storage.

Return type:

dict

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.readout.ro_combined_optimization.parameters.ROThreeStateCombinedOptimizationQOI[source]#

Bases: BaseQoi

Quantity of Interest (QOI) results from the readout 3 states amplitude optimization.

Fields:
field amplitude: float = 0.0#
field frequency: float = 0.0#
field centroid_I: float = 0.0#
field centroid_Q: float = 0.0#
field omega_01: float = 0.0#
field omega_12: float = 0.0#
field omega_20: float = 0.0#
field inv_cm_opt: list[float] | None = None#
field fidelity: float = 0.0#
to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, Any]

to_redis_dict()[source]#

Convert the QOI to a dictionary suitable for Redis storage.

Return type:

dict

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Analysis classes for readout combined amplitude and frequency optimisation.

For each (amplitude, frequency) pair in the 2-D sweep, an LDA classifier is fitted to the single-shot IQ cloud (states |0> and |1>, or |0>, |1>, |2>). The optimal (amplitude, frequency) pair is the one that maximises the trace-normalised confusion-matrix diagonal (assignment fidelity).

Dataset coordinate expectations (after configure_dataset):
  • one coord whose name contains “amplitudes” → amplitude sweep axis

  • one coord whose name contains “frequencies” → frequency sweep axis

  • one coord whose name contains “state” → prepared qubit state

  • one coord whose name contains “loops” → individual shot index

class bragi_quantum.experiments.nodes.readout.ro_combined_optimization.analysis.ROCombinedOptimizationAnalysis(parameters, qoi_cls=None, **kwargs)[source]#

Bases: Analysis

Shared per-qubit LDA machinery for RO combined amplitude/frequency optimisation (unified, plotly).

Replaces the former ROCombinedOptimizationQubitAnalysis + RO{Two,Three}StateCombinedOptimizationNodeAnalysis. Subclasses (ROTwoStateCombinedOptimizationAnalysis / ROThreeStateCombinedOptimizationAnalysis) implement the state-count-specific parts of fit() and the IQ-cloud support figure.

element_kind: str = 'qubit'#
plot_title()[source]#

Title for this element’s (sub)plot. Override per node if desired.

Return type:

str

IQ(amp_index, freq_index)[source]#

Extract (N_shots, 2) IQ array for the given amplitude and frequency indices.

Parameters:
  • amp_index (int)

  • freq_index (int)

Return type:

ndarray

run_initial_fitting()[source]#

Fit LDA for every (amplitude, frequency) pair and record fidelity + confusion matrix.

store_covariance is skipped during the scan and only used when the optimal cell is re-fitted in compute_qoi.

add_traces(fig, row=1, col=1, _coloraxis=None)[source]#

Add this element’s plotly traces (and axis titles) to fig at (row, col).

Parameters:
  • row (int)

  • col (int)

  • _coloraxis (str | None)

Return type:

None

class bragi_quantum.experiments.nodes.readout.ro_combined_optimization.analysis.ROTwoStateCombinedOptimizationAnalysis(parameters, qoi_cls=None, **kwargs)[source]#

Bases: ROCombinedOptimizationAnalysis

Optimal RO amplitude/frequency for the 2-state (|0>, |1>) discrimination.

Replaces the former ROTwoStateCombinedOptimizationQubitAnalysis + ROTwoStateCombinedOptimizationNodeAnalysis.

Parameters:

qoi_cls (type[ROTwoStateCombinedOptimizationQOI] | None)

compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

BaseQoi

list_plots()[source]#

Names of the plots this analysis can render. Override for multi-plot nodes.

class bragi_quantum.experiments.nodes.readout.ro_combined_optimization.analysis.ROThreeStateCombinedOptimizationAnalysis(parameters, qoi_cls=None, **kwargs)[source]#

Bases: ROCombinedOptimizationAnalysis

Optimal RO amplitude/frequency for the 3-state (|0>, |1>, |2>) discrimination.

Replaces the former ROThreeStateCombinedOptimizationQubitAnalysis + ROThreeStateCombinedOptimizationNodeAnalysis.

Parameters:

qoi_cls (type[ROThreeStateCombinedOptimizationQOI] | None)

compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

BaseQoi

list_plots()[source]#

Names of the plots this analysis can render. Override for multi-plot nodes.

Qubit-control nodes#

Qubit spectroscopy#

Node implementation for Qubit (Two-Tone) Spectroscopy.

class bragi_quantum.experiments.nodes.qubit_control.spectroscopy.node.QubitSpectroscopy(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.qubit_control.spectroscopy.parameters.QubitSpectroscopyBaseQOI'>)[source]#

Bases: ScheduleQubitNode

Execution node for performing Qubit (Two-Tone) Spectroscopy.

A single node class handles both the 0→1 and 1→2 transitions; the transition is selected by the state and transition fields in QubitSpectroscopyParameters. The analysis class and QOI class are injected at construction time, mirroring the resonator spectroscopy interface used by the orchestrator.

Parameters:
measurement_cls#

alias of TwoTonesMultidimMeasurement

analysis_cls#

alias of QubitSpectroscopyAnalysis

parameters: QubitSpectroscopyParameters#
pydantic model bragi_quantum.experiments.nodes.qubit_control.spectroscopy.parameters.QubitSpectroscopyParameters[source]#

Bases: BaseParameters

Parameters for Qubit Spectroscopy (two-tone experiment).

Fields:
invalid_variant_combinations: ClassVar[tuple[Mapping[str, Any], ...]] = (mappingproxy({'transition': '12', 'continuous_mode': True}),)#
field transition: Literal['01', '12'] = '01'#
field continuous_mode: bool = False#

Whether to drive the qubit with a continuous tone rather than a pulse. Faster and more reliable than pulsed spectroscopy, but only useable with the 0->1 transition.

field min_amplitude: float = 0.01#

Minimum spectroscopy pulse amplitude.

field max_amplitude: float = 0.05#

Maximum spectroscopy pulse amplitude.

field amplitude_bins: int = 5#

Number of amplitude steps.

field samples: int | None = 100#

Number of frequency samples.

field half_width: float | None = 5000000.0#

Half-width of the frequency sweep window in Hz.

field spec_pulse_duration: float | None = None#

Duration of the spectroscopy drive pulse in seconds. None uses the qubit’s device value (spec.spec_duration for 0->1, spec.spec_duration_12 for 1->2), or if that is unset 20 us for 0->1 and 0.5 us for 1->2. Ignored when continuous_mode is True.

Constraints:
  • gt = 0

field continuous_reset_duration: float = 2e-05#

Idle time after each measurement in continuous mode, in seconds. Continuous mode holds the drive on and so cannot reset the qubit passively the way the pulsed schedule does; this wait instead lets the readout resonator ring down (~1/kappa) so successive measurements stay statistically independent. It exists as a parameter because reset_system has no settable duration. Ignored when continuous_mode is False.

field repetitions: int | None = 600#

Number of repetitions (averages) per point.

field significance_threshold: float = 2.9#

Minimum significance (sigma) for a peak to be accepted.

resolve_spec_pulse_duration(transmon)[source]#

Return the pulse duration to use for transmon.

An explicit spec_pulse_duration wins; otherwise the transition’s duration is read from the transmon’s spec submodule, falling back to DEFAULT_SPEC_PULSE_DURATION when that is unset (NaN).

Parameters:

transmon (ExtendedTransmon)

Return type:

float

legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = (mappingproxy({'transition': '01', 'continuous_mode': True}), mappingproxy({'transition': '01', 'continuous_mode': False}), mappingproxy({'transition': '12', 'continuous_mode': False}))#
pydantic model bragi_quantum.experiments.nodes.qubit_control.spectroscopy.parameters.QubitSpectroscopyBaseQOI[source]#

Bases: BaseQoi

Base Quantities of Interest for Qubit Spectroscopy.

Fields:
field frequency: float = 0.0#
field frequency_error: float = 0.0#
field amplitude: float = 0.0#
field significance: float = 0.0#
to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, float]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.qubit_control.spectroscopy.parameters.QubitSpectroscopy01QOI[source]#

Bases: QubitSpectroscopyBaseQOI

Quantities of Interest for Qubit Spectroscopy (0→1 transition).

Fields:

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, float]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.qubit_control.spectroscopy.parameters.QubitSpectroscopy12QOI[source]#

Bases: QubitSpectroscopyBaseQOI

Quantities of Interest for Qubit Spectroscopy (1→2 transition).

Fields:

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, float]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Module containing classes that fit and plot data from a qubit (two-tone) spectroscopy experiment.

For each spectroscopy pulse amplitude, a Lorentzian + constant baseline is fitted to the 1-D frequency trace. The amplitude whose fitted peak_height is largest (i.e. the tallest peak above the baseline) is selected as the optimal operating point, and the Lorentzian center frequency is returned as the qubit frequency.

class bragi_quantum.experiments.nodes.qubit_control.spectroscopy.analysis.PeakFitResult(lorentzian_fitted_frequency=None, lorentzian_fitted_frequency_stderr=None, significance=0.0, fit_result=None, amplitude=None, raw_maximum=None)[source]#

Bases: object

Bundle the outcome of a single-trace Lorentzian peak fit.

lorentzian_fitted_frequency/lorentzian_fitted_frequency_stderr are None when no peak was accepted; fit_result is the raw lmfit ModelResult kept for slice diagnostics. amplitude/raw_maximum are filled in by the caller for 2-D sweeps, where each slice corresponds to one spectroscopy pulse amplitude.

Parameters:
  • lorentzian_fitted_frequency (float | None)

  • lorentzian_fitted_frequency_stderr (float | None)

  • significance (float)

  • fit_result (ModelResult | None)

  • amplitude (float | None)

  • raw_maximum (float | None)

lorentzian_fitted_frequency: float | None = None#
lorentzian_fitted_frequency_stderr: float | None = None#
significance: float = 0.0#
fit_result: ModelResult | None = None#
amplitude: float | None = None#
raw_maximum: float | None = None#
class bragi_quantum.experiments.nodes.qubit_control.spectroscopy.analysis.QubitSpectroscopyAnalysis(parameters, qoi_cls=None, **kwargs)[source]#

Bases: Analysis

Fit data from a qubit (two-tone) spectroscopy experiment (unified, plotly).

Iterates over the amplitude sweep axis, applies a significance-threshold peak-finder on each 1-D frequency trace, and picks the amplitude whose trace carries the highest significance as the calibrated operating point. A single class handles both the 0→1 and 1→2 transitions, selected by parameters.transition. Replaces the former QubitSpectroscopyQubitAnalysis / QubitSpectroscopy12QubitAnalysis + QubitSpectroscopyNodeAnalysis.

Parameters:
element_kind: str = 'qubit'#
parameters: QubitSpectroscopyParameters#
plot_title()[source]#

Title for this element’s (sub)plot. Override per node if desired.

Return type:

str

qubit_spectroscopy_analysis()[source]#

Executes the peak-finding routine on the dataset populated by the abstract layer. Supports both a 2-D sweep (frequency × amplitude) and a 1-D sweep (frequency only).

Return type:

None

create_qoi_object()[source]#
Return type:

QubitSpectroscopyBaseQOI

compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

BaseQoi

add_traces(fig, row=1, col=1)[source]#

Add this element’s plotly traces (and axis titles) to fig at (row, col).

Parameters:
Return type:

None

list_plots()[source]#

Names of the plots this analysis can render. Override for multi-plot nodes.

Return type:

list[str]

support_figures()[source]#

The per-amplitude slices grid, saved to disk.

Only produced for the 2-D (frequency x amplitude) sweep — the 1-D case has nothing beyond what the main plot already shows.

Return type:

list[tuple[Figure, str]]

Rabi oscillations#

Node implementation for Rabi and N-Rabi oscillation calibration.

class bragi_quantum.experiments.nodes.qubit_control.rabi_oscillations.node.RabiOscillations(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.qubit_control.rabi_oscillations.parameters.Rabi01QOI'>)[source]#

Bases: ScheduleQubitNode

Execution node for performing Rabi oscillations.

A single node class handles both the 0->1 and 1->2 transitions; the transition is selected by the transition field in RabiParameters.

Parameters:
measurement_cls#

alias of RabiOscillationsMeasurement

analysis_cls#

alias of RabiAnalysis

parameters: RabiParameters#
class bragi_quantum.experiments.nodes.qubit_control.rabi_oscillations.node.NRabiOscillations(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.qubit_control.rabi_oscillations.parameters.NRabi01QOI'>)[source]#

Bases: ScheduleQubitNode

Execution node for performing N-Rabi (amplitude-correction) oscillations.

Sweeps a small correction to the current amp180 over several X-pulse repetition counts to amplify the amplitude error. The transition is selected by the transition field in NRabiParameters.

Parameters:
measurement_cls#

alias of NRabiOscillationsMeasurement

analysis_cls#

alias of NRabiAnalysis

parameters: NRabiParameters#
pydantic model bragi_quantum.experiments.nodes.qubit_control.rabi_oscillations.parameters.RabiParameters[source]#

Bases: BaseParameters

Parameters for Rabi oscillation calibration.

The transition field selects the transition: transition="01" drives 0->1 (the X gate amplitude, rxy.amp180), transition="12" drives 1->2 (r12.ef_amp180).

Fields:
field transition: Literal['01', '12'] = '01'#
field min_amplitude: float = -0.9#

Minimum drive amplitude.

field max_amplitude: float = 0.9#

Maximum drive amplitude.

field amplitude_bins: int = 81#

Number of amplitude steps.

field repetitions: int = 1024#

Number of repetitions (averages) per point.

field scaled_uncertainty_analysis_threshold: float = 0.02#

Maximum scaled fit uncertainty for a successful analysis.

field pi_amplitude_analysis_threshold: float = 0.95#

Maximum pi-pulse amplitude for a successful analysis.

invalid_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = (mappingproxy({'transition': '01'}), mappingproxy({'transition': '12'}))#
pydantic model bragi_quantum.experiments.nodes.qubit_control.rabi_oscillations.parameters.NRabiParameters[source]#

Bases: RabiParameters

Parameters for N-Rabi (amplitude-correction) calibration.

Fields:
field min_amplitude: float = -0.09#

Minimum amplitude correction.

field max_amplitude: float = 0.09#

Maximum amplitude correction.

field amplitude_bins: int = 50#

Number of amplitude-correction steps.

field x_repetitions: list[int] [Optional]#

Numbers of X pulses applied per correction trace.

field sinusoidal_r2_threshold: float = 0.8#

Minimum per-slice R² for a slice to enter the joint fit.

field joint_r2_threshold: float = 0.75#

Minimum mean R² of the joint sine fit across all valid slices. Slightly more permissive than the per-slice threshold because the shared correction introduces a constraint that no single slice can individually optimise away.

invalid_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = (mappingproxy({'transition': '01'}), mappingproxy({'transition': '12'}))#
pydantic model bragi_quantum.experiments.nodes.qubit_control.rabi_oscillations.parameters.RabiBaseQOI[source]#

Bases: BaseQoi

Base Quantities of Interest for Rabi oscillations.

Fields:
field amplitude: float = 0.0#
field amplitude_error: float = 0.0#
model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.qubit_control.rabi_oscillations.parameters.Rabi01QOI[source]#

Bases: RabiBaseQOI

Quantities of Interest for Rabi oscillations (0->1 transition).

Fields:

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, float]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.qubit_control.rabi_oscillations.parameters.Rabi12QOI[source]#

Bases: RabiBaseQOI

Quantities of Interest for Rabi oscillations (1->2 transition).

Fields:

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, float]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.qubit_control.rabi_oscillations.parameters.NRabiBaseQOI[source]#

Bases: RabiBaseQOI

Base Quantities of Interest for N-Rabi oscillations.

Fields:
field correction: float = 0.0#
field correction_error: float = 0.0#
model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.qubit_control.rabi_oscillations.parameters.NRabi01QOI[source]#

Bases: NRabiBaseQOI

Quantities of Interest for N-Rabi oscillations (0->1 transition).

Fields:

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, float]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.qubit_control.rabi_oscillations.parameters.NRabi12QOI[source]#

Bases: NRabiBaseQOI

Quantities of Interest for N-Rabi oscillations (1->2 transition).

Fields:

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, float]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Module containing classes that model, fit and plot data from Rabi and N-Rabi experiments.

  • RabiQubitAnalysis fits a cosine to a 1-D amplitude sweep and returns the pi-pulse amplitude.

  • NRabiQubitAnalysis fits a joint 2-D cosine model to all repetition slices simultaneously, constraining each slice to frequency r·f₀ with a shared shift (the optimal amplitude correction). The joint fit quality naturally detects failures without per-slice thresholds or combinatorial root selection.

class bragi_quantum.experiments.nodes.qubit_control.rabi_oscillations.analysis.RabiAnalysis(parameters, qoi_cls=None)[source]#

Bases: Analysis

Fit a cosine to Rabi oscillation data (unified, parameter-driven).

Replaces the former RabiQubitAnalysis (per-qubit) + RabiNodeAnalysis (node-level) pair. Analyse one qubit with analyse_element(dataset, "q06") or every qubit in parameters.qubits with run(dataset).

Parameters:
element_kind: str = 'qubit'#
plot_title()[source]#

Title for this element’s (sub)plot. Override per node if desired.

Return type:

str

compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

BaseQoi

add_traces(fig, row=1, col=1)[source]#

Add this element’s plotly traces (and axis titles) to fig at (row, col).

Parameters:
Return type:

None

class bragi_quantum.experiments.nodes.qubit_control.rabi_oscillations.analysis.NRabiAnalysis(parameters, qoi_cls=None, **kwargs)[source]#

Bases: Analysis

Analysis of N-Rabi oscillation data that determines the optimal microwave amplitude correction for qubit control (unified, plotly).

Fits a joint 2-D model to all repetition slices simultaneously, constraining slice r to frequency r·f₀ with a shared shift parameter. The shift IS the correction — no root enumeration or combinatorial selection needed. Failed experiments (data that does not satisfy the r·f₀ scaling) are detected by the joint fit failing to converge or producing undefined errorbars. Replaces the former NRabiQubitAnalysis + NRabiNodeAnalysis split.

Parameters:
element_kind: str = 'qubit'#
parameters: NRabiParameters#
compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

BaseQoi

plot_title()[source]#

Title for this element’s (sub)plot. Override per node if desired.

Return type:

str

add_traces(fig, row=1, col=1)[source]#

Add this element’s plotly traces (and axis titles) to fig at (row, col).

Parameters:
Return type:

None

support_figures()[source]#

Per-repetition 1-D cuts with their joint-fit sine overlays.

Ramsey fringes#

Node implementation for Ramsey-fringes (detuning) calibration.

class bragi_quantum.experiments.nodes.qubit_control.ramsey_fringes.node.RamseyFringes(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.qubit_control.ramsey_fringes.parameters.Ramsey01QOI'>)[source]#

Bases: ScheduleQubitNode

Execution node for performing Ramsey-fringes (detuning) calibration.

A single node class handles both the 0->1 and 1->2 transitions; the transition is selected by the transition field in RamseyParameters.

Parameters:
measurement_cls#

alias of RamseyDetuningsMeasurement

analysis_cls#

alias of RamseyDetuningsAnalysis

parameters: RamseyParameters#
pydantic model bragi_quantum.experiments.nodes.qubit_control.ramsey_fringes.parameters.RamseyParameters[source]#

Bases: BaseParameters

Parameters for Ramsey-fringes (detuning) calibration.

The transition field selects the transition: transition="01" corrects f01, transition="12" corrects f12.

Fields:
field transition: Literal['01', '12'] = '01'#
field ramsey_delays: list[float] [Optional]#

Delays between the two pi/2 pulses, in seconds.

field artificial_detunings: list[float] [Optional]#

Artificial detunings applied per Ramsey trace, in Hz.

field repetitions: int = 1024#

Number of repetitions (averages) per point.

field sequence: Literal['x90_x90', 'x90_y90'] = 'x90_x90'#

Ramsey pulse sequence run: ‘x90_x90’ or ‘x90_y90’.

field analysis_sequence: Literal['x90_x90', 'x90_y90'] | None = None#

Override which fit strategy to use, independent of sequence — e.g. to force the sign-agnostic folded fit on data whose recorded sequence is missing or unknown. Falls back to sequence when unset.

field min_r_squared_detune_fit: float = 0.85#

Minimum R^2 for a per-detuning Ramsey fit to be accepted.

field minimum_relative_error_from_fits: float = 0.02#

Floor on the relative error of each fitted detuning.

field min_r_squared_line_fit: float = 0.9#

Minimum R^2 (coefficient of determination, fitted vs. artificial detuning) accepted for the linear detuning fit. Unlike reduced chi-squared, R^2 doesn’t depend on the per-point error floor, so its scale is fixed regardless of qubit/detuning spread.

invalid_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = (mappingproxy({'transition': '01', 'sequence': 'x90_x90'}), mappingproxy({'transition': '01', 'sequence': 'x90_y90'}), mappingproxy({'transition': '12', 'sequence': 'x90_x90'}), mappingproxy({'transition': '12', 'sequence': 'x90_y90'}))#
pydantic model bragi_quantum.experiments.nodes.qubit_control.ramsey_fringes.parameters.RamseyBaseQOI[source]#

Bases: BaseQoi

Base Quantities of Interest for Ramsey fringes.

Fields:
field frequency: float = 0.0#
field frequency_error: float = 0.0#
field chi2: float = 0.0#
field r_squared: float = 0.0#

Coefficient of determination; gates is_successful.

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.qubit_control.ramsey_fringes.parameters.Ramsey01QOI[source]#

Bases: RamseyBaseQOI

Quantities of Interest for Ramsey fringes (0->1 transition).

Fields:

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, float]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.qubit_control.ramsey_fringes.parameters.Ramsey12QOI[source]#

Bases: RamseyBaseQOI

Quantities of Interest for Ramsey fringes (1->2 transition).

Fields:

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, float]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Module containing classes that fit and plot data from a Ramsey-fringes experiment.

For each artificial detuning a damped sinusoid is fitted to the delay trace to extract its Ramsey frequency; a linear fit of fitted-vs-artificial detuning then gives the frequency correction (its zero crossing).

class bragi_quantum.experiments.nodes.qubit_control.ramsey_fringes.analysis.RamseyDetuningsAnalysis(parameters, qoi_cls=None, **kwargs)[source]#

Bases: Analysis

Extract the frequency correction for one qubit (unified, plotly).

For each artificial detuning a damped sinusoid is fitted to the delay trace to extract its Ramsey frequency; a linear fit of fitted-vs-artificial detuning then gives the frequency correction (its zero crossing). Replaces the former RamseyDetuningsQubitAnalysis + RamseyDetuningsNodeAnalysis.

Parameters:
element_kind: str = 'qubit'#
parameters: RamseyParameters#
plot_title()[source]#

Title for this element’s (sub)plot. Override per node if desired.

Return type:

str

compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

BaseQoi

add_traces(fig, row=1, col=1)[source]#

Add this element’s plotly traces (and axis titles) to fig at (row, col).

Parameters:
Return type:

None

list_plots()[source]#

Names of the plots this analysis can render. Override for multi-plot nodes.

Return type:

list[str]

support_figures()[source]#

One per-detuning Ramsey-fit subplot, with R^2 and fitted detuning.

Motzoi / DRAG parameter#

Node implementation for Motzoi (DRAG beta) calibration.

class bragi_quantum.experiments.nodes.qubit_control.motzoi_parameter.node.MotzoiParameter(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.qubit_control.motzoi_parameter.parameters.Motzoi01QOI'>)[source]#

Bases: ScheduleQubitNode

Execution node for performing Motzoi (DRAG beta) calibration.

A single node class handles both the 0->1 and 1->2 transitions; the transition is selected by the transition field in MotzoiParameters.

Parameters:
measurement_cls#

alias of MotzoiMeasurement

analysis_cls#

alias of MotzoiAnalysis

parameters: MotzoiParameters#
pydantic model bragi_quantum.experiments.nodes.qubit_control.motzoi_parameter.parameters.MotzoiParameters[source]#

Bases: BaseParameters

Parameters for Motzoi (DRAG beta) calibration.

The transition field selects which DRAG coefficient is calibrated: transition="01" corrects rxy.beta, transition="12" r12.ef_beta.

Fields:
field transition: Literal['01', '12'] = '01'#
field min_motzoi: float = -2e-09#

Minimum motzoi value.

field max_motzoi: float = 2e-09#

Maximum motzoi value.

field motzoi_bins: int = 51#

Number of motzoi steps.

field repetitions: int = 1024#

Number of repetitions (averages) per point.

invalid_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = (mappingproxy({'transition': '01'}), mappingproxy({'transition': '12'}))#
pydantic model bragi_quantum.experiments.nodes.qubit_control.motzoi_parameter.parameters.MotzoiBaseQOI[source]#

Bases: BaseQoi

Base Quantities of Interest for Motzoi.

Fields:
field motzoi: float = 0.0#
field motzoi_error: float = 0.0#
model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.qubit_control.motzoi_parameter.parameters.Motzoi01QOI[source]#

Bases: MotzoiBaseQOI

Quantities of Interest for Motzoi (0->1 transition).

Fields:

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, float]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.qubit_control.motzoi_parameter.parameters.Motzoi12QOI[source]#

Bases: MotzoiBaseQOI

Quantities of Interest for Motzoi (1->2 transition).

Fields:

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, float]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Module containing classes that fit and plot data from a Motzoi (DRAG beta) calibration experiment.

For each motzoi value two complementary circuits are measured (X.Y90 and Y.X90). The readout magnitude of each circuit varies ~linearly with the motzoi parameter; the optimal beta is the intersection of the two fitted lines.

class bragi_quantum.experiments.nodes.qubit_control.motzoi_parameter.analysis.MotzoiAnalysis(parameters, qoi_cls=None, **kwargs)[source]#

Bases: Analysis

Extract the optimal motzoi (DRAG beta) for a qubit (unified, plotly).

Two complementary circuits (X.Y90, Y.X90) each vary ~linearly with the motzoi parameter; the optimal beta is the intersection of the two fitted lines. Replaces the former MotzoiQubitAnalysis + MotzoiNodeAnalysis.

Parameters:
element_kind: str = 'qubit'#
parameters: MotzoiParameters#
plot_title()[source]#

Title for this element’s (sub)plot. Override per node if desired.

Return type:

str

compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

BaseQoi

add_traces(fig, row=1, col=1)[source]#

Add this element’s plotly traces (and axis titles) to fig at (row, col).

Parameters:
Return type:

None

support_figures()[source]#

One figure per qubit: the two circuit fits side by side.

Coupler nodes#

Shared by several of the nodes below: the coupler’s CZ transition frequency (the detuning between the \(|11\rangle\) state and the targeted \(|20\rangle\)/\(|02\rangle\) state), preferring a value saved to Redis by cz_currents_from_spectroscopies and otherwise computed from the qubits’ calibrated clock frequencies.

Shared CZ transition frequency logic for cz_parametrization and cz_chevron.

The CZ transition frequency (Hz) is the detuning between the \(|11\rangle\) state and the targeted \(|20\rangle\) / \(|02\rangle\) state, computed from the qubits’ calibrated 01/12 clock frequencies. cz_currents_from_spectroscopies computes and stores this value on the coupler’s Redis hash (fields cz_transition_frequency_20 / cz_transition_frequency_02); consumers should prefer that stored value and only fall back to recomputing it live from the device when Redis has nothing stored yet (e.g. cz_currents_from_spectroscopies has never run for that coupler).

bragi_quantum.experiments.nodes.coupler.cz_transition_frequency.compute_transition_frequency(device, coupler, cz_transition)[source]#

Raw (unrounded) CZ transition frequency (Hz) for coupler, computed from the qubits’ current clock frequencies on device.

Parameters:
  • coupler (str)

  • cz_transition (str)

Return type:

float

bragi_quantum.experiments.nodes.coupler.cz_transition_frequency.get_cz_transition_frequency(device, redis_connection, coupler, cz_transition, cz_half_frequency_wp=False)[source]#

CZ transition frequency (Hz) for coupler, preferring the value last saved to Redis by cz_currents_from_spectroscopies and falling back to computing it live from the device’s clock frequencies if Redis has nothing stored for cz_transition.

Parameters:
  • redis_connection (Any | None)

  • coupler (str)

  • cz_transition (str)

  • cz_half_frequency_wp (bool)

Return type:

float

Resonator spectroscopy vs. current#

Node implementation for Resonator Spectroscopy vs coupler DC current.

Ported from tergite-autocalibration (ResonatorSpectroscopyVsCurrentNode).

class bragi_quantum.experiments.nodes.coupler.resonator_spectroscopy_vs_current.node.ResonatorSpectroscopyVsCurrent(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.coupler.resonator_spectroscopy_vs_current.parameters.ResonatorSpectroscopyVsCurrentQOI'>)[source]#

Bases: ExternalParameterFixedScheduleCouplerNode

Resonator spectroscopy on both qubits of each coupler while sweeping the coupler’s DC bias current via the SPI rack.

The resonator schedule is compiled once; for every current in the external samplespace the coupler DACs are ramped and the schedule is re-executed. The analysis tracks the fitted resonator frequency versus current and reports the currents at which the coupler crosses the resonator.

Parameters:
measurement_cls#

alias of ResonatorSpectroscopyMeasurement

analysis_cls#

alias of ResonatorSpectroscopyVsCurrentAnalysis

parameters: ResonatorSpectroscopyVsCurrentParameters#
property transmons: dict[str, ExtendedTransmon]#

The coupled qubits’ transmons; measured (and read out) by this node.

pre_measurement_operation(reduced_ext_space)[source]#

Ramp the coupler DACs to this iteration’s currents before measuring.

Parameters:

reduced_ext_space (dict[str, Any])

Return type:

None

final_operation()[source]#

Ramp all swept coupler DACs back to zero after the sweep.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.coupler.resonator_spectroscopy_vs_current.parameters.ResonatorSpectroscopyVsCurrentParameters[source]#

Bases: ResonatorSpectroscopyParameters

Parameters for Resonator Spectroscopy vs coupler DC current.

Extends the plain resonator spectroscopy parameters with the external DC-current sweep applied to each coupler and the thresholds used by the crossing-current detection. Ported from tergite-autocalibration (ResonatorSpectroscopyVsCurrentNode).

Fields:
field min_current: float = -0.001#

Start of the DC-current sweep in Amps.

field max_current: float = 0.001#

End (exclusive) of the DC-current sweep in Amps.

field current_step: float = 0.0001#

Step of the DC-current sweep in Amps.

field crossing_threshold: float = 30000.0#

Minimum resonator frequency jump (Hz) between consecutive detected points to count as a coupler crossing.

field spurious_threshold: float = 4000.0#

Maximum frequency difference (Hz) between the neighbours of a missing point for it to be filled in as a spurious gap.

field min_crossing_interval: float = 0.0005#

Minimum current span (A) a group of jumps must cover before it is collapsed into a single crossing current.

invalid_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = (mappingproxy({'readout_state': 0}), mappingproxy({'readout_state': 1}), mappingproxy({'readout_state': 2}))#
pydantic model bragi_quantum.experiments.nodes.coupler.resonator_spectroscopy_vs_current.parameters.ResonatorSpectroscopyVsCurrentQOI[source]#

Bases: BaseQoi

Quantities of Interest for Resonator Spectroscopy vs current on one coupler.

Holds, for each of the coupler’s two qubits, the list of DC currents at which the coupler crosses the readout resonator.

Fields:
field crossing_currents: dict[str, list[float]] [Optional]#

Mapping from qubit name to the detected resonator crossing currents in Amps.

items()[source]#

Iterate like a mapping so bragi_quantum.datalayer’s update_redis_trusted_values can inspect the QOI keys when routing coupler results.

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, list[float]]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, str]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Analysis for resonator spectroscopy as a function of coupler DC current.

Ported from tergite-autocalibration (lib/nodes/coupler/spectroscopy/analysis.py). Each coupler dataset holds a resonator spectroscopy per DC-current point for both of the coupler’s qubits; every spectroscopy is fitted individually and the fitted resonator frequency is tracked versus current. A sudden jump in the tracked frequency (or a gap where the fit fails) marks a current at which the coupler crosses the resonator — the “crossing currents” reported as this node’s QOI.

The dataset’s data variables are named after each qubit (e.g. q06, q07), not after the coupler (q06_q07) — so unlike a plain qubit/coupler analysis, an element (“q06_q07”) cannot be sliced out with the generic slice_element helper. ResonatorSpectroscopyVsCurrentAnalysis overrides analyse_element/_process to group the coupler’s two qubit variables directly, mirroring the former _group_by_coupler.

class bragi_quantum.experiments.nodes.coupler.resonator_spectroscopy_vs_current.analysis.ResonatorSpectroscopyVsCurrentAnalysis(parameters, qoi_cls=None, **kwargs)[source]#

Bases: Analysis

Runs the frequency-vs-current analysis for both qubits of one coupler and packages their crossing currents into a single QOI (unified, plotly).

Replaces the former ResonatorSpectroscopyVsCurrentQubitAnalysis + ResonatorSpectroscopyVsCurrentCouplerAnalysis + ResonatorSpectroscopyVsCurrentNodeAnalysis.

Parameters:
element_kind: str = 'coupler'#
parameters: ResonatorSpectroscopyVsCurrentParameters#
plot_title()[source]#

Title for this element’s (sub)plot. Override per node if desired.

Return type:

str

analyse_element(dataset, element)[source]#

Slice element from dataset (Dataset or path) and fit it here.

Parameters:

element (str)

Return type:

BaseQoi

compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

BaseQoi

add_traces(fig, row=1, col=1)[source]#

Both qubits’ tracked frequency-vs-current traces overlaid (main plot). The raw |S21| heatmaps and per-current fit grids move to support_figures().

The two qubits’ absolute resonator frequencies typically differ by tens/hundreds of MHz, which would swamp a shared y-axis and hide the (kHz-scale) jumps this plot exists to show — so each trace is centred on its own median frequency (failed-fit zeros excluded) and plotted in kHz deviation instead of absolute Hz.

Parameters:
Return type:

None

support_figures()[source]#

Extra per-element diagnostic figures as (plotly_figure, filename).

Called on each analysed element’s worker during save. Default: none. Override for nodes with 1-D projections / per-slice diagnostics.

Qubit spectroscopy vs. current#

Node implementation for Qubit Spectroscopy vs coupler DC current.

Ported from tergite-autocalibration (QubitSpectroscopyVsCurrentNode).

class bragi_quantum.experiments.nodes.coupler.qubit_spectroscopy_vs_current.node.QubitSpectroscopyVsCurrent(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.coupler.qubit_spectroscopy_vs_current.parameters.QubitSpectroscopyVsCurrentQOI'>)[source]#

Bases: ExternalParameterFixedScheduleCouplerNode

Qubit (two-tone) spectroscopy on both qubits of each coupler while sweeping the coupler’s DC bias current via the SPI rack.

The spectroscopy schedule is compiled once; for every current in the external samplespace the coupler DACs are ramped and the schedule is re-executed. The analysis tracks the fitted qubit frequency versus current and reports the currents at which the coupler crosses the qubit, vetoing candidates near the resonator crossings found by resonator_spectroscopy_vs_current.

Parameters:
measurement_cls#

alias of TwoTonesMultidimMeasurement

analysis_cls#

alias of QubitSpectroscopyVsCurrentAnalysis

parameters: QubitSpectroscopyVsCurrentParameters#
property transmons: dict[str, ExtendedTransmon]#

The coupled qubits’ transmons; measured (and read out) by this node.

pre_measurement_operation(reduced_ext_space)[source]#

Ramp the coupler DACs to this iteration’s currents before measuring.

Parameters:

reduced_ext_space (dict[str, Any])

Return type:

None

final_operation()[source]#

Ramp all swept coupler DACs back to zero after the sweep.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.coupler.qubit_spectroscopy_vs_current.parameters.QubitSpectroscopyVsCurrentParameters[source]#

Bases: QubitSpectroscopyParameters

Parameters for Qubit Spectroscopy vs coupler DC current.

Extends the plain qubit (two-tone) spectroscopy parameters with the external DC-current sweep applied to each coupler and the thresholds used by the crossing-current detection.

Fields:
field min_current: float = -0.0025#

Start of the DC-current sweep in Amps.

field max_current: float = 0.0025#

End (exclusive) of the DC-current sweep in Amps.

field current_step: float = 5e-05#

Step of the DC-current sweep in Amps.

field crossing_threshold: float = 2000000.0#

Minimum qubit frequency jump (Hz) between consecutive detected points to count as a coupler crossing.

field spurious_threshold: float = 300000.0#

Maximum frequency difference (Hz) between the neighbours of a missing point for it to be filled in as a spurious gap.

field min_crossing_interval: float = 0.0003#

Minimum current span (A) a group of jumps must cover before it is collapsed into a single crossing current.

field resonator_crossing_interval: float = 0.00015#

Candidate crossings within this current distance (A) of a known resonator crossing (from resonator_spectroscopy_vs_current) are discarded as resonator artefacts.

field max_fit_workers: int | None = None#

Worker processes for the per-current-slice fits. None auto-sizes to os.cpu_count().

invalid_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = (mappingproxy({'transition': '12', 'continuous_mode': True}),)#
legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = (mappingproxy({'transition': '01', 'continuous_mode': True}), mappingproxy({'transition': '01', 'continuous_mode': False}), mappingproxy({'transition': '12', 'continuous_mode': False}))#
pydantic model bragi_quantum.experiments.nodes.coupler.qubit_spectroscopy_vs_current.parameters.QubitSpectroscopyVsCurrentQOI[source]#

Bases: BaseQoi

Quantities of Interest for Qubit Spectroscopy vs current on one coupler.

Holds, for each of the coupler’s two qubits, the list of DC currents at which the coupler crosses the qubit.

Fields:
field crossing_currents: dict[str, list[float]] [Optional]#

Mapping from qubit name to the detected qubit crossing currents in Amps.

items()[source]#

Iterate like a mapping so bragi_quantum.datalayer’s update_redis_trusted_values can inspect the QOI keys when routing coupler results.

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, list[float]]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, str]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Analysis for qubit (two-tone) spectroscopy as a function of coupler DC current.

Ported from tergite-autocalibration (lib/nodes/coupler/spectroscopy/analysis.py). Each coupler dataset holds a qubit spectroscopy per DC-current point for both of the coupler’s qubits; every spectroscopy is fitted individually and the fitted qubit frequency is tracked versus current. A sudden jump in the tracked frequency (or a gap where the fit fails) marks a current at which the coupler crosses the qubit — the “crossing currents” reported as this node’s QOI. Candidates too close to a resonator crossing (stored in Redis by resonator_spectroscopy_vs_current) are discarded as readout artefacts.

Like resonator_spectroscopy_vs_current, the dataset’s data variables are named after each qubit, not the coupler — so QubitSpectroscopyVsCurrentAnalysis overrides analyse_element/_process to group the coupler’s two qubit variables directly rather than relying on the generic slice_element.

class bragi_quantum.experiments.nodes.coupler.qubit_spectroscopy_vs_current.analysis.QubitSpectroscopyVsCurrentAnalysis(parameters, qoi_cls=None, **kwargs)[source]#

Bases: Analysis

Runs the frequency-vs-current analysis for both qubits of one coupler and packages their crossing currents into a single QOI (unified, plotly).

Replaces the former QubitSpectroscopyVsCurrentQubitAnalysis + QubitSpectroscopyVsCurrentCouplerAnalysis + QubitSpectroscopyVsCurrentNodeAnalysis.

Parameters:
element_kind: str = 'coupler'#
parameters: QubitSpectroscopyVsCurrentParameters#
plot_title()[source]#

Title for this element’s (sub)plot. Override per node if desired.

Return type:

str

analyse_element(dataset, element)[source]#

Slice element from dataset (Dataset or path) and fit it here.

Parameters:

element (str)

Return type:

BaseQoi

compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

BaseQoi

add_traces(fig, row=1, col=1)[source]#

Both qubits’ tracked frequency-vs-current traces overlaid (main plot). The per-current fit grids move to support_figures().

As with resonator_spectroscopy_vs_current, the two qubits’ absolute frequencies typically differ by tens/hundreds of MHz, which would swamp a shared y-axis — so each trace is centred on its own median frequency (failed-fit zeros excluded) and plotted in kHz deviation.

Parameters:
Return type:

None

support_figures()[source]#

Extra per-element diagnostic figures as (plotly_figure, filename).

Called on each analysed element’s worker during save. Default: none. Override for nodes with 1-D projections / per-slice diagnostics.

CZ currents from spectroscopies#

Node implementation for deriving CZ working-point currents from spectroscopies.

Ported from tergite-autocalibration (CZCurrentsFromSpectroscopiesNode).

class bragi_quantum.experiments.nodes.coupler.cz_currents_from_spectroscopies.node.CZCurrentsFromSpectroscopies(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.coupler.cz_currents_from_spectroscopies.parameters.CZCurrentsFromSpectroscopiesQOI'>)[source]#

Bases: CouplerNode

Analysis-only node evaluating the candidate currents at which the coupler can be operated to perform a CZ gate.

No measurement is performed: the analysis fits the tunable-coupler frequency model to the qubit and resonator crossing currents stored in Redis by qubit_spectroscopy_vs_current and resonator_spectroscopy_vs_current (combined with the qubits’ clock frequencies from the session device), and solves the fit for the CZ avoided-crossing currents.

Parameters:
measurement_cls: BaseMeasurement = None#
analysis_cls#

alias of CZCurrentsFromSpectroscopiesAnalysis

parameters: CZCurrentsFromSpectroscopiesParameters#
pydantic model bragi_quantum.experiments.nodes.coupler.cz_currents_from_spectroscopies.parameters.CZCurrentsFromSpectroscopiesParameters[source]#

Bases: BaseParameters

Parameters for CZCurrentsFromSpectroscopies.

Analysis-only node: no measurement is performed. The coupler-frequency model is fitted to the crossing points stored in Redis by qubit_spectroscopy_vs_current and resonator_spectroscopy_vs_current, and candidate CZ working-point currents are computed from the fit. Ported from tergite-autocalibration (CZCurrentsFromSpectroscopiesNode).

Fields:
field guess: list[float] [Optional]#
field lower_bounds: list[float] [Optional]#
field upper_bounds: list[float] [Optional]#
field min_total_crossing_points: int = 4#

Minimum overall crossings required to fit.

field minimum_qubit_crossing_points: int = 2#
field minimum_resonator_crossing_points: int = 0#
field fit_quality_threshold: float = 0.12#
field calculate_wp: bool = True#

Compute candidate CZ working-point currents from the fitted coupler frequency (otherwise only the fit results are stored).

field max_cz_frequency_in_GHz: float = 1.0#

CZ modulation frequencies above this are outside the electronics range; working points are not calculated for them.

field max_number_of_wp: int = 15#

Maximum number of working points to scan for.

field use_fix_frequency_step: bool = False#

Scan working points on a fixed frequency grid instead of the CZ frequencies derived from the qubit transition frequencies.

field fixed_frequency_step_in_GHz: float = 0.25#
invalid_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
pydantic model bragi_quantum.experiments.nodes.coupler.cz_currents_from_spectroscopies.parameters.CZCurrentsFromSpectroscopiesQOI[source]#

Bases: BaseQoi

Quantities of Interest for CZCurrentsFromSpectroscopies on one coupler: the fitted coupler-frequency model parameters and the candidate CZ working-point currents for the 20 and 02 avoided crossings.

Fields:
field cz_currents_from_spectroscopies_20: list[float] [Optional]#
field cz_currents_from_spectroscopies_02: list[float] [Optional]#
field cz_transition_frequency_20: float = 0.0#
field cz_transition_frequency_02: float = 0.0#
field coupler_frequency: float = 0.0#
field coupler_frequency_error: float = 0.0#
field coupler_amplitude: float = 0.0#
field coupler_amplitude_error: float = 0.0#
field current_offset: float = 0.0#
field current_offset_error: float = 0.0#
field coupler_minimum_frequency: float = 0.0#
field coupler_minimum_frequency_error: float = 0.0#
items()[source]#

Iterate like a mapping so bragi_quantum.datalayer’s update_redis_trusted_values can inspect the QOI keys when routing coupler results.

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict

to_redis_dict()[source]#
Return type:

dict[str, dict]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Analysis for deriving candidate CZ working-point currents from spectroscopies.

Ported from tergite-autocalibration (lib/nodes/coupler/cz_currents_from_spectroscopies/analysis.py). This node has no measurement of its own: the qubit and resonator crossing currents stored in Redis by qubit_spectroscopy_vs_current and resonator_spectroscopy_vs_current are combined with the qubits’ clock frequencies (from the session device) into (frequency, current) points, a tunable-coupler frequency model is fitted through them, and the currents at which the coupler frequency matches the CZ avoided-crossing frequencies (20 and 02) are solved from the fit.

bragi_quantum.experiments.nodes.coupler.cz_currents_from_spectroscopies.analysis.coupler_freq(x, bare_coupler_frequency, amplitude, offset, minimum_coupler_frequency)[source]#

Model function for the frequency of a tunable coupler.

Models the coupler frequency as a function of the DC current applied to the coupler, using a cosine function to represent the modulation of the frequency by the current.

Parameters:
  • x (float) – The current applied to the coupler, in mA.

  • bare_coupler_frequency (float) – The bare frequency of the coupler, in GHz.

  • amplitude (float) – Amplitude of the modulation.

  • offset (float) – Phase shift of the modulation, in mA.

  • minimum_coupler_frequency (float) – This parameter is used to improve fitting stability. Users should check its value as it is supposed to be small.

Returns:

The frequency of the coupler at the given current, in GHz.

Return type:

float

class bragi_quantum.experiments.nodes.coupler.cz_currents_from_spectroscopies.analysis.CZCurrentsFromSpectroscopiesAnalysis(parameters, qoi_cls=None, **kwargs)[source]#

Bases: Analysis

Derive candidate CZ working-point currents for every coupler (unified).

This is an analysis-only node: there is no measured dataset. For each coupler it reads the qubit/resonator crossing currents from Redis and the qubits’ clock frequencies from the session device, fits the tunable-coupler frequency model, and solves for the CZ avoided-crossing currents. Replaces the former CZCurrentsFromSpectroscopiesCouplerAnalysis / ...NodeAnalysis split.

Parameters:

parameters (CZCurrentsFromSpectroscopiesParameters)

element_kind: str = 'coupler'#
parameters: CZCurrentsFromSpectroscopiesParameters#
run(dataset=None)[source]#

Analyse every coupler in parameters.couplers.

Analysis-only: the dataset argument is accepted (the pipeline passes the node’s would-be HDF5 path) but ignored — inputs come from Redis and the session device.

Return type:

dict[str, BaseQoi]

plot_title()[source]#

Title for this element’s (sub)plot. Override per node if desired.

Return type:

str

initial_guess(qubit_currents)[source]#

Estimate the current offset of the coupler modulation as the midpoint of the widest gap between consecutive qubit crossing currents.

compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

BaseQoi

is_fit_successful()[source]#
add_traces(fig, row=1, col=1)[source]#

Add this element’s plotly traces (and axis titles) to fig at (row, col).

Parameters:
Return type:

None

CZ parametrization (fixed duration)#

Node implementation for CZ parametrization with a fixed pulse duration.

Ported from tergite-autocalibration (CZParametrizationFixDurationNode).

class bragi_quantum.experiments.nodes.coupler.cz_parametrization.node.CZParametrizationFixDuration(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.coupler.cz_parametrization.parameters.CZParametrizationFixDurationQOI'>)[source]#

Bases: ScheduleCouplerNode

Tests a candidate CZ working-point current by sweeping the coupler’s flux pulse frequency and amplitude (duration held fixed).

Both qubits of a coupler are excited to |1> and the coupler flux pulse is applied at every (frequency, amplitude) point; the analysis looks for the point where population exchanges into the targeted |20> or |02> state (parameters.cz_transition), consistently between both qubits — i.e. whether a usable CZ avoided crossing exists at this current.

Parameters:
measurement_cls#

alias of CZParametrizationFixDurationMeasurement

analysis_cls#

alias of CZParametrizationFixDurationAnalysis

parameters: CZParametrizationFixDurationParameters#
property transmons: dict[str, ExtendedTransmon]#

The coupled qubits’ transmons; measured (and read out) by this node.

pydantic model bragi_quantum.experiments.nodes.coupler.cz_parametrization.parameters.CZParametrizationFixDurationParameters[source]#

Bases: BaseParameters

Parameters for CZ parametrization with a fixed pulse duration.

Tests a candidate CZ working-point current by sweeping the coupler’s flux pulse frequency and amplitude (duration held fixed) to find whether a usable |11>-|20> (or |11>-|02>) avoided crossing exists there. Ported from tergite-autocalibration (CZParametrizationFixDurationNode).

Fields:
field repetitions: int = 1024#

Repetitions (averages) per point.

field frequency_sweep: float = 15000000.0#

Half-width (Hz) of the CZ pulse frequency sweep.

field frequency_bins: int = 20#

Number of frequency points.

field amplitude_min: float = 0.0#

Start of the amplitude sweep (fullscale).

Constraints:
  • ge = -1

  • le = 1

field amplitude_max: float = 0.5#

End of the amplitude sweep (fullscale); capped at 0.70 to stay under the AWG gain limit.

Constraints:
  • ge = -1

  • le = 1

field amplitude_bins: int = 15#

Number of amplitude points.

field cz_pulse_duration: float = 1e-07#

Duration of the CZ flux pulse (s).

field cz_transition: str = '20'#

Targeted transition: ‘20’ or ‘02’.

field cz_half_frequency_wp: bool = False#

Center the frequency sweep at half the computed CZ transition frequency, for couplers operated at a half-frequency working point.

field parking_current: float = 0.0#

Coupler DC parking current (A), for plot labels only.

field downconvert_frequency: float = 4400000000.0#

Flux-line downconversion offset (Hz).

field max_transition_frequency: float = 1000000000.0#

Couplers whose computed transition frequency exceeds this (Hz) are skipped entirely.

invalid_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
pydantic model bragi_quantum.experiments.nodes.coupler.cz_parametrization.parameters.CZParametrizationFixDurationQOI[source]#

Bases: BaseQoi

Quantities of Interest for CZ parametrization on one coupler: the (frequency, amplitude) working point found, and a quality score for ranking candidate parking currents against each other.

Fields:
field cz_pulse_frequency: float = 0.0#
field cz_pulse_frequency_error: float = 0.0#
field cz_pulse_amplitude: float = 0.0#
field cz_pulse_amplitude_error: float = 0.0#
field cz_parametrization_transition_quality: float = 0.0#
items()[source]#

Iterate like a mapping so bragi_quantum.datalayer’s update_redis_trusted_values can inspect the QOI keys when routing coupler results.

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict

to_redis_dict()[source]#
Return type:

dict[str, dict]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Analysis for CZ parametrization with a fixed pulse duration.

Ported from tergite-autocalibration (lib/nodes/coupler/cz_parametrization/analysis.py). Each coupler dataset holds a 2-D (frequency, amplitude) CZ-pulse scan per qubit of the coupler; the qubit driven towards |2> is expected to show a magnitude maximum and the qubit driven towards |0> a magnitude minimum at the same (frequency, amplitude) point if a real CZ avoided crossing exists there.

Like qubit_spectroscopy_vs_current, the dataset’s data variables are named after each qubit, not the coupler — so CZParametrizationFixDurationAnalysis overrides analyse_element/ _process to group the coupler’s two qubit variables directly rather than relying on the generic slice_element.

bragi_quantum.experiments.nodes.coupler.cz_parametrization.analysis.spatial_coherence_zscore(magnitude_map, n_shuffle=200, seed=0)[source]#

Quantifies how spatially coherent a 2D magnitude map is, i.e. whether it contains a smooth blob/chevron rather than uncorrelated noise.

A real feature varies smoothly between neighboring sweep points, so its total variation (mean absolute difference between adjacent pixels) is much lower than that of the same pixel values randomly shuffled, which destroys any spatial structure. Pure noise has no structure to destroy, so shuffling barely changes the total variation and the z-score stays near zero. The z-score is how many standard deviations below the shuffled-null mean the real total variation sits.

Parameters:
Return type:

float

class bragi_quantum.experiments.nodes.coupler.cz_parametrization.analysis.CombinedFrequencyVsAmplitudeAnalysis(result_to2, result_to0, max_diff_point, to2_raw_magnitudes=None, to0_raw_magnitudes=None)[source]#

Bases: object

Combines the results of a coupler’s two qubit analyses in a CZ parametrization experiment. Finds the point of maximum q_to2-q_to0 magnitude difference and checks that it agrees with either the q_to2 max point or the q_to0 min point within tolerance, and that both qubits’ magnitude maps show spatially coherent structure rather than just noise. If either check fails, the analysis fails.

Parameters:
  • result_to2 (list)

  • result_to0 (list)

  • max_diff_point (list)

  • to2_raw_magnitudes (np.ndarray | None)

  • to0_raw_magnitudes (np.ndarray | None)

are_two_qubits_compatible()[source]#

Check if the maximum-difference point is near either the q_to2 max or the q_to0 min point, and that both qubits’ magnitude maps show real spatial structure.

Return type:

bool

best_parameters()[source]#

The point of maximum q_to2-q_to0 magnitude difference (the working point).

Return type:

list

transition_quality()[source]#

A score for ranking how good this transition region is across multiple candidate datasets (e.g. different parking currents): the weaker of the two qubits’ spatial-coherence z-scores, mirroring the AND-gate used by _has_significant_structure. Higher is a cleaner, more chevron-like map.

Return type:

float

class bragi_quantum.experiments.nodes.coupler.cz_parametrization.analysis.CZParametrizationFixDurationAnalysis(parameters, qoi_cls=None, **kwargs)[source]#

Bases: Analysis

Runs the frequency-vs-amplitude CZ parametrization analysis for both qubits of one coupler and packages the working point into a single QOI.

Parameters:
element_kind: str = 'coupler'#
parameters: CZParametrizationFixDurationParameters#
plot_title()[source]#

Title for this element’s (sub)plot. Override per node if desired.

Return type:

str

analyse_element(dataset, element)[source]#

Slice element from dataset (Dataset or path) and fit it here.

Parameters:

element (str)

Return type:

BaseQoi

compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

BaseQoi

add_traces(fig, row=1, col=1)[source]#

Draw both qubits’ raw magnitude maps side by side at (row, col) and (row, col+1).

Parameters:
Return type:

None

CZ wall finder#

Node implementation for the CZ wall finder.

Ported from tergite-autocalibration (CZWallFinder).

class bragi_quantum.experiments.nodes.coupler.cz_wall_finder.node.CZWallFinder(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.coupler.cz_wall_finder.parameters.CZWallFinderQOI'>)[source]#

Bases: ScheduleCouplerNode

Sweeps the coupler’s CZ flux pulse amplitude at a single fixed frequency (its CZ transition frequency) to find, per qubit, the amplitude beyond which the magnitude response departs from its baseline – a “wall” past which driving the coupler further is unsafe or uncontrolled. Reuses CZParametrizationFixDuration’s measurement (fixed duration, swept frequency/amplitude), collapsed here to a single frequency point.

Parameters:
measurement_cls#

alias of CZParametrizationFixDurationMeasurement

analysis_cls#

alias of CZWallFinderAnalysis

parameters: CZWallFinderParameters#
property transmons: dict[str, ExtendedTransmon]#

The coupled qubits’ transmons; measured (and read out) by this node.

pydantic model bragi_quantum.experiments.nodes.coupler.cz_wall_finder.parameters.CZWallFinderParameters[source]#

Bases: CZParametrizationFixDurationParameters

Parameters for the CZ wall finder.

Sweeps the coupler’s CZ flux pulse amplitude at a single fixed frequency (the coupler’s CZ transition frequency) to find, per qubit, the amplitude beyond which the magnitude response departs from its baseline – a “wall” past which driving the coupler further is unsafe or uncontrolled. Ported from tergite-autocalibration (CZWallFinder).

Reuses CZParametrizationFixDuration’s fields (cz_pulse_duration, cz_transition, max_transition_frequency, …) and its measurement; frequency_sweep / frequency_bins are inherited but unused here – the frequency sweep always collapses to the single point at the coupler’s CZ transition frequency.

Fields:
field amplitude_max: float = 1.0#

End of the amplitude sweep (fullscale); capped at 0.70 to stay under the AWG gain limit.

Constraints:
  • ge = -1

  • le = 1

field amplitude_bins: int = 21#

Number of amplitude points.

invalid_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
pydantic model bragi_quantum.experiments.nodes.coupler.cz_wall_finder.parameters.CZWallFinderQOI[source]#

Bases: BaseQoi

Quantities of Interest for the CZ wall finder on one coupler: the wall amplitude, the more conservative (lower) of its two qubits’ wall amplitudes. Informational only – there is no device field to update, so to_redis_dict uses a plain (non-submodule:field) key.

Fields:
field coupler_wall_amplitude: float = 1.0#
items()[source]#

Iterate like a mapping so bragi_quantum.datalayer’s update_redis_trusted_values can inspect the QOI keys when routing coupler results.

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict

to_redis_dict()[source]#
Return type:

dict[str, dict]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Analysis for the CZ wall finder.

Ported from tergite-autocalibration (lib/nodes/coupler/cz_wall_finder/analysis.py). Each coupler dataset holds a single-frequency amplitude sweep per qubit (reusing CZParametrizationFixDuration’s measurement, collapsed to one frequency point); the “wall” is the amplitude at which a qubit’s magnitude response first drops below its own sweep mean, scanned from the highest amplitude down. The coupler’s wall amplitude is the more conservative (lower) of its two qubits’.

Like cz_parametrization, the dataset’s data variables are named after each qubit, not the coupler, so CZWallFinderAnalysis overrides analyse_element/_process to group the coupler’s two qubit variables directly rather than relying on the generic slice_element.

bragi_quantum.experiments.nodes.coupler.cz_wall_finder.analysis.find_wall_amplitude(amplitudes, magnitudes)[source]#

The amplitude at which magnitudes first drops below its own sweep mean, scanning from the highest amplitude down – the onset of the “wall”.

A wall is only searched for if the sweep shows a clear rise from its first two points to its last three (more than 3 standard deviations of the first two points’ spread); flat/noisy sweeps report NO_WALL_FOUND.

Parameters:
Return type:

float

class bragi_quantum.experiments.nodes.coupler.cz_wall_finder.analysis.CZWallFinderAnalysis(parameters, qoi_cls=None, **kwargs)[source]#

Bases: Analysis

Finds each coupler’s CZ wall amplitude – the lower of its two qubits’ wall amplitudes – from a single-frequency amplitude sweep.

Parameters:

parameters (CZWallFinderParameters)

element_kind: str = 'coupler'#
parameters: CZWallFinderParameters#
plot_title()[source]#

Title for this element’s (sub)plot. Override per node if desired.

Return type:

str

analyse_element(dataset, element)[source]#

Slice element from dataset (Dataset or path) and fit it here.

Parameters:

element (str)

Return type:

BaseQoi

compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

BaseQoi

add_traces(fig, row=1, col=1)[source]#

Draw both qubits’ amplitude sweeps side by side at (row, col) and (row, col+1).

Parameters:
Return type:

None

CZ chevron#

Node implementation for the CZ chevron (fixed pulse amplitude).

Ported from tergite-autocalibration (CZChevronNode).

class bragi_quantum.experiments.nodes.coupler.cz_chevron.node.CZChevron(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.coupler.cz_chevron.parameters.CZChevronQOI'>)[source]#

Bases: ScheduleCouplerNode

Tests a candidate CZ working-point current by sweeping the coupler’s flux pulse frequency and duration (amplitude held fixed).

Both qubits of a coupler are excited to |1> and the coupler flux pulse is applied at every (frequency, duration) point; the analysis looks for the point where population exchanges into the targeted |20> or |02> state (parameters.cz_transition), consistently between both qubits — i.e. whether a usable CZ avoided crossing exists at this current — and refines the CZ pulse duration from the resulting oscillation period.

Parameters:
measurement_cls#

alias of CZChevronMeasurement

analysis_cls#

alias of CZChevronAnalysis

parameters: CZChevronParameters#
property transmons: dict[str, ExtendedTransmon]#

The coupled qubits’ transmons; measured (and read out) by this node.

pydantic model bragi_quantum.experiments.nodes.coupler.cz_chevron.parameters.CZChevronParameters[source]#

Bases: BaseParameters

Parameters for the CZ chevron: sweeping the coupler’s flux pulse frequency and duration (amplitude held fixed) to find whether a usable |11>-|20> (or |11>-|02>) avoided crossing exists at a candidate current, and to refine the CZ pulse duration itself. Ported from tergite-autocalibration (CZChevronNode).

Fields:
field repetitions: int = 1024#

Repetitions (averages) per point.

field frequency_sweep: float = 10000000.0#

Half-width (Hz) of the CZ pulse frequency sweep.

field frequency_bins: int = 15#

Number of frequency points.

field duration_min: float = 2e-08#

Start of the duration sweep (s).

field duration_max: float = 7e-07#

End of the duration sweep (s).

field duration_bins: int = 30#

Number of duration points.

field cz_pulse_amplitude: float = 0.5#

Amplitude of the CZ flux pulse (fullscale).

Constraints:
  • ge = -1

  • le = 1

field cz_transition: str = '20'#

Targeted transition: ‘20’ or ‘02’.

field cz_half_frequency_wp: bool = False#

Center the frequency sweep at half the computed CZ transition frequency, for couplers operated at a half-frequency working point.

field parking_current: float = 0.0#

Coupler DC parking current (A), for plot labels only.

field downconvert_frequency: float = 4400000000.0#

Flux-line downconversion offset (Hz).

field max_transition_frequency: float = 1000000000.0#

Couplers whose computed transition frequency exceeds this (Hz) are skipped entirely.

field trace_fit_failure_threshold: float = 0.66#

Support-trace fit failure fraction above which a working point is discarded.

invalid_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
pydantic model bragi_quantum.experiments.nodes.coupler.cz_chevron.parameters.CZChevronQOI[source]#

Bases: BaseQoi

Quantities of Interest for the CZ chevron on one coupler: the (frequency, duration) working point found, plus diagnostics on how many of the neighboring support-trace fits resolved a genuine oscillation.

Fields:
field cz_pulse_frequency: float = 0.0#
field cz_pulse_frequency_error: float = 0.0#
field cz_pulse_duration: float = 0.0#
field cz_pulse_duration_error: float = 0.0#
field cz_chevron_trace_periods: str = '[]'#
field cz_chevron_trace_fit_failure_fraction: float = 0.0#
items()[source]#

Iterate like a mapping so bragi_quantum.datalayer’s update_redis_trusted_values can inspect the QOI keys when routing coupler results.

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict

to_redis_dict()[source]#
Return type:

dict[str, dict]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Analysis for the CZ chevron: sweeping the frequency and duration of a coupler’s flux pulse (amplitude held fixed), to find the CZ working point.

Ported from tergite-autocalibration (lib/nodes/coupler/cz_chevron/analysis.py), structured like the sibling cz_parametrization node (frequency vs. amplitude): each coupler dataset holds a 2-D (frequency, duration) CZ-pulse scan per qubit, the qubit driven towards |2> is expected to show a magnitude maximum and the qubit driven towards |0> a magnitude minimum at the same (frequency, duration) point if a real CZ avoided crossing exists there.

Unlike cz_parametrization, the duration sweep is dense enough to resolve a population oscillation, so the chosen duration is refined further: a damped-sinusoid (Ramsey) model is fitted to the duration trace at the chosen frequency for both qubits and their fitted periods are averaged. The same fit is repeated at the 8 neighboring frequencies (9 total) to gauge how reliably the oscillation resolves around the chosen point; if too many of those fits fail, the working point is discarded even when the coarser two-qubit-compatibility check passed.

Like cz_parametrization, the dataset’s data variables are named after each qubit, not the coupler — so CZChevronAnalysis overrides analyse_element/_process to group the coupler’s two qubit variables directly rather than relying on the generic slice_element.

class bragi_quantum.experiments.nodes.coupler.cz_chevron.analysis.CombinedFrequencyVsDurationAnalysis(result_to2, result_to0, max_diff_point)[source]#

Bases: object

Combines the results of a coupler’s two qubit analyses in a CZ chevron experiment. Finds the point of maximum q_to2-q_to0 magnitude difference and checks that it agrees with either the q_to2 max point or the q_to0 min point within tolerance. If not, the analysis fails.

Parameters:
are_two_qubits_compatible()[source]#

Check if the maximum-difference point is near either the q_to2 max or the q_to0 min point.

Return type:

bool

best_parameters()[source]#

The point of maximum q_to2-q_to0 magnitude difference (the working point).

Return type:

list

class bragi_quantum.experiments.nodes.coupler.cz_chevron.analysis.CZChevronAnalysis(parameters, qoi_cls=None, **kwargs)[source]#

Bases: Analysis

Runs the frequency-vs-duration CZ chevron analysis for both qubits of one coupler and packages the working point into a single QOI.

Parameters:
element_kind: str = 'coupler'#
SUPPORT_TRACE_HALF_WINDOW = 4#
parameters: CZChevronParameters#
plot_title()[source]#

Title for this element’s (sub)plot. Override per node if desired.

Return type:

str

analyse_element(dataset, element)[source]#

Slice element from dataset (Dataset or path) and fit it here.

Parameters:

element (str)

Return type:

BaseQoi

compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

BaseQoi

add_traces(fig, row=1, col=1)[source]#

Draw both qubits’ raw magnitude maps side by side at (row, col) and (row, col+1).

Parameters:
Return type:

None

support_figures()[source]#

Extra per-element diagnostic figures as (plotly_figure, filename).

Called on each analysed element’s worker during save. Default: none. Override for nodes with 1-D projections / per-slice diagnostics.

CZ conditional phase & local phases#

Node implementation for CZ phase calibration.

Ported from tergite-autocalibration (CZConditionalPhaseSSRONode / CZLocalPhaseSSRONode / CZLocalPhaseSwapSSRONode). Those three node classes differed only by two booleans on an otherwise-identical measurement and analysis, so here they collapse into one node class, registered in nodes.yaml as three parameters:-variants of it (cz_phases_conditional, cz_phases_local, cz_phases_local_swap).

class bragi_quantum.experiments.nodes.coupler.cz_phases.node.CZPhases(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.coupler.cz_phases.parameters.CZConditionalPhaseQOI'>)[source]#

Bases: ScheduleCouplerNode

Measures the CZ conditional phase, or (with local_phases=True) one of the two CZ local phases, for each coupler.

Parameters:
measurement_cls#

alias of CZPhasesMeasurement

analysis_cls#

alias of CZPhasesAnalysis

parameters: CZPhasesParameters#
property transmons: dict[str, ExtendedTransmon]#

The coupled qubits’ transmons; measured (and read out) by this node.

Parameters and QOIs for CZ phase calibration.

Ported from tergite-autocalibration (lib/nodes/coupler/cz_phases). The three node variants there (CZConditionalPhaseSSRONode, CZLocalPhaseSSRONode, CZLocalPhaseSwapSSRONode) differed only by two booleans on one shared measurement/analysis pair, so here they share a single CZPhasesParameters and node class, and are registered in nodes.yaml as three parameters: variants of it (see the “shared class + parameter variants” convention documented at the top of nodes.yaml, e.g. resonator_spectroscopy_1/_2).

pydantic model bragi_quantum.experiments.nodes.coupler.cz_phases.parameters.CZPhasesParameters[source]#

Bases: BaseParameters

Parameters for CZ phase calibration (conditional phase and local phases).

Sweeps a Ramsey-type phase on the target qubit, with the coupler’s CZ pulse (at its already-calibrated frequency/amplitude/duration) turned on or off / applied with the control qubit in |0> or |1>, depending on local_phases / swap_control_and_target:

  • Conditional phase (local_phases=False): compares the target qubit’s Ramsey phase with the control qubit in |0> vs |1>, with the coupler’s virtual-Z phase corrections applied. The difference is the CZ conditional phase (ideal: 180 degrees).

  • Local phase (local_phases=True, swap_control_and_target=False): compares the target qubit’s Ramsey phase with the CZ pulse off vs on (no virtual-Z corrections, no conditional X on the control qubit), giving the local phase the target qubit itself picks up from the CZ pulse.

  • Local phase, swapped (local_phases=True, swap_control_and_target=True): same as above with the control and target roles swapped, giving the local phase on the other qubit.

Fields:
invalid_variant_combinations: ClassVar[tuple[dict[str, Any], ...]] = (mappingproxy({'local_phases': False, 'swap_control_and_target': True}),)#
field repetitions: int = 1024#

Repetitions (averages) per point.

field ramsey_phases_max: float = 720.0#

End of the Ramsey-phase sweep (degrees).

field ramsey_phases_bins: int = 25#

Number of Ramsey-phase points.

field cz_transition: str = '20'#

Targeted transition: ‘20’ or ‘02’.

field local_phases: bool = False#

If False, measure the CZ conditional phase. If True, measure a local phase instead (gate off vs on, no virtual-Z corrections).

field swap_control_and_target: bool = False#

Only used when local_phases=True: swap which qubit of the coupler plays Control vs Target, to measure the other qubit’s local phase.

field downconvert_frequency: float = 4400000000.0#

Flux-line downconversion offset (Hz).

legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = (mappingproxy({'local_phases': True, 'swap_control_and_target': True}), mappingproxy({'local_phases': True, 'swap_control_and_target': False}), mappingproxy({'local_phases': False, 'swap_control_and_target': False}))#
pydantic model bragi_quantum.experiments.nodes.coupler.cz_phases.parameters.CZConditionalPhaseQOI[source]#

Bases: BaseQoi

QOI for the CZ conditional-phase node.

Fields:
field cz_phase: float = 0.0#
field cz_phase_error: float = 0.0#
field cz_pop_loss: float = 0.0#
items()[source]#

Iterate like a mapping so bragi_quantum.datalayer’s update_redis_trusted_values can inspect the QOI keys when routing coupler results.

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict

to_redis_dict()[source]#
Return type:

dict[str, dict]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.coupler.cz_phases.parameters.CZLocalPhaseQOI[source]#

Bases: BaseQoi

QOI for the CZ local-phase (target qubit) node.

Fields:
field cz_local_target: float = 0.0#
field cz_local_target_error: float = 0.0#
items()[source]#

Iterate like a mapping so bragi_quantum.datalayer’s update_redis_trusted_values can inspect the QOI keys when routing coupler results.

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict

to_redis_dict()[source]#
Return type:

dict[str, dict]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.coupler.cz_phases.parameters.CZLocalPhaseSwapQOI[source]#

Bases: BaseQoi

QOI for the CZ local-phase (control qubit, swapped) node.

Fields:
field cz_local_control: float = 0.0#
field cz_local_control_error: float = 0.0#
items()[source]#

Iterate like a mapping so bragi_quantum.datalayer’s update_redis_trusted_values can inspect the QOI keys when routing coupler results.

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict

to_redis_dict()[source]#
Return type:

dict[str, dict]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Analysis for CZ phase calibration.

Ported from tergite-autocalibration (lib/nodes/coupler/cz_phases/analysis.py). Each coupler dataset holds a Ramsey-phase scan on the target qubit, for both values of control_ons, for each of the coupler’s two qubits (only the Target qubit’s data is fit with a cosine; the Control qubit’s is not expected to oscillate and is shown as a flat reference).

Like cz_parametrization, the dataset’s data variables are named after each qubit, not the coupler — so CZPhasesAnalysis overrides analyse_element/_process to group the coupler’s two qubit variables directly rather than relying on the generic slice_element.

class bragi_quantum.experiments.nodes.coupler.cz_phases.analysis.CZPhasesAnalysis(parameters, qoi_cls=None, **kwargs)[source]#

Bases: Analysis

Fits a coupler’s Control and Target qubit Ramsey-phase scans and packages the CZ (conditional or local) phase into a single QOI.

Parameters:
element_kind: str = 'coupler'#
parameters: CZPhasesParameters#
plot_title()[source]#

Title for this element’s (sub)plot. Override per node if desired.

Return type:

str

analyse_element(dataset, element)[source]#

Slice element from dataset (Dataset or path) and fit it here.

Parameters:

element (str)

Return type:

BaseQoi

compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

BaseQoi

add_traces(fig, row=1, col=1)[source]#

Draw both qubits’ Ramsey-phase scans side by side at (row, col) and (row, col+1).

Parameters:
Return type:

None

Two-qubit gate randomized benchmarking#

Node implementations for two-qubit-gate randomized benchmarking (TQG RB).

Ported from tergite-autocalibration (TQGRandomizedBenchmarkingSSRONode / TQGRandomizedBenchmarkingInterleavedSSRONode). TQGRandomizedBenchmarking runs standard RB; TQGRandomizedBenchmarkingInterleaved additionally interleaves a bare CZ Clifford into every sequence, and combines its decay parameter with the standard run’s (via Redis) to derive the CZ gate fidelity. Both share the same measurement class and coupler CZ settings, resolved here from self.edges[coupler].cz rather than read from Redis directly (matching the cz_phases / cz_parametrization convention).

class bragi_quantum.experiments.nodes.coupler.tqg_randomized_benchmarking.node.TQGRandomizedBenchmarking(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.coupler.tqg_randomized_benchmarking.parameters.TQGRandomizedBenchmarkingQOI'>)[source]#

Bases: ScheduleCouplerNode

Standard two-qubit-gate randomized benchmarking on a coupler.

Parameters:
measurement_cls#

alias of TQGRandomizedBenchmarkingMeasurement

analysis_cls#

alias of TQGRandomizedBenchmarkingAnalysis

parameters: TQGRandomizedBenchmarkingParameters#
property transmons: dict[str, ExtendedTransmon]#

The coupled qubits’ transmons; measured (and read out) by this node.

class bragi_quantum.experiments.nodes.coupler.tqg_randomized_benchmarking.node.TQGRandomizedBenchmarkingInterleaved(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.coupler.tqg_randomized_benchmarking.parameters.TQGRandomizedBenchmarkingInterleavedQOI'>)[source]#

Bases: TQGRandomizedBenchmarking

Two-qubit-gate RB with a bare CZ Clifford interleaved into every sequence, used to extract the CZ gate fidelity against a prior standard RB run on the same coupler.

Parameters:
analysis_cls#

alias of TQGRandomizedBenchmarkingInterleavedAnalysis

Parameters and QOIs for two-qubit-gate randomized benchmarking (TQG RB).

Ported from tergite-autocalibration (lib/nodes/coupler/tqg_randomized_benchmarking). Standard RB (TQGRandomizedBenchmarking) and CZ-interleaved RB (TQGRandomizedBenchmarkingInterleaved) share this one parameters class; the two node classes differ only in whether the CZ Clifford is interleaved into every sequence (see node.py).

pydantic model bragi_quantum.experiments.nodes.coupler.tqg_randomized_benchmarking.parameters.TQGRandomizedBenchmarkingParameters[source]#

Bases: BaseParameters

Parameters for two-qubit-gate randomized benchmarking on a coupler.

Runs n_seeds independent random Clifford sequences (drawn from the two-qubit Clifford group) at each length in clifford_sequence_lengths, each averaged over number_of_shots single-shot repetitions. Negative lengths in clifford_sequence_lengths are calibration points (-1: state |1>, -2: state |2>) used by the analysis to correct for per-seed IQ drift.

Fields:
field n_seeds: int = 10#

Number of random Clifford sequences per length.

field number_of_shots: int = 500#

Single-shot repetitions averaged per point.

field clifford_sequence_lengths: list[int] [Optional]#

Number of Cliffords per sequence. Negative values are calibration points: -1 prepares |1>, -2 prepares |2>.

field apply_inverse_gate: bool = True#

Append the recovery Clifford that inverts each sequence.

field cz_transition: str = '20'#

Targeted transition: ‘20’ or ‘02’.

field downconvert_frequency: float = 4400000000.0#

Flux-line downconversion offset (Hz).

invalid_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
pydantic model bragi_quantum.experiments.nodes.coupler.tqg_randomized_benchmarking.parameters.TQGRandomizedBenchmarkingBaseQOI[source]#

Bases: BaseQoi

Shared QOI fields and redis layout for the SRB and IRB variants.

Fields:
redis_key_suffix: ClassVar[str]#
field tqg_fidelity: float = 0.0#
field tqg_fidelity_error: float = 0.0#
field reduced_chi2: float = 0.0#
field leakage: float = 0.0#
field error_rate: float = 0.0#
field tqg_rb_p: float | None = None#
field tqg_rb_p_error: float | None = None#
field tqg_rb_p_A: float | None = None#
field tqg_rb_p_A_error: float | None = None#
field tqg_rb_p_B: float | None = None#
field tqg_rb_p_B_error: float | None = None#
field p_L: float | None = None#
field p_L_error: float | None = None#
field a: float | None = None#
field a_error: float | None = None#
field L_1: float | None = None#
field L_1_error: float | None = None#
field L_2: float | None = None#
field L_2_error: float | None = None#
field p_r: float | None = None#
field p_r_error: float | None = None#
items()[source]#

Iterate like a mapping so bragi_quantum.datalayer’s update_redis_trusted_values can inspect the QOI keys when routing coupler results.

to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict

to_redis_dict()[source]#
Return type:

dict[str, dict]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.coupler.tqg_randomized_benchmarking.parameters.TQGRandomizedBenchmarkingQOI[source]#

Bases: TQGRandomizedBenchmarkingBaseQOI

QOI for standard (non-interleaved) two-qubit-gate RB.

Fields:

redis_key_suffix: ClassVar[str] = 'SRB'#
model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

pydantic model bragi_quantum.experiments.nodes.coupler.tqg_randomized_benchmarking.parameters.TQGRandomizedBenchmarkingInterleavedQOI[source]#

Bases: TQGRandomizedBenchmarkingBaseQOI

QOI for CZ-interleaved two-qubit-gate RB.

tqg_fidelity here is the CZ gate fidelity, derived by combining this run’s interleaved decay parameter with the standard RB run’s decay parameter (read back from Redis; see analysis.py).

Fields:

redis_key_suffix: ClassVar[str] = 'IRB'#
model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Analysis for two-qubit-gate randomized benchmarking (TQG RB).

Ported from tergite-autocalibration (lib/nodes/coupler/tqg_randomized_benchmarking/analysis.py). Fits an exponential decay to the |00> return probability, and a second exponential decay to the population confined to the computational subspace (|00>, |01>, |10>, |11>) to extract a leakage rate. When calibration points (n_cl < 0) are present, per-seed IQ drift is corrected before classification using the 3-state readout boundary (centroid + omega_01/12/20) read from Redis.

TQGRandomizedBenchmarkingInterleavedAnalysis additionally combines its own decay parameter with the standard-RB run’s decay parameter (read back from Redis, written there from the SRB run’s QOI) to derive the CZ gate fidelity.

class bragi_quantum.experiments.nodes.coupler.tqg_randomized_benchmarking.analysis.TQGRandomizedBenchmarkingAnalysis(parameters, qoi_cls=None, **kwargs)[source]#

Bases: Analysis

Fits an exponential decay function to two-qubit-gate randomized benchmarking data for one coupler.

Parameters:

qoi_cls (type[BaseQoi] | None)

element_kind: str = 'coupler'#
suffix = 'SRB'#
plot_title()[source]#

Title for this element’s (sub)plot. Override per node if desired.

Return type:

str

analyse_element(dataset, element)[source]#

Slice element from dataset (Dataset or path) and fit it here.

Parameters:

element (str)

Return type:

BaseQoi

compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

BaseQoi

add_traces(fig, row=1, col=1)[source]#

Add this element’s plotly traces (and axis titles) to fig at (row, col).

Parameters:
Return type:

None

support_figures()[source]#

Extra per-element diagnostic figures as (plotly_figure, filename).

Called on each analysed element’s worker during save. Default: none. Override for nodes with 1-D projections / per-slice diagnostics.

class bragi_quantum.experiments.nodes.coupler.tqg_randomized_benchmarking.analysis.TQGRandomizedBenchmarkingInterleavedAnalysis(parameters, qoi_cls=None, **kwargs)[source]#

Bases: TQGRandomizedBenchmarkingAnalysis

Two-qubit-gate RB with the CZ Clifford interleaved into every sequence.

Combines this run’s decay parameter with the standard-RB run’s decay parameter (read back from Redis) to derive the CZ gate fidelity.

Parameters:

qoi_cls (type[BaseQoi] | None)

suffix = 'IRB'#
compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

BaseQoi

support_figures()[source]#

Extra per-element diagnostic figures as (plotly_figure, filename).

Called on each analysed element’s worker during save. Default: none. Override for nodes with 1-D projections / per-slice diagnostics.

class bragi_quantum.experiments.nodes.coupler.tqg_randomized_benchmarking.utils.clifford_group.Clifford(idx)[source]#

Bases: object

Base class for Clifford

Abstract base class for all Clifford operations.

Variables:
  • idx (int) – Index of the Clifford operation

  • GROUP_SIZE (ClassVar[int]) – Size of the Clifford group

  • CLIFFORD_HASH_TABLE (CLassVar[Dict[int, int]]) – Hash table for fast lookup of Clifford indices

Parameters:

idx (int)

CLIFFORD_HASH_TABLE: ClassVar[dict[int, int]]#
GROUP_SIZE: ClassVar[int]#
get_inverse()[source]#

Get the inverse of this Clifford operation

Returns:

The inverse operation

Return type:

Clifford

property pauli_transfer_matrix: ndarray#

Returns the Pauli transfer matrix of the Clifford operation.

Returns:

The Pauli transfer matrix

Return type:

np.ndarray

property gate_decomposition: list[tuple[list[str], str]]#

Returns the gate decomposition of the Clifford gate

Returns:

Gate decomposition as a list of tuples (gate_name, qubit_identifier)

Return type:

List

classmethod find_clifford_index(matrix)[source]#

Find the index of a Clifford matrix using hash lookup

Parameters:

matrix (np.ndarray) – The Pauli transfer matrix

Returns:

The index of the Clifford operation

Return type:

int

Raises:

ValueError – If the Clifford index is not found

class bragi_quantum.experiments.nodes.coupler.tqg_randomized_benchmarking.utils.clifford_group.SingleQubitClifford(idx)[source]#

Bases: Clifford

Single Qubit Clifford gate class

The decomposition of the single qubit clifford group follows paper Epstein et al. Phys. Rev. A 89, 062321 (2014)

Parameters:

idx (int)

CLIFFORD_HASH_TABLE: ClassVar[dict] = {}#
GROUP_SIZE: ClassVar[int] = 24#
property pauli_transfer_matrix: ndarray#

Returns the Pauli transfer matrix of the single qubit Clifford operation

property gate_decomposition: list[tuple[list[str], str]]#

Returns the gate decomposition of the single qubit Clifford group according to the decomposition by Epstein et al.

Returns:

List of tuples where each tuple contains (gate_name, qubit_identifier)

class bragi_quantum.experiments.nodes.coupler.tqg_randomized_benchmarking.utils.clifford_group.TwoQubitClifford(idx)[source]#

Bases: Clifford

Two Qubit Clifford gate class

The Clifford decomposition closely follows two papers:

1. Corcoles et al. Process verification … Phys. Rev. A. 2013 https://journals.aps.org/pra/pdf/10.1103/PhysRevA.87.030301 for the different classes of two-qubit Cliffords.

2. Barends et al. Superconducting quantum circuits at the … Nature 2014 https://www.nature.com/articles/nature13171?lang=en for writing the cliffords in terms of CZ gates.

2-qubit clifford decompositions#

The two qubit clifford group (C2) consists of 11520 two-qubit cliffords These gates can be subdivided into four classes.

  1. The Single-qubit like class | 576 elements (24^2)

  2. The CNOT-like class | 5184 elements (24^2 * 3^2)

  3. The iSWAP-like class | 5184 elements (24^2 * 3^2)

4. The SWAP-like class | 576 elements (24^2) ——————————–|————- + Two-qubit Clifford group C2 | 11520 elements

  1. The Single-qubit like class

    – C1 – – C1 –

  2. The CNOT-like class
    –C1–”–S1– –C1–”–S1——
    -> |

    –C1–?–S1– –C1–”–S1^Y90–

  3. The iSWAP-like class
    –C1–*–S1– –C1–”—Y90–”–S1^Y90–
    -> | |

    –C1–*–S1– –C1–”–mY90–”–S1^X90–

  4. The SWAP-like class
    --C1--x--

    –C1–“-mY90–”–Y90–”——- | -> | | |

    --C1--x--

    –C1–”–Y90–“-mY90–”–Y90–

C1: element of the single qubit Clifford group

Note: We use the decomposition defined in Epstein et al. here

S1: element of the S1 group, a subgroup of the single qubit Clifford group

CLIFFORD_HASH_TABLE: ClassVar[dict] = {}#
GROUP_SIZE_CLIFFORD = 24#
GROUP_SIZE_SINGLE_QUBIT = 576#
GROUP_SIZE_S1 = 3#
GROUP_SIZE_CNOT = 5184#
GROUP_SIZE_ISWAP = 5184#
GROUP_SIZE_SWAP = 576#
GROUP_SIZE: ClassVar[int] = 11520#
property pauli_transfer_matrix: ndarray#

Returns the Pauli transfer matrix of the Clifford operation.

Returns:

The Pauli transfer matrix

Return type:

np.ndarray

property gate_decomposition#

Returns the gate decomposition of the two qubit Clifford group.

Single qubit Cliffords are decomposed according to Epstein et al.

classmethod single_qubit_like_PTM(idx)[source]#
Returns the pauli transfer matrix for gates of the single qubit like class

(q0) – C1 – (q1) – C1 –

Parameters:

idx (int)

Return type:

ndarray

classmethod single_qubit_like_gates(idx)[source]#
Returns the gates for Cliffords of the single qubit like class

(q0) – C1 – (q1) – C1 –

Parameters:

idx (int)

Return type:

list[tuple[str, str]]

classmethod CNOT_like_PTM(idx)[source]#
Returns the pauli transfer matrix for gates of the cnot like class
(q0) –C1–”–S1– –C1–”–S1——
-> |

(q1) –C1–?–S1– –C1–”–S1^Y90–

Parameters:

idx (int)

Return type:

ndarray

classmethod CNOT_like_gates(idx)[source]#
Returns the gates for Cliffords of the cnot like class
(q0) –C1–”–S1– –C1–”–S1——
-> |

(q1) –C1–?–S1– –C1–”–S1^Y90–

Parameters:

idx (int)

classmethod iSWAP_like_PTM(idx)[source]#
Returns the pauli transfer matrix for gates of the iSWAP like class
(q0) –C1–*–S1– –C1–”—Y90–”–S1^Y90–
-> | |

(q1) –C1–*–S1– –C1–”–mY90–”–S1^X90–

Parameters:

idx (int)

Return type:

ndarray

classmethod iSWAP_like_gates(idx)[source]#
Returns the gates for Cliffords of the iSWAP like class
(q0) –C1–*–S1– –C1–”—Y90–”–S1^Y90–
-> | |

(q1) –C1–*–S1– –C1–”–mY90–”–S1^X90–

Parameters:

idx (int)

classmethod SWAP_like_PTM(idx)[source]#

Returns the pauli transfer matrix for gates of the SWAP like class

(q0) –C1–x– –C1–“-mY90–”–Y90–”——-
-> | | |

(q1) –C1–x– –C1–”–Y90–“-mY90–”–Y90–

Parameters:

idx (int)

Return type:

ndarray

classmethod SWAP_like_gates(idx)[source]#

Returns the gates for Cliffords of the SWAP like class

(q0) –C1–x– –C1–“-mY90–”–Y90–”——-
-> | | |

(q1) –C1–x– –C1–”–Y90–“-mY90–”–Y90–

Parameters:

idx (int)

Parameters:

idx (int)

bragi_quantum.experiments.nodes.coupler.tqg_randomized_benchmarking.utils.randomized_benchmarking.calculate_net_clifford(clifford_indices, CliffordClass)[source]#

Calculate the net-clifford from a list of cliffords indices.

Parameters:
  • clifford_indices (np.ndarray) – Array of integers specifying the Cliffords.

  • CliffordClass (type[Clifford]) – Clifford class used to determine the inversion technique and valid indices. Valid choices are SingleQubitClifford and TwoQubitClifford.

Returns:

a Clifford object containing the net-clifford.

the Clifford index is contained in the Clifford.idx attribute.

Return type:

net_clifford

Note: the order corresponds to the order in a pulse sequence but is

the reverse of what it would be in a chained dot product.

bragi_quantum.experiments.nodes.coupler.tqg_randomized_benchmarking.utils.randomized_benchmarking.add_interleaved_clifford(clifford_sequence, interleaved_clifford)[source]#

Adds an interleaved Clifford gate to the sequence.

Parameters:
  • clifford_sequence (np.ndarray) – Array of Clifford indices.

  • interleaved_clifford (int)

Returns:

Array with interleaved Clifford.

Return type:

np.ndarray

bragi_quantum.experiments.nodes.coupler.tqg_randomized_benchmarking.utils.randomized_benchmarking.add_inverse_clifford(clifford_sequence, CliffordClass)[source]#

Adds the inverse of the total sequence to the end of the sequence.

Parameters:
  • clifford_sequence (np.ndarray) – Array of Clifford indices.

  • CliffordClass (type[Clifford]) – The class of the Clifford group used.

Returns:

Array with appended inverse Clifford.

Return type:

np.ndarray

bragi_quantum.experiments.nodes.coupler.tqg_randomized_benchmarking.utils.randomized_benchmarking.randomized_benchmarking_sequence(number_of_cliffords, apply_inverse=True, clifford_group=1, interleaved_clifford_idx=None, seed=None)[source]#

Generates a randomized benchmarking sequence using the one- or two-qubit Clifford group.

Parameters:
  • number_of_cliffords (int) – Number of Clifford gates in the sequence (excluding the optional inverse).

  • apply_inverse (bool) – Whether to append the recovery Clifford that inverts the total sequence.

  • clifford_group (int) – Specifies which Clifford group to use. 1 for single-qubit (24 elements), 2 for two-qubit (11,520 elements).

  • interleaved_clifford_idx (Optional[int]) – Optional ID for interleaving a specific Clifford gate.

  • seed (Optional[int]) – Optional seed for reproducibility.

Returns:

Array of Clifford indices representing the randomized benchmarking sequence.

Return type:

np.ndarray

Raises:
bragi_quantum.experiments.nodes.coupler.tqg_randomized_benchmarking.utils.pauli_transfer_matrices.X_theta(theta, unit='deg')[source]#

Return the Pauli Transfer Matrix (PTM) of a rotation of angle theta around the X-axis.

Parameters:
  • theta (float) – Rotation angle.

  • unit (str) – Unit of the angle, either “deg” for degrees or “rad” for radians.

Returns:

The 4x4 PTM matrix corresponding to the X rotation.

Return type:

np.ndarray

bragi_quantum.experiments.nodes.coupler.tqg_randomized_benchmarking.utils.pauli_transfer_matrices.Y_theta(theta, unit='deg')[source]#

Return the Pauli Transfer Matrix (PTM) of a rotation of angle theta around the Y-axis.

Parameters:
  • theta (float) – Rotation angle.

  • unit (str) – Unit of the angle, either “deg” for degrees or “rad” for radians.

Returns:

The 4x4 PTM matrix corresponding to the Y rotation.

Return type:

np.ndarray

Characterization nodes#

T1#

Node implementation for T1 relaxation-time characterization.

class bragi_quantum.experiments.nodes.characterization.t1.node.T1(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.characterization.t1.parameters.T1QOI'>)[source]#

Bases: ExternalParameterFixedScheduleQubitNode

Execution node for T1 relaxation-time characterization.

The delay sweep (with its per-point hardware averaging expressed as a loop register, plus the automatic calibration-points block appended by BaseNode.precompile) is compiled once and then executed independently t1_repetitions times: ExternalParameterFixedScheduleNode tags each execution’s data — sweep AND calibration points alike — with its own t1_repetitions coordinate. T1Analysis fits each repeat separately against its own calibration axis and reports the T1 error as the spread across those independent fits.

Parameters:
measurement_cls#

alias of T1Measurement

analysis_cls#

alias of T1Analysis

append_calibration_points: bool = True#
parameters: T1Parameters#
pydantic model bragi_quantum.experiments.nodes.characterization.t1.parameters.T1Parameters[source]#

Bases: CoherenceParameters

Parameters for T1 relaxation-time characterization.

Fields:
field transition: Literal['01'] = '01'#
field max_duration: float = 0.00036#

Longest waiting time, in seconds. Recommended: 5x expected T1 of the qubit.Ignored if list of delays is given explicitly.

Constraints:
  • gt = 0.0

field num_steps: int = 31#

Number of points between 0 and max_duration, default is 31.Ignored if list of delays is given explicitly.

Constraints:
  • ge = 2

field delays: list[float] | None = None#

Explicit delays between the excitation pulse and the readout, in seconds.If defined, this overwrites max_duration and num_steps.

field repetitions: int = 1024#

Number of hardware-averaged shots per delay point.

field t1_repetitions: int = 3#

Number of independent repeats of the full delay sweep (and its own calibration points). T1 is fitted separately per repeat; the reported t1 is the mean across repeats and t1_error is their standard deviation.

field histogram_bins: int = 10#

Number of bins for the per-repeat T1 histogram plot.

invalid_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = (mappingproxy({'transition': '01'}),)#
pydantic model bragi_quantum.experiments.nodes.characterization.t1.parameters.T1QOI[source]#

Bases: BaseQoi

Quantities of Interest from T1 characterization.

Times are stored in microseconds, matching the fitting units.

Fields:
field t1: float = 0.0#
field t1_error: float = 0.0#
field offset: float = 0.0#
field offset_error: float = 0.0#
field amplitude: float = 0.0#
field amplitude_error: float = 0.0#
to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, float]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Module containing classes that fit and plot data from a T1 experiment.

class bragi_quantum.experiments.nodes.characterization.t1.analysis.T1Analysis(parameters, qoi_cls)[source]#

Bases: ExponentialDecayAnalysis

Analysis that fits T1 decay of a single qubit, repeated independently t1_repetitions times.

Every delay point is a single hardware-averaged value (repetitions hardware-averaged shots collapse into it — that averaging is not a coordinate this analysis has access to). Each of the t1_repetitions independent sweeps is projected onto the |0>-|1> calibration axis using its own calibration points (project broadcasts per slice of the outer t1_repetitions dimension, never averaging calibration points across repeats) and fitted separately to an exponential decay. The reported T1 is the mean of the per-repeat fits and its error is the plain standard deviation across those repeats.

Parameters:
label: ClassVar[str] = 'T1'#
repetitions_key: ClassVar[str] = 't1_repetitions'#
parameters: T1Parameters#

T2 (Ramsey)#

Node implementation for T2* (Ramsey) coherence-time characterization.

class bragi_quantum.experiments.nodes.characterization.t2.node.T2(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.characterization.t2.parameters.T2QOI'>)[source]#

Bases: ExternalParameterFixedScheduleQubitNode

Execution node for T2* (Ramsey) coherence-time characterization.

Each qubit’s two pi/2 pulses are separated by a swept idle time, with a shared artificial_detuning_Hz applied via a clock-phase shift to produce a Ramsey fringe; T2Analysis fits the resulting decaying oscillation to extract T2*.

Parameters:
parameters: T2Parameters#
measurement_cls#

alias of T2Measurement

analysis_cls#

alias of T2Analysis

append_calibration_points: bool = True#
pydantic model bragi_quantum.experiments.nodes.characterization.t2.parameters.T2Parameters[source]#

Bases: CoherenceParameters

Parameters for T2 relaxation-time characterization.

Fields:
field transition: Literal['01'] = '01'#
field delays: list[float] [Optional]#

Sweeping delay times tau between the two pi/2-pulses, in seconds, as an array of setpoints per qubit, keyed by qubit name.

field artificial_detuning_Hz: float = 1000000.0#

Artificial detuning, in Hz, applied to every qubit via a clock-phase shift after the idle time, used to generate the Ramsey fringe.

field repetitions: int = 1024#

Number of hardware-averaged shots per delay point.

field t2_repetitions: int = 3#

Number of independent repeats of the full delay sweep (and its own calibration points). T2* is fitted separately per repeat; the reported t2 is the mean across repeats and t2_error is their standard deviation.

field histogram_bins: int = 10#

Number of bins for the per-repeat T2* histogram plot.

invalid_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = (mappingproxy({'transition': '01'}),)#
pydantic model bragi_quantum.experiments.nodes.characterization.t2.parameters.T2QOI[source]#

Bases: BaseQoi

Quantities of Interest from T2* (Ramsey) characterization.

t2 and tau both hold the fitted decay time, in microseconds, matching the fitting units (the same quantity — tau is the underlying damped-oscillation fit parameter name, t2 is the reported characterization quantity). frequency and frequency_error are in Hz, matching artificial_detuning_Hz.

Fields:
field t2: float = 0.0#
field t2_error: float = 0.0#
field offset: float = 0.0#
field offset_error: float = 0.0#
field amplitude: float = 0.0#
field amplitude_error: float = 0.0#
field frequency: float = 0.0#
field frequency_error: float = 0.0#
field tau: float = 0.0#
field tau_error: float = 0.0#
to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, float]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Module containing classes that fit and plot data from a T2* (Ramsey) experiment.

class bragi_quantum.experiments.nodes.characterization.t2.analysis.T2Analysis(parameters, qoi_cls)[source]#

Bases: CoherenceAnalysis

Analysis that fits a damped Ramsey oscillation to a single qubit’s T2* delay sweep, repeated independently t2_repetitions times.

Every delay point is a single hardware-averaged value (repetitions hardware-averaged shots collapse into it — that averaging is not a coordinate this analysis has access to). Each of the t2_repetitions independent sweeps is projected onto the |0>-|1> calibration axis using its own calibration points (project broadcasts per slice of the outer t2_repetitions dimension, never averaging calibration points across repeats) and fitted separately to an exponentially decaying sinusoid (RamseyModel), seeded with the known (signed) artificial_detuning_Hz so each fit converges on the physically correct oscillation frequency rather than an arbitrary sign. A fit whose frequency lands at or beyond the delay sampling’s Nyquist limit is rejected as an alias, and a fit whose amplitude implausibly exceeds the trace’s own peak-to-peak/2 is rejected as a runaway fit. The reported T2* is the mean of the per-repeat fits and its error is the plain standard deviation across those repeats.

Delays (and so t2/tau) are fitted and reported in microseconds;

frequency/frequency_error stay in Hz,

matching artificial_detuning_Hz — the fitted oscillation frequency is converted between the fit’s native cycles/microsecond and Hz at the fit/report boundary.

Parameters:
label: ClassVar[str] = 'T2*'#
repetitions_key: ClassVar[str] = 't2_repetitions'#
model_cls#

alias of RamseyModel

time_param: ClassVar[str] = 'tau'#
peak_to_peak_per_amplitude: ClassVar[float] = 2.0#
parameters: T2Parameters#

T2 echo#

Node implementation for T2 Echo (Hahn echo) characterization.

class bragi_quantum.experiments.nodes.characterization.t2_echo.node.T2Echo(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.characterization.t2_echo.parameters.T2EchoQOI'>)[source]#

Bases: ExternalParameterFixedScheduleQubitNode

Execution node for T2 Echo (Hahn echo) characterization.

The delay sweep (with its per-point hardware averaging expressed as a loop register, plus the automatic calibration-points block appended by BaseNode.precompile) is compiled once and then executed independently t2_echo_repetitions times: ExternalParameterFixedScheduleNode tags each execution’s data — sweep AND calibration points alike — with its own t2_echo_repetitions coordinate. T2EchoAnalysis fits each repeat separately against its own calibration axis and reports the T2 echo error as the spread across those independent fits.

Parameters:
measurement_cls#

alias of T2EchoMeasurement

analysis_cls#

alias of T2EchoAnalysis

append_calibration_points: bool = True#
parameters: T2EchoParameters#
pydantic model bragi_quantum.experiments.nodes.characterization.t2_echo.parameters.T2EchoParameters[source]#

Bases: CoherenceParameters

Parameters for T2 Echo (Hahn echo) characterization.

Fields:
field transition: Literal['01'] = '01'#
field delays: list[float] [Optional]#

Total echo delays between the two pi/2 pulses, in seconds.

field repetitions: int = 1024#

Number of hardware-averaged shots per delay point.

field t2_echo_repetitions: int = 3#

Number of independent repeats of the full delay sweep (and its own calibration points). T2 echo is fitted separately per repeat; the reported t2_echo is the mean across repeats and t2_echo_error is their standard deviation.

field histogram_bins: int = 10#

Number of bins for the per-repeat T2 echo histogram plot.

invalid_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = (mappingproxy({'transition': '01'}),)#
pydantic model bragi_quantum.experiments.nodes.characterization.t2_echo.parameters.T2EchoQOI[source]#

Bases: BaseQoi

Quantities of Interest from T2 Echo characterization.

Times are stored in microseconds, matching the fitting units.

Fields:
field t2_echo: float = 0.0#
field t2_echo_error: float = 0.0#
field offset: float = 0.0#
field offset_error: float = 0.0#
field amplitude: float = 0.0#
field amplitude_error: float = 0.0#
to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, float]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Module containing classes that fit and plot data from a T2 Echo experiment.

class bragi_quantum.experiments.nodes.characterization.t2_echo.analysis.T2EchoAnalysis(parameters, qoi_cls)[source]#

Bases: ExponentialDecayAnalysis

Analysis that fits T2 echo decay of a single qubit, repeated independently t2_echo_repetitions times.

Every delay point is a single hardware-averaged value (repetitions hardware-averaged shots collapse into it — that averaging is not a coordinate this analysis has access to). Each of the t2_echo_repetitions independent sweeps is projected onto the |0>-|1> calibration axis using its own calibration points (project broadcasts per slice of the outer t2_echo_repetitions dimension, never averaging calibration points across repeats) and fitted separately to an exponential decay. The reported T2 echo is the mean of the per-repeat fits and its error is the plain standard deviation across those repeats.

The recorded delays coordinate is the half-delay (tau/2) the measurement schedule swept — see T2EchoMeasurement — so it is doubled back to the total echo delay before fitting.

Parameters:
label: ClassVar[str] = 'T2 echo'#
repetitions_key: ClassVar[str] = 't2_echo_repetitions'#
delay_scale: ClassVar[float] = 2.0#
parameters: T2EchoParameters#

Randomized benchmarking#

Node implementation for single-qubit randomized benchmarking (RB).

class bragi_quantum.experiments.nodes.characterization.randomized_benchmarking.node.RandomizedBenchmarking(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.characterization.randomized_benchmarking.parameters.RBQOI'>)[source]#

Bases: ScheduleQubitNode

Execution node for single-qubit randomized benchmarking (SSRO-classified).

Each of the n_seeds independent random-Clifford realizations needs a genuinely different compiled schedule (the random sequence is baked directly into the pulses, not expressible as a hardware Variable sweep), so — unlike every other node so far — this one drives its outer loop via ScheduleNode.outer_schedule_samplespace (recompile fresh per iteration) rather than ExternalParameterFixedScheduleQubitNode (compile once, re-execute). seeds is the outer dimension; the clifford_sequence_lengths sweep is inner, expressed as a plain Python loop within each seed’s own compiled schedule (also not a hardware Variable sweep, since each sequence length needs its own randomly generated gates). Every per-seed compile also gets its own automatic calibration-points block, so each seed’s state populations are normalized against its own calibration, never an average across seeds.

Parameters:
measurement_cls#

alias of RandomizedBenchmarkingMeasurement

analysis_cls#

alias of RBAnalysis

append_calibration_points: bool = True#
parameters: RBParameters#
pydantic model bragi_quantum.experiments.nodes.characterization.randomized_benchmarking.parameters.RBParameters[source]#

Bases: BaseParameters

Parameters for single-qubit randomized benchmarking (SSRO-classified).

Fields:
field n_seeds: int = 8#

Number of independent random-Clifford-sequence realizations (a fresh, differently seeded sequence per sequence length). Recompiled and executed once per seed; fidelity is fit against their seed-averaged state populations, weighted by the seed-to-seed spread at each sequence length.

field number_of_shots: int = 500#

Single-shot repeats measured per (seed, sequence length) point.

field repetitions: int = 1024#

Hardware-averaged shots for the automatic calibration-points block appended by BaseNode.precompile — independent of number_of_shots, which drives the main single-shot RB loop.

field clifford_sequence_lengths: list[int] [Optional]#

Numbers of random Cliffords applied (then inverted) per sequence.

field seed_number: str | None = None#

1-based seed(s) to show in the IQ-cloud plot, e.g. 1; 3-5; 3,4,5. Defaults to the first seed (1); several seeds render as a grid.

field clifford_sequence_index: str | None = None#

1-based index/indices into clifford_sequence_lengths to show in the IQ-cloud plot, e.g. 1; 3-5; 3,4,5. Defaults to the last one; several indices render as a grid.

invalid_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
pydantic model bragi_quantum.experiments.nodes.characterization.randomized_benchmarking.parameters.RBQOI[source]#

Bases: BaseQoi

Quantities of Interest from randomized benchmarking.

Fields:
field fidelity: float = 0.0#
field fidelity_error: float = 0.0#
field reduced_chi2: float = 0.0#
field leakage: float = 0.0#
field leakage_error: float = 0.0#
field seepage: float = 0.0#
field seepage_error: float = 0.0#
to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, float]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Module containing the class that classifies, fits and plots data from a randomized benchmarking (RB) experiment.

class bragi_quantum.experiments.nodes.characterization.randomized_benchmarking.analysis.RBAnalysis(parameters, qoi_cls)[source]#

Bases: Analysis

Analysis that classifies single-shot RB data into states 0/1/2 and fits the resulting population decays.

Every shot is classified via nearest-centroid (Voronoi) comparison built from three pairwise calibration-axis projections (bragi_quantum.experiments.utils.calibration_points.project_onto_calibration with (low, high) = (0, 1), (1, 2) and (0, 2)): treating each state’s calibration population as bivariate Gaussian with shared covariance, each pairwise axis’s 0.5 threshold is exactly that pair’s Bayes decision boundary, so the state that wins both of its relevant pairwise comparisons is the globally nearest centroid (see _classify_shots). All three axes are needed — |2> is not generally collinear with |0>-|1>, so a sequential two-axis check would silently misclassify. If the qubit’s 1->2 pulse isn’t calibrated (no CAL=2 point), classification falls back to 0-vs-1 only and leakage/seepage are left unmeasured (NaN).

Every one of the n_seeds independent random-Clifford realizations carries its OWN calibration points (never an average across seeds), so each seed’s shots are classified against calibration measured in that same compiled schedule. State populations are then averaged across seeds; the seed-to-seed standard deviation is used as the fit weight — a sequence length whose population is well-determined across seeds pulls harder on the fit.

Parameters:
element_kind: str = 'qubit'#
expects_calibration_points: bool = True#
parameters: RBParameters#
compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

RBQOI

plot_title()[source]#

Title for this element’s (sub)plot. Override per node if desired.

Return type:

str

list_plots()[source]#

Names of the plots this analysis can render. Override for multi-plot nodes.

support_figures()[source]#

The IQ-cloud figure, saved to disk alongside the main decay plot.

Same figure as the interactive “iq_cloud” plot in bragi_quantum.gui; skipped when there’s no calibration/classification to show it against.

Return type:

list[tuple[Figure, str]]

add_traces(fig, row=1, col=1)[source]#

Add this element’s plotly traces (and axis titles) to fig at (row, col).

Parameters:
Return type:

None

Purity benchmarking#

Node implementation for single-qubit purity benchmarking.

class bragi_quantum.experiments.nodes.characterization.purity_benchmarking.node.PurityBenchmarking(parameters, qoi_cls=<class 'bragi_quantum.experiments.nodes.characterization.purity_benchmarking.parameters.PurityBenchmarkingQOI'>)[source]#

Bases: ScheduleQubitNode

Execution node for single-qubit purity benchmarking.

As in RandomizedBenchmarking, each of the n_seeds independent random-Clifford realizations needs its own compiled schedule (the random sequence is baked directly into the pulses), so this node drives its outer loop via ScheduleNode.outer_schedule_samplespace (recompile fresh per seed) rather than ExternalParameterFixedScheduleQubitNode. seeds is the outer dimension; clifford_sequence_lengths and the three measurement bases are inner, expressed as plain Python loops within each seed’s own compiled schedule. Every per-seed compile also gets its own automatic calibration-points block, so each seed’s populations are normalized against its own calibration, never an average across seeds.

Parameters:
measurement_cls#

alias of PurityBenchmarkingMeasurement

analysis_cls#

alias of PurityBenchmarkingAnalysis

append_calibration_points: bool = True#
parameters: PurityBenchmarkingParameters#
pydantic model bragi_quantum.experiments.nodes.characterization.purity_benchmarking.parameters.PurityBenchmarkingParameters[source]#

Bases: BaseParameters

Parameters for single-qubit purity benchmarking.

Fields:
field n_seeds: int = 10#

Number of independent random-Clifford-sequence realizations (a fresh, differently seeded sequence per sequence length). Recompiled and executed once per seed; purity is fit against their seed-averaged values, weighted by the seed-to-seed spread at each sequence length.

field repetitions: int = 1024#

Hardware-averaged shots per (seed, sequence length, basis) point, and for the automatic calibration-points block appended by BaseNode.precompile.

field clifford_sequence_lengths: list[int] [Optional]#

Numbers of random Cliffords applied per sequence. Each sequence is measured in the X, Y and Z bases (no recovery Clifford) so the Pauli expectation values can be combined into a purity.

invalid_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
legal_variant_combinations: ClassVar[tuple[ParameterCombination, ...]] = ()#
pydantic model bragi_quantum.experiments.nodes.characterization.purity_benchmarking.parameters.PurityBenchmarkingQOI[source]#

Bases: BaseQoi

Quantities of Interest from purity benchmarking.

purity_fidelity is the raw purity-decay fit parameter, i.e. the unitarity u of Wallman et al. (“Estimating the coherence of noise”, New J. Phys. 17 113020) / Zhu et al. (arXiv:2407.07960) — the name is kept for backward compatibility with the original tergite-autocalibration node. incoherent_error is the decoherence-limited error bound derived from u alone (Zhu et al. eq. 13). coherent_error additionally needs a companion randomized-benchmarking result for the same qubit (read back from Redis, see PurityBenchmarkingAnalysis); it is float("nan") when no such result is available.

Fields:
field purity_fidelity: float = 0.0#
field purity_fidelity_error: float = 0.0#
field reduced_chi2: float = 0.0#
field incoherent_error: float = 0.0#
field incoherent_error_error: float = 0.0#
field coherent_error: float = 0.0#
field coherent_error_error: float = 0.0#
to_dict()[source]#

Returns the calculated QOIs as a dictionary. The keys should match the attribute paths in the bragi_quantum.datalayer models (e.g., {‘rxy.amp180’: 0.5}).

Return type:

dict[str, float]

to_redis_dict()[source]#
Return type:

dict[str, dict[str, float]]

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Module containing the class that computes, fits and plots purity from a purity benchmarking experiment.

class bragi_quantum.experiments.nodes.characterization.purity_benchmarking.analysis.PurityBenchmarkingAnalysis(parameters, qoi_cls)[source]#

Bases: Analysis

Analysis that combines per-basis Pauli expectation values into a purity and fits its decay against the number of Cliffords.

Every shot is hardware-averaged (never classified), and each of the n_seeds independent random-Clifford realizations carries its OWN calibration points (never an average across seeds — mirrors RBAnalysis): each seed’s three basis measurements are projected onto the |0>-|1> axis using calibration measured in that same compiled schedule, converted to Pauli expectation values (x_exp = 2 * p_x - 1 etc.) and combined into purity = x_exp**2 + y_exp**2 + z_exp**2. Purity is then averaged across seeds; the seed-to-seed standard deviation is used as the fit weight, same as RBAnalysis.

The purity decay parameter u (unitarity) alone already bounds the incoherent (decoherence-limited) error, independent of any other measurement — Wallman et al. (“Estimating the coherence of noise”, New J. Phys. 17 113020), restated as eq. 13 of Zhu et al. (arXiv:2407.07960): incoherent_error = (1/2)(1 - sqrt(u)) for a single qubit. Combining that with a companion randomized-benchmarking (RB) result for the same qubit additionally isolates the coherent (“true”, systematic / calibration) error: coherent_error = total_error - incoherent_error (Zhu et al. eq. 14), where total_error = 1 - rb_fidelity is RB’s average gate error rate (Zhu et al. eq. 4). RB’s result is read back from Redis (the rb_fidelity trusted value written by RandomizedBenchmarking for this same qubit) — if none is found (RB hasn’t been run yet, or no active session), coherent_error is reported as float("nan") rather than failing the analysis: incoherent_error never depends on it.

Parameters:
element_kind: str = 'qubit'#
expects_calibration_points: bool = True#
parameters: PurityBenchmarkingParameters#
compute_qoi()[source]#

Compute the QOI for the current element.

Runs against self.dataset / self.magnitudes / self.data_var (already set for the current element) and should store whatever state add_traces() needs on self.

Return type:

PurityBenchmarkingQOI

plot_title()[source]#

Title for this element’s (sub)plot. Override per node if desired.

Return type:

str

add_traces(fig, row=1, col=1)[source]#

Add this element’s plotly traces (and axis titles) to fig at (row, col).

Parameters:
Return type:

None

Registry#

See also the Node Registry guide.

Access to the bragi_quantum.experiments node registry.

pydantic model bragi_quantum.experiments.registry.RequiresSpec[source]#

Bases: BaseModel

A variant’s dependency on gates/parameters. See schema in nodes.yaml

Fields:
field measure_gate_class: str | None = None#
field calibrated_gates: list[str] [Optional]#
field calibrated_parameters: list[str] [Optional]#
pydantic model bragi_quantum.experiments.registry.VariantEntry[source]#

Bases: BaseModel

One concrete variant of a node entry. See schema in nodes.yaml

Fields:
field name: str [Required]#
field qoi: str [Required]#
field parameters: dict[str, Any] [Optional]#
field requires: RequiresSpec | None = None#
field calibrates: list[str] [Optional]#
field show_in_graph: bool = True#
pydantic model bragi_quantum.experiments.registry.NodeEntry[source]#

Bases: BaseModel

One registry entry. See schema in nodes.yaml

Fields:
field node: str [Required]#
field analysis: str [Required]#
field doc: str | None = None#
field variants: list[VariantEntry] [Required]#
Constraints:
  • min_length = 1

pydantic model bragi_quantum.experiments.registry.NodeCategory[source]#

Bases: BaseModel

A group of entries sharing an import root (e.g. readout).

Fields:
field package: str [Required]#
field entries: dict[str, NodeEntry] [Required]#
pydantic model bragi_quantum.experiments.registry.NodeRegistryFile[source]#

Bases: BaseModel

The validated shape of nodes.yaml.

Fields:
field nodes: dict[str, NodeCategory] [Required]#
class bragi_quantum.experiments.registry.ExperimentNodeVariant(name, node_cls, qoi_cls, analysis_cls, category, parameters=<factory>, requires=None, calibrates=<factory>, doc=None, show_in_graph=True)[source]#

Bases: object

A registered node variant, ready to be instantiated.

Variables:
  • name (str) – The stable registry name of the variant.

  • node_cls (type) – The node class to instantiate.

  • qoi_cls (type) – QOI class injected as qoi_cls.

  • analysis_cls (type) – Analysis class injected as analysis_cls.

  • category (str) – The top-level nodes.yaml category this variant’s entry lives under (e.g. "readout").

  • parameters (dict[str, Any]) – Fixed parameter values that define the variant (e.g. {"state": 1, "transition": "12"}). These always win over caller-supplied overrides in create().

  • requires (bragi_quantum.experiments.registry.RequiresSpec | None) – The variant’s declared gate/parameter dependencies, if any.

  • calibrates (list[str]) – The redis keys this variant’s QOI writes.

  • doc (str | None) – The entry’s docs/node-library/nodes/<doc>.md stem, if any.

  • show_in_graph (bool) – Whether this variant should appear in the docs dependency graph.

Parameters:
name: str#
node_cls: type#
qoi_cls: type#
analysis_cls: type#
category: str#
parameters: dict[str, Any]#
requires: RequiresSpec | None = None#
calibrates: list[str]#
doc: str | None = None#
show_in_graph: bool = True#
property parameters_cls: type#

The node’s Parameters model, from its __init__ annotation.

create(**parameter_overrides)[source]#

Build the node: validate parameters, inject QOI/analysis classes.

Must be called inside an active calibration session (node __init__ requires it). parameter_overrides are free (sweep sizes, qubits, …) but cannot override the spec’s own parameters — those define the variant’s identity.

Parameters:

parameter_overrides (Any)

bragi_quantum.experiments.registry.load_node_registry()[source]#

Return the registered node variants as {variant_name: ExperimentNodeVariant}.

Reads bragi_quantum.experiments/nodes.yaml, validates it against NodeRegistryFile, then imports each referenced class. Every entry’s variants are flattened into this one dict, keyed by each variant’s own name.

Return type:

dict[str, ExperimentNodeVariant]

Utilities#

Deprecated compatibility shim.

Every declaration formerly defined in this module has moved to bragi_quantum.experiments.fitting_tools (split into fitting_tools.models and fitting_tools.functions). Importing from here still works, but emits a FutureWarning pointing at the new location.

Calibration-points block: schedule-side detection, dataset-side lookup and projection, and the exceptions raised when it can’t be found.

Import wholesale: from bragi_quantum.experiments.utils import calibration_points as cal.

exception bragi_quantum.experiments.utils.calibration_points.CalibrationPointsError[source]#

Bases: KeyError

Base class for calibration-point lookup failures.

Subclasses KeyError so existing except KeyError sites still work.

exception bragi_quantum.experiments.utils.calibration_points.NoCalibrationPointsError[source]#

Bases: CalibrationPointsError

No <element>_CAL data variable found in the dataset.

exception bragi_quantum.experiments.utils.calibration_points.PartialCalibrationPointsError[source]#

Bases: CalibrationPointsError

<element>_CAL exists but is missing a required CAL state.

bragi_quantum.experiments.utils.calibration_points.has_calibration_points(schedule)[source]#

Whether schedule contains a schedulable labeled CALIBRATION_POINTS_LABEL.

Parameters:

schedule (TimeableScheduleBase) – A schedule, typically already compiled (see BaseNode.precompile).

Return type:

bool

bragi_quantum.experiments.utils.calibration_points.element_has_calibration_data(dataset, element_name)[source]#

Whether dataset carries a <element_name>_CAL variable at all.

Parameters:
  • dataset (xr.Dataset) – This element’s (already-sliced) dataset.

  • element_name (str) – The qubit/coupler name, e.g. "q06".

Return type:

bool

bragi_quantum.experiments.utils.calibration_points.available_calibration_states(dataset, element_name)[source]#

The CAL state values present for element_name.

Parameters:
  • dataset (xr.Dataset) – This element’s (already-sliced) dataset.

  • element_name (str) – The qubit/coupler name, e.g. "q06".

Returns:

Empty if element_name has no calibration data at all.

Return type:

frozenset[float]

bragi_quantum.experiments.utils.calibration_points.get_calibration_complex(dataset, element_name, *, required_states=frozenset({0.0, 1.0}))[source]#

Return element_name’s calibration IQ values as complex numbers.

Parameters:
  • dataset (xr.Dataset) – This element’s (already-sliced) dataset.

  • element_name (str) – The qubit/coupler name, e.g. "q06".

  • required_states (frozenset[float], optional) – CAL values that must be present. By default {0.0, 1.0}.

Returns:

Complex IQ values, one per CAL state (and any outer dimensions, e.g. repetitions, preserved unaveraged).

Return type:

xr.DataArray

Raises:
bragi_quantum.experiments.utils.calibration_points.project_onto_calibration(complex_data, calib, *, low=0, high=1)[source]#

Rotate and normalize IQ data onto the low-high axis calib defines.

CAL=low maps to 0, CAL=high maps to 1. Normalization is applied per slice of any outer dimensions calib carries (e.g. repetitions): xarray broadcasting pairs each slice of complex_data with its own calibration points, never an average of them.

Parameters:
  • complex_data (xr.DataArray) – Complex-valued IQ data whose outer dimensions align with calib. Typically self.S21[self.data_var].

  • calib (xr.DataArray) – This element’s calibration points, from get_calibration_complex.

  • low (float, optional) – Calibrated state mapped to 0. By default the ground state (0).

  • high (float, optional) – Calibrated state mapped to 1. By default the first excited state (1).

Returns:

Real-valued, same shape as complex_data, near 0 at low and near 1 at high.

Return type:

xr.DataArray

bragi_quantum.experiments.utils.calibration_points.dataset_has_calibration_points_for_all_qubits(dataset, element_name, *, required_states=frozenset({0.0, 1.0}))[source]#

Whether get_calibration_complex would succeed for element_name.

Never raises; use to decide upfront (e.g. to label a plot axis) without needing to catch project’s CalibrationPointsError.

Parameters:
  • dataset (xr.Dataset) – This element’s (already-sliced) dataset.

  • element_name (str) – The qubit/coupler name, e.g. "q06".

  • required_states (frozenset[float], optional) – CAL values that must be present. By default {0.0, 1.0}.

Return type:

bool

bragi_quantum.experiments.utils.calibration_points.project(dataset, element_name, complex_data, *, low=0, high=1)[source]#

get_calibration_complex + project_onto_calibration.

Parameters:
  • dataset (xr.Dataset) – This element’s (already-sliced) dataset.

  • element_name (str) – The qubit/coupler name, e.g. "q06".

  • complex_data (xr.DataArray) – Complex-valued IQ data. Typically self.S21[self.data_var].

  • low (float, optional) – Calibrated state mapped to 0. By default the ground state (0).

  • high (float, optional) – Calibrated state mapped to 1. By default the first excited state (1).

Returns:

Real-valued, same shape as complex_data, near 0 at low and near 1 at high.

Return type:

xr.DataArray

Raises:

CalibrationPointsError – Calibration data for element_name is missing or doesn’t cover both low and high. Callers that want to degrade gracefully (e.g. fall back to raw magnitude) should catch this themselves — that’s a judgment call for the analysis, not this module.

Ported from tergite-autocalibration (lib/utils/classification_functions).

Classifies raw IQ points into the |0>, |1>, |2> states using the three angular boundaries (omega_01, omega_12, omega_20) and centroid produced by a 3-state readout calibration (see bragi_quantum.experiments.fitting_tools.models.classification.ThreeClassBoundary). Unlike the tergite original, the boundary values are passed in explicitly rather than read from Redis inside this function, so callers control where those values come from (Redis, the device model, or a test fixture) and the classifier itself stays pure and easily testable.

bragi_quantum.experiments.utils.classification_functions.assign_state(iq_values, *, centroid_i, centroid_q, omega_01, omega_12, omega_20)[source]#

Classify each point in iq_values into state 0, 1, or 2.

The three angular boundaries divide the IQ plane (relative to the centroid) into three sectors, one per state; iq_values is translated so the centroid sits at the origin, converted to an angle, and each angle is assigned to the sector it falls into.

Parameters:
Return type:

DataArray

The single-qubit Clifford group (24 elements) decomposed into physical XY rotations, used to find the recovery/inverse operation of a random Clifford sequence for randomized benchmarking.

Correctness is enforced at the group level, not the element level: S4ElementXY just turns its physical pulses into a Pauli Transfer Matrix (PTM), while S4GroupPTM validates that its tabulated elements actually form a group (closed, contains the identity, every element has an inverse) rather than checking each element’s angles in isolation.

S4GroupPTM also builds a PTM -> index lookup table lazily on first use and caches it for the group’s lifetime (functools.cached_property). At 24 elements this barely matters, but it’s built this way because it will: the two-qubit Clifford group has 11,520 elements, and recovery() gets called once per random RB sequence – a linear scan over that many elements, every time, is not something you want to pay for repeatedly.

Ported from tergite-autocalibration’s utils/clifford_elements_decomposition.py.

pydantic model bragi_quantum.experiments.utils.clifford_elements_decomposition.Clifford1XYdecomp_pulse[source]#

Bases: BaseModel

A single physical rotation Rxy(theta, phi), in degrees.

Fields:
field theta: int [Required]#
field phi: int [Required]#
pydantic model bragi_quantum.experiments.utils.clifford_elements_decomposition.S4ElementXY[source]#

Bases: BaseModel

One of the 24 single-qubit Cliffords, decomposed into 1-3 physical XY pulses.

Modulo global phase, the single-qubit Clifford group is exactly the rotational symmetry group of the octahedron whose vertices are the six Pauli eigenstates on the Bloch sphere – a group of order 24 isomorphic to S4, the symmetric group on 4 elements.

Fields:
field pulses: tuple[Clifford1XYdecomp_pulse, ...] [Required]#
classmethod from_angles(*pulses)[source]#

Build from (theta, phi) pairs, e.g. (90, 0).

Parameters:

pulses (tuple[int, int])

Return type:

S4ElementXY

to_ptm()[source]#

The 4x4 Pauli Transfer Matrix of the composed physical pulses.

Unlike the raw 2x2 unitary, the PTM represents conjugation rho -> U rho U^dagger rather than U itself, so any global phase on U cancels out; this makes the PTM a faithful representation of PU(2) (unitaries modulo global phase) instead of U(2), which is what “which Clifford is this” actually means physically.

Return type:

ndarray

pydantic model bragi_quantum.experiments.utils.clifford_elements_decomposition.S4GroupPTM[source]#

Bases: BaseModel

The 24-element single-qubit Clifford group.

Rather than checking each S4ElementXY’s angles in isolation, this validates that the tabulated elements actually satisfy the group axioms as PTMs: exactly 24 distinct elements, closed under composition, containing the identity, and every element has an inverse within the set.

elements is a ClassVar, not a field: there is exactly one single-qubit Clifford group, its 24 elements are a fixed mathematical fact, not per-instance configuration.

elements: ClassVar[tuple[S4ElementXY, ...]] = (S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=0, phi=0),)), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=90, phi=90), Clifford1XYdecomp_pulse(theta=90, phi=0))), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=-90, phi=0), Clifford1XYdecomp_pulse(theta=-90, phi=90))), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=180, phi=0),)), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=-90, phi=90), Clifford1XYdecomp_pulse(theta=-90, phi=0))), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=90, phi=0), Clifford1XYdecomp_pulse(theta=-90, phi=90))), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=180, phi=90),)), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=-90, phi=90), Clifford1XYdecomp_pulse(theta=90, phi=0))), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=90, phi=0), Clifford1XYdecomp_pulse(theta=90, phi=90))), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=180, phi=0), Clifford1XYdecomp_pulse(theta=180, phi=90))), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=90, phi=90), Clifford1XYdecomp_pulse(theta=-90, phi=0))), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=-90, phi=0), Clifford1XYdecomp_pulse(theta=90, phi=90))), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=90, phi=90), Clifford1XYdecomp_pulse(theta=180, phi=0))), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=-90, phi=0),)), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=90, phi=0), Clifford1XYdecomp_pulse(theta=-90, phi=90), Clifford1XYdecomp_pulse(theta=-90, phi=0))), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=-90, phi=90),)), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=90, phi=0),)), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=90, phi=0), Clifford1XYdecomp_pulse(theta=90, phi=90), Clifford1XYdecomp_pulse(theta=90, phi=0))), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=-90, phi=90), Clifford1XYdecomp_pulse(theta=180, phi=0))), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=90, phi=0), Clifford1XYdecomp_pulse(theta=180, phi=90))), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=90, phi=0), Clifford1XYdecomp_pulse(theta=-90, phi=90), Clifford1XYdecomp_pulse(theta=90, phi=0))), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=90, phi=90),)), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=-90, phi=0), Clifford1XYdecomp_pulse(theta=180, phi=90))), S4ElementXY(pulses=(Clifford1XYdecomp_pulse(theta=90, phi=0), Clifford1XYdecomp_pulse(theta=90, phi=90), Clifford1XYdecomp_pulse(theta=-90, phi=0))))#
index_of(ptm)[source]#

The index of the element whose PTM is ptm.

Only meaningful for a PTM that is actually one of the group’s own elements (e.g. a product or inverse of tabulated PTMs) – guaranteed to be found by the group axioms checked in _check_group_axioms.

Parameters:

ptm (ndarray)

Return type:

int

net_ptm(rng_sequence)[source]#

The composed PTM of the physical pulses for a sequence of element indices.

Parameters:

rng_sequence (ndarray)

Return type:

ndarray

recovery(rng_sequence)[source]#

Find the Clifford (and its index) that inverts the net Clifford operation of rng_sequence, so appending it recovers the identity.

The group is closed and every element has an inverse (checked once, by _check_group_axioms), so the recovery element is guaranteed to exist – no defensive “not found” handling needed. Since every PTM here is an orthogonal integer matrix, its inverse is just its transpose, so there’s no need for np.linalg.inv either.

Parameters:

rng_sequence (ndarray)

Return type:

tuple[int, S4ElementXY]

bragi_quantum.experiments.utils.cluster_snapshots.cluster_metadata_dir(data_path, measurement)[source]#

Return (and create) the per-submeasurement metadata root.

Structure:

<data_path>/cluster_metadata/measurement_<N>/
Parameters:
Return type:

Path

bragi_quantum.experiments.utils.cluster_snapshots.take_cluster_snapshots(data_path, measurement, cluster_names, *, label)[source]#

Save a JSON snapshot of every cluster under cluster_metadata/.

Each cluster gets its own subfolder inside the per-submeasurement directory:

cluster_metadata/measurement_<N>/<cluster_name>/before.json
cluster_metadata/measurement_<N>/<cluster_name>/after.json
cluster_metadata/measurement_<N>/<cluster_name>/snapshot.diff
Parameters:
Return type:

None

Helpers to load a saved node dataset and run a single-element analysis on it.

A node’s HDF5 stores every element (qubit or coupler) as its own data variable named after the element (q06, q06_q07, …). Before an analysis can run, that full dataset must be sliced down to one element — the same operation the node does internally in _analyze_all_qubits and that bragi_quantum.gui does when it replays a plot. These helpers centralise that slicing so callers (scripts, notebooks, reanalysis tooling) never have to touch xarray by hand.

bragi_quantum.experiments.utils.dataset_utils.as_dataset(dataset)[source]#

Return an open dataset, accepting either an xr.Dataset or a file path.

Parameters:

dataset (Dataset | str | PathLike)

Return type:

Dataset

bragi_quantum.experiments.utils.dataset_utils.slice_element(dataset, element, *, kind='qubit', node_name=None)[source]#

Slice a single element out of a full node dataset.

Merges the data variable(s) named after element, tags the result, and — for qubits — restricts it to the element’s own sweep coordinate. The returned dataset is exactly what process_qubit / process_coupler expect.

Also picks up element’s own "<element>_CAL" companion variable (if present), so calibration-point data travels with its owning qubit rather than being dropped by the slice — see bragi_quantum.experiments.utils.calibration_points.get_calibration_complex/ project.

Parameters:
  • dataset (Dataset | str | PathLike) – an open xarray.Dataset or a path to an HDF5 file.

  • element (str) – the qubit ("q06") or coupler ("q06_q07") to extract.

  • kind (str) – "qubit" (default) or "coupler".

  • node_name (str | None) – optional value recorded in ds.attrs["node"].

Returns:

The single-element dataset. If element is not present as a variable (already a single-element dataset), it is returned unchanged.

Return type:

Dataset

bragi_quantum.experiments.utils.dataset_utils.validate_raw_dataset(raw_ds, transmons)[source]#

Raise/log on an empty or suspicious raw dataset before any processing.

Parameters:
Return type:

None

bragi_quantum.experiments.utils.dataset_utils.drop_active_reset_and_extra_coords(raw_ds, schedule_samplespace)[source]#

Drop AR (active reset) sample channels and coords outside the inner sweep.

The coordinate ‘acq_index_<i>’ is special: it corresponds to the flat measurement-index dimension of channel <i> and must always be kept.

Parameters:
  • raw_ds (Dataset)

  • schedule_samplespace (dict[str, Any])

Return type:

Dataset

bragi_quantum.experiments.utils.dataset_utils.sorted_by_acq_channel(transmons)[source]#
Parameters:

transmons (dict[str, ExtendedTransmon])

Return type:

list[ExtendedTransmon]

bragi_quantum.experiments.utils.dataset_utils.rename_channels_to_qubit_names(ds, transmons)[source]#

Invert the acquisition-channel-to-qubit-name mapping on the dataset’s data vars.

The acquisition dimensions are created by measure_system using int(acq_channel), so the cast here must match: an acq_channel overlaid from Redis can arrive as a float (e.g. 0.0), which would otherwise produce “acq_index_0.0” and mismatch the “acq_index_0” dimension the cluster actually returns.

Parameters:
Return type:

Dataset

bragi_quantum.experiments.utils.dataset_utils.resolve_dimension_names(schedule_samplespace, raw_ds)[source]#

The sweep dimensions to reshape the flat acquisition index into.

Appends ‘shot_index’ when the dataset carries single-shot data, so the multi-index built from it is aware of that extra dimension.

Parameters:
  • schedule_samplespace (dict[str, Any])

  • raw_ds (Dataset)

Return type:

list[str]

bragi_quantum.experiments.utils.dataset_utils.get_acq_index_dim_name(da, acq_channel)[source]#

Return the acquisition-index dimension name for da.

qblox-scheduler records the authoritative name in da.attrs["acq_index_dim_name"] — acquisition channels that share identical coords in the schedule are merged into one such shared dimension (e.g. "acq_index_0_1"), so it is no longer safe to assume every channel owns its own private acq_index_<channel> dimension. Falls back to that legacy convention when the attribute is absent.

Parameters:
  • da (DataArray)

  • acq_channel (int)

Return type:

str

bragi_quantum.experiments.utils.dataset_utils.filter_rows_for_channel(da, acq_dim, anchor_coord)[source]#

Keep only the rows of a (possibly shared) acquisition dimension for one channel.

When several channels share acq_dim, rows belonging to other channels carry NaN at anchor_coord. anchor_coord must be per-qubit distinct — the first schedule_samplespace coordinate, built via make_linear_domains, satisfies this. A no-op when the channel owns acq_dim outright (no NaNs present).

Parameters:
  • da (DataArray)

  • acq_dim (str)

  • anchor_coord (str)

Return type:

DataArray

bragi_quantum.experiments.utils.dataset_utils.drop_unrelated_coords(da, coord_names)[source]#

Drop every non-dimension coordinate on da except coord_names.

Parameters:
  • da (DataArray)

  • coord_names (list[str])

Return type:

DataArray

bragi_quantum.experiments.utils.dataset_utils.reshape_flat_acquisition_dim(da, acq_dim, coord_names)[source]#

Replace the flat acquisition dimension with proper named coordinate dimensions.

For a single coordinate swap_dims is used to avoid xarray’s single-level-MultiIndex restriction on unstack. For multiple coordinates set_index + unstack builds an N-D grid.

Parameters:
  • da (DataArray)

  • acq_dim (str)

  • coord_names (list[str])

Return type:

DataArray

bragi_quantum.experiments.utils.dataset_utils.build_channel_dataset(ds, transmon, dimension_names)[source]#

Isolate and reshape one qubit’s acquisition data out of its flat dim.

Parameters:
Return type:

Dataset

bragi_quantum.experiments.utils.dataset_utils.build_channel_datasets(ds, transmons, dimension_names)[source]#
Parameters:
Return type:

list[Dataset]

bragi_quantum.experiments.utils.dataset_utils.merge_channel_datasets(datasets)[source]#
Parameters:

datasets (list[Dataset])

Return type:

Dataset

bragi_quantum.experiments.utils.deprecation.deprecated(replacement)[source]#

Mark a callable or class as deprecated, pointing callers to replacement.

Parameters:

replacement (str)

Return type:

Callable[[_F], _F]

bragi_quantum.experiments.utils.measurement_utils.reduce_samplespace(iteration, samplespace)[source]#
Parameters:
  • iteration (int)

  • samplespace (dict)

Return type:

dict

bragi_quantum.experiments.utils.q1asm_dump.plot_module_waveforms(module_dir, measurement_id, seq_waveforms)[source]#

Plot waveforms for all sequencers of a module into a single figure.

Create one subplot per sequencer that has waveforms (up to 6), arranged in a single column with a shared x axis. Each subplot title is the sequencer index; each line label (sequencer-prefixed, in the shared legend) is the waveform index field. The figure title is the measurement ID.

Safe to call from a background thread.

Return the path to the written waveforms.jpg, or None when there is nothing to plot.

Parameters:
Return type:

Path | None

bragi_quantum.experiments.utils.q1asm_dump.dump_q1asm_programs(data_path, compiled_schedule, measurement)[source]#

Dump compiled q1asm programs to data_path/q1asm_programs/<cluster>/<module>/<sequencer>.json.

The folder hierarchy mirrors the hardware topology:

data_path/q1asm_programs/<cluster_name>/<module_name>/<sequencer_name>.json

For each sequencer the following files are written:
  • sequencerX.json — full serialised sequencer data

  • sequencerX.q1asm — extracted assembly program text

  • waveforms.jpg — one subplot per sequencer with waveforms (per module)

Parameters:
  • data_path (Path | None)

  • compiled_schedule (CompiledSchedule)

  • measurement (tuple[int, int])

Return type:

None

Utility functions for generating sample space arrays for spectroscopy measurements.

bragi_quantum.experiments.utils.samplespace.resonator_samples(qubit, state=0, samples=None, half_width=None)[source]#

Dynamically generates the frequency sweep array for a resonator spectroscopy measurement.

Fetches the central readout frequency for the targeted qubit directly from the active SessionContext’s device, applying a state-dependent shift, and generating a linear space around it.

Parameters:
  • qubit (str) – The name of the target qubit (e.g., ‘q16’).

  • state (int) – The target qubit state (0 for ground, 1 for first excited, etc.).

  • samples (Optional[int]) – Number of points in the sweep. Defaults to 100 if None.

  • half_width (Optional[float]) – The half-width of the sweep window in Hz. Defaults to 1 MHz if None.

Returns:

A linear array of frequencies to sweep.

Return type:

np.ndarray

Raises:

KeyError – If the qubit is not found in the device.

bragi_quantum.experiments.utils.samplespace.qubit_samples(qubit, transition='01', samples=None, half_width=None, use_freq_12_from_config=None)[source]#

Dynamically generates the frequency sweep array for a qubit spectroscopy measurement.

Fetches the central transition frequency for the targeted qubit directly from the active SessionContext’s device, applying detuning logic for higher transitions.

Parameters:
  • qubit (str) – The name of the target qubit (e.g., ‘q16’).

  • transition (str) – The target transition (‘01’ or ‘12’). Defaults to ‘01’.

  • samples (Optional[int]) – Number of points in the sweep. Defaults to 100 if None.

  • half_width (Optional[float]) – The half-width of the sweep window in Hz. Defaults to 5 MHz if None.

  • use_freq_12_from_config (Optional[bool]) – If True, attempts to use explicit f12 from config.

Returns:

A linear array of frequencies to sweep.

Return type:

np.ndarray

Raises:
  • ValueError – If an unknown transition is provided.

  • KeyError – If the qubit is not found in the device.

bragi_quantum.experiments.utils.schedule_execution.execute_schedule(compiled_schedule, hardware_agent, *, execution_mode, measurement=(0, 1), data_path=None, cluster_names=None, save_cluster_metadata_to_disk=False)[source]#
Parameters:
  • compiled_schedule (CompiledSchedule)

  • hardware_agent (HardwareAgent)

  • execution_mode (ExecutionMode)

  • measurement (tuple[int, int])

  • data_path (Path | None)

  • cluster_names (list[str] | None)

  • save_cluster_metadata_to_disk (bool)

Return type:

Dataset

bragi_quantum.experiments.utils.timing.timed(label, suffix_fn=None, timing_category=None, timing_trace_args=None)[source]#

Context manager that logs the wall-clock duration of the wrapped block.

Also records this span into the active session’s Chrome/Perfetto timing trace (timing_trace_events.json), on top of the human-readable log line.

Usage:

with timed("Measurement took: "):
    hardware_agent.run(compiled_schedule)

Pass suffix_fn to append a string computed from the elapsed time:

with timed("Measurement took: ", suffix_fn=lambda d: f" ({d - expected:+.5g} sec)"):
    thread_lab.join()

Pass timing_category (timing categories defined in bragi_quantum.datalayer.managing.time_tracing) to bucket it under one of the four named categories; defaults to TIMING_OTHER if not specified.

Parameters:
Return type:

Generator[None, None, None]

pydantic model bragi_quantum.experiments.utils.validators.SimpleSamplespace[source]#

Bases: RootModel

Fields:
field root: dict[str, dict[str, NDArray]] [Required]#
pydantic model bragi_quantum.experiments.utils.validators.MixedSamplespace[source]#

Bases: RootModel

Fields:
field root: dict[str, dict[str, NDArray] | dict[str, list[NDArray]]] [Required]#
pydantic model bragi_quantum.experiments.utils.validators.Samplespace[source]#

Bases: RootModel

Fields:
field root: SimpleSamplespace | MixedSamplespace [Required]#
pydantic model bragi_quantum.experiments.utils.validators.BatchedArray[source]#

Bases: RootModel

Fields:
field root: dict[str, list[NDArray]] [Required]#
pydantic model bragi_quantum.experiments.utils.validators.SimpleArray[source]#

Bases: RootModel

Fields:
field root: dict[str, NDArray] [Required]#
pydantic model bragi_quantum.experiments.utils.validators.Array[source]#

Bases: RootModel

Fields:
field root: BatchedArray | SimpleArray [Required]#
bragi_quantum.experiments.utils.validators.get_number_of_batches(samplespace)[source]#

if the samplespace is a list of NDarrays, return the number of individual arrays per qubit

Parameters:

samplespace (dict[str, dict[str, NDArray] | dict[str, list[NDArray]]])

bragi_quantum.experiments.utils.validators.get_batched_dimensions(samplespace)[source]#

if the samplespace is a list of NDarrays, return the name of the settable, e.g. ‘frequencies’

Parameters:

samplespace (dict[str, dict[str, list[NDArray]]])

Return type:

list[str]

bragi_quantum.experiments.utils.validators.reduce_batch(samplespace, batch)[source]#

if the samplespace is a list of NDarrays, keep only the array of index=batch. the reduced samplespace has the same structure as a regular samplespace.

Parameters:

batch (int)