qibocal.protocols.randomized_benchmarking package

Submodules

qibocal.protocols.randomized_benchmarking.dict_utils module

qibocal.protocols.randomized_benchmarking.dict_utils.find_cliffords(cz_list)[source]

Splits a clifford (list of gates) into sublists based on the occurrence of the “CZ” gate.

qibocal.protocols.randomized_benchmarking.dict_utils.separator(clifford)[source]

Separates values in the given clifford sublist based on certain conditions.

Returns:

A tuple containing three elements:
  • values_with_1 (str): A comma-separated string of values containing ‘1’.

  • values_with_2 (str): A comma-separated string of values containing ‘2’.

  • value_with_CZ (bool): True if ‘CZ’ is present in the clifford list, False otherwise.

Return type:

tuple

qibocal.protocols.randomized_benchmarking.dict_utils.clifford2gates(clifford)[source]

Converts a Clifford string into a list of gates.

Parameters:

clifford (str) – A comma-separated string representing a sequence of gates that represent a Clifford gate.

qibocal.protocols.randomized_benchmarking.dict_utils.clifford_to_matrix(clifford)[source]

Converts a Clifford gate as a string to its corresponding unitary matrix representation.

qibocal.protocols.randomized_benchmarking.dict_utils.generate_inv_dict_cliffords_file(two_qubit_cliffords, output_file=None)[source]

Generate an inverse dictionary of Clifford matrices and save it to a npz file.

Parameters: two_qubit_cliffords (dict): A dictionary of two-qubit Cliffords. output_file (str): The path to the output npz file.

qibocal.protocols.randomized_benchmarking.dict_utils.clifford_to_pulses(clifford)[source]

From a Clifford gate sequence into the number of pulses required to implement it.

Parameters:

clifford (str) – A comma-separated string representing the Clifford gate sequence.

Returns:

The number of pulses required to implement the given Clifford gate sequence.

Return type:

int

qibocal.protocols.randomized_benchmarking.dict_utils.calculate_pulses_clifford(cliffords)[source]

Calculate the average number of pulses per Clifford operation.

Parameters: - cliffords (dict): A dictionary of Clifford operations.

Returns: - pulses_per_clifford (float): The average number of pulses per Clifford operation.

qibocal.protocols.randomized_benchmarking.dict_utils.load_inverse_cliffords(file_inv)[source]
qibocal.protocols.randomized_benchmarking.dict_utils.load_cliffords(file_cliffords)[source]

qibocal.protocols.randomized_benchmarking.filtered_rb module

qibocal.protocols.randomized_benchmarking.fitting module

In this python script the fitting methods for the gate set protocols are defined. They consist mostly of exponential decay fitting.

qibocal.protocols.randomized_benchmarking.fitting.exp1_func(x: ndarray, A: float, f: float) ndarray[source]

Return \(A\cdot f^x\) where x is an np.ndarray and A, f are floats

qibocal.protocols.randomized_benchmarking.fitting.exp1B_func(x: ndarray, A: float, f: float, B: float) ndarray[source]

Return \(A\cdot f^x+B\) where x is an np.ndarray and A, f, B are floats

qibocal.protocols.randomized_benchmarking.fitting.exp2_func(x: ndarray, A1: float, A2: float, f1: float, f2: float) ndarray[source]

Return \(A_1\cdot f_1^x+A_2\cdot f_2^x\) where x is an np.ndarray and A1, f1, A2, f2 are floats. There is no linear offsett B.

qibocal.protocols.randomized_benchmarking.fitting.esprit(xdata: ndarray, ydata: ndarray, num_decays: int, hankel_dim: int | None = None) ndarray[source]

Implements the ESPRIT algorithm for peak detection.

Parameters:
  • xdata (np.ndarray) – Labels of data. Has to be equally spaced.

  • ydata (np.ndarray) – The data where multiple decays are fitted in.

  • num_decays (int) – How many decays should be fitted.

  • hankel_dim (int | None, optional) – The Hankel dimension. Defaults to None.

Returns:

The decay parameters.

Return type:

np.ndarray

Raises:

ValueError – When the x-labels are not equally spaced the algorithm does not work.

qibocal.protocols.randomized_benchmarking.fitting.fit_exp1B_func(xdata: ndarray | list, ydata: ndarray | list, **kwargs) tuple[tuple, tuple][source]

Calculate an single exponential A*p^m+B fit to the given ydata.

Parameters:
  • xdata (Union[np.ndarray, list]) – The x-labels.

  • ydata (Union[np.ndarray, list]) – The data to be fitted.

Returns:

The fitting parameters (A, p, B) and the estimated error

(A_err, p_err, B_err)

Return type:

tuple[tuple, tuple]

qibocal.protocols.randomized_benchmarking.fitting.fit_exp1_func(xdata: ndarray | list, ydata: ndarray | list, **kwargs) tuple[tuple, tuple][source]

Calculate an single exponential A*p^m fit to the given ydata, no linear offset.

Parameters:
  • xdata (Union[np.ndarray, list]) – The x-labels.

  • ydata (Union[np.ndarray, list]) – The data to be fitted.

Returns:

The fitting parameters (A, p) and the estimated error (A_err, p_err).

Return type:

tuple[tuple, tuple]

qibocal.protocols.randomized_benchmarking.fitting.fit_expn_func(xdata: ndarray | list, ydata: ndarray | list, n: int = 2) tuple[tuple, tuple][source]

Calculate n exponentials on top of each other, fit to the given ydata. No linear offset, the ESPRIT algorithm is used to identify n exponential decays.

Parameters:
  • xdata (Union[np.ndarray, list]) – The x-labels.

  • ydata (Union[np.ndarray, list]) – The data to be fitted.

  • n (int) – number of decays to fit. Default is 2.

Returns:

(A1, …, An, f1, …, fn) with f* the decay parameters.

Return type:

tuple[tuple, tuple]

qibocal.protocols.randomized_benchmarking.fitting.fit_exp2_func(xdata: ndarray | list, ydata: ndarray | list) tuple[tuple, tuple][source]

Calculate 2 exponentials on top of each other, fit to the given ydata.

No linear offset, the ESPRIT algorithm is used to identify the two exponential decays.

Parameters:
  • xdata (Union[np.ndarray, list]) – The x-labels.

  • ydata (Union[np.ndarray, list]) – The data to be fitted

Returns:

(A1, A2, f1, f2) with f* the decay parameters.

Return type:

tuple[tuple, tuple]

qibocal.protocols.randomized_benchmarking.standard_rb module

class qibocal.protocols.randomized_benchmarking.standard_rb.StandardRBParameters(depths: list | Depthsdict, niter: int, uncertainties: float | None = None, seed: int | None = None, nshots: int = 10)[source]

