qibocal.auto package

Autocalibration runner.

class qibocal.auto.BoundProtocol(protocol: Protocol[_ParametersT, _FitParsT, _ReportParsT, _DataT, _ResultsT], parameters: _ParametersT, fitpars: _FitParsT | None = None, reportpars: _ReportParsT | None = None)[source]

Bases: Generic[_ParametersT, _FitParsT, _ReportParsT, _DataT, _ResultsT]

A protocol bound with specific parameters and execution configuration.

This represents a specific protocol execution with all required parameters and optional phase parameters already determined.

_is_protocol = False
protocol: Protocol[_ParametersT, _FitParsT, _ReportParsT, _DataT, _ResultsT]

The protocol being bound.

parameters: _ParametersT

Acquisition parameters.

fitpars: _FitParsT | None = None

Optional fit phase parameters.

reportpars: _ReportParsT | None = None

Optional report phase parameters.

class qibocal.auto.Protocol(acquisition: Callable[[...], _DataT], fit: Callable[[...], _ResultsT] | None = None, report: Callable[[...], Any] | None = None, update: Callable[[...], None] | None = None, two_qubit_gates: bool | None = False)[source]

Bases: Generic[_ParametersT, _FitParsT, _ReportParsT, _DataT, _ResultsT]

A calibration protocol with explicit type-safe interface.

This protocol definition separates concerns into distinct phases: - acquisition: collects raw data from hardware - fit: processes data and produces results - report: generates visualizations and summaries - update: applies results back to the platform configuration

All phases except acquisition are optional, allowing flexible workflow composition.

Type Parameters:

_ParametersT: Type of acquisition parameters _FitParsT: Type of fit function parameters _ReportParsT: Type of report function parameters _DataT: Type of data returned by acquisition _ResultsT: Type of results returned by fit

acquisition: Callable[[...], _DataT]

Acquire data with parameters and optional platform/targets.

fit: Callable[[...], _ResultsT] | None = None

Process data and produce results. Takes data and optional fit params.

report: Callable[[...], Any] | None = None

Generate reports/visualizations and return their output.

update: Callable[[...], None] | None = None

Update platform with results.

two_qubit_gates: bool | None = False

Flag to determine whether to allocate list of Qubits or Pairs.

property parameters_type: type

Extract the type of acquisition parameters.

property data_type: type

Extract the return type of acquisition.

property results_type: type

Extract the return type of fit.

_is_protocol = False
class qibocal.auto.Completed(task: ~qibocal.auto.task.Task | None = None, path: ~pathlib.Path | None = None, _data: ~qibocal.auto.operation.Data | None = None, _results: ~qibocal.auto.operation.Results | None = None, data_time: float = 0, results_time: float = 0, bound: ~qibocal.auto.operation.BoundProtocol | None = None, reports: ~typing.Any = None, protocol_id: str | None = None, error: Exception | None = None, success: bool = True, _targets: list[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]] | list[~typing.Annotated[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~types.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[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ...]] | None = None, notes: list[~qibocal.auto.notes.Note] = <factory>)[source]

Bases: object

A complete or partial protocol execution, optionally backed by a task.

task: Task | None = None

A snapshot of the task when it was completed.

path: Path | None = None

Optional folder containing data and results files for task.

_data: Data | None = None

Protocol data.

_results: Results | None = None

Fitting output.

data_time: float = 0

Protocol data.

results_time: float = 0

Fitting output.

bound: BoundProtocol | None = None

Bound protocol used for this execution.

reports: Any = None

Report output, keyed by target for per-target callbacks.

protocol_id: str | None = None

Identifier for the protocol that was executed.

error: Exception | None = None

Error that occurred during execution, if any.

success: bool = True

Whether execution completed successfully.

