qibocal.protocols package

Subpackages

Submodules

qibocal.protocols.calibrate_mixers module

qibocal.protocols.flipping module

qibocal.protocols.flipping.flipping = Routine(acquisition=<function _acquisition>, fit=<function _fit>, report=<function _plot>, update=<function _update>, two_qubit_gates=False)

Flipping Routine object.

qibocal.protocols.utils module

qibocal.protocols.utils.EXTREME_CHI = 10000.0

Chi2 output when errors list contains zero elements

qibocal.protocols.utils.DELAY_FIT_PERCENTAGE = 10

Percentage of the first and last points used to fit the cable delay.

qibocal.protocols.utils.MAX_PIXELS = 2

How many pixels at most two clusters’ endpoints should be far for merging them.

qibocal.protocols.utils.DISTANCE_XY = 3.0

Minimum distance for separate clusters. Clusters below this distance will be merged. Since it is given in a 3D-space, with a compressed vertical dimension, and the horizontal plane measured in pixels, this distance correspond to diagonally adjacent pixels, with some additional leeway for the extra dimension.

qibocal.protocols.utils.DISTANCE_Z = 0.5

See DISTANCE_XY.

exception qibocal.protocols.utils.FeatExtractionError[source]

Bases: Exception

Exception for feature extraction errors.

add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class qibocal.protocols.utils.PowerLevel(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: str, Enum

Power Regime for Resonator Spectroscopy

high = 'high'
low = 'low'
encode(encoding='utf-8', errors='strict')

Encode the string using the codec registered for encoding.

encoding

The encoding in which to encode the string.

errors

The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

replace(old, new, count=-1, /)

Return a copy with all occurrences of substring old replaced by new.

count

Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

split(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the front of the string and works to the end.

Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.

rsplit(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the end of the string and works to the front.

join(iterable, /)

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

capitalize()

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

casefold()

Return a version of the string suitable for caseless comparisons.

title()

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

center(width, fillchar=' ', /)

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

count(sub[, start[, end]]) int

Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

expandtabs(tabsize=8)

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find(sub[, start[, end]]) int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

partition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

index(sub[, start[, end]]) int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

ljust(width, fillchar=' ', /)

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

lower()

Return a copy of the string converted to lowercase.

lstrip(chars=None, /)

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

rfind(sub[, start[, end]]) int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

rindex(sub[, start[, end]]) int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

rjust(width, fillchar=' ', /)

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

rstrip(chars=None, /)

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

rpartition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

splitlines(keepends=False)

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

strip(chars=None, /)

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

swapcase()

Convert uppercase characters to lowercase and lowercase characters to uppercase.

translate(table, /)

Replace each character in the string using the given translation table.

table

Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper()

Return a copy of the string converted to uppercase.

startswith(prefix[, start[, end]]) bool

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

endswith(suffix[, start[, end]]) bool

Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.

removeprefix(prefix, /)

Return a str with the given prefix string removed if present.

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.

removesuffix(suffix, /)

Return a str with the given suffix string removed if present.

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.

isascii()

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

islower()

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isupper()

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

istitle()

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isspace()

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

isdecimal()

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

isdigit()

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isnumeric()

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

isalpha()

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isalnum()

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isidentifier()

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.

isprintable()

Return True if the string is printable, False otherwise.

A string is printable if all of its characters are considered printable in repr() or if it is empty.

zfill(width, /)

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

format(*args, **kwargs) str

Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).

format_map(mapping) str

Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).

static maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

qibocal.protocols.utils.readout_frequency(target: Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], platform: CalibrationPlatform, power_level: PowerLevel = PowerLevel.low, state=0) float[source]

Returns readout frequency depending on power level.

qibocal.protocols.utils.lorentzian(frequency, amplitude, center, sigma, offset, slope)[source]
qibocal.protocols.utils.lorentzian_fit(data, resonator_type=None, fit=None)[source]
qibocal.protocols.utils.effective_qubit_temperature(prob_0: ndarray[tuple[int, ...], dtype[_ScalarType_co]], prob_1: ndarray[tuple[int, ...], dtype[_ScalarType_co]], qubit_frequency: float, nshots: int)[source]

Calculates the qubit effective temperature.

The formula used is the following one:

kB Teff = - h qubit_freq / ln(prob_1/prob_0)

Parameters:
  • prob_0 (NDArray) – population 0 samples

  • prob_1 (NDArray) – population 1 samples

  • qubit_frequency (float) – frequency of qubit

  • nshots (int) – number of shots