Bases: Parameters

Standard Randomized Benchmarking runcard inputs.

depths: list | Depthsdict

A list of depths/sequence lengths.

If a dictionary is given the list will be build.

niter: int

Sets how many iterations over the same depth value.

uncertainties: float | None = None

Method of computing the error bars of the signal and uncertainties of the fit.

If None, it computes the standard deviation. Otherwise it computes the corresponding confidence interval. Defaults None.

seed: int | None = None

A fixed seed to initialize np.random.Generator.

If None, uses a random seed. Defaults is None.

nshots: int = 10

Just to add the default value.

hardware_average: bool = False

By default hardware average will be performed.

relaxation_time: float

Wait time for the qubit to decohere back to the gnd state.

class qibocal.protocols.randomized_benchmarking.standard_rb.RBData(depths: list[int], uncertainties: float | None, seed: int | None, nshots: int, niter: int, data: dict[tuple[~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], int] | tuple[~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], int], ~numpy.ndarray[tuple[int, ...], ~numpy.dtype[dtype([('survival_probs', '<f8')])]]] = <factory>, npulses_per_clifford: float = 1.875)[source]

Bases: Data

The output of the acquisition function.

depths: list[int]

Circuits depths.

uncertainties: float | None

Parameters uncertainties.

seed: int | None
nshots: int

Number of shots.

niter: int

Number of iterations for each depth.

data: dict[tuple[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], int] | tuple[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], int], ndarray[tuple[int, ...], dtype[dtype(['survival_probs', '<f8'])]]]

Raw data acquired.

npulses_per_clifford: float = 1.875

Number of pulses for an average clifford.

_to_json(path: Path, filename: str)

Helper function to dump to json.

_to_npz(path: Path, filename: str)

Helper function to use np.savez while converting keys into strings.

static load_data(path: Path, filename: str)

Load data stored in a npz file.

static load_params(path: Path, filename: str)

Load parameters stored in a json file.

property pairs

Access qubit pairs from data structure.

property params: dict

Convert non-arrays attributes into dict.

property qubits: list[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]]

Access qubits from data structure.

register_qubit(dtype, data_keys, data_dict)

Store output for single qubit.

Parameters:
  • data_keys (tuple) – Keys of Data.data.

  • data_dict (dict) – The keys are the fields of dtype and

  • arrays. (the values are the related)

save(path: Path, filename: str = 'data')

Store data to file.

qibocal.protocols.randomized_benchmarking.standard_rb_2q module

class qibocal.protocols.randomized_benchmarking.standard_rb_2q.StandardRB2QParameters(depths: list | Depthsdict, niter: int, uncertainties: float | None = None, seed: int | None = None, nshots: int = 10, file: str = '2qubitCliffs.json', file_inv: str = '2qubitCliffsInv.npz')[source]

Bases: StandardRBParameters

Parameters for the standard 2q randomized benchmarking protocol.

file: str = '2qubitCliffs.json'

File with the cliffords to be used.

file_inv: str = '2qubitCliffsInv.npz'

File with the cliffords to be used in an inverted dict.

hardware_average: bool = False

By default hardware average will be performed.

nshots: int = 10

Just to add the default value.

seed: int | None = None

A fixed seed to initialize np.random.Generator.

If None, uses a random seed. Defaults is None.

uncertainties: float | None = None

Method of computing the error bars of the signal and uncertainties of the fit.

If None, it computes the standard deviation. Otherwise it computes the corresponding confidence interval. Defaults None.

depths: list | Depthsdict

A list of depths/sequence lengths.

If a dictionary is given the list will be build.

niter: int

Sets how many iterations over the same depth value.

relaxation_time: float

Wait time for the qubit to decohere back to the gnd state.

qibocal.protocols.randomized_benchmarking.standard_rb_2q_inter module

qibocal.protocols.randomized_benchmarking.standard_rb_sweeper module

qibocal.protocols.randomized_benchmarking.utils module

class qibocal.protocols.randomized_benchmarking.utils.CircuitIndex(*, qubit: ~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])] | ~typing.Annotated[tuple[~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]], ~pydantic.functional_validators.BeforeValidator(func=~qibocal.calibration.calibration.<lambda>, json_schema_input_type=PydanticUndefined), ~pydantic.functional_serializers.PlainSerializer(func=~qibocal.calibration.calibration.<lambda>, return_type=PydanticUndefined, when_used=always)], depth: int, iteration: int)[source]

Bases: BaseModel

Tracks the (qubit, depth, iteration) CircuitIndex of a circuit.

model_config: ClassVar[ConfigDict] = {'extra': 'forbid', 'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

qubit: <lambda>, return_type=PydanticUndefined, when_used=always)]
depth: int
iteration: int
_abc_impl = <_abc._abc_data object>
_calculate_keys(*args: Any, **kwargs: Any) Any
_copy_and_set_values(*args: Any, **kwargs: Any) Any
classmethod _get_value(*args: Any, **kwargs: Any) Any
_iter(*args: Any, **kwargs: Any) Any
_setattr_handler(name: str, value: Any) Callable[[BaseModel, str, Any], None] | None

Get a handler for setting an attribute on the model instance.

Returns:

A handler for setting an attribute on the model instance. Used for memoization of the handler. Memoizing the handlers leads to a dramatic performance improvement in __setattr__ Returns None when memoization is not safe, then the attribute is set directly.

classmethod construct(_fields_set: set[str] | None = None, **values: Any) Self
copy(*, include: AbstractSetIntStr | MappingIntStrAny | None = None, exclude: AbstractSetIntStr | MappingIntStrAny | None = None, update: Dict[str, Any] | None = None, deep: bool = False) Self

Returns a copy of the model.

!!! warning “Deprecated”

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

`python {test="skip" lint="skip"} data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) `

Parameters:
  • include – Optional set or mapping specifying which fields to include in the copied model.

  • exclude – Optional set or mapping specifying which fields to exclude in the copied model.

  • update – Optional dictionary of field-value pairs to override field values in the copied model.

  • deep – If True, the values of fields that are Pydantic models will be deep-copied.

Returns:

A copy of the model with included, excluded and updated fields as specified.

dict(*, include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) Dict[str, Any]
classmethod from_orm(obj: Any) Self
json(*, include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Callable[[Any], Any] | None = PydanticUndefined, models_as_dict: bool = PydanticUndefined, **dumps_kwargs: Any) str
model_computed_fields = {}
classmethod model_construct(_fields_set: set[str] | None = None, **values: Any) Self

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