_targets: list[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]] | list[~typing.Annotated[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~types.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[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ...]] | None = None

Acquisition targets, when not recorded by a task.

notes: list[Note]

Comment history for this individual protocol execution.

property targets: list[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]] | list[~typing.Annotated[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~types.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[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ...]]

Targets recorded at acquisition.

property data: Data

Access task’s data.

property results

Access task’s results.

dump_parameters()[source]

Dump parameters.

dump_notes()[source]

Save only protocol comments, without rewriting acquisition or fit data.

dump_data()[source]

Dumping data.

dump_results()[source]

Dumping results.

should_update(mode: ExecutionMode, update: bool) → bool[source]

Whether to update the platform after this execution.

Requires fitting in mode, both the global and the task-level update flags, a protocol with an update callback and available fit results.

update_platform(platform: Platform)[source]

Perform update on platform’ parameters by looping over qubits or pairs.

class qibocal.auto.Note(*, content: ~typing.Annotated[str, ~pydantic.types.StringConstraints(strip_whitespace=True, to_upper=None, to_lower=None, strict=None, min_length=1, max_length=None, pattern=None, ascii_only=None)], timestamp: ~pydantic.types.AwareDatetime = <factory>, author: str | None = None)[source]

Bases: BaseModel

A comment with its creation time and optional externally supplied author.

model_config = {'frozen': True}

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

content: Annotated[str, StringConstraints(strip_whitespace=True, to_upper=None, to_lower=None, strict=None, min_length=1, max_length=None, pattern=None, ascii_only=None)]
timestamp: AwareDatetime
author: str | None
classmethod normalize_timestamp(value: datetime) → datetime[source]

Store all timestamps in UTC.

_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 = {'author': FieldInfo(annotation=Union[str, NoneType], required=False, default=None), 'content': FieldInfo(annotation=str, required=True, metadata=[StringConstraints(strip_whitespace=True, to_upper=None, to_lower=None, strict=None, min_length=1, max_length=None, pattern=None, ascii_only=None)]), 'timestamp': FieldInfo(annotation=AwareDatetime, required=False, default_factory=<lambda>)}
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[GenerateJsonSchema] = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: Literal['validation', 'serialization']='validation', *, union_format: 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

Submodules

qibocal.auto.execute module

Tasks execution.

qibocal.auto.execute.check_overlap_in_input_qubits(targets: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str])[source]

Check that target qubits do not contain duplicates.

qibocal.auto.execute._resolve(protocol: BoundProtocol, kwargs: dict) → BoundProtocol[source]

Apply execution parameter overrides without mutating a bound protocol.

qibocal.auto.execute._invoke(callback: Callable, argument: object, **context: Any) → Any[source]

Pass only explicitly declared context, including positional-only parameters.

qibocal.auto.execute._runcard_value(value: Any) → Any[source]

Convert a parameter value to the plain types found in runcards.

Parameters may hold values normalized after loading, e.g. enumerations, ranges with NumPy scalars, or arrays computed during acquisition, which YAML cannot represent.

qibocal.auto.execute._action_parameters(parameters: Any) → dict[str, Any][source]

Serializable parameters of a bound protocol, as found in runcards.

class qibocal.auto.execute.Executor(platform: ~qibolab._core.platform.platform.Platform | None, *, history: ~qibocal.auto.history.History | None = None, targets: list[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]] | list[~typing.Annotated[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~types.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[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ...]] | None = None, update: bool = True, path: ~os.PathLike | None = None, meta: ~qibocal.auto.output.Metadata | None = None)[source]

Bases: object

Protocol executor for direct execution of protocols.

Acquisition requires a BoundProtocol without requiring protocol registration. Subsequent phases consume and produce Completed instances. Context is passed to explicitly named callback parameters. Calibration output, history and lifecycle management are optional. Direct acquisition requires caller-managed platform connections.

Once its output folder is initialized (cf. open() and __enter__()), the executor records the complete executions of built-in protocols (__call__()) in its history and output folder, as soon as executed.

classmethod create(path: ~os.PathLike, targets: list[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]] | list[~typing.Annotated[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~types.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[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ...]] | None = None, platform: ~qibocal.calibration.platform.CalibrationPlatform | ~qibolab._core.platform.platform.Platform | str | None = None, **kwargs: ~typing.Any) → Executor[source]

Create protocols’ executor.

This is a wrapper of the default constructor, which is only handling different platforms specification.

For the full set of arguments, cf. Executor.

_init(force: bool = False)[source]

Initialize execution once and connect the platform.

close()[source]

Close execution.

classmethod open(path: ~os.PathLike, targets: list[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]] | list[~typing.Annotated[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~types.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[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ...]] | None = None, force: bool = False, platform: ~qibocal.calibration.platform.CalibrationPlatform | str | None = None, update: bool | None = None, **kwargs: ~typing.Any)[source]