Returns:

effective temperature error (float): error on effective temperature

Return type:

temp (float)

qibocal.protocols.utils.compute_qnd(ones_first_measure, zeros_first_measure, ones_second_measure, zeros_second_measure, pi=False) tuple[float, list, list][source]

QND calculation.

For the standard QND we follow https://arxiv.org/pdf/2106.06173 for the pi variant we follow https://arxiv.org/pdf/2110.04285

Returns the QND and the two measurement matrices.

qibocal.protocols.utils.marginalize_qubit_counts(counts: Counter[str], qubit_id: Sequence[int] | int) Counter[str][source]

Extract marginal distribution from measurement counts over selected qubit indices.

Parameters:
  • counts – Counter mapping big-endian bitstrings to counts (e.g. {‘0101’: 10, …})

  • qubit_id – Qubit ids to marginalize over.

Returns:

Counter of the marginal distribution.

qibocal.protocols.utils.compute_assignment_fidelity(one_samples: ndarray, zero_samples: ndarray) float[source]

Computing assignment fidelity from shots. The first argument are the samples when preparing state 1 and the second argument are the samples when preparing state 0.

qibocal.protocols.utils.classify(arr: ndarray, angle: float, threshold: float) ndarray[source]

Mapping IQ array in 0s and 1s given angle and threshold.

qibocal.protocols.utils.norm(x_mags)[source]
qibocal.protocols.utils.cumulative(input_data, points)[source]

Evaluates in data the cumulative distribution function of points.

qibocal.protocols.utils.eval_magnitude(value: int | float | number) int[source]

number of non decimal digits in value

qibocal.protocols.utils.round_report(measure: list) tuple[list, list][source]

Rounds the measured values and their errors according to their significant digits.

Parameters:

measure (list) – Variable-Errors couples.

Returns:

A tuple with the lists of values and errors in the correct string format.

qibocal.protocols.utils.format_error_single_cell(measure: tuple) str[source]

Helper function to print mean value and error in one line.

qibocal.protocols.utils.chi2_reduced(observed: ndarray[tuple[int, ...], dtype[_ScalarType_co]], estimated: ndarray[tuple[int, ...], dtype[_ScalarType_co]], errors: ndarray[tuple[int, ...], dtype[_ScalarType_co]], dof: float | None = None) float[source]
qibocal.protocols.utils.chi2_reduced_complex(observed: tuple[ndarray[tuple[int, ...], dtype[_ScalarType_co]], ndarray[tuple[int, ...], dtype[_ScalarType_co]]], estimated: ndarray[tuple[int, ...], dtype[_ScalarType_co]], errors: tuple[ndarray[tuple[int, ...], dtype[_ScalarType_co]], ndarray[tuple[int, ...], dtype[_ScalarType_co]]], dof: float | None = None) float[source]
qibocal.protocols.utils.get_color_state0(number) str[source]
qibocal.protocols.utils.get_color_state1(number) str[source]
qibocal.protocols.utils.significant_digit(number: float) int[source]

Computes the position of the first significant digit of a given number.

Parameters:

number (Number) – number for which the significant digit is computed. Can be complex.

Returns:

position of the first significant digit. Returns -1 if the given number

is >= 1, = 0 or inf.

Return type:

int

qibocal.protocols.utils.evaluate_grid(data: ndarray[tuple[int, ...], dtype[_ScalarType_co]])[source]

This function returns a matrix grid evaluated from the datapoints data.

qibocal.protocols.utils.plot_results(data: Data, qubit: Annotated[int | str, FieldInfo(annotation=NoneType, required=True, metadata=[_PydanticGeneralMetadata(union_mode='left_to_right')])], qubit_states: list, fit: Results) list[Figure][source]

Plots for the qubit and qutrit classification.

Parameters:
  • data (Data) – acquisition data

  • qubit (QubitID) – qubit

  • qubit_states (list) – list of qubit states available.

  • fit (Results) – fit results

