Backends#
qibo.backends.abstract.Backend is the main calculation engine to execute circuits.
Qibo provides backends for quantum simulation on classical hardware, as well as quantum hardware
management and control. For a complete list of available backends, refer to the
Packages section. To create new backends, inherit from
qibo.backends.abstract.Backend and implement its new methods.
This abstract class defines the required methods for circuit execution.
The user can set the backend using the qibo.set_backend() function.
import qibo
qibo.set_backend("qibojit")
# Switch to the numpy backend
qibo.set_backend("numpy")
If no backend is specified, the default backend is used.
The default backend is selected in the following order: qibojit, numpy, and qiboml.
The list of default backend candidates can be changed using the QIBO_BACKEND environment variable.
Some backends support different platforms. For example, the qibojit backend
provides two platforms (cupy and cuquantum) when used on GPU.
The platform can be specified using the platform parameter in the qibo.set_backend() function.
import qibo
qibo.set_backend("qibojit", platform="cuquantum")
# Switch to the cupy platform
qibo.set_backend("qibojit", platform="cupy")
- class qibo.backends.abstract.Backend[source]#
-
- property connectivity: list[tuple[int | str, int | str]] | None#
Return available qubit pairs of the backend.
- property natives: list[str] | None#
Return the native gates of the backend.
- Returns:
For hardware backends, return the native gates of the backend. For the simulation backends, return
None.- Return type:
List[str] or None
- cast(array, dtype=None, copy=False)[source]#
Cast an object as the array type of the current backend.
- Parameters:
array (ArrayLike) – Object to cast to array.
dtype (str or type, optional) – data type of
arrayafter casting. Options are"complex128","complex64","float64", or"float32". IfNone, defaults toBackend.dtype. Defaults toNone.copy (bool, optional) – If
Truea copy of the object is created in memory. Defaults toFalse.
- Returns:
arraycasted todtype, possibly copied in memory.- Return type:
ArrayLike
- is_sparse(array)[source]#
Determine if a given array is a sparse tensor.
- Parameters:
array (ArrayLike) – array to determine the sparsity of.
- Returns:
Trueifarrayis sparse,Falseotherwise.- Return type:
- set_device(device)[source]#
Set simulation device. Works in-place.
- Parameters:
device (str) – Device index, e.g.
/CPU:0for CPU, or/GPU:1for the second GPU in a multi-GPU environment.- Return type:
None
- set_dtype(dtype)[source]#
Set data type of arrays created using the backend. Works in-place.
Note
The data types
float32andfloat64are intended to be used when the circuits to be simulated only contain gates with real-valued matrix representations. Using one of the aforementioned data types with circuits that contain complex-valued matrices will raise a casting error.Note
List of gates that always admit a real-valued matrix representation:
qibo.gates.I,qibo.gates.X,qibo.gates.Z,qibo.gates.H,qibo.gates.Align,qibo.gates.RY,qibo.gates.CNOT,qibo.gates.CZ,qibo.gates.CH,qibo.gates.CRY,qibo.gates.SWAP,qibo.gates.FSWAP,qibo.gates.GIVENS,qibo.gates.RBS,qibo.gates.TOFFOLI,qibo.gates.CCZ, andqibo.gates.FanOut.Note
The following parametrized gates can have real-valued matrix representations depending on the values of their parameters:
qibo.gates.RX,qibo.gates.RZ,qibo.gates.U1,qibo.gates.U2,qibo.gates.U3,qibo.gates.CRX,qibo.gates.CRZ,qibo.gates.CU1,qibo.gates.CU2,qibo.gates.CU3,qibo.gates.fSim,qibo.gates.GeneralizedfSim,qibo.gates.RXX,qibo.gates.RYY,qibo.gates.RZZ,qibo.gates.RZX, andqibo.gates.GeneralizedRBS.- Parameters:
dtype (str) – the options are the following:
complex128,complex64,float64, andfloat32.- Return type:
None
- set_seed(seed)[source]#
Set the seed of the random number generator. Works in-place.
- Parameters:
seed (int or None) – seed to be set. If
None, seed is random.- Return type:
None
- set_threads(nthreads)[source]#
Set number of threads for CPU backend simulations that accept it. Works in-place.
- Parameters:
nthreads (int) – Number of threads.
- Return type:
None
- to_numpy(array)[source]#
Convert
arrayto anumpy.ndarray.- Parameters:
array (ArrayLike) – array to be converted to
numpy.ndarray.- Returns:
Original array converted to
numpy.ndarray.- Return type:
ArrayLike
- property complex64: dtype[Any] | None | type[Any] | _SupportsDType[dtype[Any]] | str | tuple[Any, int] | tuple[Any, SupportsIndex | collections.abc.Sequence[SupportsIndex]] | list[Any] | _DTypeDict | tuple[Any, Any]#
Complex number type composed of two single-precision floating-point numbers.
- Returns:
Single-precision complex data type.
- Return type:
DTypeLike
- property complex128: dtype[Any] | None | type[Any] | _SupportsDType[dtype[Any]] | str | tuple[Any, int] | tuple[Any, SupportsIndex | collections.abc.Sequence[SupportsIndex]] | list[Any] | _DTypeDict | tuple[Any, Any]#
Complex number type composed of two double-precision floating-point numbers.
- Returns:
Double-precision complex data type.
- Return type:
DTypeLike
- create_dtype(dtype, **kwargs)[source]#
Create a data type object.
Note
This is not named
dtypebecauseBackend.dtypealready stores the default data type of arrays created using the backend.- Parameters:
- Returns:
The data type object.
- Return type:
DTypeLike
- property float32: dtype[Any] | None | type[Any] | _SupportsDType[dtype[Any]] | str | tuple[Any, int] | tuple[Any, SupportsIndex | collections.abc.Sequence[SupportsIndex]] | list[Any] | _DTypeDict | tuple[Any, Any]#
Single-precision floating-point number type.
- Returns:
Single-precision data type.
- Return type:
DTypeLike
- property float64: dtype[Any] | None | type[Any] | _SupportsDType[dtype[Any]] | str | tuple[Any, int] | tuple[Any, SupportsIndex | collections.abc.Sequence[SupportsIndex]] | list[Any] | _DTypeDict | tuple[Any, Any]#
Double-precision floating-point number type.
- Returns:
Double-precision data type.
- Return type:
DTypeLike
- property int8: dtype[Any] | None | type[Any] | _SupportsDType[dtype[Any]] | str | tuple[Any, int] | tuple[Any, SupportsIndex | collections.abc.Sequence[SupportsIndex]] | list[Any] | _DTypeDict | tuple[Any, Any]#
\(8\)-bit signed integer type.
- Returns:
Signed integer data type.
- Return type:
DTypeLike
- property int16: dtype[Any] | None | type[Any] | _SupportsDType[dtype[Any]] | str | tuple[Any, int] | tuple[Any, SupportsIndex | collections.abc.Sequence[SupportsIndex]] | list[Any] | _DTypeDict | tuple[Any, Any]#
\(16\)-bit signed integer type.
- Returns:
Signed integer data type.
- Return type:
DTypeLike
- property int32: dtype[Any] | None | type[Any] | _SupportsDType[dtype[Any]] | str | tuple[Any, int] | tuple[Any, SupportsIndex | collections.abc.Sequence[SupportsIndex]] | list[Any] | _DTypeDict | tuple[Any, Any]#
\(32\)-bit signed integer type.
- Returns:
Signed integer data type.
- Return type:
DTypeLike
- property int64: dtype[Any] | None | type[Any] | _SupportsDType[dtype[Any]] | str | tuple[Any, int] | tuple[Any, SupportsIndex | collections.abc.Sequence[SupportsIndex]] | list[Any] | _DTypeDict | tuple[Any, Any]#
\(64\)-bit signed integer type.
- Returns:
Signed integer data type.
- Return type:
DTypeLike
- property uint8: dtype[Any] | None | type[Any] | _SupportsDType[dtype[Any]] | str | tuple[Any, int] | tuple[Any, SupportsIndex | collections.abc.Sequence[SupportsIndex]] | list[Any] | _DTypeDict | tuple[Any, Any]#
\(8\)-bit unsigned integer type.
- Returns:
Unsigned integer data type.
- Return type:
DTypeLike
- add_at(array_1, indices, array_2)[source]#
Add
array_2toarray_1at specifiedindices. Works in-place.- Parameters:
array_1 (ArrayLike) – Output array to be modified.
indices (ArrayLike) – Indices at which to add elements.
array_2 (ArrayLike) – Input array with elements to add.
- Return type:
None
- all(array, **kwargs)[source]#
Test whether all
arrayelements evaluate toTrue.- Parameters:
array (ArrayLike) – array to be evaluated.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
If no axis is specified, returns
Trueif all elements evaluate toTrue,Falseotherwise. If an axis is specified, returns element-wiseTrueorFalsealong the specified axis.- Return type:
bool or ArrayLike
- allclose(array_1, array_2, **kwargs)[source]#
Return
Trueif two arrays are element-wise equal within a tolerance.- Parameters:
array_1 (ArrayLike) – first array.
array_2 (ArrayLike) – second array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Trueif both arrays are close within the set tolerance in all elements,Falseotherwise.- Return type:
- angle(array, **kwargs)[source]#
Return the element-wise angle(s) of the complex
array.- Parameters:
array (ArrayLike) – array of complex numbers.
- Returns:
Array with the element-wise angles of the complex numbers in
array.- Return type:
ArrayLike
- any(array, **kwargs)[source]#
Test whether any of the
arrayelements evaluate toTrue.- Parameters:
array (ArrayLike) – array to be evaluated.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
If no axis is specified, returns
Trueif any element inarrayevaluate toTrue,Falseotherwise. If an axis is specified, return element-wiseTrueorFalsealong the specified axis.- Return type:
bool or ArrayLike
- append(array, values, axis=None)[source]#
Append
valuesto the end ofarrayalongaxis.- Parameters:
array (ArrayLike) – array to append values to.
values (ArrayLike) – values to be appended to
array.axis (int, optional) – axis along which
valuesare appended. IfaxisisNone, botharrayandvaluesare flattened before use. Defaults toNone.
- Returns:
A copy of
arraywithvaluesappended toaxis. Note thatappenddoes not occur in-place.- Return type:
ArrayLike
- arange(*args, **kwargs)[source]#
Return evenly spaced values within a given interval.
- args (int): positional arguments for this function.
For more details, see the corresponding engine’s documentation.
- kwargs (optional): additional options for this function.
For more details, see the corresponding engine’s documentation.
- Returns:
Array of evenly spaced values.
- Return type:
ArrayLike
- Parameters:
args (int) –
- arccos(array, **kwargs)[source]#
Calculate the element-wise inverse cosine of values in
array.- Parameters:
array (ArrayLike) – array to calculate
arccosof.kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Array with the element-wise inverse cosine of elements in array`.
- Return type:
ArrayLike
- arcsin(array, **kwargs)[source]#
Calculate the element-wise inverse sine of values in
array.- Parameters:
array (ArrayLike) – array to calculate
arcsinof.kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Array with the element-wise inverse sine of elements in array`.
- Return type:
ArrayLike
- arctan2(array_1, array_2, **kwargs)[source]#
Return the element-wise principal argument of a complex number.
For a complex number \(x + i \, y\), the \(\textrm{arctan2}\) function is defined as
\[\textrm{arctan2}(y, \, x) = \textrm{arg}(x + i \, y) = \textrm{Im}(\log(x + i\,y)) \, ,\]where \(\textrm{Im}\) indicates the imaginary part.
- Parameters:
array_1 (ArrayLike) – array of \(y\) elements.
array_2 (ArrayLike) – array of \(x\) elements.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Array of angles in radians, in the range \([-\pi, \, \pi]\).
- Return type:
ArrayLike
- argmax(array, axis=None, **kwargs)[source]#
Return the indices of the maximum values in
arrayalong anaxis.- Parameters:
array (ArrayLike) – input array.
axis (Optional[int], optional) – axis along which to find the maximum value(s). If
None, the flattenedarrayis used. Defaults toNone.kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Array of indices into the
array.- Return type:
ArrayLike
- argsort(array, axis=None, **kwargs)[source]#
Return the indices that would sort
array.- Parameters:
array (ArrayLike) – input array.
axis (Optional[int], optional) – axis along which to sort. If
None, the flattenedarrayis used. Defaults toNone.kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Array of indices that sort
arrayalong the specified axis.- Return type:
ArrayLike
- array_equal(array_1, array_2, **kwargs)[source]#
Return
Trueif two arrays have the same shape and elements,Falseotherwise.- Parameters:
array_1 (ArrayLike) – first array.
array_2 (ArrayLike) – second array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Trueif the arrays are equal,Falseotherwise.- Return type:
- ascontiguousarray(array, **kwargs)[source]#
Return a contiguous array in memory.
- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Contiguous array of same shape and content as
array.- Return type:
ArrayLike
- base_repr(number, base=2, **kwargs)[source]#
Return a string representation of a
numberin the givenbasesystem.Note
If
base==2, function defaults to the fasterqibo.backends.abstract.Backend.binary_repr(). See that method’s documentation for more options.- Parameters:
- Returns:
String representation of
numberin thebasesystem.- Return type:
- binary_repr(number, length=None)[source]#
Return the binary representation of the input number as a string.
- Parameters:
- Returns:
Binary representation of
number.- Return type:
- block(arrays)[source]#
Assemble an array from a nested list of blocks of
arrays.- Parameters:
arrays (ArrayLike) – nested list of array-like containing blocks to the merged.
- Returns:
Array assembled from the given blocks.
- Return type:
ArrayLike
- block_diag(*arrays)[source]#
Create a block diagonal array from provided
arrays.- Parameters:
arrays (ArrayLike) – input arrays.
- Returns:
Array with
arrayson the diagonal of the last two dimensions.- Return type:
ArrayLike
- ceil(array, **kwargs)[source]#
Return the element-wise ceiling of
array.- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The ceiling of each element in
array.- Return type:
ArrayLike
- concatenate(arrays, **kwargs)[source]#
Join a sequence of arrays along an existing axis.
- Parameters:
arrays (Tuple[ArrayLike, ...]) – tuple of arrays to be concatenated.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The concatenated array.
- Return type:
ArrayLike
- conj(array)[source]#
Return the element-wise complex conjugate of
array.- Parameters:
array (ArrayLike) – input array.
- Returns:
The complex conjugate of
array.- Return type:
ArrayLike
- convolve(array_1, array_2, **kwargs)[source]#
Return the discrete, linear convolution of two one-dimensional arrays.
- Parameters:
array_1 (ArrayLike) – first one-dimensional array.
array_2 (ArrayLike) – second one-dimensional array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Discrete, linear convolution of
array_1andarray_2.- Return type:
ArrayLike
- coo_matrix(array, **kwargs)[source]#
Return the sparse version of
arrayin coordinate format.Also known as the
ijvortripletformat.- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The coordinate-format version of
array.- Return type:
ArrayLike
- copy(array, **kwargs)[source]#
Return a copy of
array.- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The copied array.
- Return type:
ArrayLike
- cos(array, **kwargs)[source]#
Calculate the element-wise cosine of values in
array.- Parameters:
array (ArrayLike) – array to calculate
cosof.kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Array with the element-wise cosine of elements in array`.
- Return type:
ArrayLike
- cosine_sin_decomposition(array, block_nrows, block_ncols)[source]#
Calculate the Cosine-Sine Decomposition of a unitary
array.- Parameters:
- Returns:
Block-diagonal left unitary, cosine-sine matrix, and block-diagonal right unitary, in that order.
- Return type:
Tuple[ArrayLike, ArrayLike, ArrayLike]
- count_nonzero(array, **kwargs)[source]#
Count the number of non-zero elements in
array.- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Number of non-zero elements in
array.- Return type:
ArrayLike
- csr_matrix(array, **kwargs)[source]#
Return the sparse version of
arrayin compressed sparse row format.- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The compressed-sparse-row version of
array.- Return type:
ArrayLike
- cumsum(array, **kwargs)[source]#
Return the cumulative sum of the elements in
array.- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
New array with the cumulative sum of
array.- Return type:
ArrayLike
- dagger(array)[source]#
Return the conjugate transpose of an
array.- Parameters:
array (ArrayLike) – input array.
- Returns:
Conjugate transpose of the input
array.- Return type:
ArrayLike
- default_rng(seed=None)[source]#
Create a new random number Generator using the engine’s default setting.
- Parameters:
seed (int, optional) – a seed to initialize the generator. If
None,None. (a random integer is chosen. Defaults to) –
- Returns:
The initialized random number generator.
- Return type:
ArrayLike
- delete(*args, **kwargs)[source]#
Return a new array with sub-arrays along an axis deleted.
- Parameters:
args (int) – positional arguments for this function. For more details, see the corresponding engine’s documentation.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
New array without the deleted elements.
- Return type:
ArrayLike
- det(array)[source]#
Return the determinant of
array.- Parameters:
array (ArrayLike) – input array.
- Returns:
Determinant of
array.- Return type:
ArrayLike or float
- diag(array, **kwargs)[source]#
Extract or construct a diagonal array.
If
arrayis one-dimensional, construct a two-dimensional array witharrayas its diagonal. Otherwise, extract the diagonal elements ofarray.- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The extracted or constructed diagonal array.
- Return type:
ArrayLike
- dot(array_1, array_2, **kwargs)[source]#
Dot product of two arrays.
- Parameters:
array_1 (ArrayLike) – first array.
array_2 (ArrayLike) – second array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Dot product of
array_1andarray_2.- Return type:
ArrayLike
- eig(array, **kwargs)[source]#
Compute the eigenvalues and right eigenvectors of a two-dimensional
array.- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Tuple with, respectively, array of eigenvalues and array of column-stacked eigenvectors.
- Return type:
Tuple[ArrayLike, ArrayLike]
- eigh(array, **kwargs)[source]#
Compute the eigenvalues and right eigenvectors of a two-dimensional
arraythat is assumed to be Hermitian.- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Tuple with, respectively, array of eigenvalues and array of column-stacked eigenvectors.
- Return type:
Tuple[ArrayLike, ArrayLike]
- eigsh(array, **kwargs)[source]#
Compute the eigenvalues and right eigenvectors of a two-dimensional sparse
arraythat is assumed to be Hermitian.- Parameters:
array (ArrayLike) – input sparse array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Tuple with, respectively, array of eigenvalues and array of column-stacked eigenvectors.
- Return type:
Tuple[ArrayLike, ArrayLike]
- eigvalsh(array, **kwargs)[source]#
Compute the eigenvalues of a two-dimensional sparse
arraythat is assumed to be Hermitian.- Parameters:
array (ArrayLike) – input sparse array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Array of eigenvalues.
- Return type:
ArrayLike
- eigvals(array, **kwargs)[source]#
Compute the eigenvalues of a two-dimensional
array.- Parameters:
array (ArrayLike) – input sparse array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Array of eigenvalues.
- Return type:
ArrayLike
- einsum(subscripts, *operands, **kwargs)[source]#
Evaluate the Einstein summation convention on the
operands.- Parameters:
subscripts (str) – subscripts for summation.
operands (ArrayLike) – arrays for the operation.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Array with the result of the Einstein summation.
- Return type:
ArrayLike
- expand_dims(array, axis)[source]#
Expand the shape of an
arrayalong anaxis.Insert a new
axisthat will appear at theaxisposition in the expandedarrayshape.
- expm(array)[source]#
Compute the matrix exponential of an
array.- Parameters:
array (ArrayLike) – input array.
- Returns:
The resulting matrix exponential.
- Return type:
ArrayLike
- fft(array, **kwargs)[source]#
Compute the one-dimensional discrete Fourier transform (DFT) of
arraywith the fast Fourier transform (FFT) algorithm.- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The transformed array.
- Return type:
ArrayLike
- flatnonzero(array)[source]#
Return indices that are non-zero in the flattened version of
array.- Parameters:
array (ArrayLike) – input array.
- Returns:
Indices of the nonzero elements of flattened
array.- Return type:
ArrayLike
- floor(array, **kwargs)[source]#
Return the element-wise floor of
array.- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The floor of each element in
array.- Return type:
ArrayLike
- frombuffer(buffer, **kwargs)[source]#
Interpret
bufferas a one-dimensional array.- Parameters:
buffer (bytes) – object exposing the buffer interface, e.g.
bytes.kwargs (optional) – additional options for this function, e.g.
dtype. For more details, see the corresponding engine’s documentation.
- Returns:
One-dimensional array created from the contents of
buffer.- Return type:
ArrayLike
- full(shape, fill_value, **kwargs)[source]#
Return a new array with a given
shapefilled withfill_value.- Parameters:
- Returns:
Array of
fill_valuewith the givenshape.- Return type:
ArrayLike
- hstack(arrays, **kwargs)[source]#
Stack
arraysin sequence horizontally (column wise).- Parameters:
arrays (Tuple[ArrayLike, ...]) – arrays to be stacked.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The array formed by stacking the given
arrays.- Return type:
ArrayLike
- identity(dims, dtype=None, sparse=False, **kwargs)[source]#
Return identity matrix of
dimssize anddtypedata type.- Parameters:
dims (int) – size of the identity matrix.
dtype (DTypeLike, optional) – data type of the identity matrix. If
None, defaults to the global data type of theBackend. Defaults toNone.sparse (bool, optional) – If
False, returns a dense matrix. IfTrue, returns sparse matrix in the specified format (see engine’s documentation). Defaults toFalse.kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
An array where all elements are equal to zero, except for the k-th diagonal, whose values are equal to one.
- Return type:
ArrayLike
- ifft(array, **kwargs)[source]#
Compute the one-dimensional inverse discrete Fourier transform of
arraywith the inverse fast Fourier transform algorithm.- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The inversely transformed array.
- Return type:
ArrayLike
- inv(array)[source]#
Calculate the inverse of an
array.- Parameters:
array (ArrayLike) – input array.
- Returns:
Array containing the inverse of
array.- Return type:
ArrayLike
- isnan(array, **kwargs)[source]#
Test element-wise for NaN and return result as a boolean array.
- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Trueelements wherearrayisnan,Falseotherwise.- Return type:
ArrayLike
- kron(array_1, array_2)[source]#
Kronecker product of two arrays.
- Parameters:
array_1 (ArrayLike) – first array.
array_2 (ArrayLike) – second array.
- Returns:
The resulting array.
- Return type:
ArrayLike
- logm(array, **kwargs)[source]#
Compute the matrix logarithm of an
array.- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The resulting matrix logarithm.
- Return type:
ArrayLike
- matmul(array_1, array_2, **kwargs)[source]#
Calculate the matrix product of two arrays.
- Parameters:
array_1 (ArrayLike) – first array.
array_2 (ArrayLike) – second array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The matrix product of the inputs.
- Return type:
ArrayLike
- matrix_norm(array, order='nuc', **kwargs)[source]#
Calculate norm of a two-dimensional array.
- Parameters:
array (ArrayLike) – input array.
order (int or float or str, optional) – Order of the norm. For the specific options, we refer to the engine’s official documentation. Defaults to
"nuc".kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Norm of the matrix.
- Return type:
float or ArrayLike
- maximum(array_1, array_2, **kwargs)[source]#
Return the element-wise maximum between two arrays.
- Parameters:
array_1 (ArrayLike) – first array.
array_2 (ArrayLike) – second array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The maximum between
array_1andarray_2, element-wise.- Return type:
ArrayLike
- minimum(array_1, array_2, **kwargs)[source]#
Return the element-wise minimum between two arrays.
- Parameters:
array_1 (ArrayLike) – first array.
array_2 (ArrayLike) – second array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The minimum between
array_1andarray_2, element-wise.- Return type:
ArrayLike
- mod(dividend, divisor, **kwargs)[source]#
Return the element-wise remainder of division.
- Parameters:
- Returns:
The element-wise remainder of the quotient
dividend / divisor.- Return type:
ArrayLike
- moveaxis(array, *args, **kwargs)[source]#
Move axes of an
arrayto new positions.- Parameters:
- Returns:
Array with moved axes.
- Return type:
ArrayLike
- nonzero(array)[source]#
Return the indices of the elements of
arraythat are non-zero.- Parameters:
array (ArrayLike) – input array.
- Returns:
Array with the indices of the non-zero elements of
array.- Return type:
ArrayLike
- outer(array_1, array_2)[source]#
Calculate the outer product of two arrays.
- Parameters:
array_1 (ArrayLike) – first array,
array_2 (ArrayLike) – second array.
- Returns:
The resulting array.
- Return type:
ArrayLike
- packbits(array, axis=None, **kwargs)[source]#
Pack the elements of a binary-valued
arrayinto bits of an unsigned integer array.- Parameters:
array (ArrayLike) – array of integers or booleans, whose elements are interpreted as bits according to their truth value.
axis (int, optional) – axis along which the bits are packed. If
None,arrayis flattened before packing. Defaults toNone.kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Array of \(8\)-bit unsigned integers, in which every \(8\) consecutive elements of
arrayalongaxisare packed into a single element, with zero padding if the size ofaxisis not a multiple of \(8\).- Return type:
ArrayLike
- poly(array, **kwargs)[source]#
Return the coefficients of the polynomial with the given roots.
- Parameters:
array (ArrayLike) – roots of the polynomial, or a square matrix whose eigenvalues are the roots.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Polynomial coefficients, from the highest to the lowest degree.
- Return type:
ArrayLike
- prod(array, **kwargs)[source]#
Return the product of array elements.
- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
New array with the product of elements of
array.- Return type:
ArrayLike
- qr(array, **kwargs)[source]#
Calculate the \(\textrm{QR}\) factorization of a two-dimensional
array.- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Tuple with, respectively, the orthogonal matrix \(\textrm{Q}\) and the upper-triangular matrix \(\textrm{R}\).
- Return type:
Tuple[ArrayLike, …]
- random_choice(array, size=None, replace=True, p=None, seed=None, **kwargs)[source]#
Generate random sample(s) from a given one-dimensional
arrayover the probability distributionp.- Parameters:
array (ArrayLike) – If a tensor, a random sample is generated from its elements. If an
int, the random sample is generated as if it wereBackend.arange(array).size (int or Tuple[int, ...], optional) – output shape. If
None, a single sample is returned. Defaults toNone.replace (bool, optional) – If
True, the values inarraycan be sampled multiple times. IfFalse, values are only sampled once. Defaults toTrue.p (ArrayLike, optional) – probabilities associated with each entry in
array. IfNone, defaults to the uniform distribution. Defaults toNone.seed (int, optional) – a seed to initialize the random number generator. If
None, a random integer is chosen. Defaults toNone.kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The generated random sample(s).
- Return type:
ArrayLike
- random_integers(low, high=None, size=None, seed=None, **kwargs)[source]#
Generate random integers in the interval
[low, high)over the uniform distribution.- Parameters:
low (int) – lower integer in the interval (inclusive). If
highisNone, thenhigh\(\leftarrow\)low, andlowdefaults to \(0\).high (Optional[int], optional) – if not
None, then highest integer in the interval (exclusive). IfNone, thenhigh\(\leftarrow\)low, andlowdefaults to \(0\). Defaults toNone.size (int or Tuple[int, ...], optional) – output shape. If
None, a single sample is returned. Defaults toNone.seed (int, optional) – a seed to initialize the random number generator. If
None, a random integer is chosen. Defaults toNone.kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The generated random sample(s).
- Return type:
ArrayLike
- random_normal(mean, stddev, size=None, seed=None, dtype=None)[source]#
Generate random numbers from a normal (Gaussian) distribution.
- Parameters:
mean (float or int) – mean value of the Gaussian distribution.
stddev (float or int) – standard deviation of the Gaussian distribution.
size (int or List[int] or Tuple[int, ...], optional) – output shape. If
None, a single sample is returned. Defaults toNone.seed (int, optional) – a seed to initialize the random number generator. If
None, a random integer is chosen. Defaults toNone.dtype (DTypeLike, optional) – data type of the resulting array. If
None, defaults to the global data type of theBackend. Defaults toNone.
- Returns:
The generated random sample(s).
- Return type:
ArrayLike
- random_sample(size, seed=None, **kwargs)[source]#
Generate random numbers in the interval \([0.0, \, 1.0)`\) over the uniform distribution.
- Parameters:
size (int or List[int] or Tuple[int, ...], optional) – output shape.
seed (int, optional) – a seed to initialize the random number generator. If
None, a random integer is chosen. Defaults toNone.kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The generated random sample(s).
- Return type:
ArrayLike
- random_uniform(low=0.0, high=1.0, size=None, seed=None, **kwargs)[source]#
Generate random numbers in the interval
[low, high)over the uniform distribution.- Parameters:
low (float or int, optional) – lower integer in the interval (inclusive). Defaults to \(0.0\).
high (float or int, optional) – highest integer in the interval (exclusive). Defaults to \(1.0\).
size (int or Tuple[int, ...], optional) – output shape. If
None, a single sample is returned. Defaults toNone.seed (int, optional) – a seed to initialize the random number generator. If
None, a random integer is chosen. Defaults toNone.kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The generated random sample(s).
- Return type:
ArrayLike
- ravel(array, **kwargs)[source]#
Return a contiguous flattened
array.- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Contiguous, one-dimensional array with the flattened elements of
array.- Return type:
ArrayLike
- repeat(array, repeats, axis=None)[source]#
Return an array with the elements of
arrayrepeatedrepeatstimes.- Parameters:
array (ArrayLike) – input array.
repeats (Union[int, List[int], Tuple[int, ...]]) – the number of repetitions for each element.
repeatsis broadcasted to fit the shape of the given axis.axis (int, optional) – axis along which to repeat values. If
None, use the flattened inputarray, and return a flat output array. Defaults toNone.
- Returns:
Array with repeated elements of
array.- Return type:
ArrayLike
- reshape(array, shape, **kwargs)[source]#
Return an
arraywith newshape.- Parameters:
array (ArrayLike) – input array.
shape (int or Tuple[int, ...] or List[int]) – the new shape. It should be compatible with the original shape. If
int, the result will be an one-dimensional array of that length.kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The reshaped array.
- Return type:
ArrayLike
- right_shift(*args, **kwargs)[source]#
Shift the bits of an integer to the right
- Parameters:
args (int) – positional arguments for this function. For more details, see the corresponding engine’s documentation.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The right-shifted array.
- Return type:
ArrayLike
- roll(array, shift, **kwargs)[source]#
Roll
arrayelements along a given axis byshiftpositions.- Parameters:
- Returns:
The resulting array with rolled elements.
- Return type:
ArrayLike
- roots(array, **kwargs)[source]#
Return the roots of a polynomial given its coefficients.
- Parameters:
array (ArrayLike) – polynomial coefficients, from the highest to the lowest degree.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Roots of the polynomial.
- Return type:
ArrayLike
- round(array, decimals=0, **kwargs)[source]#
Return element-wise evenly round
arrayto the given number ofdecimals.- Parameters:
array (ArrayLike) – input array.
decimals (int, optional) – number of decimal places to round to. Defaults to \(0\).
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The rounded array.
- Return type:
ArrayLike
- schur(array, **kwargs)[source]#
Compute the Schur decomposition of a square
array.The Schur decomposition of a matrix \(A\) is \(A = Z \, T \, Z^{\dagger}\), where \(Z\) is unitary and \(T\) is upper triangular, if the complex form is requested. If \(A\) is normal, which is the case of unitary matrices, \(T\) is diagonal.
- Parameters:
array (ArrayLike) – square input array.
kwargs (optional) – additional options for this function, such as
output="complex"to obtain the complex Schur form for realarray. For more details, see the corresponding engine’s documentation.
- Returns:
Schur form \(T\) and unitary matrix \(Z\), in that order.
- Return type:
Tuple[ArrayLike, ArrayLike]
- searchsorted(array_1, array_2, **kwargs)[source]#
Find indices where elements should be inserted to maintain order.
Find the indices into a sorted
array_1such that, if the corresponding elements inarray_2were inserted before the indices, the order of a would be preserved.- Parameters:
array_1 (ArrayLike) – sorted array.
array_2 (ArrayLike) – second array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Array of insertion points with the same shape as
array_2, or an integer ifarray_2is a scalar.- Return type:
ArrayLike
- shuffle(array, **kwargs)[source]#
Modify an
arrayor sequence by shuffling its contents. Works in-place.- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Return type:
_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]
- sign(array, nonzero=False, **kwargs)[source]#
Return an element-wise indication of the sign of a number.
- Parameters:
array (ArrayLike) – input array.
nonzero (bool, optional) – if
Trueand sign is \(0.0\), returns \(1.0\). IfFalseand sign is \(0.0\), returns \(0.0\). Defaults toFalse.kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The resulting array with signs of the elements in
array.- Return type:
ArrayLike
- sin(array, **kwargs)[source]#
Calculate the element-wise sine of values in
array.- Parameters:
array (ArrayLike) – array to calculate
sineof.kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Array with the element-wise sine of elements in array`.
- Return type:
ArrayLike
- sort(array, **kwargs)[source]#
Return a sorted copy of an array.
- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Sorted array of the same shape and data type as
array.- Return type:
ArrayLike
- sqrt(array)[source]#
Return the element-wise non-negative square-root of
array.- Parameters:
array (ArrayLike) – input array.
- Returns:
Array containing the positive square-root of each element in
array.- Return type:
ArrayLike
- std(array, **kwargs)[source]#
Calculate the standard deviation of
array.- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
A new array containing the standard deviation.
- Return type:
float or ArrayLike
- sum(array, axis=None, **kwargs)[source]#
Sum of
arrayelements over a givenaxis.- Parameters:
array (ArrayLike) – input array.
axis (int, optional) – axis or axes along which a sum is performed. If
None, will sum all of the elements of the inputarray. Defaults toNone.kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
An array with the resulting sum of elements of
array.- Return type:
- tanh(array, **kwargs)[source]#
Calculate the element-wise hyperbolic tangent of values in
array.- Parameters:
array (ArrayLike) – array to calculate
tanhof.kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Array with the element-wise hyperbolic tangent of elements in array`.
- Return type:
ArrayLike
- tensordot(array_1, array_2, axes=2)[source]#
Calculate the tensor dot product of two arrays along two specified
axes.
- tril(array, offset=0)[source]#
Return the lower triangle of an
array.- Parameters:
array (ArrayLike) – input array.
offset (int, optional) – diagonal above which to zero elements. Defaults to \(0\).
- Returns:
Lower triangle of
array.- Return type:
ArrayLike
- tril_indices(row, offset=0, col=None, **kwargs)[source]#
Return the indices for the lower-triangle of an
(row, col)-dimensionalarray.- Parameters:
row (int) – the row dimension of the arrays for which the returned indices will be valid.
offset (int, optional) – diagonal offset (see
qibo.backends.Backend.tril()for details). Defaults to \(0\).col (int, optional) – the column dimension of the arrays for which the returned arrays will be valid. If
None, defaults to the same value asrow. Defaults toNone.
- Returns:
The row and column indices, respectively.
- Return type:
Tuple[ArrayLike, ArrayLike]
- triu(array, offset=0)[source]#
Return the upper triangle of an
array.- Parameters:
array (ArrayLike) – input array.
offset (int, optional) – diagonal below which to zero elements. Defaults to \(0\).
- Returns:
Upper triangle of
array.- Return type:
ArrayLike
- unique(array, **kwargs)[source]#
Find the unique elements of an array.
- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The sorted unique values.
- Return type:
ArrayLike or Tuple[ArrayLike, ArrayLike]
- var(array, **kwargs)[source]#
Calculate the variance of
array.- Parameters:
array (ArrayLike) – input array.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
A new array containing the variance.
- Return type:
float or ArrayLike
- vector_norm(array, order=2, dtype=None, **kwargs)[source]#
Calculate norm of an one-dimensional
array.- Parameters:
array (ArrayLike) – input array.
order (int or float or str, optional) – Order of the norm. For the specific options, we refer to the engine’s official documentation. Defaults to \(2\).
dtype (DTypeLike, optional) – data type of the resulting array. If
None, defaults to the global data type of theBackend. Defaults toNone. kwargs (optional): additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
Norm of the
array.- Return type:
float or ArrayLike
- vstack(arrays, **kwargs)[source]#
Stack
arraysin sequence vertically (row wise).- Parameters:
arrays (Tuple[ArrayLike, ...]) – arrays to be stacked.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
The array formed by stacking the given
arrays.- Return type:
ArrayLike
- where(*args, **kwargs)[source]#
Return elements chosen from two options depending on a condition.
- Parameters:
args (int) – positional arguments for this function. For more details, see the corresponding engine’s documentation.
kwargs (optional) – additional options for this function. For more details, see the corresponding engine’s documentation.
- Returns:
An array with elements from the first option where condition is
True, and elements from the second option elsewhere.- Return type:
ArrayLike
- zeros_like(array, dtype=None, **kwargs)[source]#
Return an array of zeros with the same shape and data type as a given
array.- Parameters:
array (ArrayLike) – input array.
dtype (DTypeLike, optional) – overrides the data type of the result. If
None, the data type ofarrayis used. Defaults toNone.
- Returns:
Array of zeros with the same shape as
array.- Return type:
ArrayLike
- eigenvalues(matrix, k=6, hermitian=True)[source]#
Calculate eigenvalues of a matrix.
- eigenvectors(matrix, k=6, hermitian=True)[source]#
Calculate eigenvectors of a matrix.
- jacobian(circuit, parameters, initial_state=None, return_complex=True)[source]#
Calculate the Jacobian matrix of
circuitwith respect to varablesparams.- Parameters:
circuit (Circuit) –
parameters (_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]) –
initial_state (_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | None) –
return_complex (bool) –
- Return type:
_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]
- matrix_exp(matrix, phase=1, eigenvectors=None, eigenvalues=None)[source]#
Calculate the exponential \(e^{\theta \, A}\) of a matrix \(A\) and
phase\(\theta\).If the eigenvectors and eigenvalues are given the matrix diagonalization is used for exponentiation.
- Parameters:
matrix (_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]) –
phase (complex) –
eigenvectors (_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | None) –
eigenvalues (_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | None) –
- Return type:
_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]
- matrix_log(matrix, base=2, eigenvectors=None, eigenvalues=None)[source]#
Calculate the logarithm \(\log_{b}(A)\) with a
base\(b\) of a matrix \(A\).If the eigenvectors and eigenvalues are given the matrix diagonalization is used for exponentiation.
- Parameters:
matrix (_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]) –
base (float) –
eigenvectors (_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | None) –
eigenvalues (_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | None) –
- Return type:
_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]
- matrix_sqrt(array)[source]#
Calculate the square root of
matrix\(A\), i.e. \(A^{1/2}\).Note
For the
pytorchbackend, this method relies on a copy of the original tensor. This may break the gradient flow. For the GPU backends (i.e.cupyandcuquantum), this method falls back to CPU.- Parameters:
array (_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]) –
- Return type:
_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]
- singular_value_decomposition(array)[source]#
Calculate the Singular Value Decomposition of
matrix.- Parameters:
array (_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]) –
- Return type:
tuple[Union[numpy._typing._array_like._Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], …]
- maximally_mixed_state(nqubits, dtype=None)[source]#
Generate the \(n\)-qubit density matrix for the maximally mixed state.
\[\rho = \frac{I}{2^{n}} \, ,\]where \(I\) is the \(2^{n} \times 2^{n}\) identity operator.
- Parameters:
- Returns:
The maximally mixed quantum state.
- Return type:
ArrayLike
- overlap_statevector(state_1, state_2, dtype=None)[source]#
Calculate overlap of two pure quantum states.
- Parameters:
state_1 (_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]) –
state_2 (_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]) –
dtype (dtype[Any] | None | type[Any] | _SupportsDType[dtype[Any]] | str | tuple[Any, int] | tuple[Any, SupportsIndex | collections.abc.Sequence[SupportsIndex]] | list[Any] | _DTypeDict | tuple[Any, Any]) –
- Return type:
- plus_state(nqubits, density_matrix=False, dtype=None)[source]#
Generate \(|+++\cdots+\rangle\) state vector as an array.
- reset_error_density_matrix(gate, state, nqubits)[source]#
Apply reset error to density matrix.
- thermal_error_density_matrix(gate, state, nqubits)[source]#
Apply thermal relaxation error to density matrix.
- zero_state(nqubits, density_matrix=False, dtype=None)[source]#
Generate the \(n\)-fold tensor product of the single-qubit \(\ket{0}\) state.
- Parameters:
nqubits (int) – number of qubits \(n\).
density_matrix (bool, optional) – If
True, returns the density matrix \(\ket{0}\!\bra{0}^{\otimes \, n}\). IfFalse, returns the statevector \(\ket{0}^{\otimes \, n}\). Defaults toFalse.dtype (dtype[Any] | None | type[Any] | _SupportsDType[dtype[Any]] | str | tuple[Any, int] | tuple[Any, SupportsIndex | collections.abc.Sequence[SupportsIndex]] | list[Any] | _DTypeDict | tuple[Any, Any]) –
- Returns:
Array representation of the \(n\)-qubit zero state.
- Return type:
ArrayLike
- apply_channel(channel, state, nqubits)[source]#
Apply a
channelto quantumstate.
- apply_gate(gate, state, nqubits)[source]#
Apply a gate to quantum state.
- apply_gate_half_density_matrix(gate, state, nqubits)[source]#
Apply a gate to one side of the density matrix.
- collapse_state(state, qubits, shot, nqubits, normalize=True, density_matrix=False)[source]#
Collapse quantum state according to measurement shot.
- Parameters:
- Return type:
_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]
- execute_circuit(circuit, initial_state=None, nshots=1000)[source]#
Execute a
qibo.models.circuit.Circuit.- Parameters:
- Return type:
- execute_circuits(circuits, initial_states=None, nshots=None, processes=None)[source]#
Execute multiple
qibo.models.circuit.Circuitin parallel.- Parameters:
- Return type:
list[qibo.result.CircuitResult | qibo.result.MeasurementOutcomes | qibo.result.QuantumState]
- execute_circuit_repeated(circuit, nshots, initial_state=None)[source]#
Execute a
qibo.models.circuit.Circuitmultiple times.Useful for noise simulation using state vectors or for simulating gates controlled by measurement outcomes.
Execute the circuit nshots times to retrieve probabilities, frequencies and samples. Note that this method is called only if a unitary channel is present in the circuit (i.e. noisy simulation) and density_matrix=False, or if some collapsing measurement is performed.
- Parameters:
- Return type:
- execute_distributed_circuit(circuit, initial_state=None, nshots=None)[source]#
Execute a
qibo.models.circuit.Circuitusing multiple GPUs.- Parameters:
- Return type:
- matrix_parametrized(gate)[source]#
Convert a parametrized gate to its matrix representation in the computational basis.
- aggregate_shots(shots)[source]#
Collect shots to a single array.
- Parameters:
shots (_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]) –
- Return type:
_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]
- sample_frequencies(probabilities, nshots)[source]#
Sample measurement frequencies according to a probability distribution.
- sample_shots(probabilities, nshots)[source]#
Sample measurement shots according to a probability distribution.
- samples_to_binary(samples, nqubits)[source]#
Convert samples from decimal representation to binary.
- samples_to_decimal(samples, nqubits)[source]#
Convert samples from binary representation to decimal.
- exp_value_diagonal_observable_dense_from_samples(circuit, observable, nqubits, nshots, qubit_map=None)[source]#
Compute the expectation value of a dense Hamiltonian diagonal in a defined basis starting from the samples (measured in the same basis).
- Parameters:
circuit (
qibo.models.circuit.Circuit) – the circuit to calculate the expectation value from.observable (ndarray) – the (diagonal) matrix corresponding to the observable.
nqubits (int) – the number of qubits of the observable.
nshots (int) – how many shots to execute the circuit with.
qubit_map (Tuple[int, ...], optional) – optional qubits reordering.
- Returns:
The calculated expectation value.
- Return type:
- exp_value_diagonal_observable_symbolic_from_samples(circuit, nqubits, terms_qubits, terms_coefficients, nshots, qubit_map=None, constant=0.0)[source]#
Compute the expectation value of a symbolic observable diagonal in the computational basis, starting from the samples.
- Parameters:
circuit (
qibo.models.circuit.Circuit) – the circuit to calculate the expectation value from.nqubits (int) – number of qubits of the observable.
terms_qubits (List[Tuple[int, ...]]) – the qubits each term of the (diagonal) symbolic observable is acting on.
terms_coefficients (List[float]) – the coefficient of each term of the (diagonal) symbolic observable.
nshots (int) – how many shots to execute the circuit with.
qubit_map (Tuple[int, ...]) – custom qubit ordering.
constant (float) – the constant term of the observable. Defaults to \(0.0\).
- Returns:
The calculated expectation value.
- Return type:
- exp_value_observable_dense(circuit, observable)[source]#
Compute the expectation value of a generic dense hamiltonian starting from the state.
- exp_value_observable_symbolic(circuit, terms, term_qubits, term_coefficients, nqubits)[source]#
Compute the expectation value of a general symbolic observable that is a sum of terms.
In particular, each term of the observable is contracted with the corresponding subspace defined by the qubits it acts on.
- Parameters:
circuit (
qibo.models.circuit.Circuit) – the circuit to calculate the expectation value from.terms (List[str]) – the lists of strings defining the observables for each term, e.g.
['ZXZ', 'YI', 'IYZ', 'X'].term_coefficients (List[float]) – the coefficients of each term.
term_qubits (List[Tuple[int, ...]]) – the qubits each term is acting on, e.g.
[(0,1,2), (1,3), (2,1,3), (4,)].nqubits (int) – number of qubits of the observable.
- Returns:
The calculated expectation value.
- Return type:
- exp_value_observable_symbolic_from_samples(circuit, diagonal_terms_coefficients, diagonal_terms_observables, diagonal_terms_qubits, nqubits, constant, nshots)[source]#
Compute the expectation value of a general symbolic observable defined by groups of terms that can be diagonalized simultaneously, starting from the samples.
- Parameters:
circuit (Circuit) – the circuit to calculate the expectation value from.
diagonal_terms_coefficients (List[float]) – the coefficients of each term of the (diagonal) symbolic observable.
diagonal_terms_observables (List[List[str]]) – the lists of strings defining the observables for each group of terms, e.g.
[['IXZ', 'YII'], ['IYZ', 'XIZ']].diagonal_terms_qubits (List[Tuple[int, ...]]) – the qubits each term of the groups is acting on, e.g.
[[(0,1,2), (1,3)], [(2,1,3), (2,4)]].nqubits (int) – number of qubits of the observable.
constant (float) – the constant term of the observable.
nshots (int) – how many shots to execute the circuit with.
- Returns:
The calculated expectation value.
- Return type:
Clifford Simulation#
Qibo provides a qibo.backends.clifford.CliffordBackend that
efficiently simulates Clifford circuits using the phase-space (stabilizer)
formalism. See Clifford Simulation for a detailed
description and worked examples.
- class qibo.backends.clifford.CliffordBackend(platform=None)[source]#
Backend for the simulation of Clifford circuits following Ref. [1].
- Parameters:
platform (str, optional) – name of the backend that should be used in calculations. Options are:
"numpy",``”numba”, ``"cupy", or"stim". IfNone, global backend is used. Defaults toNone.
References
1. S. Aaronson and D. Gottesman, Improved Simulation of Stabilizer Circuits, Phys. Rev. A 70, 052328 (2004).
- zero_state(nqubits, i_phase=False)[source]#
Construct the zero state :math`ket{00…00}`.
- Parameters:
- Returns:
Symplectic matrix for the zero state.
- Return type:
ndarray
- apply_channel(channel, state, nqubits)[source]#
Apply a
channelto quantumstate.
- apply_gate_clifford(gate, symplectic_matrix, nqubits)[source]#
Apply a gate to a symplectic matrix.
- apply_unitary(gate, symplectic_matrix, nqubits)[source]#
Apply a unitary gate to a symplectic matrix following Dehaene & Moor (2003).
- execute_circuit(circuit, initial_state=None, nshots=1000)[source]#
Execute a Clifford circuits.
- Parameters:
circuit (
qibo.models.circuit.Circuit) – Input circuit.initial_state (ndarray, optional) – The
symplectic_matrixof the initial state. IfNone, defaults to the zero state. Defaults toNone.nshots (int, optional) – Number of shots to perform if
circuithas measurements. Defaults to \(10^{3}\).
- Returns:
Object storing to the final results.
- Return type:
- execute_circuit_repeated(circuit, nshots=1000, initial_state=None)[source]#
Execute a Clifford circuits
nshotstimes.This is used for all the simulations that involve repeated execution. For instance when collapsing measurement or noise channels are present.
- Parameters:
circuit (
qibo.models.circuit.Circuit) – input circuit.initial_state (ndarray, optional) – Symplectic_matrix of the initial state. If
None, defaults toqibo.backends.clifford.CliffordBackend.zero_state(). Defaults toNone.nshots (int, optional) – Number of times to repeat the execution. Defaults to \(1000\).
- Returns:
Object storing to the final results.
- Return type:
- sample_shots(state, qubits, nqubits, nshots, collapse=False)[source]#
Sample shots by measuring selected
qubitsin symplectic matrix of astate.- Parameters:
state (ndarray) – symplectic matrix from which to sample shots from.
qubits (list[int] | tuple[int, ...]) – (tuple or list): qubits to measure.
nqubits (int) – total number of qubits of the state.
nshots (int) – number of shots to sample.
collapse (bool, optional) – If
Truethe input state is going to be collapsed with the last shot. Defaults toFalse.
- Returns:
Samples shots.
- Return type:
(ndarray)
- symplectic_matrix_to_generators(symplectic_matrix, return_array=False)[source]#
Extract the stabilizers and destabilizers generators from symplectic matrix.
- Parameters:
symplectic_matrix (ndarray) – The input symplectic_matrix.
return_array (bool, optional) – If
Truereturns the generators asndarrays. IfFalse, generators are returned as strings. Defaults toFalse.
- Returns:
Extracted generators and their corresponding phases, respectively.
- Return type:
Simulation of Hamming-weight-preserving circuits#
Qibo provides a qibo.backends.hamming_weight.HammingWeightBackend
that fast-simulates circuits preserving the Hamming weight of the state, using
a compressed representation restricted to the fixed-weight subspace. See
Simulation of Hamming-weight-preserving circuits for a detailed description and
worked examples.
- class qibo.backends.hamming_weight.HammingWeightBackend(platform=None)[source]#
Dynamically create a HammingWeightBackend class based on the selected backend.
- class qibo.quantum_info.hamming_weight.HammingWeightResult(state, weight, nqubits, measurements=None, nshots=1000, platform=None)[source]#
Object storing the results of a circuit execution with the
qibo.backends.hamming_weight.HammingWeightBackend.- Parameters:
state (ArrayLike) – statevector with a fixed Hamming weight. The dimension of the state is \(d = \binom{n}{k}\), where \(n\) is the number of qubits and \(k\) is the Hamming weight. The components of the state are ordered in lexicographical order.
weight (int) – Hamming weight of
state.nqubits (int) – number of qubits of
state.measurements (list, optional) – list of measurements gates
qibo.gates.M. Defaults toNone.nshots (int, optional) – number of shots used for sampling the measurements. Defaults to \(1000\).
platform (str, optional) – platform to use in the execution of the
qibo.backends.HammingWeightBackend. It accepts"numpy","numba","cupy", and"cuquantum". IfNone, defaults to the corresponding platform from the current backend. Defaults toNone.
- symbolic(decimals=5, cutoff=1e-10, max_terms=20)[source]#
Dirac notation representation of the state in the computational basis.
- Parameters:
decimals (int, optional) – Number of decimals for the amplitudes. Defaults to \(5\).
cutoff (float, optional) – Amplitudes with absolute value smaller than the cutoff are ignored from the representation. Defaults to
1e-10.max_terms (int, optional) – Maximum number of terms to print. If the state contains more terms they will be ignored. Defaults to \(20\).
- Returns:
String representing the state in the computational basis.
- Return type:
- full_state()[source]#
Tensor representation of
statein the entire computational basis.Note
This method is inefficient in runtime and memory for a large number of qubits.
- probabilities(qubits=None)[source]#
Calculate the probabilities of the measured qubits.
If the number of shots is \(0\) or no measurements were performed, the probabilities are calculated from the statevector. Otherwise, the probabilities are calculated from the samples.
- samples(binary=True, registers=False)[source]#
Returns raw measurement samples.
- Parameters:
- Returns:
- If
binaryisTrue samples are returned in binary form as a tensor of shape
(nshots, n_measured_qubits).- If
binaryisFalse samples are returned in decimal form as a tensor of shape
(nshots,).- If
registersisTrue samples are returned in a
dictwhere the keys are the register names and the values are the samples tensors for each register.- If
registersisFalse a single tensor is returned which contains samples from all the measured qubits, independently of their registers.
- If
- Return type:
_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | dict[str, Union[numpy._typing._array_like._Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]]
- frequencies(binary=True, registers=False)[source]#
Return the frequencies of measured samples.
- Parameters:
- Returns:
A
collections.Counterwhere the keys are the observed values and the values the corresponding frequencies, that is the number of times each measured value/bitstring appears.- If
binaryisTrue the keys of the
collections.Counterare in binary form, as strings of \(0\) and \(1\).- If
binaryisFalse the keys of the
collections.Counterare integers.- If
registersisTrue a dict of
collections.Counteris returned where keys are the name of each register.- If
registersisFalse a single
collections.Counteris returned which contains samples from all the measured qubits, independently of their registers.
- If
- Return type:
Cloud Backends#
Additional backends that support the remote execution of quantum circuits through cloud service providers, such as IBM and QRC-TII, are provided by the optional qibo plugin qibo-cloud-backends. For more information please refer to the official documentation.