Enter the execution context.

For the full set of arguments, cf. Executor.

_dump_task(completed: Completed) → Completed | None[source]

Dump an acquired execution as a new task of the output folder.

Only registered protocols are recorded, since only those can be loaded back from the output folder. Returns the execution bound to its task, or None if not recorded.

_context(kwargs: dict[str, Any]) → dict[str, Any][source]
acquire(bound: BoundProtocol, **kwargs: Any) → Completed[source]

Execute only the acquisition phase.

Parameters:
  • bound – The bound protocol to acquire data from.

  • **kwargs – Execution overrides, including targets and acquisition settings. The platform cannot be overridden.

Returns:

A new Completed instance retaining data and the bound protocol.

_completed_context(completed: ~qibocal.auto.task.Completed, targets: list[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]] | list[~typing.Annotated[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~types.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[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ...]] | None) → tuple[BoundProtocol, dict[str, Any]][source]
fit(completed: ~qibocal.auto.task.Completed, *, targets: list[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]] | list[~typing.Annotated[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~types.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[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ...]] | None = None) → Completed[source]

Execute the fit phase on existing data.

This can be used to re-fit data that was previously acquired, or to apply a different fitting strategy.

Parameters:
  • completed – An acquired execution, optionally loaded from disk.

  • targets – Optional override of the targets recorded at acquisition.

Returns:

A new Completed instance with fitting results attached.

Raises:

ValueError – If the protocol does not have a fit function.

report(completed: ~qibocal.auto.task.Completed, *, targets: list[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]] | list[~typing.Annotated[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~types.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[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ...]] | None = None) → Completed[source]

Execute the report phase.

Parameters:
  • completed – An acquired or fitted execution.

  • targets – Optional override of the targets recorded at acquisition.

Returns:

A new Completed instance with report output attached.

Raises:

ValueError – If the protocol does not have a report function.

update(completed: ~qibocal.auto.task.Completed, *, targets: list[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]] | list[~typing.Annotated[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~types.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[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ...]] | None = None) → Completed[source]

Execute the update phase to apply results to platform.

Parameters:
  • completed – A fitted execution.

  • targets – Optional override of the targets recorded at acquisition.

Returns:

A new Completed instance after applying the platform update.

Raises:

ValueError – If the protocol has no update function or no platform is configured.

qibocal.auto.history module

Track execution history.

qibocal.auto.history.HISTORY = 'history.json'

File where protocols order is dumped.

class qibocal.auto.history.History(_tasks: dict[~qibocal.auto.task.Id, list[~qibocal.auto.task.Completed]]=<factory>, _order: list[TaskId] = <factory>)[source]

Bases: object

Execution history.

This is not only used for logging and debugging, but it is an actual part of the execution itself, since later routines can retrieve the output of former ones from here.

_tasks: dict[Id, list[Completed]]

List of completed tasks.

Note

Representing the object as a map of sequences makes it smoother to identify the iterations of a given task, since they are already grouped together.

_order: list[TaskId]

Record of the execution order.

property _serialized_order: list[str]

JSON friendly _order attribute.

_order, which is a list of TaskId objects, is not JSON serializable, it is converted into a list of strings which match the data folder for each protocol.

_(key: TaskId) → Completed[source]
values() → Iterator[Completed][source]

Iterate individual tasks according to the execution order.

items() → Iterator[tuple[TaskId, Completed]][source]

Consistent iteration over individual tasks and their ids.

_pending_task_id(_id: Id) → TaskId[source]

Retrieve the TaskId of a given task to be executed.

_executed_task_id(_id: Id) → TaskId[source]

Retrieve the TaskId of a given executed task.

push(completed: Completed) → TaskId[source]

Adding completed task to history.

task_path(task_id: TaskId, folder: Path) → Path[source]

Determine the path related to a completed task given TaskId.

folder should be usually the general output folder, used by Qibocal to store all the execution results. Cf. qibocal.auto.output.Output.

dump(output: Path)[source]

Dump protocols order to file.

class qibocal.auto.history.DummyHistory[source]

Bases: object

Empty History object, used by qq compare.

Used for comparing multiple reports, as their history is not saved.