qibocal.protocols.utils.table_dict(qubit: list[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')])], names: list[str], values: list, display_error=False) dict[source]

Build a dictionary to generate HTML table with table_html.

Parameters:
  • qubit (Union[list[QubitId], QubitId]) – If qubit is a scalar value,

  • repeated. (the "Qubit" entries will have only this value)

  • names (list[str]) – List of the names of the parameters.

  • values (list) – List of the values of the parameters.

  • display_errors (bool) – if True, it means that values is a list of value-error couples,

  • False. (so an Errors key will be displayed in the dictionary. The function will round the couples according to their significant digits. Default)

Returns:

A dictionary with keys Qubit, Parameters, Values (Errors).

qibocal.protocols.utils.table_html(data: dict) str[source]

This function converts a dictionary into an HTML table.

Parameters:
  • data (dict) – the keys will be converted into table entries and the

  • table. (values will be the columns of the)

  • strings. (Values must be valid HTML)

Returns:

str

qibocal.protocols.utils.euclidean_metric(point1: ndarray, point2: ndarray)[source]

Euclidean distance between two arrays.

qibocal.protocols.utils.zca_whiten(X)[source]

Applies ZCA whitening to the data (X) https://en.wikipedia.org/wiki/Whitening_transformation This implementation is analoguous of calling np.linalg.svd() function and multiplying U and Vh matrices; Example for matrix X:

`python U, S, Vh = np.linalg.svd(V) ZCA_X = X @ U @ Vh ` The aforementioned method does not require any regularization term EPS, making it formally more correct; however the current method is preferred because it scales better with respect to X dimensions and the relative error scales linear with EPS.

X: numpy 2d array

input data, rows are data points, columns are features

Returns: ZCA whitened 2d array

qibocal.protocols.utils.scaling_global(sig: ndarray) ndarray[source]

Min–max scaling over the whole np.ndarray (global).

qibocal.protocols.utils.scaling_slice(sig: ndarray, axis: int | None) ndarray[source]

Min–max scaling over a specific axis of the np.ndarray.

qibocal.protocols.utils.horizontal_diagonal(xs: ndarray, ys: ndarray) float[source]

Computing the lenght of the diagonal of a two dimensional grid.

qibocal.protocols.utils.build_clustering_data(peaks_dict: dict, z: ndarray)[source]

Preprocessing of the data to cluster.

qibocal.protocols.utils.peaks_finder(x, y, z) dict | None[source]

Function for finding the peaks over the whole signal.

This function takes as input 3 features of the signal. It slices the dataset along a preferred direction (y dimension, corresponding to the flux bias) and for each slice it determines the biggest peaks by using scipy.signal.find_peaks routine.

If peaks are found, it returns a dictionary peaks_dict containing all the features for the computed peaks. If no peaks are found returns None.

qibocal.protocols.utils.merging(data: tuple, labels: list, min_points_per_cluster: int, distance_xy: float, distance_z: float)[source]

Divides the processed signal into clusters for separating signal from noise.

data is a 3D tuple of the data to cluster, while labels is the classification made by the clustering algorithm; min_points_per_cluster is the minimum size of points for a cluster to be considered relevant signal. It is also possible to set the parameter distance, which represents the Euclidean distance between neighboring points of two clusters. If this distance is smaller than distance, the two clusters are merged. It allows a min_cluster_size=2 in order to decrease as much as possible misclassification of few points. The function returns a boolean list corresponding to the indices of the relevant signal.

qibocal.protocols.utils.clustering(peaks_dict, z_masked)[source]

In this function Hierarchical Density-Based Spatial Clustering of Applications with Noise (HDBSCAN) algorithm is used; HDBSCAN is a good algorithm for successfully capture clusters with different densities.

qibocal.protocols.utils.reshaping_raw_signal(x, y, z)[source]
qibocal.protocols.utils.guess_period(x, y)[source]

Return fft period estimation given a sinusoidal plot.

qibocal.protocols.utils.fallback_period(period)[source]

Function to estimate period if guess_period fails.

qibocal.protocols.utils.angle_wrap(angle: float)[source]

Wrap an angle from [-np.inf,np.inf] into the [0,2*np.pi] domain

qibocal.protocols.utils.baseline_als(data: ndarray[tuple[int, ...], dtype[_ScalarType_co]], lamda: float, p: float, niter: int = 10) ndarray[tuple[int, ...], dtype[_ScalarType_co]][source]

Estimate data baseline with “asymmetric least squares” method.

The lambda parameter controls the stiffness weight. A larger value will suppress more and more the fluctuations in the estimated baseline. The p parameters controls instead the asymmetry, deweighting fluctuations in one direction only.

The convergence is iterative, but it is often sufficiently fast that a closed loop with a predetermined number of iterations is enough. niter allows changing the amount of iterations.

The approach is defined in

Eilers, Paul & Boelens, Hans. (2005). Baseline Correction with Asymmetric Least Squares Smoothing. Unpubl. Manuscr.