!!! note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == ‘allow’, then all extra passed values are added to the model instance’s __dict__ and __pydantic_extra__ fields. If model_config.extra == ‘ignore’ (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == ‘forbid’ does not result in an error if extra values are passed, but they will be ignored.

Parameters:
  • _fields_set – A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

  • values – Trusted or pre-validated data dictionary.

Returns:

A new instance of the Model class with validated data.

model_copy(*, update: Mapping[str, Any] | None = None, deep: bool = False) Self
!!! abstract “Usage Documentation”

[model_copy](../concepts/models.md#model-copy)

Returns a copy of the model.

!!! note

The underlying instance’s [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:
  • update – Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

  • deep – Set to True to make a deep copy of the model.

Returns:

New model instance.

model_dump(*, mode: Literal['json', 'python'] | str = 'python', include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) dict[str, Any]
!!! abstract “Usage Documentation”

[model_dump](../concepts/serialization.md#python-mode)

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:
  • mode – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.

  • include – A set of fields to include in the output.

  • exclude – A set of fields to exclude from the output.

  • context – Additional context to pass to the serializer.

  • by_alias – Whether to use the field’s alias in the dictionary key if defined.

  • exclude_unset – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults – Whether to exclude fields that are set to their default value.

  • exclude_none – Whether to exclude fields that have a value of None.

  • exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

  • round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

  • serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.

  • polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.

Returns:

A dictionary representation of the model.

model_dump_json(*, indent: int | None = None, ensure_ascii: bool = False, include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) str
!!! abstract “Usage Documentation”

[model_dump_json](../concepts/serialization.md#json-mode)

Generates a JSON representation of the model using Pydantic’s to_json method.

Parameters:
  • indent – Indentation to use in the JSON output. If None is passed, the output will be compact.

  • ensure_ascii – If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

  • include – Field(s) to include in the JSON output.

  • exclude – Field(s) to exclude from the JSON output.

  • context – Additional context to pass to the serializer.

  • by_alias – Whether to serialize using field aliases.

  • exclude_unset – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults – Whether to exclude fields that are set to their default value.

  • exclude_none – Whether to exclude fields that have a value of None.

  • exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

  • round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

  • serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.

  • polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.

Returns:

A JSON string representation of the model.

property model_extra: dict[str, Any] | None

Get extra fields set during validation.

Returns:

A dictionary of extra fields, or None if config.extra is not set to “allow”.

model_fields = {'depth': FieldInfo(annotation=int, required=True), 'iteration': FieldInfo(annotation=int, required=True), 'qubit': FieldInfo(annotation=Union[Annotated[Union[int, str], FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], Annotated[tuple[Annotated[Union[int, str], FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], Annotated[Union[int, str], FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]], BeforeValidator, PlainSerializer]], required=True)}
property model_fields_set: set[str]

Returns the set of fields that have been explicitly set on this model instance.

Returns:

A set of strings representing the fields that have been set,

i.e. that were not filled from defaults.

classmethod model_json_schema(by_alias: bool = True, ref_template: str = '#/$defs/{model}', schema_generator: type[~pydantic.json_schema.GenerateJsonSchema] = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: ~typing.Literal['validation', 'serialization'] = 'validation', *, union_format: ~typing.Literal['any_of', 'primitive_type_array'] = 'any_of') dict[str, Any]

Generates a JSON schema for a model class.

Parameters:
  • by_alias – Whether to use attribute aliases or not.

  • ref_template – The reference template.

  • union_format

    The format to use when combining schemas from unions together. Can be one of:

    keyword to combine schemas (the default). - ‘primitive_type_array’: Use the [type](https://json-schema.org/understanding-json-schema/reference/type) keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.

  • schema_generator – To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

  • mode – The mode in which to generate the schema.

Returns:

The JSON schema for the given model class.

classmethod model_parametrized_name(params: tuple[type[Any], ...]) str

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

params – Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

Returns:

String representing the new class where params are passed to cls as type variables.

Raises:

TypeError – Raised when trying to generate concrete names for non-generic models.

model_post_init(context: Any, /) None

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

classmethod model_rebuild(*, force: bool = False, raise_errors: bool = True, _parent_namespace_depth: int = 2, _types_namespace: MappingNamespace | None = None) bool | None

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:
  • force – Whether to force the rebuilding of the model schema, defaults to False.

  • raise_errors – Whether to raise errors, defaults to True.

  • _parent_namespace_depth – The depth level of the parent namespace, defaults to 2.

  • _types_namespace – The types namespace, defaults to None.

Returns:

Returns None if the schema is already “complete” and rebuilding was not required. If rebuilding _was_ required, returns True if rebuilding was successful, otherwise False.

classmethod model_validate(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, from_attributes: bool | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self

Validate a pydantic model instance.

Parameters:
  • obj – The object to validate.

  • strict – Whether to enforce types strictly.

  • extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • from_attributes – Whether to extract data from object attributes.

  • context – Additional context to pass to the validator.

  • by_alias – Whether to use the field’s alias when validating against the provided input data.

  • by_name – Whether to use the field’s name when validating against the provided input data.

Raises:

ValidationError – If the object could not be validated.

Returns:

The validated model instance.

classmethod model_validate_json(json_data: str | bytes | bytearray, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
!!! abstract “Usage Documentation”

[JSON Parsing](../concepts/json.md#json-parsing)

Validate the given JSON data against the Pydantic model.

Parameters:
  • json_data – The JSON data to validate.

  • strict – Whether to enforce types strictly.

  • extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • context – Extra variables to pass to the validator.

  • by_alias – Whether to use the field’s alias when validating against the provided input data.

  • by_name – Whether to use the field’s name when validating against the provided input data.

Returns:

The validated Pydantic model.

Raises:

ValidationError – If json_data is not a JSON string or the object could not be validated.

classmethod model_validate_strings(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self

Validate the given object with string data against the Pydantic model.

Parameters:
  • obj – The object containing string data to validate.

  • strict – Whether to enforce types strictly.

  • extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • context – Extra variables to pass to the validator.

  • by_alias – Whether to use the field’s alias when validating against the provided input data.

  • by_name – Whether to use the field’s name when validating against the provided input data.

Returns:

The validated Pydantic model.

classmethod parse_file(path: str | Path, *, content_type: str | None = None, encoding: str = 'utf8', proto: DeprecatedParseProtocol | None = None, allow_pickle: bool = False) Self
classmethod parse_obj(obj: Any) Self
classmethod parse_raw(b: str | bytes, *, content_type: str | None = None, encoding: str = 'utf8', proto: DeprecatedParseProtocol | None = None, allow_pickle: bool = False) Self
classmethod schema(by_alias: bool = True, ref_template: str = '#/$defs/{model}') Dict[str, Any]
classmethod schema_json(*, by_alias: bool = True, ref_template: str = '#/$defs/{model}', **dumps_kwargs: Any) str
classmethod update_forward_refs(**localns: Any) None
classmethod validate(value: Any) Self
class qibocal.protocols.randomized_benchmarking.utils.IndexedCircuit(*, circuit: Circuit, index: CircuitIndex)[source]

Bases: BaseModel

A circuit paired with its (qubit, depth, iteration) CircuitIndex.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

circuit: Circuit
index: CircuitIndex
_abc_impl = <_abc._abc_data object>
_calculate_keys(*args: Any, **kwargs: Any) Any
_copy_and_set_values(*args: Any, **kwargs: Any) Any
classmethod _get_value(*args: Any, **kwargs: Any) Any
_iter(*args: Any, **kwargs: Any) Any
_setattr_handler(name: str, value: Any) Callable[[BaseModel, str, Any], None] | None

Get a handler for setting an attribute on the model instance.

Returns:

A handler for setting an attribute on the model instance. Used for memoization of the handler. Memoizing the handlers leads to a dramatic performance improvement in __setattr__ Returns None when memoization is not safe, then the attribute is set directly.

classmethod construct(_fields_set: set[str] | None = None, **values: Any) Self
copy(*, include: AbstractSetIntStr | MappingIntStrAny | None = None, exclude: AbstractSetIntStr | MappingIntStrAny | None = None, update: Dict[str, Any] | None = None, deep: bool = False) Self

Returns a copy of the model.

!!! warning “Deprecated”

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

`python {test="skip" lint="skip"} data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) `

Parameters:
  • include – Optional set or mapping specifying which fields to include in the copied model.

  • exclude – Optional set or mapping specifying which fields to exclude in the copied model.

  • update – Optional dictionary of field-value pairs to override field values in the copied model.

  • deep – If True, the values of fields that are Pydantic models will be deep-copied.

Returns:

A copy of the model with included, excluded and updated fields as specified.

dict(*, include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) Dict[str, Any]
classmethod from_orm(obj: Any) Self
json(*, include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Callable[[Any], Any] | None = PydanticUndefined, models_as_dict: bool = PydanticUndefined, **dumps_kwargs: Any) str
model_computed_fields = {}
classmethod model_construct(_fields_set: set[str] | None = None, **values: Any) Self

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

!!! note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == ‘allow’, then all extra passed values are added to the model instance’s __dict__ and __pydantic_extra__ fields. If model_config.extra == ‘ignore’ (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == ‘forbid’ does not result in an error if extra values are passed, but they will be ignored.

Parameters:
  • _fields_set – A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

  • values – Trusted or pre-validated data dictionary.

Returns:

A new instance of the Model class with validated data.

model_copy(*, update: Mapping[str, Any] | None = None, deep: bool = False) Self
!!! abstract “Usage Documentation”

[model_copy](../concepts/models.md#model-copy)

Returns a copy of the model.

!!! note

The underlying instance’s [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:
  • update – Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

  • deep – Set to True to make a deep copy of the model.

Returns:

New model instance.

model_dump(*, mode: Literal['json', 'python'] | str = 'python', include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) dict[str, Any]
!!! abstract “Usage Documentation”

[model_dump](../concepts/serialization.md#python-mode)

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:
  • mode – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.

  • include – A set of fields to include in the output.

  • exclude – A set of fields to exclude from the output.

  • context – Additional context to pass to the serializer.

  • by_alias – Whether to use the field’s alias in the dictionary key if defined.

  • exclude_unset – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults – Whether to exclude fields that are set to their default value.

  • exclude_none – Whether to exclude fields that have a value of None.

  • exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

  • round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

  • serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.

  • polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.

Returns:

A dictionary representation of the model.

model_dump_json(*, indent: int | None = None, ensure_ascii: bool = False, include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) str
!!! abstract “Usage Documentation”

[model_dump_json](../concepts/serialization.md#json-mode)

Generates a JSON representation of the model using Pydantic’s to_json method.

Parameters:
  • indent – Indentation to use in the JSON output. If None is passed, the output will be compact.

  • ensure_ascii – If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

  • include – Field(s) to include in the JSON output.

  • exclude – Field(s) to exclude from the JSON output.

  • context – Additional context to pass to the serializer.

  • by_alias – Whether to serialize using field aliases.

  • exclude_unset – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults – Whether to exclude fields that are set to their default value.

  • exclude_none – Whether to exclude fields that have a value of None.

  • exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

  • round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

  • serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.

  • polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.

Returns:

A JSON string representation of the model.

property model_extra: dict[str, Any] | None

Get extra fields set during validation.

Returns:

A dictionary of extra fields, or None if config.extra is not set to “allow”.

model_fields = {'circuit': FieldInfo(annotation=Circuit, required=True), 'index': FieldInfo(annotation=CircuitIndex, required=True)}
property model_fields_set: set[str]

Returns the set of fields that have been explicitly set on this model instance.

Returns:

A set of strings representing the fields that have been set,

i.e. that were not filled from defaults.

classmethod model_json_schema(by_alias: bool = True, ref_template: str = '#/$defs/{model}', schema_generator: type[~pydantic.json_schema.GenerateJsonSchema] = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: ~typing.Literal['validation', 'serialization'] = 'validation', *, union_format: ~typing.Literal['any_of', 'primitive_type_array'] = 'any_of') dict[str, Any]

Generates a JSON schema for a model class.

Parameters:
  • by_alias – Whether to use attribute aliases or not.

  • ref_template – The reference template.

  • union_format

    The format to use when combining schemas from unions together. Can be one of:

    keyword to combine schemas (the default). - ‘primitive_type_array’: Use the [type](https://json-schema.org/understanding-json-schema/reference/type) keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.

  • schema_generator – To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

  • mode – The mode in which to generate the schema.

Returns:

The JSON schema for the given model class.

classmethod model_parametrized_name(params: tuple[type[Any], ...]) str

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

params – Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

Returns:

String representing the new class where params are passed to cls as type variables.

Raises:

TypeError – Raised when trying to generate concrete names for non-generic models.

model_post_init(context: Any, /) None

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

classmethod model_rebuild(*, force: bool = False, raise_errors: bool = True, _parent_namespace_depth: int = 2, _types_namespace: MappingNamespace | None = None) bool | None

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:
  • force – Whether to force the rebuilding of the model schema, defaults to False.

  • raise_errors – Whether to raise errors, defaults to True.

  • _parent_namespace_depth – The depth level of the parent namespace, defaults to 2.

  • _types_namespace – The types namespace, defaults to None.

Returns:

Returns None if the schema is already “complete” and rebuilding was not required. If rebuilding _was_ required, returns True if rebuilding was successful, otherwise False.

classmethod model_validate(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, from_attributes: bool | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self

Validate a pydantic model instance.

Parameters:
  • obj – The object to validate.

  • strict – Whether to enforce types strictly.

  • extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • from_attributes – Whether to extract data from object attributes.

  • context – Additional context to pass to the validator.

  • by_alias – Whether to use the field’s alias when validating against the provided input data.

  • by_name – Whether to use the field’s name when validating against the provided input data.

Raises:

ValidationError – If the object could not be validated.

Returns:

The validated model instance.

classmethod model_validate_json(json_data: str | bytes | bytearray, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
!!! abstract “Usage Documentation”

[JSON Parsing](../concepts/json.md#json-parsing)

Validate the given JSON data against the Pydantic model.

Parameters:
  • json_data – The JSON data to validate.

  • strict – Whether to enforce types strictly.

  • extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • context – Extra variables to pass to the validator.

  • by_alias – Whether to use the field’s alias when validating against the provided input data.

  • by_name – Whether to use the field’s name when validating against the provided input data.

Returns:

The validated Pydantic model.

Raises:

ValidationError – If json_data is not a JSON string or the object could not be validated.

classmethod model_validate_strings(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self

Validate the given object with string data against the Pydantic model.

Parameters:
  • obj – The object containing string data to validate.

  • strict – Whether to enforce types strictly.

  • extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • context – Extra variables to pass to the validator.

  • by_alias – Whether to use the field’s alias when validating against the provided input data.

  • by_name – Whether to use the field’s name when validating against the provided input data.

Returns:

The validated Pydantic model.

classmethod parse_file(path: str | Path, *, content_type: str | None = None, encoding: str = 'utf8', proto: DeprecatedParseProtocol | None = None, allow_pickle: bool = False) Self
classmethod parse_obj(obj: Any) Self
classmethod parse_raw(b: str | bytes, *, content_type: str | None = None, encoding: str = 'utf8', proto: DeprecatedParseProtocol | None = None, allow_pickle: bool = False) Self
classmethod schema(by_alias: bool = True, ref_template: str = '#/$defs/{model}') Dict[str, Any]
classmethod schema_json(*, by_alias: bool = True, ref_template: str = '#/$defs/{model}', **dumps_kwargs: Any) str
classmethod update_forward_refs(**localns: Any) None
classmethod validate(value: Any) Self
class qibocal.protocols.randomized_benchmarking.utils.IndexedResult(*, result: Counter, index: CircuitIndex)[source]

Bases: BaseModel

An execution result paired with its (qubit, depth, iteration) CircuitIndex.

model_config: ClassVar[ConfigDict] = {'extra': 'forbid', 'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

result: Counter
index: CircuitIndex
_abc_impl = <_abc._abc_data object>
_calculate_keys(*args: Any, **kwargs: Any) Any
_copy_and_set_values(*args: Any, **kwargs: Any) Any
classmethod _get_value(*args: Any, **kwargs: Any) Any
_iter(*args: Any, **kwargs: Any) Any
_setattr_handler(name: str, value: Any) Callable[[BaseModel, str, Any], None] | None

Get a handler for setting an attribute on the model instance.

Returns:

A handler for setting an attribute on the model instance. Used for memoization of the handler. Memoizing the handlers leads to a dramatic performance improvement in __setattr__ Returns None when memoization is not safe, then the attribute is set directly.

classmethod construct(_fields_set: set[str] | None = None, **values: Any) Self
copy(*, include: AbstractSetIntStr | MappingIntStrAny | None = None, exclude: AbstractSetIntStr | MappingIntStrAny | None = None, update: Dict[str, Any] | None = None, deep: bool = False) Self

Returns a copy of the model.

!!! warning “Deprecated”

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

`python {test="skip" lint="skip"} data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) `

Parameters:
  • include – Optional set or mapping specifying which fields to include in the copied model.

  • exclude – Optional set or mapping specifying which fields to exclude in the copied model.

  • update – Optional dictionary of field-value pairs to override field values in the copied model.

  • deep – If True, the values of fields that are Pydantic models will be deep-copied.

Returns:

A copy of the model with included, excluded and updated fields as specified.

dict(*, include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) Dict[str, Any]
classmethod from_orm(obj: Any) Self
json(*, include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Callable[[Any], Any] | None = PydanticUndefined, models_as_dict: bool = PydanticUndefined, **dumps_kwargs: Any) str
model_computed_fields = {}
classmethod model_construct(_fields_set: set[str] | None = None, **values: Any) Self

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

!!! note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == ‘allow’, then all extra passed values are added to the model instance’s __dict__ and __pydantic_extra__ fields. If model_config.extra == ‘ignore’ (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == ‘forbid’ does not result in an error if extra values are passed, but they will be ignored.

Parameters:
  • _fields_set – A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

  • values – Trusted or pre-validated data dictionary.

Returns:

A new instance of the Model class with validated data.

model_copy(*, update: Mapping[str, Any] | None = None, deep: bool = False) Self
!!! abstract “Usage Documentation”

[model_copy](../concepts/models.md#model-copy)

Returns a copy of the model.

!!! note

The underlying instance’s [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:
  • update – Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

  • deep – Set to True to make a deep copy of the model.

Returns:

New model instance.

model_dump(*, mode: Literal['json', 'python'] | str = 'python', include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) dict[str, Any]
!!! abstract “Usage Documentation”

[model_dump](../concepts/serialization.md#python-mode)

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:
  • mode – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.

  • include – A set of fields to include in the output.

  • exclude – A set of fields to exclude from the output.

  • context – Additional context to pass to the serializer.

  • by_alias – Whether to use the field’s alias in the dictionary key if defined.

  • exclude_unset – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults – Whether to exclude fields that are set to their default value.

  • exclude_none – Whether to exclude fields that have a value of None.

  • exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

  • round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

  • serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.

  • polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.

Returns:

A dictionary representation of the model.

model_dump_json(*, indent: int | None = None, ensure_ascii: bool = False, include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) str
!!! abstract “Usage Documentation”

[model_dump_json](../concepts/serialization.md#json-mode)

Generates a JSON representation of the model using Pydantic’s to_json method.

Parameters:
  • indent – Indentation to use in the JSON output. If None is passed, the output will be compact.

  • ensure_ascii – If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

  • include – Field(s) to include in the JSON output.

  • exclude – Field(s) to exclude from the JSON output.

  • context – Additional context to pass to the serializer.

  • by_alias – Whether to serialize using field aliases.

  • exclude_unset – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults – Whether to exclude fields that are set to their default value.

  • exclude_none – Whether to exclude fields that have a value of None.

  • exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

  • round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

  • serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.

  • polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.

Returns:

A JSON string representation of the model.

property model_extra: dict[str, Any] | None

Get extra fields set during validation.

Returns:

A dictionary of extra fields, or None if config.extra is not set to “allow”.

model_fields = {'index': FieldInfo(annotation=CircuitIndex, required=True), 'result': FieldInfo(annotation=Counter, required=True)}
property model_fields_set: set[str]

Returns the set of fields that have been explicitly set on this model instance.

Returns:

A set of strings representing the fields that have been set,

i.e. that were not filled from defaults.

classmethod model_json_schema(by_alias: bool = True, ref_template: str = '#/$defs/{model}', schema_generator: type[~pydantic.json_schema.GenerateJsonSchema] = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: ~typing.Literal['validation', 'serialization'] = 'validation', *, union_format: ~typing.Literal['any_of', 'primitive_type_array'] = 'any_of') dict[str, Any]

Generates a JSON schema for a model class.

Parameters:
  • by_alias – Whether to use attribute aliases or not.

  • ref_template – The reference template.

  • union_format

    The format to use when combining schemas from unions together. Can be one of:

    keyword to combine schemas (the default). - ‘primitive_type_array’: Use the [type](https://json-schema.org/understanding-json-schema/reference/type) keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.

  • schema_generator – To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

  • mode – The mode in which to generate the schema.

Returns:

The JSON schema for the given model class.

classmethod model_parametrized_name(params: tuple[type[Any], ...]) str

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

params – Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

Returns:

String representing the new class where params are passed to cls as type variables.

Raises:

TypeError – Raised when trying to generate concrete names for non-generic models.

model_post_init(context: Any, /) None

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

classmethod model_rebuild(*, force: bool = False, raise_errors: bool = True, _parent_namespace_depth: int = 2, _types_namespace: MappingNamespace | None = None) bool | None

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:
  • force – Whether to force the rebuilding of the model schema, defaults to False.

  • raise_errors – Whether to raise errors, defaults to True.

  • _parent_namespace_depth – The depth level of the parent namespace, defaults to 2.

  • _types_namespace – The types namespace, defaults to None.

Returns:

Returns None if the schema is already “complete” and rebuilding was not required. If rebuilding _was_ required, returns True if rebuilding was successful, otherwise False.

classmethod model_validate(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, from_attributes: bool | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self

Validate a pydantic model instance.

Parameters:
  • obj – The object to validate.

  • strict – Whether to enforce types strictly.

  • extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • from_attributes – Whether to extract data from object attributes.

  • context – Additional context to pass to the validator.

  • by_alias – Whether to use the field’s alias when validating against the provided input data.

  • by_name – Whether to use the field’s name when validating against the provided input data.

Raises:

ValidationError – If the object could not be validated.

Returns:

The validated model instance.

classmethod model_validate_json(json_data: str | bytes | bytearray, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
!!! abstract “Usage Documentation”

[JSON Parsing](../concepts/json.md#json-parsing)

Validate the given JSON data against the Pydantic model.

Parameters:
  • json_data – The JSON data to validate.

  • strict – Whether to enforce types strictly.

  • extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • context – Extra variables to pass to the validator.

  • by_alias – Whether to use the field’s alias when validating against the provided input data.

  • by_name – Whether to use the field’s name when validating against the provided input data.

Returns:

The validated Pydantic model.

Raises:

ValidationError – If json_data is not a JSON string or the object could not be validated.

classmethod model_validate_strings(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self

Validate the given object with string data against the Pydantic model.

Parameters:
  • obj – The object containing string data to validate.

  • strict – Whether to enforce types strictly.

  • extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • context – Extra variables to pass to the validator.

  • by_alias – Whether to use the field’s alias when validating against the provided input data.

  • by_name – Whether to use the field’s name when validating against the provided input data.

Returns:

The validated Pydantic model.

classmethod parse_file(path: str | Path, *, content_type: str | None = None, encoding: str = 'utf8', proto: DeprecatedParseProtocol | None = None, allow_pickle: bool = False) Self
classmethod parse_obj(obj: Any) Self
classmethod parse_raw(b: str | bytes, *, content_type: str | None = None, encoding: str = 'utf8', proto: DeprecatedParseProtocol | None = None, allow_pickle: bool = False) Self
classmethod schema(by_alias: bool = True, ref_template: str = '#/$defs/{model}') Dict[str, Any]
classmethod schema_json(*, by_alias: bool = True, ref_template: str = '#/$defs/{model}', **dumps_kwargs: Any) str
classmethod update_forward_refs(**localns: Any) None
classmethod validate(value: Any) Self
qibocal.protocols.randomized_benchmarking.utils.NPULSES_PER_CLIFFORD = 1.875

Global phases that could appear in the Clifford group we defined in the “2q_cliffords.json” file due to the gates we selected to generate the Clifford group.

qibocal.protocols.randomized_benchmarking.utils.RBType = dtype([('survival_probs', '<f8')])

Custom dtype for RB.

qibocal.protocols.randomized_benchmarking.utils.random_clifford(random_index_gen)[source]

Generates random Clifford operator.

qibocal.protocols.randomized_benchmarking.utils.random_2q_clifford(random_index_gen, two_qubit_cliffords)[source]

Generates random two qubit Clifford operator.

qibocal.protocols.randomized_benchmarking.utils.number_to_str(value: Number, uncertainty: Number | list | tuple | ndarray | None = None, precision: int | None = None)[source]

Converts a number into a string.

Parameters:
  • value (Number) – the number to display

  • uncertainty (Number or list or tuple or np.ndarray, optional) – number or 2-element interval with the low and high uncertainties of value. Defaults to None.

  • precision (int, optional) – nonnegative number of floating points of the displayed value. If None, defaults to the second significant digit of uncertainty or 3 if uncertainty is None. Defaults to None.

Returns:

The number expressed as a string, with the uncertainty if given.

Return type:

str

qibocal.protocols.randomized_benchmarking.utils.data_uncertainties(data, method=None, data_median=None, homogeneous=True)[source]

Compute the uncertainties of the median (or specified) values.

Parameters:
  • data (list or np.ndarray) – 2d array with rows containing data points from which the median value is extracted.

  • method (float, optional) – method of computing the method. If it is None, computes the standard deviation, otherwise it computes the corresponding confidence interval using np.percentile. Defaults to None.

  • data_median (list or np.ndarray, optional) – 1d array for computing the errors from the confidence interval. If None, the median values are computed from data.

  • homogeneous (bool) – if True, assumes that all rows in data are of the same size and returns np.ndarray. Default is True.

Returns:

uncertainties of the data.

Return type:

np.ndarray

class qibocal.protocols.randomized_benchmarking.utils.RBGenerator(seed, file=None)[source]

Bases: object

This class generates random two qubit cliffords for randomized benchmarking.

random_index(gate_dict)[source]

Generates a random index within the range of the given file len.

random_layer_gen_single_qubit()[source]

Generates a random single-qubit clifford gate.

random_layer_gen_two_qubit()[source]

Generates a random two-qubit clifford gate.

calculate_average_pulses()[source]

Average number of pulses per clifford.

class qibocal.protocols.randomized_benchmarking.utils.RBData(depths: list[int], uncertainties: float | None, seed: int | None, nshots: int, niter: int, data: dict[tuple[~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], int] | tuple[~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], int], ~numpy.ndarray[tuple[int, ...], ~numpy.dtype[dtype([('survival_probs', '<f8')])]]] = <factory>, npulses_per_clifford: float = 1.875)[source]

Bases: Data

The output of the acquisition function.

depths: list[int]

Circuits depths.

uncertainties: float | None

Parameters uncertainties.

seed: int | None
nshots: int

Number of shots.

niter: int

Number of iterations for each depth.

data: dict[tuple[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], int] | tuple[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], int], ndarray[tuple[int, ...], dtype[dtype(['survival_probs', '<f8'])]]]

Raw data acquired.

npulses_per_clifford: float = 1.875

Number of pulses for an average clifford.

_to_json(path: Path, filename: str)

Helper function to dump to json.

_to_npz(path: Path, filename: str)

Helper function to use np.savez while converting keys into strings.

static load_data(path: Path, filename: str)

Load data stored in a npz file.

static load_params(path: Path, filename: str)

Load parameters stored in a json file.

property pairs

Access qubit pairs from data structure.

property params: dict

Convert non-arrays attributes into dict.

property qubits: list[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]]

Access qubits from data structure.

register_qubit(dtype, data_keys, data_dict)

Store output for single qubit.

Parameters:
  • data_keys (tuple) – Keys of Data.data.

  • data_dict (dict) – The keys are the fields of dtype and

  • arrays. (the values are the related)

save(path: Path, filename: str = 'data')

Store data to file.

class qibocal.protocols.randomized_benchmarking.utils.RB2QData(depths: list[int], uncertainties: float | None, seed: int | None, nshots: int, niter: int, data: dict[tuple[~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], int] | tuple[~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], int], ~numpy.ndarray[tuple[int, ...], ~numpy.dtype[dtype([('survival_probs', '<f8')])]]] = <factory>, npulses_per_clifford: float = 8.6)[source]

Bases: RBData

The output of the acquisition function.

npulses_per_clifford: float = 8.6

Number of pulses for an average clifford.

extract_probabilities(qubits)[source]

Extract the probabilities given (qubit, qubit)

_to_json(path: Path, filename: str)

Helper function to dump to json.

_to_npz(path: Path, filename: str)

Helper function to use np.savez while converting keys into strings.

static load_data(path: Path, filename: str)

Load data stored in a npz file.

static load_params(path: Path, filename: str)

Load parameters stored in a json file.

property pairs

Access qubit pairs from data structure.

property params: dict

Convert non-arrays attributes into dict.

property qubits: list[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]]

Access qubits from data structure.

register_qubit(dtype, data_keys, data_dict)

Store output for single qubit.

Parameters:
  • data_keys (tuple) – Keys of Data.data.

  • data_dict (dict) – The keys are the fields of dtype and

  • arrays. (the values are the related)

save(path: Path, filename: str = 'data')

Store data to file.

depths: list[int]

Circuits depths.

uncertainties: float | None

Parameters uncertainties.

seed: int | None
nshots: int

Number of shots.

niter: int

Number of iterations for each depth.

data: dict[tuple[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], int] | tuple[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], int], ndarray[tuple[int, ...], dtype[dtype(['survival_probs', '<f8'])]]]

Raw data acquired.

class qibocal.protocols.randomized_benchmarking.utils.RB2QInterData(depths: list[int], uncertainties: float | None, seed: int | None, nshots: int, niter: int, data: dict[tuple[~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], int] | tuple[~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], int], ~numpy.ndarray[tuple[int, ...], ~numpy.dtype[dtype([('survival_probs', '<f8')])]]] = <factory>, npulses_per_clifford: float = 8.6, fidelity: dict[~typing.Annotated[tuple[~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]], ~pydantic.functional_validators.BeforeValidator(func=~qibocal.calibration.calibration.<lambda>, json_schema_input_type=PydanticUndefined), ~pydantic.functional_serializers.PlainSerializer(func=~qibocal.calibration.calibration.<lambda>, return_type=PydanticUndefined, when_used=always)], list] = <factory>)[source]

Bases: RB2QData

The output of the acquisition function.

fidelity: dict[~typing.Annotated[tuple[~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]], ~pydantic.functional_validators.BeforeValidator(func=~qibocal.calibration.calibration.<lambda>, json_schema_input_type=PydanticUndefined), ~pydantic.functional_serializers.PlainSerializer(func=~qibocal.calibration.calibration.<lambda>, return_type=PydanticUndefined, when_used=always)], list]

The interleaved fidelity of this qubit.

_to_json(path: Path, filename: str)

Helper function to dump to json.

_to_npz(path: Path, filename: str)

Helper function to use np.savez while converting keys into strings.

extract_probabilities(qubits)

Extract the probabilities given (qubit, qubit)

static load_data(path: Path, filename: str)

Load data stored in a npz file.

static load_params(path: Path, filename: str)

Load parameters stored in a json file.

npulses_per_clifford: float = 8.6

Number of pulses for an average clifford.

property pairs

Access qubit pairs from data structure.

property params: dict

Convert non-arrays attributes into dict.

property qubits: list[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]]

Access qubits from data structure.

register_qubit(dtype, data_keys, data_dict)

Store output for single qubit.

Parameters:
  • data_keys (tuple) – Keys of Data.data.

  • data_dict (dict) – The keys are the fields of dtype and

  • arrays. (the values are the related)

save(path: Path, filename: str = 'data')

Store data to file.

depths: list[int]

Circuits depths.

uncertainties: float | None

Parameters uncertainties.

seed: int | None
nshots: int

Number of shots.

niter: int

Number of iterations for each depth.

data: dict[tuple[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], int] | tuple[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], int], ndarray[tuple[int, ...], dtype[dtype(['survival_probs', '<f8'])]]]

Raw data acquired.

class qibocal.protocols.randomized_benchmarking.utils.StandardRBResult(fidelity: dict[~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], float], pulse_fidelity: dict[~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], float], fit_parameters: dict[~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], list[float]], fit_uncertainties: dict[~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], list[float]], error_bars: dict[~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], float | list[float] | None] = <factory>)[source]

Bases: Results

Standard RB outputs.

fidelity: dict[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], float]

The overall fidelity of this qubit.

pulse_fidelity: dict[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], float]

The pulse fidelity of the gates acting on this qubit.

_to_json(path: Path, filename: str)

Helper function to dump to json.

_to_npz(path: Path, filename: str)

Helper function to use np.savez while converting keys into strings.

static load_data(path: Path, filename: str)

Load data stored in a npz file.

static load_params(path: Path, filename: str)

Load parameters stored in a json file.

property params: dict

Convert non-arrays attributes into dict.

save(path: Path, filename: str = 'results')

Store results to file.

fit_parameters: dict[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], list[float]]

Raw fitting parameters.

fit_uncertainties: dict[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], list[float]]

Fitting parameters uncertainties.

error_bars: dict[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], float | list[float] | None]

Error bars for y.

qibocal.protocols.randomized_benchmarking.utils.setup_data(params: Parameters, npulses_per_clifford: float, single_qubit: bool = True, interleave: str | None = None)[source]

Set up the randomized benchmarking experiment data class.

Parameters:
  • params (Parameters) – The parameters for the experiment.

  • single_qubit (bool, optional) – Flag indicating whether the experiment is for a single qubit or two qubits. Defaults to True.

  • interleave – (str, optional): The type of interleaving to apply. Defaults to None.

Returns:

The experiment data class.

Return type:

data

qibocal.protocols.randomized_benchmarking.utils._generate_indexed_circuits(params: Parameters, rb_gen: RBGenerator, targets, inverse_layer: bool = True, interleave: str | None = None) list[IndexedCircuit][source]

Generate randomized benchmarking circuits with explicit indexing of (qubit, depth, iteration) coordinates.

Parameters:
  • params – Experiment parameters containing depths, niter.

  • rb_gen – RBGenerator instance to use for generating Clifford gates.

  • targets – List of target qubit IDs.

  • inverse_layer – Whether to add an inverse layer to the circuits. Defaults to True.

  • interleave – Interleaving pattern for the circuits. Defaults to None.

Returns:

List of IndexedCircuit objects with explicit (qubit, depth, iteration) metadata.

qibocal.protocols.randomized_benchmarking.utils._execute_indexed_circuits(indexed_circuits: list[IndexedCircuit], params: Parameters, platform: CalibrationPlatform, averaging_mode: AveragingMode = AveragingMode.SINGLESHOT) list[IndexedResult][source]

Execute indexed circuits and return results paired with their indices.

Parameters:
  • indexed_circuits – List of IndexedCircuit objects to execute.

  • targets – List of target qubit IDs.

  • params – Experiment parameters.

  • platform – CalibrationPlatform to execute on.

Returns:

List of IndexedResult objects with execution results paired with their indices.

qibocal.protocols.randomized_benchmarking.utils.rb_acquisition(params: Parameters, platform: CalibrationPlatform, targets: list[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]], inverse_layer: bool = True, interleave: str | None = None) RBData[source]

RB data acquisition function using explicit circuit indexing.

Parameters:
  • params – Experiment parameters including depths, niter, nshots, seed.

  • platform – CalibrationPlatform to execute circuits on.

  • targets – List of target qubit IDs.

  • inverse_layer – Whether to add an inverse layer to circuits. Defaults to True.

  • interleave – Interleaving pattern for circuits. Defaults to None.

Returns:

Validated RB data structure with results organized by (qubit, depth).

Return type:

RBData

qibocal.protocols.randomized_benchmarking.utils.twoq_rb_acquisition(params: ~qibocal.auto.operation.Parameters, platform: ~qibocal.calibration.platform.CalibrationPlatform, targets: list[~typing.Annotated[tuple[~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]], ~pydantic.functional_validators.BeforeValidator(func=~qibocal.calibration.calibration.<lambda>, json_schema_input_type=PydanticUndefined), ~pydantic.functional_serializers.PlainSerializer(func=~qibocal.calibration.calibration.<lambda>, return_type=PydanticUndefined, when_used=always)]], inverse_layer: bool = True, interleave: str | None = None) RB2QData | RB2QInterData[source]

The data acquisition stage of two qubit Standard Randomized Benchmarking.

Parameters:
  • params (RB2QParameters) – The parameters for the randomized benchmarking experiment.

  • targets (list[QubitPairId]) – The list of qubit pair IDs on which to perform the benchmarking.

  • inverse_layer (bool, optional) – Whether to add an inverse layer to the circuits. Defaults to True.

  • interleave (str, optional) – The type of interleaving to apply. Defaults to None.

Returns:

The acquired data for two qubit randomized benchmarking.

Return type:

RB2QData

qibocal.protocols.randomized_benchmarking.utils.layer_circuit(rb_gen: ~qibocal.protocols.randomized_benchmarking.utils.RBGenerator, depth: int, target: ~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])] | ~typing.Annotated[tuple[~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]], ~pydantic.functional_validators.BeforeValidator(func=~qibocal.calibration.calibration.<lambda>, json_schema_input_type=PydanticUndefined), ~pydantic.functional_serializers.PlainSerializer(func=~qibocal.calibration.calibration.<lambda>, return_type=PydanticUndefined, when_used=always)], interleave: str | None = None) Circuit[source]

Creates a circuit of depth layers from a generator layer_gen yielding Circuit or Gate and a dictionary with random indexes used to select the clifford gates.

Parameters:
  • layer_gen (Callable) – Should return gates or a full circuit specifying a layer.

  • depth (int) – Number of layers.

  • interleave (str, optional) – Interleaving pattern for the circuits. Defaults to None.

Returns:

with depth many layers.

Return type:

Circuit

qibocal.protocols.randomized_benchmarking.utils.add_inverse_layer(circuit: Circuit, rb_gen: RBGenerator, file_inv: Path | None = None)[source]

Adds an inverse gate/inverse gates at the end of a circuit (in place).

Parameters:

circuit (Circuit) – circuit

qibocal.protocols.randomized_benchmarking.utils.add_measurement_layer(circuit: Circuit)[source]

Adds a measurement layer at the end of the circuit.

Parameters:

circuit (Circuit) – Measurement gates added in place to end of this circuit.

qibocal.protocols.randomized_benchmarking.utils.fit(data, single_qubit: bool = True) StandardRBResult[source]

Takes data, extracts the depths and the signal and fits it with an exponential function y = Ap^x+B.