items()[source]

qibocal.auto.mode module

class qibocal.auto.mode.ExecutionMode(value)[source]

Bases: Flag

Different execution modes.

ACQUIRE = 1

Peform acquisition only.

FIT = 2

Perform fitting only.

_generate_next_value_(start, count, last_values)

Generate the next value when not given.

name: the name of the member start: the initial start value or None count: the number of existing members last_values: the last value assigned or None

_numeric_repr_(obj, /)

Return the canonical string representation of the object.

For many object types, including most builtins, eval(repr(obj)) == obj.

classmethod _iter_member_by_value_(value)

Extract all members from the value in definition (i.e. increasing value) order.

classmethod _iter_member_(value)

Extract all members from the value in definition (i.e. increasing value) order.

classmethod _iter_member_by_def_(value)

Extract all members from the value in definition order.

classmethod _missing_(value)

Create a composite member containing all canonical members present in value.

If non-member values are present, result depends on _boundary_ setting.

_get_value(flag)
_boundary_ = 'strict'
_flag_mask_ = 3
_singles_mask_ = 3
_all_bits_ = 3
_inverted_ = None
qibocal.auto.mode.AUTOCALIBRATION = <ExecutionMode.ACQUIRE|FIT: 3>

Perform acquisition and fitting.

qibocal.auto.notes module

Persistent comments on calibration sessions and protocol executions.

qibocal.auto.notes.NOTES = 'notes.json'

Comment history file, relative to a session or protocol output folder.

class qibocal.auto.notes.Note(*, content: ~typing.Annotated[str, ~pydantic.types.StringConstraints(strip_whitespace=True, to_upper=None, to_lower=None, strict=None, min_length=1, max_length=None, pattern=None, ascii_only=None)], timestamp: ~pydantic.types.AwareDatetime = <factory>, author: str | None = None)[source]

Bases: BaseModel

A comment with its creation time and optional externally supplied author.

model_config = {'frozen': True}

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

content: Annotated[str, StringConstraints(strip_whitespace=True, to_upper=None, to_lower=None, strict=None, min_length=1, max_length=None, pattern=None, ascii_only=None)]
timestamp: AwareDatetime
author: str | None
classmethod normalize_timestamp(value: datetime) → datetime[source]

Store all timestamps in UTC.

_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 = {'author': FieldInfo(annotation=Union[str, NoneType], required=False, default=None), 'content': FieldInfo(annotation=str, required=True, metadata=[StringConstraints(strip_whitespace=True, to_upper=None, to_lower=None, strict=None, min_length=1, max_length=None, pattern=None, ascii_only=None)]), 'timestamp': FieldInfo(annotation=AwareDatetime, required=False, default_factory=<lambda>)}
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[GenerateJsonSchema] = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: Literal['validation', 'serialization']='validation', *, union_format: 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.auto.notes.load_notes(path: Path) → list[Note][source]

Load comment history, treating outputs without notes as empty.

qibocal.auto.notes.dump_notes(notes: list[Note], path: Path)[source]

Save comment history without touching calibration data or metadata.

qibocal.auto.operation module

class qibocal.auto.operation.BoundProtocol(protocol: Protocol[_ParametersT, _FitParsT, _ReportParsT, _DataT, _ResultsT], parameters: _ParametersT, fitpars: _FitParsT | None = None, reportpars: _ReportParsT | None = None)[source]

Bases: Generic[_ParametersT, _FitParsT, _ReportParsT, _DataT, _ResultsT]

A protocol bound with specific parameters and execution configuration.

This represents a specific protocol execution with all required parameters and optional phase parameters already determined.

_is_protocol = False
protocol: Protocol[_ParametersT, _FitParsT, _ReportParsT, _DataT, _ResultsT]

The protocol being bound.

parameters: _ParametersT

Acquisition parameters.

fitpars: _FitParsT | None = None

Optional fit phase parameters.

reportpars: _ReportParsT | None = None

Optional report phase parameters.

class qibocal.auto.operation.Protocol(acquisition: Callable[[...], _DataT], fit: Callable[[...], _ResultsT] | None = None, report: Callable[[...], Any] | None = None, update: Callable[[...], None] | None = None, two_qubit_gates: bool | None = False)[source]

Bases: Generic[_ParametersT, _FitParsT, _ReportParsT, _DataT, _ResultsT]

A calibration protocol with explicit type-safe interface.

This protocol definition separates concerns into distinct phases: - acquisition: collects raw data from hardware - fit: processes data and produces results - report: generates visualizations and summaries - update: applies results back to the platform configuration

All phases except acquisition are optional, allowing flexible workflow composition.

Type Parameters:

_ParametersT: Type of acquisition parameters _FitParsT: Type of fit function parameters _ReportParsT: Type of report function parameters _DataT: Type of data returned by acquisition _ResultsT: Type of results returned by fit

acquisition: Callable[[...], _DataT]

Acquire data with parameters and optional platform/targets.

fit: Callable[[...], _ResultsT] | None = None

Process data and produce results. Takes data and optional fit params.

report: Callable[[...], Any] | None = None

Generate reports/visualizations and return their output.

update: Callable[[...], None] | None = None

Update platform with results.

two_qubit_gates: bool | None = False

Flag to determine whether to allocate list of Qubits or Pairs.

property parameters_type: type

Extract the type of acquisition parameters.

property data_type: type

Extract the return type of acquisition.

property results_type: type

Extract the return type of fit.

_is_protocol = False
qibocal.auto.operation.ProtocolsCollection

Collection of protocols.

This collection is supposed to be a bundle, either built-in or provided by external extensions.

alias of dict[str, Protocol]

qibocal.auto.output module

class qibocal.auto.output.Versions(other: dict, qibocal: str = '0.2.7')[source]

Bases: object

Versions of the main software used.

other: dict
qibocal: str = '0.2.7'
class qibocal.auto.output.TaskStats(acquisition: float, fit: float)[source]

Bases: object

Statistics about task execution.

acquisition: float

Acquisition timing.

fit: float

Fitting timing.

property tot: float

Total execution time.

class qibocal.auto.output.Metadata(backend: str, platform: str, start_time: ~datetime.datetime | None, end_time: ~datetime.datetime | None, stats: dict[str, ~qibocal.auto.output.TaskStats], versions: ~qibocal.auto.output.Versions, author: str | None = None, tag: list[str] | None = <factory>, targets: list[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]] | list[~typing.Annotated[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~types.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[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ...]] | None = None)[source]

Bases: object

Execution metadata.

backend: str
platform: str
start_time: datetime | None
end_time: datetime | None
stats: dict[str, TaskStats]
versions: Versions
author: str | None = None
tag: list[str] | None
targets: list[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]] | list[~typing.Annotated[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~types.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[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ...]] | None = None
classmethod generate(backend)[source]

Generate template metadata.

The purpose is to fill the arguments with defaults, or extract them from the few arguments.

start()[source]

Register start time.

end()[source]

Register completion time.

dump() → dict[source]

Dump to serializable to dictionary.

qibocal.auto.output._new_output() → Path[source]
class qibocal.auto.output.Output(history: History, meta: Metadata, platform: CalibrationPlatform | None = None, notes: list[Note] = <factory>)[source]

Bases: object

Output manager.

This object represents the output folder, serializing from and deserialing to it.

history: History
meta: Metadata
platform: CalibrationPlatform | None = None
notes: list[Note]

Session comment history, populated only by explicit user or agent input.

static mkdir(path: Path | None = None, force: bool = False) → Path[source]

Create output directory.

If a path is given and existing, it is overwritten only in the case force is enabled, otherwise an error is thrown. If not already existing, it is just used.

If no path is given, a default one is generated (according to user name and time stamp).

dump(path: Path)[source]

Dump output content to an output folder.

dump_notes(path: Path)[source]

Save only session comments, without rewriting calibration output.

static update_platform(platform: CalibrationPlatform, path: Path)[source]

Dump platform used.

If the original one is not defined, use the current one as the original, else update the new one.

_export_stats()[source]

Export task statistics.

Extract statistics from the history, and record them in the metadata.

process(output: Path, mode: ExecutionMode, update: bool = True, force: bool = False)[source]

Process an existing output directory.

Reconstruct the calibration platform from the live backend during acquisition or from the saved datafolder during fitting, then rerun each completed task using the requested execution mode and output folder. If update is enabled and the task supports platform updates, the platform is refreshed accordingly. When force is False, tasks that already contain fitting results raise an error to avoid overwriting them.

qibocal.auto.runcard module

Specify runcard layout, handles (de)serialization.

qibocal.auto.runcard.RUNCARD = 'runcard.yml'

Runcard filename.

class qibocal.auto.runcard.Runcard(actions: list[~qibocal.auto.task.Action], targets: list[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]] | list[~typing.Annotated[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~types.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[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ...]] | None = None, backend: str = 'qibolab', platform: str = 'mock', update: bool = True)[source]

Bases: object

Structure of an execution runcard.

actions: list[Action]

List of action to be executed.

targets: list[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]] | list[~typing.Annotated[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~types.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[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ...]] | None = None

Qubits to be calibrated.

If None the protocols will be executed on all qubits available in the platform.

backend: str = 'qibolab'

Qibo backend.

platform: str = 'mock'

Qibolab platform.

update: bool = True
dump(path)[source]

Dump runcard object to yaml.

run(output: Path, platform: CalibrationPlatform, mode: ExecutionMode, update: bool = True) → History[source]

Run runcard and dump to output.

qibocal.auto.serialize module

qibocal.auto.serialize.deserialize(raw: dict)[source]

Deserialization of nested dict.

qibocal.auto.serialize.serialize(raw: dict)[source]

JSON-friendly serialization for nested dict.

qibocal.auto.serialize._nested_list_to_tuples(raw)[source]

Convert nested lists to nested tuples.

qibocal.auto.status module

Describe the status of a completed task.

Simple and general statuses are defined here, but more of them can be defined by individual calibrations routines, and user code as well:

class PinkFirst(Status):
    '''Follow the pink arrow as the next one.'''

@dataclass
class ParametrizedException(Status):
    '''Trigger exceptional workflow, passing down a further parameter.

    Useful if the handler function is using some kind of threshold, or can
    make somehow use of the parameter to decide, but in a way that is not
    completely established, so it should not be hardcoded in the status
    type.

    '''
    myvalue: int

@dataclass
class ExceptionWithInput(Status):
    '''Pass to next routine as input.'''
    routine_x_input: float

In general, statuses can encode a predetermined decision about what to do next, so the decision has been handled by the fitting function, or an open decision, that is left up to the handler function.

class qibocal.auto.status.Status[source]

Bases: object

The exit status of a calibration routine.

class qibocal.auto.status.Normal[source]

Bases: Status

All green.

class qibocal.auto.status.Failure[source]

Bases: Status

Unrecoverable.

qibocal.auto.task module

Action execution tracker.

class qibocal.auto.task.Id

Action identifiers type.

alias of str

qibocal.auto.task.Targets = list[typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]] | 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')])]], BeforeValidator(func=<function <lambda>>, json_schema_input_type=PydanticUndefined), PlainSerializer(func=<function <lambda>>, return_type=PydanticUndefined, when_used='always')]] | list[tuple[typing.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ...]]

Elements to be calibrated by a single protocol.

class qibocal.auto.task.Action(id: ~qibocal.auto.task.Id, operation: ~qibocal.auto.operation.OperationId, targets: list[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]] | list[~typing.Annotated[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~types.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[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ...]] | None = None, update: bool = True, parameters: dict[str, ~typing.Any] | None = None)[source]

Bases: object

Action specification in the runcard.

id: Id

Action unique identifier.

operation: OperationId

Operation to be performed by the executor.

targets: list[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]] | list[~typing.Annotated[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~types.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[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ...]] | None = None

Local qubits (optional).

update: bool = True

Runcard update mechanism.

parameters: dict[str, Any] | None = None

Input parameters, either values or provider reference.

dump(path: Path)[source]

Dump single action to yaml.

classmethod cast(source: dict | Action, operation: str | None = None)[source]

Cast an action source to an action.

class qibocal.auto.task.TaskId(id: Id, iteration: int)[source]

Bases: object

Unique identifier for executed tasks.

id: Id
iteration: int
qibocal.auto.task.DEFAULT_NSHOTS = 100

Default number on shots when the platform is not provided.

class qibocal.auto.task.Task(action: qibocal.auto.task.Action, operation: qibocal.auto.operation.Protocol)[source]

Bases: object

action: Action

Action object parsed from Runcard.

operation: Protocol
dump(path)[source]
property targets: list[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]] | list[~typing.Annotated[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~types.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[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ...]]

Protocol targets.

property id: Id

Task Id.

property parameters

Inputs parameters for self.operation.

property update

Local update parameter.

run(mode: ~qibocal.auto.mode.ExecutionMode, folder: ~pathlib.Path, platform: ~qibolab._core.platform.platform.Platform | None = None, targets: list[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]] | list[~typing.Annotated[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~types.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[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ...]] | None = None) → Completed[source]
class qibocal.auto.task.Completed(task: ~qibocal.auto.task.Task | None = None, path: ~pathlib.Path | None = None, _data: ~qibocal.auto.operation.Data | None = None, _results: ~qibocal.auto.operation.Results | None = None, data_time: float = 0, results_time: float = 0, bound: ~qibocal.auto.operation.BoundProtocol | None = None, reports: ~typing.Any = None, protocol_id: str | None = None, error: Exception | None = None, success: bool = True, _targets: list[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]] | list[~typing.Annotated[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~types.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[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ...]] | None = None, notes: list[~qibocal.auto.notes.Note] = <factory>)[source]

Bases: object

A complete or partial protocol execution, optionally backed by a task.

task: Task | None = None

A snapshot of the task when it was completed.

path: Path | None = None

Optional folder containing data and results files for task.

_data: Data | None = None

Protocol data.

_results: Results | None = None

Fitting output.

data_time: float = 0

Protocol data.

results_time: float = 0

Fitting output.

bound: BoundProtocol | None = None

Bound protocol used for this execution.

reports: Any = None

Report output, keyed by target for per-target callbacks.

protocol_id: str | None = None

Identifier for the protocol that was executed.

error: Exception | None = None

Error that occurred during execution, if any.

success: bool = True

Whether execution completed successfully.

_targets: list[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]] | list[~typing.Annotated[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~types.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[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ...]] | None = None

Acquisition targets, when not recorded by a task.

notes: list[Note]

Comment history for this individual protocol execution.

property targets: list[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]] | list[~typing.Annotated[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ~types.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[tuple[~types.Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], ...]]

Targets recorded at acquisition.

property data: Data

Access task’s data.

property results

Access task’s results.

dump_parameters()[source]

Dump parameters.

dump_notes()[source]

Save only protocol comments, without rewriting acquisition or fit data.

dump_data()[source]

Dumping data.

dump_results()[source]

Dumping results.

should_update(mode: ExecutionMode, update: bool) → bool[source]

Whether to update the platform after this execution.

Requires fitting in mode, both the global and the task-level update flags, a protocol with an update callback and available fit results.

update_platform(platform: Platform)[source]

Perform update on platform’ parameters by looping over qubits or pairs.

qibocal.auto.transpile module

qibocal.auto.transpile._string_to_integer_qubit_maps(qubit_maps: list[list[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]]], platform: Platform) → list[list[int]][source]

QubitId can be integers or strings. pad_circuit only works with integer qubit IDs, so if the qubit maps contain string IDs, we convert them to integer indices based on the platform’s qubit order.

qibocal.auto.transpile._pad_circuit(nqubits: int, circuit: Circuit, qubit_map: list[int]) → Circuit[source]

Pad circuit in a new one with nqubits qubits, according to qubit_map. qubit_map is a list [i, j, k, …], where physical qubit i is mapped into the 0th logical qubit and so on.

Parameters:
  • nqubits – The total number of qubits in the new circuit.

  • circuit – The original quantum circuit to be padded.

  • qubit_map – A list mapping physical qubits to logical qubits in the new circuit.

Returns:

A Circuit instance with nqubits qubits, containing the original circuit’s gates mapped according to qubit_map.

qibocal.auto.transpile._transpile_circuits(circuits: list[Circuit], qubit_maps: list[list[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]]], platform: Platform, transpiler: Passes) → list[Circuit][source]

Transpile and pad circuits according to the platform.

Apply the transpiler to circuits and pad them in circuits with the same number of qubits in the platform. Before manipulating the circuits, this function check that the qubit_maps contain string ids and in the positive case it remap them in integers, following the ids order provided by the platform.

Note

In this function we are implicitly assume that the qubit ids are all string or all integers.

Returns:

List of transpiled and padded Circuit instances, one per input circuit.

qibocal.auto.transpile._validate_gate(gate, qubit_map)[source]

Validate measurement gate against qubit map.

qibocal.auto.transpile._validate_sequence(sequence, readout)[source]

Validate measurement sequence against readout results.

qibocal.auto.transpile._validate_measurement(gate, sequence, qubit_map, readout)[source]

Validate measurement gate and sequence consistency.

qibocal.auto.transpile._counts_with_hardware_averaging(qubit_maps: list[list[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]]], measurement_maps, readout, nshots: int) → list[Counter[str]][source]

Build Counters when hardware averaging is enabled.

qibocal.auto.transpile._counts_with_singleshot(qubit_maps: list[list[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]]], measurement_maps, readout) → list[Counter[str]][source]

Build Counters when single-shot measurements are available.

qibocal.auto.transpile._execute_circuits(platform: Platform, compiler: Compiler, circuits: list[Circuit], qubit_maps: list[list[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]]], nshots: int, averaging_mode: AveragingMode = AveragingMode.SINGLESHOT) → list[Counter[str]][source]

Executes multiple quantum circuits with a single communication with the control electronics.

Circuits are unrolled to a single pulse sequence.

qibocal.auto.transpile.execute_circuits(circuits: list[Circuit], qubit_maps: list[list[Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])]]], platform: Platform, transpiler: Passes, compiler: Compiler, nshots: int, averaging_mode: AveragingMode = AveragingMode.SINGLESHOT) → list[Counter[str]][source]

Execute multiple quantum circuits.

Combines transpile_circuits() and execute_circuits() into a single call.

Parameters:
  • circuits – List of quantum circuits to transpile and execute.

  • qubit_maps – List of qubit maps, one per circuit. Each qubit map maps physical qubit IDs to logical qubit indices.

  • platform – The platform to transpile circuits for and execute on.

  • transpiler – The transpiler to apply to the circuits.

  • compiler – The compiler to use for circuit compilation.

  • nshots – Number of times to sample from the experiment.

  • averaging_mode – Averaging mode for measurements. Default is single-shot.

Returns:

List of measurement outcome as Counter objects, one per circuit. Each Counter maps measurement outcome states as strings (e.g., “01”, “10”) to their occurrence counts. Total counts per counter equals nshots.

Examples


from qibo import Circuit, gates from qibolab import create_platform from qibocal.auto.transpile import (

dummy_transpiler, set_compiler, execute_circuits,

)

platform = create_platform(“dummy”) transpiler = dummy_transpiler(platform) compiler = set_compiler(platform)

circuit = Circuit(1) circuit.add(gates.M(0))

qubit = next(iter(platform.qubits)) [counts] = execute_circuits(

circuits=[circuit], qubit_maps=[[qubit]], platform=platform, transpiler=transpiler, compiler=compiler, nshots=100,

)

assert sum(counts.values()) == 100

qibocal.auto.transpile._natives(platform: Platform) → dict[str, NativeContainer][source]

Return the dict of native gates name with the associated native container defined in the platform. This function assumes the native gates to be the same for each qubit and pair.

qibocal.auto.transpile._create_rule(name: str, natives: NativeContainer) → Callable[source]

Create rule for gate name given container natives.

qibocal.auto.transpile.build_native_gate_compiler(platform: Platform) → Compiler[source]

Build a compiler that follows the native gates defined by platform.

Starting from Compiler.default(), this function overrides and extends gate rules using the native containers available on the platform so circuit compilation is consistent with the selected hardware configuration.

Parameters:

platform – The quantum platform containing native gate definitions.

Returns:

A Compiler instance with rules set according to the platform’s native gates.

qibocal.auto.transpile.build_native_gate_transpiler(platform: Platform) → Passes[source]

If the backend is qibolab, a transpiler with just an unroller is returned, otherwise None. This function overwrites the compiler defined in the backend, taking into account the native gates defined in the`platform` (see build_native_gate_compiler()).

Parameters:

platform – The quantum platform containing native gate definitions.

Returns:

A Passes instance with an unroller set according to the platform’s native gates.