Models#
Qibo provides models for both the circuit based and the adiabatic quantum
computation paradigms. Circuit based models include Circuit models which
allow defining arbitrary circuits and Quantum Fourier Transform (QFT) such as the
Quantum Fourier Transform (qibo.models.QFT
) and the
Variational Quantum Eigensolver (qibo.models.VQE
).
Adiabatic quantum computation is simulated using the Time evolution
of state vectors.
In order to perform calculations and apply gates to a state vector a backend
has to be used. The backends are defined in qibo/backends
.
Circuit and gate objects are backend independent and can be executed with
any of the available backends.
Qibo uses big-endian byte order, which means that the most significant qubit is the one with index 0, while the least significant qubit is the one with the highest index.
Circuit models#
Circuit#
- class qibo.models.circuit.Circuit(nqubits, accelerators=None, density_matrix=False)#
Circuit object which holds a list of gates.
This circuit is symbolic and cannot perform calculations. A specific backend has to be used for performing calculations.
- Parameters:
nqubits (int) – Total number of qubits in the circuit.
init_kwargs (dict) –
a dictionary with the following keys
nqubits
accelerators
density_matrix.
queue (_Queue) – List that holds the queue of gates of a circuit.
parametrized_gates (_ParametrizedGates) – List of parametric gates.
trainable_gates (_ParametrizedGates) – List of trainable gates.
measurements (list) – List of non-collapsible measurements
_final_state (CircuitResult) – Final state after full simulation of the circuit
compiled (CompiledExecutor) – Circuit executor. Defaults to
None
.repeated_execution (bool) – If True, the circuit would be re-executed when sampling. Defaults to
False
.density_matrix (bool) – If True, the circuit would evolve density matrices. Defaults to
False
.accelerators (dict) – Dictionary that maps device names to the number of times each device will be used. Defaults to
None
.ndevices (int) – Total number of devices. Defaults to
None
.nglobal (int) – Base two logarithm of the number of devices. Defaults to
None
.nlocal (int) – Total number of available qubits in each device. Defaults to
None
.queues (DistributedQueues) – Gate queues for each accelerator device. Defaults to
None
.
- on_qubits(*qubits)#
Generator of gates contained in the circuit acting on specified qubits.
Useful for adding a circuit as a subroutine in a larger circuit.
- Parameters:
qubits (int) – Qubit ids that the gates should act.
Example
from qibo import gates, models # create small circuit on 4 qubits smallc = models.Circuit(4) smallc.add((gates.RX(i, theta=0.1) for i in range(4))) smallc.add((gates.CNOT(0, 1), gates.CNOT(2, 3))) # create large circuit on 8 qubits largec = models.Circuit(8) largec.add((gates.RY(i, theta=0.1) for i in range(8))) # add the small circuit to the even qubits of the large one largec.add(smallc.on_qubits(*range(0, 8, 2)))
- light_cone(*qubits)#
Reduces circuit to the qubits relevant for an observable.
Useful for calculating expectation values of local observables without requiring simulation of large circuits. Uses the light cone construction described in issue #571.
- Parameters:
qubits (int) – Qubit ids that the observable has support on.
- Returns:
- Circuit that contains only
the qubits that are required for calculating expectation involving the given observable qubits.
- qubit_map (dict): Dictionary mapping the qubit ids of the original
circuit to the ids in the new one.
- Return type:
circuit (qibo.models.Circuit)
- copy(deep: bool = False)#
Creates a copy of the current
circuit
as a newCircuit
model.- Parameters:
deep (bool) – If
True
copies of the gate objects will be created for the new circuit. IfFalse
, the same gate objects ofcircuit
will be used.- Returns:
The copied circuit object.
- invert()#
Creates a new
Circuit
that is the inverse of the original.Inversion is obtained by taking the dagger of all gates in reverse order. If the original circuit contains parametrized gates, dagger will change their parameters. This action is not persistent, so if the parameters are updated afterwards, for example using
qibo.models.circuit.Circuit.set_parameters()
, the action of dagger will be overwritten. If the original circuit contains measurement gates, these are included in the inverted circuit.- Returns:
The circuit inverse.
- decompose(*free: int)#
Decomposes circuit’s gates to gates supported by OpenQASM.
- Parameters:
free – Ids of free (work) qubits to use for gate decomposition.
- Returns:
Circuit that contains only gates that are supported by OpenQASM and has the same effect as the original circuit.
- with_pauli_noise(noise_map: Tuple[int, int, int] | Dict[int, Tuple[int, int, int]])#
Creates a copy of the circuit with Pauli noise gates after each gate.
If the original circuit uses state vectors then noise simulation will be done using sampling and repeated circuit execution. In order to use density matrices the original circuit should be created setting the flag
density_matrix=True
. For more information we refer to the How to perform noisy simulation? example.- Parameters:
noise_map (dict) – list of tuples \((P_{k}, p_{k})\), where \(P_{k}\) is a
str
representing the \(k\)-th \(n\)-qubit Pauli operator, and \(p_{k}\) is the associated probability.- Returns:
Circuit object that contains all the gates of the original circuit and additional noise channels on all qubits after every gate.
Example
from qibo import Circuit, gates # use density matrices for noise simulation c = Circuit(2, density_matrix=True) c.add([gates.H(0), gates.H(1), gates.CNOT(0, 1)]) noise_map = { 0: list(zip(["X", "Z"], [0.1, 0.2])), 1: list(zip(["Y", "Z"], [0.2, 0.1])) } noisy_c = c.with_pauli_noise(noise_map) # ``noisy_c`` will be equivalent to the following circuit c2 = Circuit(2, density_matrix=True) c2.add(gates.H(0)) c2.add(gates.PauliNoiseChannel(0, [("X", 0.1), ("Z", 0.2)])) c2.add(gates.H(1)) c2.add(gates.PauliNoiseChannel(1, [("Y", 0.2), ("Z", 0.1)])) c2.add(gates.CNOT(0, 1)) c2.add(gates.PauliNoiseChannel(0, [("X", 0.1), ("Z", 0.2)])) c2.add(gates.PauliNoiseChannel(1, [("Y", 0.2), ("Z", 0.1)]))
- add(gate)#
Add a gate to a given queue.
- Parameters:
gate (
qibo.gates.Gate
) – the gate object to add. See Gates for a list of available gates. gate can also be an iterable or generator of gates. In this case all gates in the iterable will be added in the circuit.- Returns:
If the circuit contains measurement gates with
collapse=True
asympy.Symbol
that parametrizes the corresponding outcome.
- gates_of_type(gate: str | type) List[Tuple[int, Gate]] #
Finds all gate objects of specific type or name.
- set_parameters(parameters)#
Updates the parameters of the circuit’s parametrized gates.
For more information on how to use this method we refer to the How to use parametrized gates? example.
- Parameters:
parameters – Container holding the new parameter values. It can have one of the following types: List with length equal to the number of parametrized gates and each of its elements compatible with the corresponding gate. Dictionary with keys that are references to the parametrized gates and values that correspond to the new parameters for each gate. Flat list with length equal to the total number of free parameters in the circuit. A backend supported tensor (for example
np.ndarray
ortf.Tensor
) may also be given instead of a flat list.
Example
from qibo import Circuit, gates # create a circuit with all parameters set to 0. c = Circuit(3) c.add(gates.RX(0, theta=0)) c.add(gates.RY(1, theta=0)) c.add(gates.CZ(1, 2)) c.add(gates.fSim(0, 2, theta=0, phi=0)) c.add(gates.H(2)) # set new values to the circuit's parameters using list params = [0.123, 0.456, (0.789, 0.321)] c.set_parameters(params) # or using dictionary params = {c.queue[0]: 0.123, c.queue[1]: 0.456, c.queue[3]: (0.789, 0.321)} c.set_parameters(params) # or using flat list (or an equivalent `np.array`/`tf.Tensor`) params = [0.123, 0.456, 0.789, 0.321] c.set_parameters(params)
- get_parameters(format: str = 'list', include_not_trainable: bool = False) List | Dict #
Returns the parameters of all parametrized gates in the circuit.
Inverse method of
qibo.models.circuit.Circuit.set_parameters()
.- Parameters:
format (str) – How to return the variational parameters. Available formats are
'list'
,'dict'
and'flatlist'
. Seeqibo.models.circuit.Circuit.set_parameters()
for more details on each format. Default is'list'
.include_not_trainable (bool) – If
True
it includes the parameters of non-trainable parametrized gates in the returned list or dictionary. Default isFalse
.
- associate_gates_with_parameters()#
Associates to each parameter its gate.
- Returns:
A nparams-long flatlist whose i-th element is the gate parameterized by the i-th parameter.
- summary() str #
Generates a summary of the circuit.
The summary contains the circuit depths, total number of qubits and the all gates sorted in decreasing number of appearance.
Example
from qibo import Circuit, gates c = Circuit(3) c.add(gates.H(0)) c.add(gates.H(1)) c.add(gates.CNOT(0, 2)) c.add(gates.CNOT(1, 2)) c.add(gates.H(2)) c.add(gates.TOFFOLI(0, 1, 2)) print(c.summary()) # Prints ''' Circuit depth = 5 Total number of gates = 6 Number of qubits = 3 Most common gates: h: 3 cx: 2 ccx: 1 '''
- fuse(max_qubits=2)#
Creates an equivalent circuit by fusing gates for increased simulation performance.
- Parameters:
max_qubits (int) – Maximum number of qubits in the fused gates.
- Returns:
A
qibo.core.circuit.Circuit
object containingqibo.gates.FusedGate
gates, each of which corresponds to a group of some original gates. For more details on the fusion algorithm we refer to the Circuit fusion section.
Example
from qibo import gates, models c = models.Circuit(2) c.add([gates.H(0), gates.H(1)]) c.add(gates.CNOT(0, 1)) c.add([gates.Y(0), gates.Y(1)]) # create circuit with fused gates fused_c = c.fuse() # now ``fused_c`` contains a single ``FusedGate`` that is # equivalent to applying the five original gates
- unitary(backend=None)#
Creates the unitary matrix corresponding to all circuit gates.
This is a
(2 ** nqubits, 2 ** nqubits)
matrix obtained by multiplying all circuit gates.
- property final_state#
Returns the final state after full simulation of the circuit.
If the circuit is executed more than once, only the last final state is returned.
- execute(initial_state=None, nshots=None)#
Executes the circuit. Exact implementation depends on the backend.
- Parameters:
initial_state (np.ndarray or
qibo.models.circuit.Circuit
) – Initial configuration. It can be specified by the setting the state vector using an array or a circuit. IfNone
, the initial state is|000..00>
.nshots (int) – Number of shots.
- to_qasm()#
Convert circuit to QASM.
- Parameters:
filename (str) – The filename where the code is saved.
- classmethod from_qasm(qasm_code, accelerators=None, density_matrix=False)#
Constructs a circuit from QASM code.
- Parameters:
qasm_code (str) – String with the QASM script.
- Returns:
A
qibo.models.circuit.Circuit
that contains the gates specified by the given QASM script.
Example
from qibo import gates, models qasm_code = '''OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; h q[0]; h q[1]; cx q[0],q[1];''' c = models.Circuit.from_qasm(qasm_code) # is equivalent to creating the following circuit c2 = models.Circuit(2) c2.add(gates.H(0)) c2.add(gates.H(1)) c2.add(gates.CNOT(0, 1))
Circuit addition#
qibo.models.circuit.Circuit
objects support addition. For example
c1 = models.QFT(4)
c2 = models.Circuit(4)
c2.add(gates.RZ(0, 0.1234))
c2.add(gates.RZ(1, 0.1234))
c2.add(gates.RZ(2, 0.1234))
c2.add(gates.RZ(3, 0.1234))
c = c1 + c2
will create a circuit that performs the Quantum Fourier Transform on four qubits followed by Rotation-Z gates.
Circuit fusion#
The gates contained in a circuit can be fused up to two-qubits using the
qibo.models.circuit.Circuit.fuse()
method. This returns a new circuit
for which the total number of gates is less than the gates in the original
circuit as groups of gates have been fused to a single
qibo.gates.special.FusedGate
gate. Simulating the new circuit
is equivalent to simulating the original one but in most cases more efficient
since less gates need to be applied to the state vector.
The fusion algorithm works as follows: First all gates in the circuit are
transformed to unmarked qibo.gates.special.FusedGate
. The gates
are then processed in the order they were added in the circuit. For each gate
we identify the neighbors forth and back in time and attempt to fuse them to
the gate. Two gates can be fused if their total number of target qubits is
smaller than the fusion maximum qubits (specified by the user) and there are
no other gates between acting on the same target qubits. Gates that are fused
to others are marked. The new circuit queue contains the gates that remain
unmarked after the above operations finish.
Gates are processed in the original order given by user. There are no
additional simplifications performed such as commuting gates acting on the same
qubit or canceling gates even when such simplifications are mathematically possible.
The user can specify the maximum number of qubits in a fused gate using
the max_qubits
flag in qibo.models.circuit.Circuit.fuse()
.
For example the following:
from qibo import models, gates
c = models.Circuit(2)
c.add([gates.H(0), gates.H(1)])
c.add(gates.CZ(0, 1))
c.add([gates.X(0), gates.Y(1)])
fused_c = c.fuse()
will create a new circuit with a single qibo.gates.special.FusedGate
acting on (0, 1)
, while the following:
from qibo import models, gates
c = models.Circuit(3)
c.add([gates.H(0), gates.H(1), gates.H(2)])
c.add(gates.CZ(0, 1))
c.add([gates.X(0), gates.Y(1), gates.Z(2)])
c.add(gates.CNOT(1, 2))
c.add([gates.H(0), gates.H(1), gates.H(2)])
fused_c = c.fuse()
will give a circuit with two fused gates, the first of which will act on
(0, 1)
corresponding to
[H(0), H(1), CZ(0, 1), X(0), H(0)]
and the second will act to (1, 2)
corresponding to
[Y(1), Z(2), CNOT(1, 2), H(1), H(2)]
Quantum Fourier Transform (QFT)#
- class qibo.models.qft.QFT(nqubits, with_swaps=True, accelerators=None)#
Creates a circuit that implements the Quantum Fourier Transform.
- Parameters:
nqubits (int) – Number of qubits in the circuit.
with_swaps (bool) – Use SWAP gates at the end of the circuit so that the qubit order in the final state is the same as the initial state.
accelerators (dict) – Accelerator device dictionary in order to use a distributed circuit If
None
a simple (non-distributed) circuit will be used.
- Returns:
A qibo.models.Circuit that implements the Quantum Fourier Transform.
Example
import numpy as np from qibo.models import QFT nqubits = 6 c = QFT(nqubits) # Random normalized initial state vector init_state = np.random.random(2 ** nqubits) + 1j * np.random.random(2 ** nqubits) init_state = init_state / np.sqrt((np.abs(init_state)**2).sum()) # Execute the circuit final_state = c(init_state)
Variational Quantum Eigensolver (VQE)#
- class qibo.models.variational.VQE(circuit, hamiltonian)#
This class implements the variational quantum eigensolver algorithm.
- Parameters:
circuit (
qibo.models.circuit.Circuit
) – Circuit that implements the variaional ansatz.hamiltonian (
qibo.hamiltonians.Hamiltonian
) – Hamiltonian object.
Example
import numpy as np from qibo import gates, models, hamiltonians # create circuit ansatz for two qubits circuit = models.Circuit(2) circuit.add(gates.RY(0, theta=0)) # create XXZ Hamiltonian for two qubits hamiltonian = hamiltonians.XXZ(2) # create VQE model for the circuit and Hamiltonian vqe = models.VQE(circuit, hamiltonian) # optimize using random initial variational parameters initial_parameters = np.random.uniform(0, 2, 1) vqe.minimize(initial_parameters)
- minimize(initial_state, method='Powell', jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None, compile=False, processes=None)#
Search for parameters which minimizes the hamiltonian expectation.
- Parameters:
initial_state (array) – a initial guess for the parameters of the variational circuit.
method (str) – the desired minimization method. See
qibo.optimizers.optimize()
for available optimization methods.jac (dict) – Method for computing the gradient vector for scipy optimizers.
hess (dict) – Method for computing the hessian matrix for scipy optimizers.
hessp (callable) – Hessian of objective function times an arbitrary vector for scipy optimizers.
bounds (sequence or Bounds) – Bounds on variables for scipy optimizers.
constraints (dict) – Constraints definition for scipy optimizers.
tol (float) – Tolerance of termination for scipy optimizers.
callback (callable) – Called after each iteration for scipy optimizers.
options (dict) – a dictionary with options for the different optimizers.
compile (bool) – whether the TensorFlow graph should be compiled.
processes (int) – number of processes when using the paralle BFGS method.
- Returns:
The final expectation value. The corresponding best parameters. The optimization result object. For scipy methods it returns the
OptimizeResult
, for'cma'
theCMAEvolutionStrategy.result
, and for'sgd'
the options used during the optimization.
Adiabatically Assisted Variational Quantum Eigensolver (AAVQE)#
- class qibo.models.variational.AAVQE(circuit, easy_hamiltonian, problem_hamiltonian, s, nsteps=10, t_max=1, bounds_tolerance=1e-07, time_tolerance=1e-07)#
This class implements the Adiabatically Assisted Variational Quantum Eigensolver algorithm. See https://arxiv.org/abs/1806.02287.
- Parameters:
circuit (
qibo.models.circuit.Circuit
) – variational ansatz.easy_hamiltonian (
qibo.hamiltonians.Hamiltonian
) – initial Hamiltonian object.problem_hamiltonian (
qibo.hamiltonians.Hamiltonian
) – problem Hamiltonian object.s (callable) – scheduling function of time that defines the adiabatic evolution. It must verify boundary conditions: s(0) = 0 and s(1) = 1.
nsteps (float) – number of steps of the adiabatic evolution.
t_max (float) – total time evolution.
bounds_tolerance (float) – tolerance for checking s(0) = 0 and s(1) = 1.
time_tolerance (float) – tolerance for checking if time is greater than t_max.
Example
import numpy as np from qibo import gates, models, hamiltonians # create circuit ansatz for two qubits circuit = models.Circuit(2) circuit.add(gates.RY(0, theta=0)) circuit.add(gates.RY(1, theta=0)) # define the easy and the problem Hamiltonians. easy_hamiltonian=hamiltonians.X(2) problem_hamiltonian=hamiltonians.XXZ(2) # define a scheduling function with only one parameter # and boundary conditions s(0) = 0, s(1) = 1 s = lambda t: t # create AAVQE model aavqe = models.AAVQE(circuit, easy_hamiltonian, problem_hamiltonian, s, nsteps=10, t_max=1) # optimize using random initial variational parameters np.random.seed(0) initial_parameters = np.random.uniform(0, 2*np.pi, 2) ground_energy, params = aavqe.minimize(initial_parameters)
- set_schedule(func)#
Set scheduling function s(t) as func.
- schedule(t)#
Returns scheduling function evaluated at time t: s(t/Tmax).
- hamiltonian(t)#
Returns the adiabatic evolution Hamiltonian at a given time.
- minimize(params, method='BFGS', jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, options=None, compile=False, processes=None)#
Performs minimization to find the ground state of the problem Hamiltonian.
- Parameters:
params (np.ndarray or list) – initial guess for the parameters of the variational circuit.
method (str) – optimizer to employ.
jac (dict) – Method for computing the gradient vector for scipy optimizers.
hess (dict) – Method for computing the hessian matrix for scipy optimizers.
hessp (callable) – Hessian of objective function times an arbitrary vector for scipy optimizers.
bounds (sequence or Bounds) – Bounds on variables for scipy optimizers.
constraints (dict) – Constraints definition for scipy optimizers.
tol (float) – Tolerance of termination for scipy optimizers.
options (dict) – a dictionary with options for the different optimizers.
compile (bool) – whether the TensorFlow graph should be compiled.
processes (int) – number of processes when using the parallel BFGS method.
Quantum Approximate Optimization Algorithm (QAOA)#
- class qibo.models.variational.QAOA(hamiltonian, mixer=None, solver='exp', callbacks=[], accelerators=None)#
Quantum Approximate Optimization Algorithm (QAOA) model.
The QAOA is introduced in arXiv:1411.4028.
- Parameters:
hamiltonian (
qibo.hamiltonians.Hamiltonian
) – problem Hamiltonian whose ground state is sought.mixer (
qibo.hamiltonians.Hamiltonian
) – mixer Hamiltonian. Must be of the same type and act on the same number of qubits ashamiltonian
. IfNone
,qibo.hamiltonians.X
is used.solver (str) – solver used to apply the exponential operators. Default solver is ‘exp’ (
qibo.solvers.Exponential
).callbacks (list) – List of callbacks to calculate during evolution.
accelerators (dict) – Dictionary of devices to use for distributed execution. This option is available only when
hamiltonian
is aqibo.hamiltonians.SymbolicHamiltonian
.
Example
import numpy as np from qibo import models, hamiltonians # create XXZ Hamiltonian for four qubits hamiltonian = hamiltonians.XXZ(4) # create QAOA model for this Hamiltonian qaoa = models.QAOA(hamiltonian) # optimize using random initial variational parameters # and default options and initial state initial_parameters = 0.01 * np.random.random(4) best_energy, final_parameters, extra = qaoa.minimize(initial_parameters, method="BFGS")
- set_parameters(p)#
Sets the variational parameters.
- Parameters:
p (np.ndarray) – 1D-array holding the new values for the variational parameters. Length should be an even number.
- execute(initial_state=None)#
Applies the QAOA exponential operators to a state.
- Parameters:
initial_state (np.ndarray) – Initial state vector.
- Returns:
State vector after applying the QAOA exponential gates.
- minimize(initial_p, initial_state=None, method='Powell', loss_func=None, loss_func_param={}, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None, compile=False, processes=None)#
Optimizes the variational parameters of the QAOA. A few loss functions are provided for QAOA optimizations such as expected value (default), CVar which is introduced in Quantum 4, 256, and Gibbs loss function which is introduced in PRR 2, 023074 (2020).
- Parameters:
initial_p (np.ndarray) – initial guess for the parameters.
initial_state (np.ndarray) – initial state vector of the QAOA.
method (str) – the desired minimization method. See
qibo.optimizers.optimize()
for available optimization methods.loss_func (function) – the desired loss function. If it is None, the expectation is used.
loss_func_param (dict) – a dictionary to pass in the loss function parameters.
jac (dict) – Method for computing the gradient vector for scipy optimizers.
hess (dict) – Method for computing the hessian matrix for scipy optimizers.
hessp (callable) – Hessian of objective function times an arbitrary vector for scipy optimizers.
bounds (sequence or Bounds) – Bounds on variables for scipy optimizers.
constraints (dict) – Constraints definition for scipy optimizers.
tol (float) – Tolerance of termination for scipy optimizers.
callback (callable) – Called after each iteration for scipy optimizers.
options (dict) – a dictionary with options for the different optimizers.
compile (bool) – whether the TensorFlow graph should be compiled.
processes (int) – number of processes when using the paralle BFGS method.
- Returns:
The final energy (expectation value of the
hamiltonian
). The corresponding best parameters. The optimization result object. For scipy methods it returns theOptimizeResult
, for'cma'
theCMAEvolutionStrategy.result
, and for'sgd'
the options used during the optimization.
Example
from qibo import hamiltonians from qibo.models.utils import cvar, gibbs h = hamiltonians.XXZ(3) qaoa = models.QAOA(h) initial_p = [0.314, 0.22, 0.05, 0.59] best, params, _ = qaoa.minimize(initial_p) best, params, _ = qaoa.minimize(initial_p, loss_func=cvar, loss_func_param={'alpha':0.1}) best, params, _ = qaoa.minimize(initial_p, loss_func=gibbs, loss_func_param={'eta':0.1})
Feedback-based Algorithm for Quantum Optimization (FALQON)#
- class qibo.models.variational.FALQON(hamiltonian, mixer=None, solver='exp', callbacks=[], accelerators=None)#
Feedback-based ALgorithm for Quantum OptimizatioN (FALQON) model.
The FALQON is introduced in arXiv:2103.08619. It inherits the QAOA class.
- Parameters:
hamiltonian (
qibo.hamiltonians.Hamiltonian
) – problem Hamiltonian whose ground state is sought.mixer (
qibo.hamiltonians.Hamiltonian
) – mixer Hamiltonian. IfNone
,qibo.hamiltonians.X
is used.solver (str) – solver used to apply the exponential operators. Default solver is ‘exp’ (
qibo.solvers.Exponential
).callbacks (list) – List of callbacks to calculate during evolution.
accelerators (dict) – Dictionary of devices to use for distributed execution. This option is available only when
hamiltonian
is aqibo.hamiltonians.SymbolicHamiltonian
.
Example
import numpy as np from qibo import models, hamiltonians # create XXZ Hamiltonian for four qubits hamiltonian = hamiltonians.XXZ(4) # create FALQON model for this Hamiltonian falqon = models.FALQON(hamiltonian) # optimize using random initial variational parameters # and default options and initial state delta_t = 0.01 max_layers = 3 best_energy, final_parameters, extra = falqon.minimize(delta_t, max_layers)
- minimize(delta_t, max_layers, initial_state=None, tol=None, callback=None)#
Optimizes the variational parameters of the FALQON.
- Parameters:
delta_t (float) – initial guess for the time step. A too large delta_t will make the algorithm fail.
max_layers (int) – maximum number of layers allowed for the FALQON.
initial_state (np.ndarray) – initial state vector of the FALQON.
tol (float) – Tolerance of energy change. If not specified, no check is done.
callback (callable) – Called after each iteration for scipy optimizers.
options (dict) – a dictionary with options for the different optimizers.
- Returns:
The final energy (expectation value of the
hamiltonian
). The corresponding best parameters. extra: variable with historical data for the energy and callbacks.
Style-based Quantum Generative Adversarial Network (style-qGAN)#
- class qibo.models.qgan.StyleQGAN(latent_dim, layers=None, circuit=None, set_parameters=None, discriminator=None)#
Model that implements and trains a style-based quantum generative adversarial network.
For original manuscript: arXiv:2110.06933
- Parameters:
latent_dim (int) – number of latent dimensions.
layers (int) – number of layers for the quantum generator. Provide this value only if not using a custom quantum generator.
circuit (
qibo.models.circuit.Circuit
) – custom quantum generator circuit. If not provided, the default quantum circuit will be used.set_parameters (function) – function that creates the array of parameters for the quantum generator. If not provided, the default function will be used.
Example
import numpy as np import qibo from qibo.models.qgan import StyleQGAN # set qibo backend to tensorflow which supports gradient descent training qibo.set_backend("tensorflow") # Create reference distribution. # Example: 3D correlated Gaussian distribution normalized between [-1,1] reference_distribution = [] samples = 10 mean = [0, 0, 0] cov = [[0.5, 0.1, 0.25], [0.1, 0.5, 0.1], [0.25, 0.1, 0.5]] x, y, z = np.random.multivariate_normal(mean, cov, samples).T/4 s1 = np.reshape(x, (samples,1)) s2 = np.reshape(y, (samples,1)) s3 = np.reshape(z, (samples,1)) reference_distribution = np.hstack((s1,s2,s3)) # Train qGAN with your particular setup train_qGAN = StyleQGAN(latent_dim=1, layers=2) train_qGAN.fit(reference_distribution, n_epochs=1)
- define_discriminator(alpha=0.2, dropout=0.2)#
Define the standalone discriminator model.
- set_params(circuit, params, x_input, i)#
Set the parameters for the quantum generator circuit.
- generate_latent_points(samples)#
Generate points in latent space as input for the quantum generator.
- train(d_model, circuit, hamiltonians_list, save=True)#
Train the quantum generator and classical discriminator.
- fit(reference, initial_params=None, batch_samples=128, n_epochs=20000, lr=0.5, save=True)#
Execute qGAN training.
- Parameters:
reference (array) – samples from the reference input distribution.
initial_parameters (array) – initial parameters for the quantum generator. If not provided, the default initial parameters will be used.
discriminator (
tensorflow.keras.models
) – custom classical discriminator. If not provided, the default classical discriminator will be used.batch_samples (int) – number of training examples utilized in one iteration.
n_epochs (int) – number of training iterations.
lr (float) – initial learning rate for the quantum generator. It controls how much to change the model each time the weights are updated.
save (bool) – If
True
the results of training (trained parameters and losses) will be saved on disk. Default isTrue
.
Grover’s Algorithm#
- class qibo.models.grover.Grover(oracle, superposition_circuit=None, initial_state_circuit=None, superposition_qubits=None, superposition_size=None, number_solutions=None, target_amplitude=None, check=None, check_args=(), iterative=False)#
Model that performs Grover’s algorithm.
For Grover’s original search algorithm: arXiv:quant-ph/9605043 For the iterative version with unknown solutions:arXiv:quant-ph/9605034 For the Grover algorithm with any superposition:arXiv:quant-ph/9712011
- Parameters:
oracle (
qibo.core.circuit.Circuit
) – quantum circuit that flips the sign using a Grover ancilla initialized with -X-H-. Grover ancilla expected to be last qubit of oracle circuit.superposition_circuit (
qibo.core.circuit.Circuit
) – quantum circuit that takes an initial state to a superposition. Expected to use the first set of qubits to store the relevant superposition.initial_state_circuit (
qibo.core.circuit.Circuit
) – quantum circuit that initializes the state. If empty defaults to|000..00>
superposition_qubits (int) – number of qubits that store the relevant superposition. Leave empty if superposition does not use ancillas.
superposition_size (int) – how many states are in a superposition. Leave empty if its an equal superposition of quantum states.
number_solutions (int) – number of expected solutions. Needed for normal Grover. Leave empty for iterative version.
target_amplitude (float) – absolute value of the amplitude of the target state. Only for advanced use and known systems.
check (function) – function that returns True if the solution has been found. Required of iterative approach. First argument should be the bitstring to check.
check_args (tuple) – arguments needed for the check function. The found bitstring not included.
iterative (bool) – force the use of the iterative Grover
Example
import numpy as np from qibo import Circuit, gates from qibo.models.grover import Grover # Create an oracle. Ex: Oracle that detects state |11111> oracle = Circuit(5 + 1) oracle.add(gates.X(5).controlled_by(*range(5))) # Create superoposition circuit. Ex: Full superposition over 5 qubits. superposition = Circuit(5) superposition.add([gates.H(i) for i in range(5)]) # Generate and execute Grover class grover = Grover(oracle, superposition_circuit=superposition, number_solutions=1) solution, iterations = grover()
- initialize()#
Initialize the Grover algorithm with the superposition and Grover ancilla.
- diffusion()#
Construct the diffusion operator out of the superposition circuit.
- step()#
Combine oracle and diffusion for a Grover step.
- circuit(iterations)#
Creates circuit that performs Grover’s algorithm with a set amount of iterations.
- Parameters:
iterations (int) – number of times to repeat the Grover step.
- Returns:
qibo.core.circuit.Circuit
that performs Grover’s algorithm.
- iterative_grover(lamda_value=1.2, backend=None)#
Iterative approach of Grover for when the number of solutions is not known.
- Parameters:
lamda_value (real) – parameter that controls the evolution of the iterative method. Must be between 1 and 4/3.
backend (
qibo.backends.abstract.Backend
) – Backend to use for circuit execution.
- Returns:
bitstring measured and checked as a valid solution. total_iterations (int): number of times the oracle has been called.
- Return type:
measured (str)
- execute(nshots=100, freq=False, logs=False, backend=None)#
Execute Grover’s algorithm.
If the number of solutions is given, calculates iterations, otherwise it uses an iterative approach.
- Parameters:
nshots (int) – number of shots in order to get the frequencies.
freq (bool) – print the full frequencies after the exact Grover algorithm.
backend (
qibo.backends.abstract.Backend
) – Backend to use for circuit execution.
- Returns:
bitstring (or list of bitstrings) measured as solution of the search. iterations (int): number of oracle calls done to reach a solution.
- Return type:
solution (str)
Travelling Salesman Problem#
- class qibo.models.tsp.TSP(distance_matrix, backend=None)#
The travelling salesman problem (also called the travelling salesperson problem or TSP) asks the following question: “Given a list of cities and the distances between each pair of cities, what is the shortest possible route for a salesman to visit each city exactly once and return to the origin city?” It is an NP-hard problem in combinatorial optimization. It is also important in theoretical computer science and operations research.
This is a TSP class that enables us to implement TSP according to arxiv:1709.03489 by Hadfield (2017).
- Parameters:
distance_matrix – a numpy matrix encoding the distance matrix.
backend – Backend to use for calculations. If not given the global backend will be used.
Example
from qibo.models.tsp import TSP import numpy as np from collections import defaultdict from qibo import gates from qibo.models import QAOA from qibo.states import CircuitResult def convert_to_standard_Cauchy(config): m = int(np.sqrt(len(config))) cauchy = [-1] * m # Cauchy's notation for permutation, e.g. (1,2,0) or (2,0,1) for i in range(m): for j in range(m): if config[m * i + j] == '1': cauchy[j] = i # citi i is in slot j for i in range(m): if cauchy[i] == 0: cauchy = cauchy[i:] + cauchy[:i] return tuple(cauchy) # now, the cauchy notation for permutation begins with 0 def evaluate_dist(cauchy): ''' Given a permutation of 0 to n-1, we compute the distance of the tour ''' m = len(cauchy) return sum(distance_matrix[cauchy[i]][cauchy[(i+1)%m]] for i in range(m)) def qaoa_function_of_layer(layer, distance_matrix): ''' This is a function to study the impact of the number of layers on QAOA, it takes in the number of layers and compute the distance of the mode of the histogram obtained from QAOA ''' small_tsp = TSP(distance_matrix) obj_hamil, mixer = small_tsp.hamiltonians() qaoa = QAOA(obj_hamil, mixer=mixer) best_energy, final_parameters, extra = qaoa.minimize(initial_p=[0.1] * layer, initial_state=initial_state, method='BFGS') qaoa.set_parameters(final_parameters) quantum_state = qaoa.execute(initial_state) circuit = Circuit(9) circuit.add(gates.M(*range(9))) result = CircuitResult(small_tsp.backend, circuit, quantum_state, nshots=1000) freq_counter = result.frequencies() # let's combine freq_counter here, first convert each key and sum up the frequency cauchy_dict = defaultdict(int) for freq_key in freq_counter: standard_cauchy_key = convert_to_standard_Cauchy(freq_key) cauchy_dict[standard_cauchy_key] += freq_counter[freq_key] max_key = max(cauchy_dict, key=cauchy_dict.get) return evaluate_dist(max_key) np.random.seed(42) num_cities = 3 distance_matrix = np.array([[0, 0.9, 0.8], [0.4, 0, 0.1],[0, 0.7, 0]]) distance_matrix = distance_matrix.round(1) small_tsp = TSP(distance_matrix) initial_parameters = np.random.uniform(0, 1, 2) initial_state = small_tsp.prepare_initial_state([i for i in range(num_cities)]) qaoa_function_of_layer(2, distance_matrix)
- hamiltonians()#
- Returns:
The pair of Hamiltonian describes the phaser hamiltonian and the mixer hamiltonian.
- prepare_initial_state(ordering)#
To run QAOA by Hadsfield, we need to start from a valid permutation function to ensure feasibility.
- Parameters:
ordering (array) – A list describing permutation from 0 to n-1
- Returns:
An initial state that is used to start TSP QAOA.
Iterative Quantum Amplitude Estimation (IQAE)#
- class qibo.models.iqae.IQAE(circuit_a, circuit_q, alpha=0.05, epsilon=0.005, n_shots=1024, method='chernoff')#
Model that performs the Iterative Quantum Amplitude Estimation algorithm.
The implemented class in this code utilizes the Iterative Quantum Amplitude Estimation (IQAE) algorithm, which was proposed in arxiv:1912.05559. The algorithm provides an estimated output that, with a probability
alpha
, differs from the target value byepsilon
. Bothalpha
andepsilon
can be specified.Unlike Brassard’s original QAE algorithm arxiv:quant-ph/0005055, this implementation does not rely on Quantum Phase Estimation but instead is based solely on Grover’s algorithm. The IQAE algorithm employs a series of carefully selected Grover iterations to determine an estimate for the target amplitude.
- Parameters:
circuit_a (
qibo.models.circuit.Circuit
) – quantum circuit that specifies the QAE problem.circuit_q (
qibo.models.circuit.Circuit
) – quantum circuit of the Grover/Amplification operator.alpha (float) – confidence level, the target probability is 1 -
alpha
, has values between 0 and 1.epsilon (float) – target precision for estimation target a, has values between 0 and 0.5.
method (str) – statistical method used to estimate the confidence intervals in each iteration, can be either chernoff (default) for the Chernoff intervals or beta for the Clopper-Pearson intervals.
n_shots (int) – number of shots.
- Raises:
ValueError – If
epsilon
is not in (0, 0.5].ValueError – If
alpha
is not in (0, 1).ValueError – If
method
is not supported.ValueError – If the number of qubits in
circuit_a
is greater than incircuit_q
.
Example
from qibo import Circuit, gates from qibo.models.iqae import IQAE # Defining circuit A to integrate sin(x)^2 from [0,1] a_circuit = Circuit(2) a_circuit.add(gates.H(0)) a_circuit.add(gates.RY(q = 1, theta = 1 / 2)) a_circuit.add(gates.CU3(0, 1, 1, 0, 0)) # Defining circuit Q = -A S_0 A^-1 S_X q_circuit = Circuit(2) # S_X q_circuit.add(gates.Z(q = 1)) # A^-1 q_circuit = q_circuit + a_circuit.invert() # S_0 q_circuit.add(gates.X(0)) q_circuit.add(gates.X(1)) q_circuit.add(gates.CZ(0, 1)) # A q_circuit = q_circuit + a_circuit # Executing IQAE and obtaining the result iae = IQAE(a_circuit, q_circuit) results = iae.execute() integral_value = results.estimation integral_error = results.epsilon_estimated
- construct_qae_circuit(k)#
Generates quantum circuit for QAE.
- Parameters:
k (int) – number of times the amplification operator
circuit_q
is applied.- Returns:
The quantum circuit of the QAE algorithm.
- clopper_pearson(count, n, alpha)#
Calculates the confidence interval for the quantity to estimate a.
- h_calc_CP(n_successes, n_total_shots, upper_bound_t)#
Calculates the h function.
- calc_L_range_CP(n_shots, upper_bound_t)#
Calculate the confidence interval for the Clopper-Pearson method.
- calc_L_range_CH(n_shots, upper_bound_t)#
Calculate the confidence interval for the Chernoff method.
- find_next_k(uppercase_k_i, up_i, theta_l, theta_u, r=2)#
Find the largest integer
uppercase_k
such that the intervaluppercase_k
* [theta_l
,theta_u
] lies completely in [0, pi] or [pi, 2 pi].- Parameters:
uppercase_k_i (int) – the current
uppercase_k
suchuppercase_k
= 4k
+ 2, wherek
is the power of the operatorcircuit_q
.up_i (bool) – boolean flag of whether theta_interval lies in the upper half-circle [0, pi] or in the lower one [pi, 2 pi].
theta_l (float) – the current lower limit of the confidence interval for the angle theta.
theta_u (float) – the current upper limit of the confidence interval for the angle theta.
r (int) – lower bound for
uppercase_k
.
- Returns:
The next power K_i, and boolean flag for the extrapolated interval.
- execute(backend=None)#
Execute IQAE algorithm.
- Parameters:
backend – the qibo backend.
- Returns:
A
qibo.models.iqae.IterativeAmplitudeEstimationResult
results object.
- class qibo.models.iqae.IterativeAmplitudeEstimationResult#
The
IterativeAmplitudeEstimationResult
result object.
Time evolution#
State evolution#
- class qibo.models.evolution.StateEvolution(hamiltonian, dt, solver='exp', callbacks=[], accelerators=None)#
Unitary time evolution of a state vector under a Hamiltonian.
- Parameters:
hamiltonian (
qibo.hamiltonians.abstract.AbstractHamiltonian
) – Hamiltonian to evolve under.dt (float) – Time step to use for the numerical integration of Schrondiger’s equation.
solver (str) – Solver to use for integrating Schrodinger’s equation. Available solvers are ‘exp’ which uses the exact unitary evolution operator and ‘rk4’ or ‘rk45’ which use Runge-Kutta methods to integrate the Schordinger’s time-dependent equation in time. When the ‘exp’ solver is used to evolve a
qibo.hamiltonians.hamiltonians.SymbolicHamiltonian
then the Trotter decomposition of the evolution operator will be calculated and used automatically. If the ‘exp’ is used on a denseqibo.core.hamiltonians.hamiltonians.Hamiltonian
the full Hamiltonian matrix will be exponentiated to obtain the exact evolution operator. Runge-Kutta solvers use simple matrix multiplications of the Hamiltonian to the state and no exponentiation is involved.callbacks (list) – List of callbacks to calculate during evolution.
accelerators (dict) – Dictionary of devices to use for distributed execution. This option is available only when the Trotter decomposition is used for the time evolution.
Example
import numpy as np from qibo import models, hamiltonians # create critical (h=1.0) TFIM Hamiltonian for three qubits hamiltonian = hamiltonians.TFIM(3, h=1.0) # initialize evolution model with step dt=1e-2 evolve = models.StateEvolution(hamiltonian, dt=1e-2) # initialize state to |+++> initial_state = np.ones(8) / np.sqrt(8) # execute evolution for total time T=2 final_state2 = evolve(final_time=2, initial_state=initial_state)
- execute(final_time, start_time=0.0, initial_state=None)#
Runs unitary evolution for a given total time.
- Parameters:
- Returns:
Final state vector a
tf.Tensor
or aqibo.core.distutils.DistributedState
when a distributed execution is used.
Adiabatic evolution#
- class qibo.models.evolution.AdiabaticEvolution(h0, h1, s, dt, solver='exp', callbacks=[], accelerators=None)#
Adiabatic evolution of a state vector under the following Hamiltonian:
\[H(t) = (1 - s(t)) H_0 + s(t) H_1\]- Parameters:
h0 (
qibo.hamiltonians.abstract.AbstractHamiltonian
) – Easy Hamiltonian.h1 (
qibo.hamiltonians.abstract.AbstractHamiltonian
) – Problem Hamiltonian. These Hamiltonians should be time-independent.s (callable) – Function of time that defines the scheduling of the adiabatic evolution. Can be either a function of time s(t) or a function with two arguments s(t, p) where p corresponds to a vector of parameters to be optimized.
dt (float) – Time step to use for the numerical integration of Schrondiger’s equation.
solver (str) – Solver to use for integrating Schrodinger’s equation. Available solvers are ‘exp’ which uses the exact unitary evolution operator and ‘rk4’ or ‘rk45’ which use Runge-Kutta methods to integrate the Schordinger’s time-dependent equation in time. When the ‘exp’ solver is used to evolve a
qibo.hamiltonians.hamiltonians.SymbolicHamiltonian
then the Trotter decomposition of the evolution operator will be calculated and used automatically. If the ‘exp’ is used on a denseqibo.hamiltonians.hamiltonians.Hamiltonian
the full Hamiltonian matrix will be exponentiated to obtain the exact evolution operator. Runge-Kutta solvers use simple matrix multiplications of the Hamiltonian to the state and no exponentiation is involved.callbacks (list) – List of callbacks to calculate during evolution.
accelerators (dict) – Dictionary of devices to use for distributed execution. This option is available only when the Trotter decomposition is used for the time evolution.
- property schedule#
Returns scheduling as a function of time.
- set_parameters(params)#
Sets the variational parameters of the scheduling function.
- minimize(initial_parameters, method='BFGS', options=None, messages=False)#
Optimize the free parameters of the scheduling function.
- Parameters:
initial_parameters (np.ndarray) – Initial guess for the variational parameters that are optimized. The last element of the given array should correspond to the guess for the total evolution time T.
method (str) – The desired minimization method. One of
"cma"
(genetic optimizer),"sgd"
(gradient descent) or any of the methods supported by scipy.optimize.minimize.options (dict) – a dictionary with options for the different optimizers.
messages (bool) – If
True
the loss evolution is shown during optimization.
Error Mitigation#
Qibo allows for mitigating noise in circuits via error mitigation methods. Unlike error correction, error mitigation does not aim to correct qubit errors, but rather it provides the means to estimate the noise-free expected value of an observable measured at the end of a noisy circuit.
Readout Mitigation#
A common kind of error happening in quantum circuits is readout error, i.e. the error in the measurement of the qubits at the end of the computation. In Qibo there are currently two methods implemented for mitigating readout errors, and both can be used as standalone functions or in combination with the other general mitigation methods by setting the paramter readout.
Calibration Matrix#
Given \(n\) qubits, all the possible \(2^n\) states are constructed via the application of the corresponding sequence of \(X\) gates \(X_0\otimes I_1\otimes\cdot\cdot\cdot\otimes X_{n-1}\). In the presence of readout errors, we will measure for each state \(i\) some noisy frequencies \(F_i^{noisy}\) different from the ideal ones \(F_i^{ideal}=\delta_{i,j}\).
The effect of the error is modeled by the matrix composed of the noisy frequencies as columns \(M=\big(F_0^{noisy},...,F_{n-1}^{noisy}\big)\). We have indeed that:
and, therefore, the calibration matrix obtained as \(M_{\text{cal}}=M^{-1}\) can be used to recover the noise-free frequencies.
- qibo.models.error_mitigation.calibration_matrix(nqubits, noise_model=None, nshots: int = 1000, backend=None)#
Computes the calibration matrix for readout mitigation.
- Parameters:
nqubits (int) – Total number of qubits.
noise_model (
qibo.noise.NoiseModel
, optional) – noise model used for simulating noisy computation. This matrix can be used to mitigate the effect of qibo.noise.ReadoutError.nshots (int, optional) – number of shots.
backend (
qibo.backends.abstract.Backend
, optional) – calculation engine.
- Returns:
- The computed (nqubits, nqubits) calibration matrix for
readout mitigation.
- Return type:
numpy.ndarray
- qibo.models.error_mitigation.apply_readout_mitigation(state, calibration_matrix)#
Updates the frequencies of the input state with the mitigated ones obtained with
calibration_matrix * state.frequencies()
.- Parameters:
state (
qibo.states.CircuitResult
) – input state to be updated.calibration_matrix (numpy.ndarray) – calibration matrix for readout mitigation.
- Returns:
the input state with the updated frequencies.
- Return type:
Randomized#
This approach converts the effect of any noise map \(A\) into a single multiplication factor for each Pauli observable, that is, diagonalizes the measurement channel. The multiplication factor \(\lambda\) can be directly measured even without the quantum circuit. Dividing the measured value \(\langle O\rangle_{noisy}\) by these factor results in the mitigated Pauli expectation value \(\langle O\rangle_{ideal}\),
- qibo.models.error_mitigation.apply_randomized_readout_mitigation(circuit, noise_model=None, nshots: int = 1000, ncircuits: int = 10, backend=None)#
Implements the readout mitigation method proposed in https://arxiv.org/abs/2012.09738.
- Parameters:
circuit (
qibo.models.Circuit
) – input circuit.noise_model (
qibo.noise.NoiseModel
, optional) – noise model used for simulating noisy computation. This matrix can be used to mitigate the effects ofqibo.noise.ReadoutError
.nshots (int, optional) – number of shots.
ncircuits (int, optional) – number of randomized circuits. Each of them uses
int(nshots / ncircuits)
shots.backend (
qibo.backends.abstract.Backend
) – calculation engine.
- Returns:
- the state of the input circuit with
mitigated frequencies.
- Return type:
Zero Noise Extrapolation (ZNE)#
Given a noisy circuit \(C\) and an observable \(A\), Zero Noise Extrapolation (ZNE) consists in running \(n+1\) versions of the circuit with different noise levels \(\{c_j\}_{j=0..n}\) and, for each of them, measuring the expected value of the observable \(E_j=\langle A\rangle_j\).
Then, an estimate for the expected value of the observable in the noise-free condition is obtained as:
with \(\gamma_j\) satisfying:
This implementation of ZNE relies on the insertion of gate pairs (that resolve to the identity in the noise-free case) to realize the different noise levels \(\{c_j\}\), see He et al for more details. Hence, the canonical levels are mapped to the number of inserted pairs as \(c_j\rightarrow 2 c_j + 1\).
- qibo.models.error_mitigation.ZNE(circuit, observable, noise_levels, noise_model=None, nshots=10000, solve_for_gammas=False, insertion_gate='CNOT', readout: dict = {}, backend=None)#
Runs the Zero Noise Extrapolation method for error mitigation.
The different noise levels are realized by the insertion of pairs of either
CNOT
orRX(pi/2)
gates that resolve to the identiy in the noise-free case.- Parameters:
circuit (
qibo.models.Circuit
) – input circuit.observable (numpy.ndarray) – Observable to measure.
noise_levels (numpy.ndarray) – Sequence of noise levels.
noise_model (
qibo.noise.NoiseModel
, optional) – Noise model applied to simulate noisy computation.nshots (int, optional) – Number of shots.
solve_for_gammas (bool, optional) – If
True
, explicitly solve the equations to obtain thegamma
coefficients.insertion_gate (str, optional) – gate to be used in the insertion. If
"RX"
, the gate used is :math:RX(\pi / 2)
. Default is"CNOT"
.readout (dict, optional) – It has the structure {‘calibration_matrix’: numpy.ndarray, ‘ncircuits’: int}. If passed, the calibration matrix or the randomized method is used to mitigate readout errors.
backend (
qibo.backends.abstract.Backend
, optional) – Calculation engine.
- Returns:
Estimate of the expected value of
observable
in the noise free condition.- Return type:
numpy.ndarray
- qibo.models.error_mitigation.get_gammas(c, solve: bool = True)#
Standalone function to compute the ZNE coefficients given the noise levels.
- Parameters:
c (numpy.ndarray) – array containing the different noise levels. Note that in the CNOT insertion paradigm this corresponds to the number of CNOT pairs to be inserted. The canonical ZNE noise levels are obtained as
2 * c + 1
.solve (bool, optional) – If
True
, computes the coeffients by solving the linear system. IfFalse
, use the analytical solution valid for the CNOT insertion method. Default isTrue
.
- Returns:
The computed coefficients.
- Return type:
numpy.ndarray
- qibo.models.error_mitigation.get_noisy_circuit(circuit, num_insertions: int, insertion_gate: str = 'CNOT')#
Standalone function to generate the noisy circuit with the inverse gate pairs insertions.
- Parameters:
circuit (
qibo.models.circuit.Circuit
) – circuit to modify.num_insertions (int) – number of insertion gate pairs to add.
insertion_gate (str, optional) – gate to be used in the insertion. If
"RX"
, the gate used is :math:RX(\pi / 2)
. Default is"CNOT"
.
- Returns:
The circuit with the inserted CNOT pairs.
- Return type:
qibo.models.Circuit
Clifford Data Regression (CDR)#
In the Clifford Data Regression (CDR) method, a set of \(n\) circuits \(S_n=\{C_i\}_{i=1,..,n}\) is generated starting from the original circuit \(C_0\) by replacing some of the non-Clifford gates with Clifford ones. Given an observable \(A\), all the circuits of \(S_n\) are both simulated to obtain the correspondent expected values of \(A\) in noise-free condition \(\{a_i^{exact}\}_{i=1,..,n}\), and run in noisy conditions to obtain the noisy expected values \(\{a_i^{noisy}\}_{i=1,..,n}\).
Finally a model \(f\) is trained to minimize the mean squared error:
and learn the mapping \(a^{noisy}\rightarrow a^{exact}\). The mitigated expected value of \(A\) at the end of \(C_0\) is then obtained simply with \(f(a_0^{noisy})\).
In this implementation the initial circuit is expected to be decomposed in the three Clifford gates \(RX(\frac{\pi}{2})\), \(CNOT\), \(X\) and in \(RZ(\theta)\) (which is Clifford only for \(\theta=\frac{n\pi}{2}\)). By default the set of Clifford gates used for substitution is \(\{RZ(0),RZ(\frac{\pi}{2}),RZ(\pi),RZ(\frac{3}{2}\pi)\}\). See Sopena et al for more details.
- qibo.models.error_mitigation.CDR(circuit, observable, noise_model, nshots: int = 10000, model=<function <lambda>>, n_training_samples: int = 100, full_output: bool = False, readout: dict = {}, backend=None)#
Runs the Clifford Data Regression error mitigation method.
- Parameters:
circuit (
qibo.models.Circuit
) – input circuit decomposed in the primitive gatesX
,CNOT
,RX(pi/2)
,RZ(theta)
.observable (numpy.ndarray) – observable to be measured.
noise_model (
qibo.noise.NoiseModel
) – noise model used for simulating noisy computation.nshots (int, optional) – number of shots.
model (callable, optional) – model used for fitting. This should be a callable function object
f(x, *params)
, taking as input the predictor variable and the parameters. Default is a simple linear modelf(x,a,b) := a*x + b
.n_training_samples (int, optional) – number of training circuits to sample.
full_output (bool, optional) – if
True
, this function returns additional information:val
,optimal_params
,train_val
.readout (dict, optional) – It has the structure {‘calibration_matrix’: numpy.ndarray, ‘ncircuits’: int}. If passed, the calibration matrix or the randomized method is used to mitigate readout errors.
backend (
qibo.backends.abstract.Backend
, optional) – calculation engine.
- Returns:
Mitigated expectation value of observable. val (float): Noisy expectation value of observable. optimal_params (list): Optimal values for params. train_val (dict): Contains the noise-free and noisy expectation values obtained with the training circuits.
- Return type:
mit_val (float)
- qibo.models.error_mitigation.sample_training_circuit(circuit, replacement_gates: list | None = None, sigma: float = 0.5, backend=None)#
Samples a training circuit for CDR by susbtituting some of the non-Clifford gates.
- Parameters:
circuit (
qibo.models.Circuit
) – circuit to sample from, decomposed inRX(pi/2)
,X
,CNOT
andRZ
gates.replacement_gates (list, optional) – candidates for the substitution of the non-Clifford gates. The
list
should be composed bytuples
of the form (gates.XYZ
,kwargs
). For example, phase gates are used by default:list((RZ, {'theta':0}), (RZ, {'theta':pi/2}), (RZ, {'theta':pi}), (RZ, {'theta':3*pi/2}))
.sigma (float, optional) – standard devation of the Gaussian distribution used for sampling.
backend (
qibo.backends.abstract.Backend
, optional) – Calculation engine.
- Returns:
The sampled circuit.
- Return type:
qibo.models.Circuit
Variable Noise CDR (vnCDR)#
Variable Noise CDR (vnCDR) is an extension of the CDR method described above that factors in different noise levels as in ZNE. In detail, the set of circuits \(S_n=\{\mathbf{C}_i\}_{i=1,..,n}\) is still generated as in CDR, but for each \(\mathbf{C}_i\) we have \(k\) different versions of it with increased noise \(\mathbf{C}_i=C_i^0,C_i^1,...,C_i^{k-1}\).
Therefore, in this case we have a \(k\)-dimensional predictor variable \(\mathbf{a}_i^{noisy}=\big(a_i^0, a_i^1,..,a_i^{k-1}\big)^{noisy}\) for the same noise-free targets \(a_i^{exact}\), and we want to learn the mapping:
via minimizing the same mean squared error:
In particular, the default choice is to take \(f(\mathbf{x}):=\Gamma\cdot \mathbf{x}\;\), with \(\Gamma=\text{diag}(\gamma_0,\gamma_1,...,\gamma_{k-1})\;\), that corresponds to the ZNE calculation for the estimate of the expected value.
Here, as in the implementation of the CDR above, the circuit is supposed to be decomposed in the set of primitive gates \({RX(\frac{\pi}{2}),CNOT,X,RZ(\theta)}\). See Sopena et al for all the details.
- qibo.models.error_mitigation.vnCDR(circuit, observable, noise_levels, noise_model, nshots: int = 10000, model=<function <lambda>>, n_training_samples: int = 100, insertion_gate: str = 'CNOT', full_output: bool = False, readout: dict = {}, backend=None)#
Runs the variable-noise Clifford Data Regression error mitigation method.
- Parameters:
circuit (
qibo.models.Circuit
) – input circuit decomposed in the primitive gatesX
,CNOT
,RX(pi/2)
,RZ(theta)
.observable (numpy.ndarray) – observable to be measured.
noise_levels (numpy.ndarray) – sequence of noise levels.
noise_model (
qibo.noise.NoiseModel
) – noise model used for simulating noisy computation.nshots (int, optional) – number of shots.
model (callable, optional) – model used for fitting. This should be a callable function object
f(x, *params)
, taking as input the predictor variable and the parameters. Default is a simple linear modelf(x,a,b) := a*x + b
.n_training_samples (int, optional) – number of training circuits to sample.
insertion_gate (str, optional) – gate to be used in the insertion. If
"RX"
, the gate used is :math:RX(\pi / 2)
. Default is"CNOT"
.full_output (bool, optional) – if
True
, this function returns additional information:val
,optimal_params
,train_val
.readout (dict, optional) – It has the structure {‘calibration_matrix’: numpy.ndarray, ‘ncircuits’: int}. If passed, the calibration matrix or the randomized method is used to mitigate readout errors.
backend (
qibo.backends.abstract.Backend
, optional) – calculation engine.
- Returns:
Mitigated expectation value of observable. val (list): Expectation value of observable with increased noise levels. optimal_params (list): Optimal values for params. train_val (dict): Contains the noise-free and noisy expectation values obtained with the training circuits.
- Return type:
mit_val (float)
Gates#
All supported gates can be accessed from the qibo.gates
module.
Read below for a complete list of supported gates.
All gates support the controlled_by
method that allows to control
the gate on an arbitrary number of qubits. For example
gates.X(0).controlled_by(1, 2)
is equivalent togates.TOFFOLI(1, 2, 0)
,gates.RY(0, np.pi).controlled_by(1, 2, 3)
applies the Y-rotation to qubit 0 when qubits 1, 2 and 3 are in the|111>
state.gates.SWAP(0, 1).controlled_by(3, 4)
swaps qubits 0 and 1 when qubits 3 and 4 are in the|11>
state.
Abstract gate#
- class qibo.gates.abstract.Gate#
The base class for gate implementation.
All base gates should inherit this class.
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
- property parameters#
Returns a tuple containing the current value of gate’s parameters.
- commutes(gate: Gate) bool #
Checks if two gates commute.
- Parameters:
gate – Gate to check if it commutes with the current gate.
- Returns:
True
if the gates commute, otherwiseFalse
.
- on_qubits(qubit_map) Gate #
Creates the same gate targeting different qubits.
- Parameters:
qubit_map (int) – Dictionary mapping original qubit indices to new ones.
- Returns:
A
qibo.gates.Gate
object of the original gate type targeting the given qubits.
Example
from qibo import models, gates c = models.Circuit(4) # Add some CNOT gates c.add(gates.CNOT(2, 3).on_qubits({2: 2, 3: 3})) # equivalent to gates.CNOT(2, 3) c.add(gates.CNOT(2, 3).on_qubits({2: 3, 3: 0})) # equivalent to gates.CNOT(3, 0) c.add(gates.CNOT(2, 3).on_qubits({2: 1, 3: 3})) # equivalent to gates.CNOT(1, 3) c.add(gates.CNOT(2, 3).on_qubits({2: 2, 3: 1})) # equivalent to gates.CNOT(2, 1) print(c.draw())
q0: ───X───── q1: ───|─o─X─ q2: ─o─|─|─o─ q3: ─X─o─X───
- dagger() Gate #
Returns the dagger (conjugate transpose) of the gate.
Note that dagger is not persistent for parametrized gates. For example, applying a dagger to an
qibo.gates.gates.RX
gate will change the sign of its parameter at the time of application. However, if the parameter is updated after that, for example usingqibo.models.circuit.Circuit.set_parameters()
, then the action of dagger will be lost.- Returns:
A
qibo.gates.Gate
object representing the dagger of the original gate.
- decompose(*free) List[Gate] #
Decomposes multi-control gates to gates supported by OpenQASM.
Decompositions are based on arXiv:9503016.
- Parameters:
free – Ids of free qubits to use for the gate decomposition.
- Returns:
List with gates that have the same effect as applying the original gate.
- matrix(backend=None)#
Returns the matrix representation of the gate.
- Parameters:
backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.- Returns:
Matrix representation of gate.
- Return type:
ndarray
Note
Gate.matrix
was an defined as an atribute inqibo
versions prior to0.2.0
. From0.2.0
on, it has been converted into a method and has replaced theasmatrix
method.
- generator_eigenvalue()#
This function returns the eigenvalues of the gate’s generator.
- Returns:
np.float generator’s eigenvalue or raise an error if not implemented.
- basis_rotation()#
Transformation required to rotate the basis for measuring the gate.
Single qubit gates#
Hadamard (H)#
- class qibo.gates.H(q)#
The Hadamard gate.
Corresponds to the following unitary matrix
\[\begin{split}\frac{1}{\sqrt{2}} \, \begin{pmatrix} 1 & 1 \\ 1 & -1 \\ \end{pmatrix}\end{split}\]- Parameters:
q (int) – the qubit id number.
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
Pauli X (X)#
- class qibo.gates.X(q)#
The Pauli-\(X\) gate.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} 0 & 1 \\ 1 & 0 \\ \end{pmatrix}\end{split}\]- Parameters:
q (int) – the qubit id number.
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
- decompose(*free, use_toffolis=True)#
Decomposes multi-control
X
gate to one-qubit,CNOT
andTOFFOLI
gates.- Parameters:
free – Ids of free qubits to use for the gate decomposition.
use_toffolis – If
True
the decomposition contains onlyTOFFOLI
gates. IfFalse
a congruent representation is used forTOFFOLI
gates. Seeqibo.gates.TOFFOLI
for more details on this representation.
- Returns:
List with one-qubit,
CNOT
andTOFFOLI
gates that have the same effect as applying the original multi-control gate.
- basis_rotation()#
Transformation required to rotate the basis for measuring the gate.
Pauli Y (Y)#
- class qibo.gates.Y(q)#
The Pauli-\(Y\) gate.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} 0 & -i \\ i & 0 \\ \end{pmatrix}\end{split}\]- Parameters:
q (int) – the qubit id number.
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
- basis_rotation()#
Transformation required to rotate the basis for measuring the gate.
Pauli Z (Z)#
- class qibo.gates.Z(q)#
The Pauli-\(Z\) gate.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} 1 & 0 \\ 0 & -1 \\ \end{pmatrix}\end{split}\]- Parameters:
q (int) – the qubit id number.
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
- basis_rotation()#
Transformation required to rotate the basis for measuring the gate.
Square-root of Pauli X (SX)#
- class qibo.gates.SX(q)#
The \(\sqrt{X}\) gate.
Corresponds to the following unitary matrix
\[\begin{split}\frac{1}{2} \, \begin{pmatrix} 1 + i & 1 - i \\ 1 - i & 1 + i \\ \end{pmatrix}\end{split}\]- Parameters:
q (int) – the qubit id number.
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
- decompose()#
A global phase difference exists between the definitions of \(\sqrt{X}\) and \(\text{RX}(\pi / 2)\), with \(\text{RX}\) being the
qibo.gates.RX
gate. More precisely, \(\sqrt{X} = e^{i \pi / 4} \, \text{RX}(\pi / 2)\).
S gate (S)#
T gate (T)#
Identity (I)#
Align (A)#
Measurement (M)#
- class qibo.gates.M(*q, register_name: str | None = None, collapse: bool = False, basis: ~qibo.gates.abstract.Gate = <class 'qibo.gates.gates.Z'>, p0: ProbsType | None = None, p1: ProbsType | None = None)#
The measure gate.
- Parameters:
*q (int) – id numbers of the qubits to measure. It is possible to measure multiple qubits using
gates.M(0, 1, 2, ...)
. If the qubits to measure are held in an iterable (eg. list) the*
operator can be used, for examplegates.M(*[0, 1, 4])
orgates.M(*range(5))
.register_name (str) – Optional name of the register to distinguish it from other registers when used in circuits.
collapse (bool) – Collapse the state vector after the measurement is performed. Can be used only for single shot measurements. If
True
the collapsed state vector is returned. IfFalse
the measurement result is returned.basis (
qibo.gates.Gate
, list) – Basis to measure. Can be a qibo gate or a callable that accepts a qubit, for example:lambda q: gates.RX(q, 0.2)
or a list of these, if a different basis will be used for each measurement qubit. Default is Z.p0 (dict) – Optional bitflip probability map. Can be: A dictionary that maps each measured qubit to the probability that it is flipped, a list or tuple that has the same length as the tuple of measured qubits or a single float number. If a single float is given the same probability will be used for all qubits.
p1 (dict) – Optional bitflip probability map for asymmetric bitflips. Same as
p0
but controls the 1->0 bitflip probability. Ifp1
isNone
thenp0
will be used both for 0->1 and 1->0 bitflips.
- add(gate)#
Adds target qubits to a measurement gate.
This method is only used for creating the global measurement gate used by the models.Circuit. The user is not supposed to use this method and a ValueError is raised if he does so.
- Parameters:
gate – Measurement gate to add its qubits in the current gate.
Rotation X-axis (RX)#
- class qibo.gates.RX(q, theta, trainable=True)#
Rotation around the X-axis of the Bloch sphere.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} \cos \frac{\theta }{2} & -i\sin \frac{\theta }{2} \\ -i\sin \frac{\theta }{2} & \cos \frac{\theta }{2} \\ \end{pmatrix}\end{split}\]- Parameters:
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
- generator_eigenvalue()#
This function returns the eigenvalues of the gate’s generator.
- Returns:
np.float generator’s eigenvalue or raise an error if not implemented.
Rotation Y-axis (RY)#
- class qibo.gates.RY(q, theta, trainable=True)#
Rotation around the Y-axis of the Bloch sphere.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} \cos \frac{\theta }{2} & -\sin \frac{\theta }{2} \\ \sin \frac{\theta }{2} & \cos \frac{\theta }{2} \\ \end{pmatrix}\end{split}\]- Parameters:
q (int) – the qubit id number.
theta (float) – the rotation angle.
trainable (bool) – whether gate parameters can be updated using
qibo.models.circuit.Circuit.set_parameters()
. Defaults toTrue
.
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
- generator_eigenvalue()#
This function returns the eigenvalues of the gate’s generator.
- Returns:
np.float generator’s eigenvalue or raise an error if not implemented.
Rotation Z-axis (RZ)#
- class qibo.gates.RZ(q, theta, trainable=True)#
Rotation around the Z-axis of the Bloch sphere.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} e^{-i \theta / 2} & 0 \\ 0 & e^{i \theta / 2} \\ \end{pmatrix}\end{split}\]- Parameters:
q (int) – the qubit id number.
theta (float) – the rotation angle.
trainable (bool) – whether gate parameters can be updated using
qibo.models.circuit.Circuit.set_parameters()
. Defaults toTrue
.
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
- generator_eigenvalue()#
This function returns the eigenvalues of the gate’s generator.
- Returns:
np.float generator’s eigenvalue or raise an error if not implemented.
First general unitary (U1)#
Second general unitary (U2)#
- class qibo.gates.U2(q, phi, lam, trainable=True)#
Second general unitary gate.
Corresponds to the following unitary matrix
\[\begin{split}\frac{1}{\sqrt{2}} \begin{pmatrix} e^{-i(\phi + \lambda )/2} & -e^{-i(\phi - \lambda )/2} \\ e^{i(\phi - \lambda )/2} & e^{i (\phi + \lambda )/2} \\ \end{pmatrix}\end{split}\]- Parameters:
q (int) – the qubit id number.
phi (float) – first rotation angle.
lamb (float) – second rotation angle.
trainable (bool) – whether gate parameters can be updated using
qibo.models.circuit.Circuit.set_parameters()
. Defaults toTrue
.
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
Third general unitary (U3)#
- class qibo.gates.U3(q, theta, phi, lam, trainable=True)#
Third general unitary gate.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} e^{-i(\phi + \lambda )/2}\cos\left (\frac{\theta }{2}\right ) & -e^{-i(\phi - \lambda )/2}\sin\left (\frac{\theta }{2}\right ) \\ e^{i(\phi - \lambda )/2}\sin\left (\frac{\theta }{2}\right ) & e^{i (\phi + \lambda )/2}\cos\left (\frac{\theta }{2}\right ) \\ \end{pmatrix}\end{split}\]- Parameters:
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
Two qubit gates#
Controlled-NOT (CNOT)#
- class qibo.gates.CNOT(q0, q1)#
The Controlled-NOT gate.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 \\ \end{pmatrix}\end{split}\]- property qasm_label#
String corresponding to OpenQASM operation of the gate.
- decompose(*free, use_toffolis: bool = True) List[Gate] #
Decomposes multi-control gates to gates supported by OpenQASM.
Decompositions are based on arXiv:9503016.
- Parameters:
free – Ids of free qubits to use for the gate decomposition.
- Returns:
List with gates that have the same effect as applying the original gate.
Controlled-phase (CZ)#
- class qibo.gates.CZ(q0, q1)#
The Controlled-Phase gate.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & -1 \\ \end{pmatrix}\end{split}\]- property qasm_label#
String corresponding to OpenQASM operation of the gate.
Controlled-Square Root of X (CSX)#
- class qibo.gates.CSX(q0, q1)#
The Controlled-\(\sqrt{X}\) gate.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & e^{i\pi/4} & e^{-i\pi/4} \\ 0 & 0 & e^{-i\pi/4} & e^{i\pi/4} \\ \end{pmatrix}\end{split}\]- property qasm_label#
String corresponding to OpenQASM operation of the gate.
Controlled-rotation X-axis (CRX)#
- class qibo.gates.CRX(q0, q1, theta, trainable=True)#
Controlled rotation around the X-axis for the Bloch sphere.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & \cos \frac{\theta }{2} & -i\sin \frac{\theta }{2} \\ 0 & 0 & -i\sin \frac{\theta }{2} & \cos \frac{\theta }{2} \\ \end{pmatrix}\end{split}\]- Parameters:
q0 (int) – the control qubit id number.
q1 (int) – the target qubit id number.
theta (float) – the rotation angle.
trainable (bool) – whether gate parameters can be updated using
qibo.models.circuit.Circuit.set_parameters()
. Defaults toTrue
.
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
Controlled-rotation Y-axis (CRY)#
- class qibo.gates.CRY(q0, q1, theta, trainable=True)#
Controlled rotation around the Y-axis for the Bloch sphere.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & \cos \frac{\theta }{2} & -\sin \frac{\theta }{2} \\ 0 & 0 & \sin \frac{\theta }{2} & \cos \frac{\theta }{2} \\ \end{pmatrix}\end{split}\]Note that this differs from the
qibo.gates.RZ
gate.- Parameters:
q0 (int) – the control qubit id number.
q1 (int) – the target qubit id number.
theta (float) – the rotation angle.
trainable (bool) – whether gate parameters can be updated using
qibo.models.circuit.Circuit.set_parameters()
. Defaults toTrue
.
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
Controlled-rotation Z-axis (CRZ)#
- class qibo.gates.CRZ(q0, q1, theta, trainable=True)#
Controlled rotation around the Z-axis for the Bloch sphere.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & e^{-i \theta / 2} & 0 \\ 0 & 0 & 0 & e^{i \theta / 2} \\ \end{pmatrix}\end{split}\]- Parameters:
q0 (int) – the control qubit id number.
q1 (int) – the target qubit id number.
theta (float) – the rotation angle.
trainable (bool) – whether gate parameters can be updated using
qibo.models.circuit.Circuit.set_parameters()
. Defaults toTrue
.
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
Controlled first general unitary (CU1)#
- class qibo.gates.CU1(q0, q1, theta, trainable=True)#
Controlled first general unitary gate.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & e^{i \theta } \\ \end{pmatrix}\end{split}\]Note that this differs from the
qibo.gates.CRZ
gate.- Parameters:
q0 (int) – the control qubit id number.
q1 (int) – the target qubit id number.
theta (float) – the rotation angle.
trainable (bool) – whether gate parameters can be updated using
qibo.models.circuit.Circuit.set_parameters()
. Defaults toTrue
.
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
Controlled second general unitary (CU2)#
- class qibo.gates.CU2(q0, q1, phi, lam, trainable=True)#
Controlled second general unitary gate.
Corresponds to the following unitary matrix
\[\begin{split}\frac{1}{\sqrt{2}} \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & e^{-i(\phi + \lambda )/2} & -e^{-i(\phi - \lambda )/2} \\ 0 & 0 & e^{i(\phi - \lambda )/2} & e^{i (\phi + \lambda )/2} \\ \end{pmatrix}\end{split}\]
Controlled third general unitary (CU3)#
- class qibo.gates.CU3(q0, q1, theta, phi, lam, trainable=True)#
Controlled third general unitary gate.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & e^{-i(\phi + \lambda )/2}\cos\left (\frac{\theta }{2}\right ) & -e^{-i(\phi - \lambda )/2}\sin\left (\frac{\theta }{2}\right ) \\ 0 & 0 & e^{i(\phi - \lambda )/2}\sin\left (\frac{\theta }{2}\right ) & e^{i (\phi + \lambda )/2}\cos\left (\frac{\theta }{2}\right ) \\ \end{pmatrix}\end{split}\]- Parameters:
q0 (int) – the control qubit id number.
q1 (int) – the target qubit id number.
theta (float) – first rotation angle.
phi (float) – second rotation angle.
lamb (float) – third rotation angle.
trainable (bool) – whether gate parameters can be updated using
qibo.models.circuit.Circuit.set_parameters()
. Defaults toTrue
.
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
Swap (SWAP)#
- class qibo.gates.SWAP(q0, q1)#
The swap gate.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ \end{pmatrix}\end{split}\]- Parameters:
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
iSwap (iSWAP)#
- class qibo.gates.iSWAP(q0, q1)#
The iswap gate.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & i & 0 \\ 0 & i & 0 & 0 \\ 0 & 0 & 0 & 1 \\ \end{pmatrix}\end{split}\]- Parameters:
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
f-Swap (FSWAP)#
- class qibo.gates.FSWAP(q0, q1)#
The fermionic swap gate.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & -1 \\ \end{pmatrix}\end{split}\]- Parameters:
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
fSim#
- class qibo.gates.fSim(q0, q1, theta, phi, trainable=True)#
The fSim gate defined in arXiv:2001.08343.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & \cos \theta & -i\sin \theta & 0 \\ 0 & -i\sin \theta & \cos \theta & 0 \\ 0 & 0 & 0 & e^{-i \phi } \\ \end{pmatrix}\end{split}\]- Parameters:
q0 (int) – the first qubit to be swapped id number.
q1 (int) – the second qubit to be swapped id number.
theta (float) – Angle for the one-qubit rotation.
phi (float) – Angle for the
|11>
phase.trainable (bool) – whether gate parameters can be updated using
qibo.models.circuit.Circuit.set_parameters()
. Defaults toTrue
.
Sycamore gate#
- class qibo.gates.SYC(q0, q1)#
The Sycamore gate, defined in the Supplementary Information of Quantum supremacy using a programmable superconducting processor.
Corresponding to the following unitary matrix
\[\begin{split}\text{fSim}(\pi / 2, \, \pi / 6) = \beging{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & -i & 0 \\ 0 & -i & 0 & 0 \\ 0 & 0 & 0 & e^{-i \pi / 6} \\ \end{pmatrix} \, ,\end{split}\]where \(\text{fSim}\) is the
qibo.gates.fSim
gate.
fSim with general rotation#
- class qibo.gates.GeneralizedfSim(q0, q1, unitary, phi, trainable=True)#
The fSim gate with a general rotation.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & R_{00} & R_{01} & 0 \\ 0 & R_{10} & R_{11} & 0 \\ 0 & 0 & 0 & e^{-i \phi } \\ \end{pmatrix}\end{split}\]- Parameters:
q0 (int) – the first qubit to be swapped id number.
q1 (int) – the second qubit to be swapped id number.
unitary (np.ndarray) – Unitary that corresponds to the one-qubit rotation.
phi (float) – Angle for the
|11>
phase.trainable (bool) – whether gate parameters can be updated using
qibo.models.circuit.Circuit.set_parameters()
. Defaults toTrue
.
- property parameters#
Returns a tuple containing the current value of gate’s parameters.
Parametric XX interaction (RXX)#
- class qibo.gates.RXX(q0, q1, theta, trainable=True)#
Parametric 2-qubit XX interaction, or rotation about XX-axis.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} \cos \frac{\theta }{2} & 0 & 0 & -i\sin \frac{\theta }{2} \\ 0 & \cos \frac{\theta }{2} & -i\sin \frac{\theta }{2} & 0 \\ 0 & -i\sin \frac{\theta }{2} & \cos \frac{\theta }{2} & 0 \\ -i\sin \frac{\theta }{2} & 0 & 0 & \cos \frac{\theta }{2} \\ \end{pmatrix}\end{split}\]- Parameters:
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
Parametric YY interaction (RYY)#
- class qibo.gates.RYY(q0, q1, theta, trainable=True)#
Parametric 2-qubit YY interaction, or rotation about YY-axis.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} \cos \frac{\theta }{2} & 0 & 0 & i\sin \frac{\theta }{2} \\ 0 & \cos \frac{\theta }{2} & -i\sin \frac{\theta }{2} & 0 \\ 0 & -i\sin \frac{\theta }{2} & \cos \frac{\theta }{2} & 0 \\ i\sin \frac{\theta }{2} & 0 & 0 & \cos \frac{\theta }{2} \\ \end{pmatrix}\end{split}\]- Parameters:
q0 (int) – the first entangled qubit id number.
q1 (int) – the second entangled qubit id number.
trainable (bool) – whether gate parameters can be updated using
qibo.models.circuit.Circuit.set_parameters()
. Defaults toTrue
.
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
Parametric ZZ interaction (RZZ)#
- class qibo.gates.RZZ(q0, q1, theta, trainable=True)#
Parametric 2-qubit ZZ interaction, or rotation about ZZ-axis.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} e^{-i \theta / 2} & 0 & 0 & 0 \\ 0 & e^{i \theta / 2} & 0 & 0 \\ 0 & 0 & e^{i \theta / 2} & 0 \\ 0 & 0 & 0 & e^{-i \theta / 2} \\ \end{pmatrix}\end{split}\]- Parameters:
q0 (int) – the first entangled qubit id number.
q1 (int) – the second entangled qubit id number.
theta (float) – the rotation angle.
trainable (bool) – whether gate parameters can be updated using
qibo.models.circuit.Circuit.set_parameters()
. Defaults toTrue
.
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
Parametric ZX interaction (RZX)#
- class qibo.gates.RZX(q0, q1, theta, trainable=True)#
Parametric 2-qubit ZX interaction, or rotation about ZX-axis.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} \text{RX}(\theta) & 0 \\ 0 & \text{RX}(-\theta) \\ \end{pmatrix} = \begin{pmatrix} \cos{\frac{\theta}{2}} & -i \sin{\frac{\theta}{2}} & 0 & 0 \\ -i \sin{\frac{\theta}{2}} & \cos{\frac{\theta}{2}} & 0 & 0 \\ 0 & 0 & \cos{\frac{\theta}{2}} & i \sin{\frac{\theta}{2}} \\ 0 & 0 & i \sin{\frac{\theta}{2}} & \cos{\frac{\theta}{2}} \\ \end{pmatrix} \, ,\end{split}\]where \(\text{RX}\) is the
qibo.gates.RX
gate.- Parameters:
q0 (int) – the first entangled qubit id number.
q1 (int) – the second entangled qubit id number.
theta (float) – the rotation angle.
trainable (bool) – whether gate parameters can be updated using
qibo.models.circuit.Circuit.set_parameters()
. Defaults toTrue
.
Parametric XX-YY interaction (RXY)#
- class qibo.gates.RXY(q0, q1, theta, trainable=True)#
Parametric 2-qubit \(XX + YY\) interaction, or rotation about \(XX + YY\)-axis.
Corresponds to the following unitary matrix
\[\begin{split}\exp\left(-i \frac{\theta}{4}(XX + YY)\right) = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & \cos{\frac{\theta}{2}} & -i \sin{\frac{\theta}{2}} & 0 \\ 0 & -i \sin{\frac{\theta}{2}} & \cos{\frac{\theta}{2}} & 0 \\ 0 & 0 & 0 & 1 \\ \end{pmatrix} \, ,\end{split}\]- Parameters:
q0 (int) – the first entangled qubit id number.
q1 (int) – the second entangled qubit id number.
theta (float) – the rotation angle.
trainable (bool) – whether gate parameters can be updated using
qibo.models.circuit.Circuit.set_parameters()
. Defaults toTrue
.
Givens gate#
- class qibo.gates.GIVENS(q0, q1, theta, trainable=True)#
The Givens gate.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & \cos(\theta) & -\sin(\theta) & 0 \\ 0 & \sin(\theta) & \cos(\theta) & 0 \\ 0 & 0 & 0 & 1 \\ \end{pmatrix}\end{split}\]- Parameters:
- decompose(*free, use_toffolis: bool = True) List[Gate] #
Decomposition of Givens gate according to ArXiv:2106.13839.
Reconfigurable Beam Splitter gate (RBS)#
- class qibo.gates.RBS(q0, q1, theta, trainable=True)#
The Reconfigurable Beam Splitter gate.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & \cos(\theta) & \sin(\theta) & 0 \\ 0 & -\sin(\theta) & \cos(\theta) & 0 \\ 0 & 0 & 0 & 1 \\ \end{pmatrix}\end{split}\]Note that, in our implementation, \(\text{RBS}(\theta) = \text{Givens}(-\theta)\), where \(\text{Givens}\) is the
qibo.gates.GIVENS
gate. However, we point out that this definition is not unique.- Parameters:
- decompose(*free, use_toffolis: bool = True) List[Gate] #
Decomposition of RBS gate according to ArXiv:2109.09685.
Echo Cross-Resonance gate (ECR)#
- class qibo.gates.ECR(q0, q1)#
THe Echo Cross-Resonance gate.
Corresponds ot the following matrix
\[\begin{split}\frac{1}{\sqrt{2}} \left( X \, I - Y \, X \right) = \frac{1}{\sqrt{2}} \, \begin{pmatrix} 0 & 0 & 1 & i \\ 0 & 0 & i & 1 \\ 1 & -i & 0 & 0 \\ -i & 1 & 0 & 0 \\ \end{pmatrix}\end{split}\]
Special gates#
Toffoli#
- class qibo.gates.TOFFOLI(q0, q1, q2)#
The Toffoli gate.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\ 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\ \end{pmatrix}\end{split}\]- Parameters:
- property qasm_label#
String corresponding to OpenQASM operation of the gate.
- decompose(*free, use_toffolis: bool = True) List[Gate] #
Decomposes multi-control gates to gates supported by OpenQASM.
Decompositions are based on arXiv:9503016.
- Parameters:
free – Ids of free qubits to use for the gate decomposition.
- Returns:
List with gates that have the same effect as applying the original gate.
- congruent(use_toffolis: bool = True) List[Gate] #
Congruent representation of
TOFFOLI
gate.This is a helper method for the decomposition of multi-control
X
gates. The congruent representation is based on Sec. 6.2 of arXiv:9503016. The sequence of the gates produced here has the same effect asTOFFOLI
with the phase of the|101>
state reversed.- Parameters:
use_toffolis – If
True
a singleTOFFOLI
gate is returned. IfFalse
the congruent representation is returned.- Returns:
List with
RY
andCNOT
gates that have the same effect as applying the originalTOFFOLI
gate.
Deutsch#
- class qibo.gates.DEUTSCH(q0, q1, q2, theta, trainable=True)#
The Deutsch gate.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & i \cos{\theta} & \sin{\theta} \\ 0 & 0 & 0 & 0 & 0 & 0 & \sin{\theta} & i \cos{\theta} \\ \end{pmatrix}\end{split}\]
Arbitrary unitary#
- class qibo.gates.Unitary(unitary, *q, trainable=True, name: str | None = None, check_unitary: bool = True)#
Arbitrary unitary gate.
- Parameters:
unitary – Unitary matrix as a tensor supported by the backend.
*q (int) – Qubit id numbers that the gate acts on.
trainable (bool) – whether gate parameters can be updated using
qibo.models.circuit.Circuit.set_parameters()
. Defaults toTrue
.name (str) – Optional name for the gate.
check_unitary (bool) – if
True
, checks ifunitary
is an unitary operator. IfFalse
, check is not performed andunitary
attribute defaults toFalse
. Note that, even when the check is performed, there is no enforcement. This allows the user to create non-unitary gates. Default isTrue
.
- property parameters#
Returns a tuple containing the current value of gate’s parameters.
- on_qubits(qubit_map)#
Creates the same gate targeting different qubits.
- Parameters:
qubit_map (int) – Dictionary mapping original qubit indices to new ones.
- Returns:
A
qibo.gates.Gate
object of the original gate type targeting the given qubits.
Example
from qibo import models, gates c = models.Circuit(4) # Add some CNOT gates c.add(gates.CNOT(2, 3).on_qubits({2: 2, 3: 3})) # equivalent to gates.CNOT(2, 3) c.add(gates.CNOT(2, 3).on_qubits({2: 3, 3: 0})) # equivalent to gates.CNOT(3, 0) c.add(gates.CNOT(2, 3).on_qubits({2: 1, 3: 3})) # equivalent to gates.CNOT(1, 3) c.add(gates.CNOT(2, 3).on_qubits({2: 2, 3: 1})) # equivalent to gates.CNOT(2, 1) print(c.draw())
q0: ───X───── q1: ───|─o─X─ q2: ─o─|─|─o─ q3: ─X─o─X───
Callback gate#
- class qibo.gates.CallbackGate(callback: Callback)#
Calculates a
qibo.callbacks.Callback
at a specific point in the circuit.This gate performs the callback calulation without affecting the state vector.
- Parameters:
callback (
qibo.callbacks.Callback
) – Callback object to calculate.
Fusion gate#
- class qibo.gates.FusedGate(*q)#
Collection of gates that will be fused and applied as single gate during simulation. This gate is constructed automatically by
qibo.models.circuit.Circuit.fuse()
and should not be used by user.- can_fuse(gate, max_qubits)#
Check if two gates can be fused.
- matrix(backend=None)#
Returns matrix representation of special gate.
- Parameters:
backend (
qibo.backends.abstract.Backend
, optional) – backendNone (to be used in the execution. If) –
uses (it) –
:param
qibo.backends.GlobalBackend
. Defaults toNone
.:- Returns:
Matrix representation of special gate.
- Return type:
ndarray
- fuse(gate)#
Fuses two gates.
IONQ Native gates#
GPI#
- class qibo.gates.GPI(q, phi, trainable=True)#
The GPI gate.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} 0 & e^{- i \phi} \\ e^{i \phi} & 0 \\ \end{pmatrix}\end{split}\]
GPI2#
- class qibo.gates.GPI2(q, phi, trainable=True)#
The GPI2 gate.
Corresponds to the following unitary matrix
\[\begin{split}\frac{1}{\sqrt{2}} \, \begin{pmatrix} 1 & -i e^{- i \phi} \\ -i e^{i \phi} & 1 \\ \end{pmatrix}\end{split}\]
Mølmer–Sørensen (MS)#
- class qibo.gates.MS(q0, q1, phi0, phi1, theta: float = 1.5707963267948966, trainable=True)#
The Mølmer–Sørensen (MS) gate is a two-qubit gate native to trapped ions.
Corresponds to the following unitary matrix
\[\begin{split}\begin{pmatrix} \cos(\theta / 2) & 0 & 0 & -i e^{-i( \phi_0 + \phi_1)} \sin(\theta / 2) \\ 0 & \cos(\theta / 2) & -i e^{-i( \phi_0 - \phi_1)} \sin(\theta / 2) & 0 \\ 0 & -i e^{i( \phi_0 - \phi_1)} \sin(\theta / 2) & \cos(\theta / 2) & 0 \\ -i e^{i( \phi_0 + \phi_1)} \sin(\theta / 2) & 0 & 0 & \cos(\theta / 2) \\ \end{pmatrix}\end{split}\]- Parameters:
q0 (int) – the first qubit to be swapped id number.
q1 (int) – the second qubit to be swapped id number.
phi0 (float) – first qubit’s phase.
phi1 (float) – second qubit’s phase
theta (float, optional) – arbitrary angle in the interval \(0 \leq \theta \leq \pi /2\). If \(\theta \rightarrow \pi / 2\), the fully-entangling MS gate is defined. Defaults to \(\pi / 2\).
trainable (bool) – whether gate parameters can be updated using
qibo.models.circuit.Circuit.set_parameters()
. Defaults toTrue
.
Channels#
Channels are implemented in Qibo as additional gates and can be accessed from
the qibo.gates
module. Channels can be used on density matrices to perform
noisy simulations. Channels that inherit qibo.gates.UnitaryChannel
can also be applied to state vectors using sampling and repeated execution.
For more information on the use of channels to simulate noise we refer to
How to perform noisy simulation?
The following channels are currently implemented:
Kraus channel#
- class qibo.gates.KrausChannel(qubits, operators)#
General channel defined by arbitrary Kraus operators.
Implements the following transformation:
\[\mathcal{E}(\rho ) = \sum _k A_k \rho A_k^\dagger\]where A are arbitrary Kraus operators given by the user. Note that Kraus operators set should be trace preserving, however this is not checked. Simulation of this gate requires the use of density matrices. For more information on channels and Kraus operators please check J. Preskill’s notes.
- Parameters:
qubits (int or list or tuple) – Qubits that the Kraus operators act on. Type
int
andtuple
will be considered as the same qubit ids for all operators. Alist
should contain tuples of qubits corresponding to each operator. Can be[]
ifoperators
are of typeqibo.gates.Gate
, otherwise adds given gates on specified qubits.operators (list) – List of Kraus operators
Ak
as matrices of typendarray | tf.Tensor
or gatesqibo.gates.Gate
.
Example
import numpy as np from qibo import Circuit, gates # initialize circuit with 3 qubits circuit = Circuit(3, density_matrix=True) # define a sqrt(0.4) * X gate a_1 = np.sqrt(0.4) * np.array([[0, 1], [1, 0]]) # define a sqrt(0.6) * CNOT gate a_2 = np.sqrt(0.6) * np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]) # define the channel rho -> 0.4 X{1} rho X{1} + 0.6 CNOT{0, 2} rho CNOT{0, 2} channel_1 = gates.KrausChannel([(1,), (0, 2)], [a_1, a_2]) # add channel to the circuit circuit.add(channel_1) # define the same channel using qibo.gates.Unitary a_1 = gates.Unitary(a_1, 1) a_2 = gates.Unitary(a_2, 0, 2) channel_2 = gates.KrausChannel([], [a_1, a_2]) # add channel to the circuit circuit.add(channel_2) # define the channel rho -> 0.4 X{0} rho X{0} + 0.6 CNOT{1, 2} rho CNOT{1, 2} channel_3 = gates.KrausChannel([(0,), (1, 2)], [a_1, a_2]) # add channel to the circuit circuit.add(channel_3)
Unitary channel#
- class qibo.gates.UnitaryChannel(qubits, operators)#
Channel that is a probabilistic sum of unitary operations.
Implements the following transformation:
\[\mathcal{E}(\rho ) = \left (1 - \sum _k p_k \right )\rho + \sum _k p_k U_k \rho U_k^\dagger\]where U are arbitrary unitary operators and p are floats between 0 and 1. Note that unlike
qibo.gates.KrausChannel
which requires density matrices, it is possible to simulate the unitary channel using state vectors and probabilistic sampling. For more information on this approach we refer to Using repeated execution.- Parameters:
qubits (int or list or tuple) – Qubits that the unitary operators act on. Types
int
andtuple
will be considered as the same qubit(s) for all unitaries. Alist
should contain tuples of qubits corresponding to each operator. Can be[]
ifoperators
are of typeqibo.gates.Gate
, otherwise adds given gates on specified qubits.operators (list) – List of operators as pairs
(pk, Uk)
wherepk
is float probability corresponding to a unitaryUk
of typendarray
/tf.Tensor
or gatesqibo.gates.Gate
.
Pauli noise channel#
- class qibo.gates.PauliNoiseChannel(qubits: Tuple[int, list, tuple], operators: list)#
Multi-qubit noise channel that applies Pauli operators with given probabilities.
Implements the following transformation:
\[\mathcal{E}(\rho ) = \left (1 - \sum _{k} p_{k} \right ) \, \rho + \sum_{k} \, p_{k} \, P_{k} \, \rho \, P_{k}\]where \(P_{k}\) is the \(k\)-th Pauli
string
and \(p_{k}\) is the probability associated to \(P_{k}\).Example
from itertools import product import numpy as np from qibo.gates.channels import PauliNoiseChannel qubits = (0, 2) nqubits = len(qubits) # excluding the Identity operator paulis = list(product(["I", "X"], repeat=nqubits))[1:] # this next line is optional paulis = [''.join(pauli) for pauli in paulis] probabilities = np.random.rand(len(paulis) + 1) probabilities /= np.sum(probabilities) #Excluding probability of Identity operator probabilities = probabilities[1:] channel = PauliNoiseChannel( qubits, list(zip(paulis, probabilities)) )
This channel can be simulated using either density matrices or state vectors and sampling with repeated execution. See How to perform noisy simulation? for more information.
Depolarizing channel#
- class qibo.gates.DepolarizingChannel(qubits, lam: float)#
\(n\)-qubit Depolarizing quantum error channel,
\[\mathcal{E}(\rho ) = (1 - \lambda) \rho + \lambda \text{Tr}_q[\rho]\otimes \frac{I}{2^n}\]where \(\lambda\) is the depolarizing error parameter and \(0 \le \lambda \le 4^n / (4^n - 1)\).
If \(\lambda = 1\) this is a completely depolarizing channel \(E(\rho) = I / 2^n\)
If \(\lambda = 4^n / (4^n - 1)\) this is a uniform Pauli error channel: \(E(\rho) = \sum_j P_j \rho P_j / (4^n - 1)\) for all \(P_j \neq I\).
Thermal relaxation channel#
- class qibo.gates.ThermalRelaxationChannel(qubit: int, parameters: list)#
Single-qubit thermal relaxation error channel.
Implements the following transformation:
If \(T_1 \geq T_2\):
\[\mathcal{E} (\rho ) = (1 - p_z - p_0 - p_1) \rho + p_z \, Z\rho Z + \mathrm{Tr}_{q}[\rho] \otimes (p_0 | 0\rangle \langle 0| + p_1|1\rangle \langle 1|)\]while if \(T_1 < T_2\):
\[\mathcal{E}(\rho ) = \mathrm{Tr}_\mathcal{X} \left[\Lambda_{\mathcal{X}\mathcal{Y}} (\rho_\mathcal{X}^T \otimes I_{\mathcal{Y}}) \right]\]with
\[\begin{split}\Lambda = \begin{pmatrix} 1 - p_1 & 0 & 0 & e^{-t / T_2} \\ 0 & p_1 & 0 & 0 \\ 0 & 0 & p_0 & 0 \\ e^{-t / T_2} & 0 & 0 & 1 - p_0 \end{pmatrix}\end{split}\]where \(p_0 = (1 - e^{-t / T_1})(1 - \eta )\), \(p_1 = (1 - e^{-t / T_1})\eta\), and \(p_z = (e^{-t / T_1} - e^{-t / T_2})/2\). Here \(\eta\) is the
excited_population
and \(t\) is thetime
, both controlled by the user. This gate is based on Qiskit’s thermal relaxation error channel.- Parameters:
qubit (int) – Qubit id that the noise channel acts on.
parameters (list) – list of 3 or 4 parameters (t_1, t_2, time, excited_population=0), where t_1 (float): T1 relaxation time. Should satisfy
t_1 > 0
. t_2 (float): T2 dephasing time. Should satisfyt_1 > 0
andt_2 < 2 * t_1
. time (float): the gate time for relaxation error. excited_population (float): the population of the excited state at equilibrium. Default is 0.
Amplitude damping channel#
- class qibo.gates.AmplitudeDampingChannel(qubit, gamma: float)#
Single-qubit amplitude damping channel in its Kraus representation, i.e.
\[\begin{split}K_{0} = \begin{pmatrix} 1 & 0 \\ 0 & \sqrt{1 - \gamma} \\ \end{pmatrix} \,\, , \,\, K_{1} = \begin{pmatrix} 0 & \sqrt{\gamma} \\ 0 & 0 \\ \end{pmatrix}\end{split}\]
Phase damping channel#
- class qibo.gates.PhaseDampingChannel(qubit, gamma: float)#
Single-qubit phase damping channel in its Kraus representation, i.e.
\[\begin{split}K_{0} = \begin{pmatrix} 1 & 0 \\ 0 & \sqrt{1 - \gamma} \\ \end{pmatrix} \,\, , \,\, K_{1} = \begin{pmatrix} 0 & 0 \\ 0 & \sqrt{\gamma} \\ \end{pmatrix}\end{split}\]
Readout error channel#
- class qibo.gates.ReadoutErrorChannel(qubits: Tuple[int, list, tuple], probabilities)#
Readout error channel implemented as a quantum-to-classical channel.
- Parameters:
Example
For 1 qubit, the transition matrix \(P\) would be
\[\begin{split}P = \begin{pmatrix} p(0 \, | \, 0) & p(1 \, | \, 0) \\ p(0 \, | \, 1) & p(1 \, | \, 1) \end{pmatrix} \, .\end{split}\]
Reset channel#
- class qibo.gates.ResetChannel(qubit, probabilities)#
Single-qubit reset channel.
Implements the following transformation:
\[\mathcal{E}(\rho ) = (1 - p_{0} - p_{1}) \rho + \mathrm{Tr}_{q}[\rho] \otimes (p_{0} \, |0\rangle \langle 0| + p_{1} \, |1\rangle \langle 1|),\]
Noise#
In Qibo it is possible to create a custom noise model using the
class qibo.noise.NoiseModel
. This enables the user to create
circuits where the noise is gate and qubit dependent.
For more information on the use of qibo.noise.NoiseModel
see
How to perform noisy simulation?
- class qibo.noise.NoiseModel#
Class for the implementation of a custom noise model.
Example:
from qibo import models, gates from qibo.noise import NoiseModel, PauliError # Build specific noise model with 2 quantum errors: # - Pauli error on H only for qubit 1. # - Pauli error on CNOT for all the qubits. noise = NoiseModel() noise.add(PauliError([("X", 0.5)]), gates.H, 1) noise.add(PauliError([("Y", 0.5)]), gates.CNOT) # Generate noiseless circuit. c = models.Circuit(2) c.add([gates.H(0), gates.H(1), gates.CNOT(0, 1)]) # Apply noise to the circuit according to the noise model. noisy_c = noise.apply(c)
- add(error, gate=None, qubits=None, condition=None)#
Add a quantum error for a specific gate and qubit to the noise model.
- Parameters:
error – quantum error to associate with the gate. Possible choices are
qibo.noise.PauliError
,qibo.noise.DepolarizingError
,qibo.noise.ThermalRelaxationError
,qibo.noise.AmplitudeDampingError
,qibo.noise.PhaseDampingError
,qibo.noise.ReadoutError
,qibo.noise.ResetError
,qibo.noise.UnitaryError
,qibo.noise.KrausError
andqibo.noise.CustomError
.gate (
qibo.gates.Gate
) – gate after which the noise will be added. IfNone
, the noise will be added after each gate exceptqibo.gates.Channel
andqibo.gates.M
.qubits (tuple) – qubits where the noise will be applied. If
None
, the noise will be added after every instance of the gate.condition (callable, optional) – function that takes
qibo.gates.Gate
object as an input and returnsTrue
if noise should be added to it.
Example:
import numpy as np from qibo import Circuit, gates from qibo.noise import NoiseModel, PauliError # Check if a gate is RX(pi/2). def is_sqrt_x(gate): return np.pi/2 in gate.parameters # Build a noise model with a Pauli error on RX(pi/2) gates. error = PauliError(list(zip(["X", "Y", "Z"], [0.01, 0.5, 0.1]))) noise = NoiseModel() noise.add(PauliError([("X", 0.5)]), gates.RX, condition=is_sqrt_x) # Generate a noiseless circuit. circuit = Circuit(1) circuit.add(gates.RX(0, np.pi / 2)) circuit.add(gates.RX(0, 3 * np.pi / 2)) circuit.add(gates.X(0)) # Apply noise to the circuit. noisy_circuit = noise.apply(circuit)
- composite(params)#
Build a noise model to simulate the noisy behaviour of a quantum computer.
- Parameters:
params (dict) –
contains the parameters of the channels organized as follow
{‘t1’ : (
t1
,t2
,…,tn
), ‘t2’ : (t1
,t2
,…,tn
), ‘gate time’ : (time1
,time2
), ‘excited population’ : 0, ‘depolarizing error’ : (lambda1
,lambda2
), ‘bitflips error’ : ([p1
,p2
,…,pm
],[p1
,p2
,…,pm
]), ‘idle_qubits’ : True} where n is the number of qubits, and m the number of measurement gates. The first four parameters are used by the thermal relaxation error. The first two elements are the tuple containing the \(T_1\) and \(T_2\) parameters; the third one is a tuple which contain the gate times, for single and two qubit gates; then we have the excited population parameter. The fifth parameter is a tuple containing the depolaraziong errors for single and 2 qubit gate. The sisxth parameter is a tuple containg the two arrays for bitflips probability errors: the first one implements 0->1 errors, the other one 1->0. The last parameter is a boolean variable: ifTrue
the noise model takes into account idle qubits.
- apply(circuit)#
Generate a noisy quantum circuit according to the noise model built.
- Parameters:
circuit (
qibo.models.circuit.Circuit
) – quantum circuit- Returns:
A (
qibo.models.circuit.Circuit
) which corresponds to the initial circuit with noise gates added according to the noise model.
Quantum errors#
The quantum errors available to build a noise model are the following:
- class qibo.noise.KrausError(ops)#
Quantum error associated with the
qibo.gates.KrausChannel
.- Parameters:
ops (list) – List of Kraus operators of type
np.ndarray
ortf.Tensor
and of the same shape.
- class qibo.noise.UnitaryError(probabilities, unitaries)#
Quantum error associated with the
qibo.gates.UnitaryChannel
.
- class qibo.noise.PauliError(operators)#
Quantum error associated with the
qibo.gates.PauliNoiseChannel
.- Parameters:
operators (list) – see
qibo.gates.PauliNoiseChannel
- class qibo.noise.DepolarizingError(lam)#
Quantum error associated with the
qibo.gates.DepolarizingChannel
.- Parameters:
options (float) – see
qibo.gates.DepolarizingChannel
- class qibo.noise.ThermalRelaxationError(t1, t2, time, excited_population=0)#
Quantum error associated with the
qibo.gates.ThermalRelaxationChannel
.- Parameters:
options (tuple) – see
qibo.gates.ThermalRelaxationChannel
- class qibo.noise.AmplitudeDampingError(gamma)#
Quantum error associated with the
qibo.gates.AmplitudeDampingChannel
.- Parameters:
options (float) – see
qibo.gates.AmplitudeDampingChannel
- class qibo.noise.PhaseDampingError(gamma)#
Quantum error associated with the
qibo.gates.PhaseDampingChannel
.- Parameters:
options (float) – see
qibo.gates.PhaseDampingChannel
- class qibo.noise.ReadoutError(probabilities)#
Quantum error associated with :class:’qibo.gates;ReadoutErrorChannel’.
- Parameters:
options (array) – see :class:’qibo.gates.ReadoutErrorChannel’
- class qibo.noise.ResetError(p0, p1)#
Quantum error associated with the qibo.gates.ResetChannel.
- Parameters:
options (tuple) – see
qibo.gates.ResetChannel
- class qibo.noise.CustomError(channel)#
Quantum error associated with the
qibo.gates.Channel
- Parameters:
channel (
qibo.gates.Channel
) – any channel
Example:
import numpy as np from qibo.gates import KrausChannel from qibo.noise import CustomError # define |0><0| a1 = np.array([[1, 0], [0, 0]]) # define |0><1| a2 = np.array([[0, 1], [0, 0]]) # Create an Error associated with Kraus Channel # rho -> |0><0| rho |0><0| + |0><1| rho |0><1| error = CustomError(gates.KrausChannel((0,), [a1, a2]))
Realistic noise model#
In Qibo, it is possible to build a realistic noise model of a real quantum computer
by using the qibo.noise.NoiseModel.composite()
method.
The noise model is built using a combination of the
qibo.gates.ThermalRelaxationChannel
and qibo.gates.DepolarizingChannel
channels. After each gate of the original circuit, the function applies a depolarizing
and a thermal relaxation channel. At the end of the circuit, if the qubit is measured,
bitflips errors are set. Moreover, the model handles idle qubits by applying a thermal
relaxation channel for the duration of the idle-time.
For more information on the qibo.noise.NoiseModel.composite()
method, see the
example on Simulating quantum hardware.
Hamiltonians#
The main abstract Hamiltonian object of Qibo is:
- class qibo.hamiltonians.abstract.AbstractHamiltonian#
Qibo abstraction for Hamiltonian objects.
- abstract eigenvalues(k=6)#
Computes the eigenvalues for the Hamiltonian.
- Parameters:
k (int) – Number of eigenvalues to calculate if the Hamiltonian was created using a sparse matrix. This argument is ignored if the Hamiltonian was created using a dense matrix. See
qibo.backends.abstract.AbstractBackend.eigvalsh()
for more details.
- abstract eigenvectors(k=6)#
Computes a tensor with the eigenvectors for the Hamiltonian.
- Parameters:
k (int) – Number of eigenvalues to calculate if the Hamiltonian was created using a sparse matrix. This argument is ignored if the Hamiltonian was created using a dense matrix. See
qibo.backends.abstract.AbstractBackend.eigh()
for more details.
- ground_state()#
Computes the ground state of the Hamiltonian.
Uses
qibo.hamiltonians.AbstractHamiltonian.eigenvectors()
and returns eigenvector corresponding to the lowest energy.
- abstract exp(a)#
Computes a tensor corresponding to exp(-1j * a * H).
- Parameters:
a (complex) – Complex number to multiply Hamiltonian before exponentiation.
- abstract expectation(state, normalize=False)#
Computes the real expectation value for a given state.
- Parameters:
state (array) – the expectation state.
normalize (bool) – If
True
the expectation value is divided with the state’s norm squared.
- Returns:
Real number corresponding to the expectation value.
- abstract expectation_from_samples(freq, qubit_map=None)#
Computes the real expectation value of a diagonal observable given the frequencies when measuring in the computational basis.
- Parameters:
freq (collections.Counter) – the keys are the observed values in binary form
frequencies (and the values the corresponding) –
number (that is the) –
appears. (of times each measured value/bitstring) –
qubit_map (tuple) – Mapping between frequencies and qubits. If None, [1,…,len(key)]
- Returns:
Real number corresponding to the expectation value.
Matrix Hamiltonian#
The first implementation of Hamiltonians uses the full matrix representation
of the Hamiltonian operator in the computational basis. This matrix has size
(2 ** nqubits, 2 ** nqubits)
and therefore its construction is feasible
only when number of qubits is small.
Alternatively, the user can construct this Hamiltonian using a sparse matrices.
Sparse matrices from the
scipy.sparse
module are supported by the numpy
and qibojit
backends while the
tensorflow.sparse can be
used for tensorflow
. Scipy sparse matrices support algebraic
operations (addition, subtraction, scalar multiplication), linear algebra
operations (eigenvalues, eigenvectors, matrix exponentiation) and
multiplication to dense or other sparse matrices. All these properties are
inherited by qibo.hamiltonians.Hamiltonian
objects created
using sparse matrices. Tensorflow sparse matrices support only multiplication
to dense matrices. Both backends support calculating Hamiltonian expectation
values using a sparse Hamiltonian matrix.
- class qibo.hamiltonians.Hamiltonian(nqubits, matrix=None, backend=None)#
Hamiltonian based on a dense or sparse matrix representation.
- Parameters:
nqubits (int) – number of quantum bits.
matrix (np.ndarray) – Matrix representation of the Hamiltonian in the computational basis as an array of shape
(2 ** nqubits, 2 ** nqubits)
. Sparse matrices based onscipy.sparse
for numpy/qibojit backends or ontf.sparse
for the tensorflow backend are also supported.
- property matrix#
Returns the full matrix representation.
Can be a dense
(2 ** nqubits, 2 ** nqubits)
array or a sparse matrix, depending on how the Hamiltonian was created.
- classmethod from_symbolic(symbolic_hamiltonian, symbol_map, backend=None)#
Creates a
Hamiltonian
from a symbolic Hamiltonian.We refer to the How to define custom Hamiltonians using symbols? example for more details.
- Parameters:
symbolic_hamiltonian (sympy.Expr) – The full Hamiltonian written with symbols.
symbol_map (dict) – Dictionary that maps each symbol that appears in the Hamiltonian to a pair of (target, matrix).
- Returns:
A
qibo.hamiltonians.SymbolicHamiltonian
object that implements the Hamiltonian represented by the given symbolic expression.
- eigenvalues(k=6)#
Computes the eigenvalues for the Hamiltonian.
- Parameters:
k (int) – Number of eigenvalues to calculate if the Hamiltonian was created using a sparse matrix. This argument is ignored if the Hamiltonian was created using a dense matrix. See
qibo.backends.abstract.AbstractBackend.eigvalsh()
for more details.
- eigenvectors(k=6)#
Computes a tensor with the eigenvectors for the Hamiltonian.
- Parameters:
k (int) – Number of eigenvalues to calculate if the Hamiltonian was created using a sparse matrix. This argument is ignored if the Hamiltonian was created using a dense matrix. See
qibo.backends.abstract.AbstractBackend.eigh()
for more details.
- exp(a)#
Computes a tensor corresponding to exp(-1j * a * H).
- Parameters:
a (complex) – Complex number to multiply Hamiltonian before exponentiation.
- expectation(state, normalize=False)#
Computes the real expectation value for a given state.
- Parameters:
state (array) – the expectation state.
normalize (bool) – If
True
the expectation value is divided with the state’s norm squared.
- Returns:
Real number corresponding to the expectation value.
- expectation_from_samples(freq, qubit_map=None)#
Computes the real expectation value of a diagonal observable given the frequencies when measuring in the computational basis.
- Parameters:
freq (collections.Counter) – the keys are the observed values in binary form
frequencies (and the values the corresponding) –
number (that is the) –
appears. (of times each measured value/bitstring) –
qubit_map (tuple) – Mapping between frequencies and qubits. If None, [1,…,len(key)]
- Returns:
Real number corresponding to the expectation value.
Symbolic Hamiltonian#
Qibo allows the user to define Hamiltonians using sympy
symbols. In this
case the full Hamiltonian matrix is not constructed unless this is required.
This makes the implementation more efficient for larger qubit numbers.
For more information on constructing Hamiltonians using symbols we refer to the
How to define custom Hamiltonians using symbols? example.
- class qibo.hamiltonians.SymbolicHamiltonian(form=None, nqubits=None, symbol_map={}, backend=None)#
Hamiltonian based on a symbolic representation.
Calculations using symbolic Hamiltonians are either done directly using the given
sympy
expression as it is (form
) or by parsing the correspondingterms
(which areqibo.core.terms.SymbolicTerm
objects). The latter approach is more computationally costly as it uses asympy.expand
call on the given form before parsing the terms. For this reason theterms
are calculated only when needed, for example during Trotterization. The dense matrix of the symbolic Hamiltonian can be calculated directly fromform
without requiringterms
calculation (seeqibo.core.hamiltonians.SymbolicHamiltonian.calculate_dense()
for details).- Parameters:
form (sympy.Expr) – Hamiltonian form as a
sympy.Expr
. Ideally the Hamiltonian should be written using Qibo symbols. See How to define custom Hamiltonians using symbols? example for more details.symbol_map (dict) – Dictionary that maps each
sympy.Symbol
to a tuple of (target qubit, matrix representation). This feature is kept for compatibility with older versions where Qibo symbols were not available and may be deprecated in the future. It is not required if the Hamiltonian is constructed using Qibo symbols. The symbol_map can also be used to pass non-quantum operator arguments to the symbolic Hamiltonian, such as the parameters in theqibo.hamiltonians.models.MaxCut()
Hamiltonian.
- property dense#
Creates the equivalent
qibo.hamiltonians.MatrixHamiltonian
.
- property terms#
List of
qibo.core.terms.HamiltonianTerm
objects of which the Hamiltonian is a sum of.
- property matrix#
Returns the full
(2 ** nqubits, 2 ** nqubits)
matrix representation.
- eigenvalues(k=6)#
Computes the eigenvalues for the Hamiltonian.
- Parameters:
k (int) – Number of eigenvalues to calculate if the Hamiltonian was created using a sparse matrix. This argument is ignored if the Hamiltonian was created using a dense matrix. See
qibo.backends.abstract.AbstractBackend.eigvalsh()
for more details.
- eigenvectors(k=6)#
Computes a tensor with the eigenvectors for the Hamiltonian.
- Parameters:
k (int) – Number of eigenvalues to calculate if the Hamiltonian was created using a sparse matrix. This argument is ignored if the Hamiltonian was created using a dense matrix. See
qibo.backends.abstract.AbstractBackend.eigh()
for more details.
- ground_state()#
Computes the ground state of the Hamiltonian.
Uses
qibo.hamiltonians.AbstractHamiltonian.eigenvectors()
and returns eigenvector corresponding to the lowest energy.
- exp(a)#
Computes a tensor corresponding to exp(-1j * a * H).
- Parameters:
a (complex) – Complex number to multiply Hamiltonian before exponentiation.
- expectation(state, normalize=False)#
Computes the real expectation value for a given state.
- Parameters:
state (array) – the expectation state.
normalize (bool) – If
True
the expectation value is divided with the state’s norm squared.
- Returns:
Real number corresponding to the expectation value.
- expectation_from_samples(freq, qubit_map=None)#
Computes the real expectation value of a diagonal observable given the frequencies when measuring in the computational basis.
- Parameters:
freq (collections.Counter) – the keys are the observed values in binary form
frequencies (and the values the corresponding) –
number (that is the) –
appears. (of times each measured value/bitstring) –
qubit_map (tuple) – Mapping between frequencies and qubits. If None, [1,…,len(key)]
- Returns:
Real number corresponding to the expectation value.
- apply_gates(state, density_matrix=False)#
Applies gates corresponding to the Hamiltonian terms to a given state. Helper method for
__matmul__
.
- circuit(dt, accelerators=None)#
Circuit that implements a Trotter step of this Hamiltonian for a given time step
dt
.
When a qibo.hamiltonians.SymbolicHamiltonian
is used for time
evolution then Qibo will automatically perform this evolution using the Trotter
of the evolution operator. This is done by automatically splitting the Hamiltonian
to sums of commuting terms, following the description of Sec. 4.1 of
arXiv:1901.05824.
For more information on time evolution we refer to the
How to simulate time evolution? example.
In addition to the abstract Hamiltonian models, Qibo provides the following pre-coded Hamiltonians:
Heisenberg XXZ#
- class qibo.hamiltonians.XXZ(nqubits, delta=0.5, dense=True, backend=None)#
Heisenberg XXZ model with periodic boundary conditions.
\[H = \sum _{i=0}^N \left ( X_iX_{i + 1} + Y_iY_{i + 1} + \delta Z_iZ_{i + 1} \right ).\]- Parameters:
Example
from qibo.hamiltonians import XXZ h = XXZ(3) # initialized XXZ model with 3 qubits
Non-interacting Pauli-X#
- class qibo.hamiltonians.X(nqubits, dense=True, backend=None)#
Non-interacting Pauli-X Hamiltonian.
\[H = - \sum _{i=0}^N X_i.\]
Non-interacting Pauli-Y#
- class qibo.hamiltonians.Y(nqubits, dense=True, backend=None)#
Non-interacting Pauli-Y Hamiltonian.
\[H = - \sum _{i=0}^N Y_i.\]
Non-interacting Pauli-Z#
- class qibo.hamiltonians.Z(nqubits, dense=True, backend=None)#
Non-interacting Pauli-Z Hamiltonian.
\[H = - \sum _{i=0}^N Z_i.\]
Transverse field Ising model#
- class qibo.hamiltonians.TFIM(nqubits, h=0.0, dense=True, backend=None)#
Transverse field Ising model with periodic boundary conditions.
\[H = - \sum _{i=0}^N \left ( Z_i Z_{i + 1} + h X_i \right ).\]
Max Cut#
- class qibo.hamiltonians.MaxCut(nqubits, dense=True, backend=None)#
Max Cut Hamiltonian.
\[H = - \sum _{i,j=0}^N \frac{1 - Z_i Z_j}{2}.\]
Note
All pre-coded Hamiltonians can be created as
qibo.hamiltonians.Hamiltonian
using dense=True
or qibo.hamiltonians.SymbolicHamiltonian
using the dense=False
. In the first case the Hamiltonian is created
using its full matrix representation of size (2 ** n, 2 ** n)
where n
is the number of qubits that the Hamiltonian acts on. This
matrix is used to calculate expectation values by direct matrix multiplication
to the state and for time evolution by exact exponentiation.
In contrast, when dense=False
the Hamiltonian contains a more compact
representation as a sum of local terms. This compact representation can be
used to calculate expectation values via a sum of the local term expectations
and time evolution via the Trotter decomposition of the evolution operator.
This is useful for systems that contain many qubits for which constructing
the full matrix is intractable.
Symbols#
Qibo provides a basic set of symbols which inherit the sympy.Symbol
object
and can be used to construct qibo.hamiltonians.SymbolicHamiltonian
objects as described in the previous section.
- class qibo.symbols.Symbol(q, matrix=None, name='Symbol', commutative=False, **assumptions)#
Qibo specialization for
sympy
symbols.These symbols can be used to create
qibo.hamiltonians.hamiltonians.SymbolicHamiltonian
. See How to define custom Hamiltonians using symbols? for more details.Example
from qibo import hamiltonians from qibo.symbols import X, Y, Z # construct a XYZ Hamiltonian on two qubits using Qibo symbols form = X(0) * X(1) + Y(0) * Y(1) + Z(0) * Z(1) ham = hamiltonians.SymbolicHamiltonian(form)
- Parameters:
q (int) – Target qubit id.
matrix (np.ndarray) – 2x2 matrix represented by this symbol.
name (str) – Name of the symbol which defines how it is represented in symbolic expressions.
commutative (bool) – If
True
the constructed symbols commute with each other. Default isFalse
. This argument should be used with caution because quantum operators are not commutative objects and therefore switching this toTrue
may lead to wrong results. It is useful for improving performance in symbolic calculations in cases where the user is sure that the operators participating in the Hamiltonian form are commuting (for example when the Hamiltonian consists of Z terms only).
- property gate#
Qibo gate that implements the action of the symbol on states.
- full_matrix(nqubits)#
Calculates the full dense matrix corresponding to the symbol as part of a bigger system.
- Parameters:
nqubits (int) – Total number of qubits in the system.
- Returns:
Matrix of dimension (2^nqubits, 2^nqubits) composed of the Kronecker product between identities and the symbol’s single-qubit matrix.
- class qibo.symbols.X(q, commutative=False, **assumptions)#
Qibo symbol for the Pauli-X operator.
- Parameters:
q (int) – Target qubit id.
- class qibo.symbols.Y(q, commutative=False, **assumptions)#
Qibo symbol for the Pauli-X operator.
- Parameters:
q (int) – Target qubit id.
- class qibo.symbols.Z(q, commutative=False, **assumptions)#
Qibo symbol for the Pauli-X operator.
- Parameters:
q (int) – Target qubit id.
States#
Qibo circuits return qibo.states.CircuitResult
objects
when executed. By default, Qibo works as a wave function simulator in the sense
that propagates the state vector through the circuit applying the
corresponding gates. In this default usage the result of a circuit execution
is the full final state vector which can be accessed via qibo.states.CircuitResult.state()
.
However, for specific applications it is useful to have measurement samples
from the final wave function, instead of its full vector form.
To that end, qibo.states.CircuitResult
provides the
qibo.states.CircuitResult.samples()
and
qibo.states.CircuitResult.frequencies()
methods.
The state vector (or density matrix) is saved in memory as a tensor supported
by the currently active backend (see Backends for more information).
A copy of the state can be created using qibo.states.CircuitResult.copy()
.
The new state will point to the same tensor in memory as the original one unless
the deep=True
option was used during the copy
call.
Note that the qibojit backend performs in-place updates
state is used as input to a circuit or time evolution. This will modify the
state’s tensor and the tensor of all shallow copies and the current state vector
values will be lost. If you intend to keep the current state values,
we recommend creating a deep copy before using it as input to a qibo model.
In order to perform measurements the user has to add the measurement gate
qibo.gates.M
to the circuit and then execute providing a number
of shots. If this is done, the qibo.states.CircuitResult
returned by the circuit will contain the measurement samples.
For more information on measurements we refer to the How to perform measurements? example.
Circuit result#
- class qibo.states.CircuitResult(backend, circuit, execution_result, nshots=None)#
Data structure returned by circuit execution.
Contains all the results produced by the circuit execution, such as the state vector or density matrix, measurement samples and frequencies.
- Parameters:
backend (
qibo.backends.abstract.AbstractBackend
) – Backend to use for calculations.circuit (
qibo.models.Circuit
) – Circuit object that is producing this result.execution_result – Abstract raw data created by the circuit execution. The format of these data depends on the backend and they are processed by the backend. For simulation backends
execution_result
is a tensor holding the state vector or density matrix representation in the computational basis.nshots (int) – Number of measurement shots, if measurements are performed.
- state(numpy=False, decimals=-1, cutoff=1e-10, max_terms=20)#
State’s tensor representation as an backend tensor.
- Parameters:
numpy (bool) – If
True
the returned tensor will be a numpy array, otherwise it will follow the backend tensor type. Default isFalse
.decimals (int) – If positive the Dirac representation of the state in the computational basis will be returned as a string.
decimals
will be the number of decimals of each amplitude. Default is -1.cutoff (float) – Amplitudes with absolute value smaller than the cutoff are ignored from the Dirac representation. Ignored if
decimals < 0
. Default is 1e-10.max_terms (int) – Maximum number of terms in the Dirac representation. If the state contains more terms they will be ignored. Ignored if
decimals < 0
. Default is 20.
- Returns:
If
decimals < 0
a tensor representing the state in the computational basis, otherwise a string with the Dirac representation of the state in the computational basis.
- symbolic(decimals=5, cutoff=1e-10, max_terms=20)#
Dirac notation representation of the state in the computational basis.
- Parameters:
decimals (int) – Number of decimals for the amplitudes. Default is 5.
cutoff (float) – Amplitudes with absolute value smaller than the cutoff are ignored from the representation. Default is 1e-10.
max_terms (int) – Maximum number of terms to print. If the state contains more terms they will be ignored. Default is 20.
- Returns:
A string representing the state in the computational basis.
- probabilities(qubits=None)#
Calculates measurement probabilities by tracing out qubits. When noisy model is applied to a circuit and circuit.density_matrix=False, this method returns the average probability resulting from repeated execution. This probability distribution approximates the exact probability distribution obtained when circuit.density_matrix=True.
- property measurement_gate#
Single measurement gate containing all measured qubits.
Useful for sampling all measured qubits at once when simulating.
- samples(binary=True, registers=False)#
Returns raw measurement samples.
- Parameters:
- Returns:
- If binary is True
samples are returned in binary form as a tensor of shape (nshots, n_measured_qubits).
- If binary is False
samples are returned in decimal form as a tensor of shape (nshots,).
- If registers is True
samples are returned in a dict where the keys are the register names and the values are the samples tensors for each register.
- If registers is False
a single tensor is returned which contains samples from all the measured qubits, independently of their registers.
- frequencies(binary=True, registers=False)#
Returns the frequencies of measured samples.
- Parameters:
- Returns:
A collections.Counter where the keys are the observed values and the values the corresponding frequencies, that is the number of times each measured value/bitstring appears.
- If binary is True
the keys of the Counter are in binary form, as strings of 0s and 1s.
- If binary is False
the keys of the Counter are integers.
- If registers is True
a dict of Counter s is returned where keys are the name of each register.
- If registers is False
a single Counter is returned which contains samples from all the measured qubits, independently of their registers.
- expectation_from_samples(observable)#
Computes the real expectation value of a diagonal observable from frequencies.
- Parameters:
observable (Hamiltonian/SymbolicHamiltonian) – diagonal observable in the computational basis.
- Returns:
Real number corresponding to the expectation value.
Callbacks#
Callbacks provide a way to calculate quantities on the state vector as it
propagates through the circuit. Example of such quantity is the entanglement
entropy, which is currently the only callback implemented in
qibo.callbacks.EntanglementEntropy
.
The user can create custom callbacks by inheriting the
qibo.callbacks.Callback
class. The point each callback is
calculated inside the circuit is defined by adding a qibo.gates.CallbackGate
.
This can be added similarly to a standard gate and does not affect the state vector.
- class qibo.callbacks.Callback#
Base callback class.
Results of a callback can be accessed by indexing the corresponding object.
- property nqubits#
Total number of qubits in the circuit that the callback was added in.
Entanglement entropy#
- class qibo.callbacks.EntanglementEntropy(partition: List[int] | None = None, compute_spectrum: bool = False)#
Von Neumann entanglement entropy callback.
\[S = \mathrm{Tr} \left ( \rho \log _2 \rho \right )\]- Parameters:
Example
from qibo import models, gates, callbacks # create entropy callback where qubit 0 is the first subsystem entropy = callbacks.EntanglementEntropy([0], compute_spectrum=True) # initialize circuit with 2 qubits and add gates c = models.Circuit(2) # add callback gates between normal gates c.add(gates.CallbackGate(entropy)) c.add(gates.H(0)) c.add(gates.CallbackGate(entropy)) c.add(gates.CNOT(0, 1)) c.add(gates.CallbackGate(entropy)) # execute the circuit final_state = c() print(entropy[:]) # Should print [0, 0, 1] which is the entanglement entropy # after every gate in the calculation. print(entropy.spectrum) # Print the entanglement spectrum.
- property nqubits#
Total number of qubits in the circuit that the callback was added in.
Norm#
- class qibo.callbacks.Norm#
State norm callback.
\[\mathrm{Norm} = \left \langle \Psi | \Psi \right \rangle = \mathrm{Tr} (\rho )\]
Overlap#
- class qibo.callbacks.Overlap(state)#
State overlap callback.
Calculates the overlap between the circuit state and a given target state:
\[\mathrm{Overlap} = |\left \langle \Phi | \Psi \right \rangle |\]- Parameters:
state (np.ndarray) – Target state to calculate overlap with.
normalize (bool) – If
True
the states are normalized for the overlap calculation.
Energy#
- class qibo.callbacks.Energy(hamiltonian: hamiltonians.Hamiltonian)#
Energy expectation value callback.
Calculates the expectation value of a given Hamiltonian as:
\[\left \langle H \right \rangle = \left \langle \Psi | H | \Psi \right \rangle = \mathrm{Tr} (\rho H)\]assuming that the state is normalized.
- Parameters:
hamiltonian (
qibo.hamiltonians.Hamiltonian
) – Hamiltonian object to calculate its expectation value.
Gap#
- class qibo.callbacks.Gap(mode: str | int = 'gap', check_degenerate: bool = True)#
Callback for calculating the gap of adiabatic evolution Hamiltonians.
Can also be used to calculate the Hamiltonian eigenvalues at each time step during the evolution. Note that this callback can only be added in
qibo.evolution.AdiabaticEvolution
models.- Parameters:
mode (str/int) – Defines which quantity this callback calculates. If
mode == 'gap'
then the difference between ground state and first excited state energy (gap) is calculated. Ifmode
is an integer, then the energy of the corresponding eigenstate is calculated.check_degenerate (bool) – If
True
the excited state number is increased until a non-zero gap is found. This is used to find the proper gap in the case of degenerate Hamiltonians. This flag is relevant only ifmode
is'gap'
. Default isTrue
.
Example
from qibo import callbacks, hamiltonians from qibo.models import AdiabaticEvolution # define easy and hard Hamiltonians for adiabatic evolution h0 = hamiltonians.X(3) h1 = hamiltonians.TFIM(3, h=1.0) # define callbacks for logging the ground state, first excited # and gap energy ground = callbacks.Gap(0) excited = callbacks.Gap(1) gap = callbacks.Gap() # define and execute the ``AdiabaticEvolution`` model evolution = AdiabaticEvolution(h0, h1, lambda t: t, dt=1e-1, callbacks=[gap, ground, excited]) final_state = evolution(final_time=1.0) # print results print(ground[:]) print(excited[:]) print(gap[:])
Solvers#
Solvers are used to numerically calculate the time evolution of state vectors. They perform steps in time by integrating the time-dependent Schrodinger equation.
- class qibo.solvers.BaseSolver(dt, hamiltonian)#
Basic solver that should be inherited by all solvers.
- Parameters:
dt (float) – Time step size.
hamiltonian (
qibo.hamiltonians.abstract.AbstractHamiltonian
) – Hamiltonian object that the state evolves under.
- property t#
Solver’s current time.
- class qibo.solvers.TrotterizedExponential(dt, hamiltonian)#
Solver that uses Trotterized exponentials.
Created automatically from the
qibo.solvers.Exponential
if the given Hamiltonian object is aqibo.hamiltonians.hamiltonians.TrotterHamiltonian
.
- class qibo.solvers.Exponential(dt, hamiltonian)#
Solver that uses the matrix exponential of the Hamiltonian:
\[U(t) = e^{-i H(t) \delta t}\]Calculates the evolution operator in every step and thus is compatible with time-dependent Hamiltonians.
- class qibo.solvers.RungeKutta4(dt, hamiltonian)#
Solver based on the 4th order Runge-Kutta method.
- class qibo.solvers.RungeKutta45(dt, hamiltonian)#
Solver based on the 5th order Runge-Kutta method.
Optimizers#
Optimizers are used automatically by the minimize
methods of
qibo.models.VQE
and qibo.evolution.AdiabaticEvolution
models.
The user does not have to use any of the optimizer methods included in the
current section, however the required options of each optimization method
can be passed when calling the minimize
method of the respective Qibo
variational model.
- qibo.optimizers.optimize(loss, initial_parameters, args=(), method='Powell', jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None, compile=False, processes=None, backend=None)#
- Main optimization method. Selects one of the following optimizers:
- Parameters:
loss (callable) – Loss as a function of
parameters
and optional extra arguments. Make sure the loss function returns a tensor formethod=sgd
and numpy object for all the other methods.initial_parameters (np.ndarray) – Initial guess for the variational parameters that are optimized.
args (tuple) – optional arguments for the loss function.
method (str) – Name of optimizer to use. Can be
'cma'
,'sgd'
or one of the Newtonian methods supported byqibo.optimizers.newtonian()
and'parallel_L-BFGS-B'
.sgd
is only available for backends based on tensorflow.jac (dict) – Method for computing the gradient vector for scipy optimizers.
hess (dict) – Method for computing the hessian matrix for scipy optimizers.
hessp (callable) – Hessian of objective function times an arbitrary vector for scipy optimizers.
bounds (sequence or Bounds) – Bounds on variables for scipy optimizers.
constraints (dict) – Constraints definition for scipy optimizers.
tol (float) – Tolerance of termination for scipy optimizers.
callback (callable) – Called after each iteration for scipy optimizers.
options (dict) – Dictionary with options. See the specific optimizer bellow for a list of the supported options.
compile (bool) – If
True
the Tensorflow optimization graph is compiled. This is relevant only for the'sgd'
optimizer.processes (int) – number of processes when using the parallel BFGS method.
- Returns:
Final best loss value; best parameters obtained by the optimizer; extra: optimizer-specific return object. For scipy methods it returns the
OptimizeResult
, for'cma'
theCMAEvolutionStrategy.result
, and for'sgd'
the options used during the optimization.- Return type:
Example
import numpy as np from qibo import gates, models from qibo.optimizers import optimize # create custom loss function # make sure the return type matches the optimizer requirements. def myloss(parameters, circuit): circuit.set_parameters(parameters) return np.square(np.sum(circuit())) # returns numpy array # create circuit ansatz for two qubits circuit = models.Circuit(2) circuit.add(gates.RY(0, theta=0)) # optimize using random initial variational parameters initial_parameters = np.random.uniform(0, 2, 1) best, params, extra = optimize(myloss, initial_parameters, args=(circuit)) # set parameters to circuit circuit.set_parameters(params)
- qibo.optimizers.cmaes(loss, initial_parameters, args=(), options=None)#
Genetic optimizer based on pycma.
- Parameters:
loss (callable) – Loss as a function of variational parameters to be optimized.
initial_parameters (np.ndarray) – Initial guess for the variational parameters.
args (tuple) – optional arguments for the loss function.
options (dict) – Dictionary with options accepted by the
cma
optimizer. The user can useimport cma; cma.CMAOptions()
to view the available options.
- qibo.optimizers.newtonian(loss, initial_parameters, args=(), method='Powell', jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None, processes=None, backend=None)#
Newtonian optimization approaches based on
scipy.optimize.minimize
.For more details check the scipy documentation.
Note
When using the method
parallel_L-BFGS-B
theprocesses
option controls the number of processes used by the parallel L-BFGS-B algorithm through themultiprocessing
library. By defaultprocesses=None
, in this case the total number of logical cores are used. Make sure to select the appropriate number of processes for your computer specification, taking in consideration memory and physical cores. In order to obtain optimal results you can control the number of threads used by each process with theqibo.set_threads
method. For example, for small-medium size circuits you may benefit from single thread per process, thus setqibo.set_threads(1)
before running the optimization.- Parameters:
loss (callable) – Loss as a function of variational parameters to be optimized.
initial_parameters (np.ndarray) – Initial guess for the variational parameters.
args (tuple) – optional arguments for the loss function.
method (str) – Name of method supported by
scipy.optimize.minimize
and'parallel_L-BFGS-B'
for a parallel version of L-BFGS-B algorithm.jac (dict) – Method for computing the gradient vector for scipy optimizers.
hess (dict) – Method for computing the hessian matrix for scipy optimizers.
hessp (callable) – Hessian of objective function times an arbitrary vector for scipy optimizers.
bounds (sequence or Bounds) – Bounds on variables for scipy optimizers.
constraints (dict) – Constraints definition for scipy optimizers.
tol (float) – Tolerance of termination for scipy optimizers.
callback (callable) – Called after each iteration for scipy optimizers.
options (dict) – Dictionary with options accepted by
scipy.optimize.minimize
.processes (int) – number of processes when using the parallel BFGS method.
- qibo.optimizers.sgd(loss, initial_parameters, args=(), options=None, compile=False, backend=None)#
Stochastic Gradient Descent (SGD) optimizer using Tensorflow backpropagation.
See tf.keras.Optimizers for a list of the available optimizers.
- Parameters:
loss (callable) – Loss as a function of variational parameters to be optimized.
initial_parameters (np.ndarray) – Initial guess for the variational parameters.
args (tuple) – optional arguments for the loss function.
options (dict) –
Dictionary with options for the SGD optimizer. Supports the following keys:
'optimizer'
(str, default:'Adagrad'
): Name of optimizer.'learning_rate'
(float, default:'1e-3'
): Learning rate.'nepochs'
(int, default:1e6
): Number of epochs for optimization.'nmessage'
(int, default:1e3
): Every how many epochs to print a message of the loss function.
Gradients#
In the context of optimization, particularly when dealing with Quantum Machine Learning problems, it is often necessary to calculate the gradients of functions that are to be minimized (or maximized). Hybrid methods, which are based on the use of classical techniques for the optimization of quantum computation procedures, have been presented in the previous section. This approach is very useful in simulation, but some classical methods cannot be used when using real circuits: for example, in the context of neural networks, the Back-Propagation algorithm is used, where it is necessary to know the value of a target function during the propagation of information within the network. Using a real circuit, we would not be able to access this information without taking a measurement, causing the state of the system to collapse and losing the information accumulated up to that moment. For this reason, in qibo we have also implemented methods for calculating the gradients which can be performed directly on the hardware, such as the Parameter Shift Rule.
- qibo.derivative.parameter_shift(circuit, hamiltonian, parameter_index, initial_state=None, scale_factor=1, nshots=None)#
In this method the parameter shift rule (PSR) is implemented. Given a circuit U and an observable H, the PSR allows to calculate the derivative of the expected value of H on the final state with respect to a variational parameter of the circuit. There is also the possibility of setting a scale factor. It is useful when a circuit’s parameter is obtained by combination of a variational parameter and an external object, such as a training variable in a Quantum Machine Learning problem. For example, performing a re-uploading strategy to embed some data into a circuit, we apply to the quantum state rotations whose angles are in the form: theta’ = theta * x, where theta is a variational parameter and x an input variable. The PSR allows to calculate the derivative with respect of theta’ but, if we want to optimize a system with respect its variational parameters we need to “free” this procedure from the x depencency. If the scale_factor is not provided, it is set equal to one and doesn’t affect the calculation. If the PSR is needed to be executed on a real quantum device, it is important to set nshots to some integer value. This enables the execution on the hardware by calling the proper methods.
- Parameters:
circuit (
qibo.models.circuit.Circuit
) – custom quantum circuit.hamiltonian (
qibo.hamiltonians.Hamiltonian
) – target observable. if you want to execute on hardware, a symbolic hamiltonian must be provided as follows (example with Pauli Z andnqubits=1
):SymbolicHamiltonian(np.prod([ Z(i) for i in range(1) ]))
.parameter_index (int) – the index which identifies the target parameter in the
circuit.get_parameters()
list.initial_state (ndarray, optional) – initial state on which the circuit acts. Default is
None
.scale_factor (float, optional) – parameter scale factor. Default is
1
.nshots (int, optional) – number of shots if derivative is evaluated on hardware. If
None
, the simulation mode is executed. Default isNone
.
- Returns:
- Value of the derivative of the expectation value of the hamiltonian
with respect to the target variational parameter.
- Return type:
(float)
Example
import qibo import numpy as np from qibo import Circuit, gates, hamiltonians from qibo.derivative import parameter_shift # defining an observable def hamiltonian(nqubits = 1): m0 = (1/nqubits)*hamiltonians.Z(nqubits).matrix ham = hamiltonians.Hamiltonian(nqubits, m0) return ham # defining a dummy circuit def circuit(nqubits = 1): c = Circuit(nqubits = 1) c.add(gates.RY(q = 0, theta = 0)) c.add(gates.RX(q = 0, theta = 0)) c.add(gates.M(0)) return c # initializing the circuit c = circuit(nqubits = 1) # some parameters test_params = np.random.randn(2) c.set_parameters(test_params) test_hamiltonian = hamiltonian() # running the psr with respect to the two parameters grad_0 = parameter_shift(circuit=c, hamiltonian=test_hamiltonian, parameter_index=0) grad_1 = parameter_shift(circuit=c, hamiltonian=test_hamiltonian, parameter_index=1)
- qibo.derivative.finite_differences(circuit, hamiltonian, parameter_index, initial_state=None, step_size=1e-07)#
Calculate derivative of the expectation value of hamiltonian on the final state obtained by executing circuit on initial_state with respect to the variational parameter identified by parameter_index in the circuit’s parameters list. This method can be used only in exact simulation mode.
- Parameters:
circuit (
qibo.models.circuit.Circuit
) – custom quantum circuit.hamiltonian (
qibo.hamiltonians.Hamiltonian
) – target observable. if you want to execute on hardware, a symbolic hamiltonian must be provided as follows (example with Pauli Z andnqubits=1
):SymbolicHamiltonian(np.prod([ Z(i) for i in range(1) ]))
.parameter_index (int) – the index which identifies the target parameter in the
circuit.get_parameters()
list.initial_state (ndarray, optional) – initial state on which the circuit acts. Default is
None
.step_size (float) – step size used to evaluate the finite difference (default 1e-7).
- Returns:
- Value of the derivative of the expectation value of the hamiltonian
with respect to the target variational parameter.
- Return type:
(float)
Quantum Information#
This module provides tools for generation and analysis of quantum (and classical) information.
Basis#
Set of functions related to basis and basis transformations.
Pauli basis#
- qibo.quantum_info.pauli_basis(nqubits: int, normalize: bool = False, vectorize: bool = False, sparse: bool = False, order: str | None = None, pauli_order: str = 'IXYZ', backend=None)#
Creates the
nqubits
-qubit Pauli basis.- Parameters:
nqubits (int) – number of qubits.
normalize (bool, optional) – If
True
, normalized basis is returned. Defaults to False.vectorize (bool, optional) – If
False
, returns a nested array with all Pauli matrices. IfTrue
, retuns an array where every row is a vectorized Pauli matrix. Defaults toFalse
.sparse (bool, optional) – representation. Default is
False
.order (str, optional) – If
"row"
, vectorization of Pauli basis is performed row-wise. If"column"
, vectorization is performed column-wise. If"system"
, system-wise vectorization is performed. Ifvectorization=False
, thenorder=None
is forced. Default isNone
.pauli_order (str, optional) – corresponds to the order of 4 single-qubit Pauli elements. Default is “IXYZ”.
backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
- all Pauli matrices forming the basis. If
sparse=True
and
vectorize=True
, tuple is composed of an array of non-zero elements and an array with their row-wise indexes.
- all Pauli matrices forming the basis. If
- Return type:
ndarray or tuple
Computational basis to Pauli basis#
- qibo.quantum_info.comp_basis_to_pauli(nqubits: int, normalize: bool = False, sparse: bool = False, order: str = 'row', pauli_order: str = 'IXYZ', backend=None)#
Unitary matrix \(U\) that converts operators from the Liouville representation in the computational basis to the Pauli-Liouville representation.
The unitary \(U\) is given by
\[U = \sum_{k = 0}^{d^{2} - 1} \, \ketbra{k}{P_{k}} \,\, ,\]where \(\ket{P_{k}}\) is the system-vectorization of the \(k\)-th Pauli operator \(P_{k}\), and \(\ket{k}\) is the computational basis element.
When converting a state \(\ket{\rho}\) to its Pauli-Liouville representation \(\ket{\rho'}\), one should use
order="system"
invectorization()
.Example
from qibo.quantum_info import random_density_matrix, vectorization, comp_basis_to_pauli nqubits = 2 d = 2**nqubits rho = random_density_matrix(d) U_c2p = comp_basis_to_pauli(nqubits) rho_liouville = vectorization(rho, order="system") rho_pauli_liouville = U_c2p @ rho_liouville
- Parameters:
nqubits (int) – number of qubits.
normalize (bool, optional) – If
True
, converts to the Pauli basis. Defaults toFalse
.sparse (bool, optional) – If
True
, returns unitary matrix in sparse representation. Default isFalse
.order (str, optional) – If
"row"
, vectorization of Pauli basis is performed row-wise. If"column"
, vectorization is performed column-wise. If"system"
, system-wise vectorization is performed. Default is"row"
.pauli_order (str, optional) – corresponds to the order of 4 single-qubit Pauli elements. Default is “IXYZ”.
backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
- Unitary matrix \(U\). If
sparse=True
, tuple is composed of array of non-zero elements and an array with their row-wise indexes.
- Unitary matrix \(U\). If
- Return type:
ndarray or tuple
Pauli basis to computational basis#
- qibo.quantum_info.pauli_to_comp_basis(nqubits: int, normalize: bool = False, sparse: bool = False, order: str = 'row', pauli_order: str = 'IXYZ', backend=None)#
Unitary matrix \(U\) that converts operators from the Pauli-Liouville representation to the Liouville representation in the computational basis.
The unitary \(U\) is given by
\[U = \sum_{k = 0}^{d^{2} - 1} \, \ketbra{P_{k}}{b_{k}} \, .\]- Parameters:
nqubits (int) – number of qubits.
normalize (bool, optional) – If
True
, converts to the Pauli basis. Defaults toFalse
.sparse (bool, optional) – If
True
, returns unitary matrix in sparse representation. Default isFalse
.order (str, optional) – If
"row"
, vectorization of Pauli basis is performed row-wise. If"column"
, vectorization is performed column-wise. If"system"
, system-wise vectorization is performed. Default is"row"
.pauli_order (str, optional) – corresponds to the order of 4 single-qubit Pauli elements. Default is “IXYZ”.
backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
- Unitary matrix \(U\). If
sparse=True
, tuple is composed of array of non-zero elements and an array with their row-wise indexes.
- Unitary matrix \(U\). If
- Return type:
ndarray or tuple
Metrics#
Set of functions that are used to calculate metrics of states, (pseudo-)distance measures between states, and distance measures between quantum channels.
Purity#
Impurity#
- qibo.quantum_info.impurity(state)#
Impurity of quantum state \(\rho\), which is given by \(1 - \text{purity}(\rho)\), where \(\text{purity}\) is defined in
qibo.quantum_info.purity()
.- Parameters:
state (ndarray) – statevector or density matrix.
- Returns:
impurity of
state
\(\rho\).- Return type:
Concurrence#
- qibo.quantum_info.concurrence(state, bipartition, check_purity: bool = True, backend=None)#
Calculates concurrence of a pure bipartite quantum state \(\rho \in \mathcal{H}_{A} \otimes \mathcal{H}_{B}\) as
\[C(\rho) = \sqrt{2 \, (\text{tr}^{2}(\rho) - \text{tr}(\rho_{A}^{2}))} \, ,\]where \(\rho_{A} = \text{tr}_{B}(\rho)\) is the reduced density operator obtained by tracing out the qubits in the
bipartition
\(B\).- Parameters:
state (ndarray) – statevector or density matrix.
bipartition (list or tuple or ndarray) – qubits in the subsystem to be traced out.
check_purity (bool, optional) – if
True
, checks ifstate
is pure. IfFalse
, it assumesstate
is pure . Defaults toTrue
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Concurrence of \(\rho\).
- Return type:
Entanglement of formation#
- qibo.quantum_info.entanglement_of_formation(state, bipartition, base: float = 2, check_purity: bool = True, backend=None)#
Calculates the entanglement of formation \(E_{f}\) of a pure bipartite quantum state \(\rho\), which is given by
\[E_{f} = H([1 - x, x]) \, ,\]where
\[x = \frac{1 + \sqrt{1 - C^{2}(\rho)}}{2} \, ,\]\(C(\rho)\) is the
qibo.quantum_info.concurrence()
of \(\rho\), and \(H\) is theqibo.quantum_info.shannon_entropy()
.- Parameters:
state (ndarray) – statevector or density matrix.
bipartition (list or tuple or ndarray) – qubits in the subsystem to be traced out.
base (float) – the base of the log in
qibo.quantum_info.shannon_entropy()
. Defaults to \(2\).check_purity (bool, optional) – if
True
, checks ifstate
is pure. IfFalse
, it assumesstate
is pure . Default:True
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
entanglement of formation of state \(\rho\).
- Return type:
Entropy#
- qibo.quantum_info.entropy(state, base: float = 2, check_hermitian: bool = False, backend=None)#
The von-Neumann entropy \(S(\rho)\) of a quantum
state
\(\rho\), which is given by\[S(\rho) = - \text{tr}\left[\rho \, \log(\rho)\right]\]- Parameters:
state (ndarray) – statevector or density matrix.
base (float, optional) – the base of the log. Defaults to \(2\).
check_hermitian (bool, optional) – if
True
, checks ifstate
is Hermitian. IfFalse
, it assumesstate
is Hermitian . Defaults toFalse
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
The von-Neumann entropy \(S\) of
state
\(\rho\).- Return type:
Note
validate
flag allows the user to choose if the function will check if input
state
is Hermitian or not. Default option is validate=False
, i.e. the
assumption of Hermiticity, because it is faster and, more importantly,
the functions are intended to be used on Hermitian inputs. When validate=True
and state
is non-Hermitian, an error will be raised when using cupy backend.
Entanglement entropy#
- qibo.quantum_info.entanglement_entropy(state, bipartition, base: float = 2, check_hermitian: bool = False, backend=None)#
Calculates the entanglement entropy \(S\) of bipartition \(A\) of
state
\(\rho\). This is given by\[S(\rho_{A}) = -\text{tr}(\rho_{A} \, \log(\rho_{A})) \, ,\]where \(\rho_{A} = \text{tr}_{B}(\rho)\) is the reduced density matrix calculated by tracing out the
bipartition
\(B\).- Parameters:
state (ndarray) – statevector or density matrix.
bipartition (list or tuple or ndarray) – qubits in the subsystem to be traced out.
base (float, optional) – the base of the log. Defaults to :math: 2.
check_hermitian (bool, optional) – if
True
, checks if \(\rho_{A}\) is Hermitian. IfFalse
, it assumesstate
is Hermitian . Default:False
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Entanglement entropy \(S\) of
state
\(\rho\).- Return type:
Note
validate
flag allows the user to choose if the function will check if
the reduced density matrix resulting from tracing out bipartition
from input
state
is Hermitian or not. Default option is validate=False
, i.e. the
assumption of Hermiticity, because it is faster and, more importantly,
the functions are intended to be used on Hermitian inputs. When validate=True
and the reduced density matrix is non-Hermitian, an error will be raised
when using cupy backend.
Trace distance#
- qibo.quantum_info.trace_distance(state, target, check_hermitian: bool = False, backend=None)#
Trace distance between two quantum states, \(\rho\) and \(\sigma\):
\[T(\rho, \sigma) = \frac{1}{2} \, \|\rho - \sigma\|_{1} = \frac{1}{2} \, \text{tr}\left[ \sqrt{(\rho - \sigma)^{\dagger}(\rho - \sigma)} \right] \, ,\]where \(\|\cdot\|_{1}\) is the Schatten 1-norm.
- Parameters:
state (ndarray) – statevector or density matrix.
target (ndarray) – statevector or density matrix.
check_hermitian (bool, optional) – if
True
, checks if \(\rho - \sigma\) is Hermitian. IfFalse
, it assumes the difference is Hermitian. Defaults toFalse
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Trace distance between
state
\(\rho\) andtarget
\(\sigma\).- Return type:
Note
validate
flag allows the user to choose if the function will check if difference
between inputs, state - target
, is Hermitian or not. Default option is
validate=False
, i.e. the assumption of Hermiticity, because it is faster and,
more importantly, the functions are intended to be used on Hermitian inputs.
When validate=True
and state - target
is non-Hermitian, an error will be
raised when using cupy backend.
Hilbert-Schmidt distance#
- qibo.quantum_info.hilbert_schmidt_distance(state, target)#
Hilbert-Schmidt distance between two quantum states:
\[\langle \rho \, , \, \sigma \rangle_{\text{HS}} = \text{tr}\left((\rho - \sigma)^{2}\right)\]- Parameters:
state (ndarray) – statevector or density matrix.
target (ndarray) – statevector or density matrix.
- Returns:
Hilbert-Schmidt distance between
state
\(\rho\) andtarget
\(\sigma\).- Return type:
Fidelity#
- qibo.quantum_info.fidelity(state, target, check_hermitian: bool = False, backend=None)#
Fidelity \(F(\rho, \sigma)\) between
state
\(\rho\) andtarget
state \(\sigma\). In general,\[F(\rho, \sigma) = \text{tr}^{2}\left( \sqrt{\sqrt{\sigma} \, \rho^{\dagger} \, \sqrt{\sigma}} \right) \, .\]However, when at least one of the states is pure, then
\[F(\rho, \sigma) = \text{tr}(\rho \, \sigma)\]- Parameters:
state (ndarray) – statevector or density matrix.
target (ndarray) – statevector or density matrix.
check_hermitian (bool, optional) – if
True
, checks ifstate
is Hermitian. Defaults toFalse
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Fidelity between
state
\(\rho\) andtarget
\(\sigma\).- Return type:
Infidelity#
- qibo.quantum_info.infidelity(state, target, check_hermitian: bool = False, backend=None)#
Infidelity between
state
\(\rho\) andtarget
state \(\sigma\), which is given by\[1 - F(\rho, \, \sigma) \, ,\]where \(F(\rho, \, \sigma)\) is the
qibo.quantum_info.fidelity()
betweenstate
andtarget
.- Parameters:
state (ndarray) – statevector or density matrix.
target (ndarray) – statevector or density matrix.
check_hermitian (bool, optional) – if
True
, checks ifstate
is Hermitian. Defaults toFalse
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Infidelity between
state
\(\rho\) andtarget
\(\sigma\).- Return type:
Bures angle#
- qibo.quantum_info.bures_angle(state, target, check_hermitian: bool = False, backend=None)#
Calculates the Bures angle \(D_{A}\) between a
state
\(\rho\) and atarget
state \(\sigma\). This is given by\[D_{A}(\rho, \, \sigma) = \text{arccos}\left(\sqrt{F(\rho, \, \sigma)}\right) \, ,\]where \(F(\rho, \sigma)\) is the
qibo.quantum_info.fidelity()
between state and target.- Parameters:
state (ndarray) – statevector or density matrix.
target (ndarray) – statevector or density matrix.
check_hermitian (bool, optional) – if
True
, checks ifstate
is Hermitian. Defaults toFalse
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Bures angle between
state
andtarget
.- Return type:
Bures distance#
- qibo.quantum_info.bures_distance(state, target, check_hermitian: bool = False, backend=None)#
Calculates the Bures distance \(D_{B}\) between a
state
\(\rho\) and atarget
state \(\sigma\). This is given by\[D_{B}(\rho, \, \sigma) = \sqrt{2 \, \left(1 - \sqrt{F(\rho, \, \sigma)}\right)}\]where \(F(\rho, \sigma)\) is the
qibo.quantum_info.fidelity()
between state and target.- Parameters:
state (ndarray) – statevector or density matrix.
target (ndarray) – statevector or density matrix.
check_hermitian (bool, optional) – if
True
, checks ifstate
is Hermitian. Defaults toFalse
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Bures distance between
state
andtarget
.- Return type:
Entanglement fidelity#
- qibo.quantum_info.entanglement_fidelity(channel, nqubits: int, state=None, check_hermitian: bool = False, backend=None)#
Entanglement fidelity \(F_{\mathcal{E}}\) of a
channel
\(\mathcal{E}\) onstate
\(\rho\) is given by\[F_{\mathcal{E}}(\rho) = F(\rho_{f}, \rho)\]where \(F\) is the
qibo.quantum_info.fidelity()
function for states, and \(\rho_{f} = \mathcal{E}_{A} \otimes I_{B}(\rho)\) is the state after the channel \(\mathcal{E}\) was applied to partition \(A\).- Parameters:
channel (
qibo.gates.channels.Channel
) – quantum channel acting on partition \(A\).nqubits (int) – total number of qubits in
state
.state (ndarray, optional) – statevector or density matrix to be evolved by
channel
. IfNone
, defaults to the maximally entangled state \(\frac{1}{2^{n}} \, \sum_{k} \, \ket{k}\ket{k}\), where \(n\) isnqubits
. Defaults toNone
.check_hermitian (bool, optional) – if
True
, checks if the final state \(\rho_{f}\) is Hermitian. IfFalse
, it assumes it is Hermitian. Defaults toFalse
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Entanglement fidelity \(F_{\mathcal{E}}\).
- Return type:
Process fidelity#
- qibo.quantum_info.process_fidelity(channel, target=None, check_unitary: bool = False, backend=None)#
Process fidelity between a quantum
channel
\(\mathcal{E}\) and atarget
unitary channel \(U\). The process fidelity is defined as\[F_{\text{pro}}(\mathcal{E}, \mathcal{U}) = \frac{1}{d^{2}} \, \text{tr}(\mathcal{E}^{\dagger} \, \mathcal{U})\]- Parameters:
channel – quantum channel \(\mathcal{E}\).
target (optional) – quantum channel \(U\). If
None
, target is the Identity channel. Defaults toNone
.check_unitary (bool, optional) – if
True
, checks if one of the input channels is unitary. Default:False
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Process fidelity between
channel
andtarget
.- Return type:
Process infidelity#
- qibo.quantum_info.process_infidelity(channel, target=None, check_unitary: bool = False, backend=None)#
Process infidelity between quantum channel \(\mathcal{E}\) and a
target
unitary channel \(U\). The process infidelity is defined as\[1 - F_{\text{pro}}(\mathcal{E}, \mathcal{U}) \, ,\]where \(F_{\text{pro}}\) is the
qibo.quantum_info.process_fidelity()
.- Parameters:
channel – quantum channel \(\mathcal{E}\).
target (optional) – quantum channel \(U\). If
None
, target is the Identity channel. Defaults toNone
.check_unitary (bool, optional) – if
True
, checks if one of the input channels is unitary. Defaults toFalse
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Process infidelity between
channel
\(\mathcal{E}\) andtarget
\(U\).- Return type:
Average gate fidelity#
- qibo.quantum_info.average_gate_fidelity(channel, target=None, check_unitary: bool = False, backend=None)#
Average gate fidelity between a quantum
channel
\(\mathcal{E}\) and atarget
unitary channel \(U\). The average gate fidelity is defined as\[F_{\text{avg}}(\mathcal{E}, \mathcal{U}) = \frac{d \, F_{pro}(\mathcal{E}, \mathcal{U}) + 1}{d + 1}\]where \(d\) is the dimension of the channels and \(F_{pro}(\mathcal{E}, \mathcal{U})\) is the
process_fidelily()
of channel \(\mathcal{E}\) with respect to the unitary channel \(\mathcal{U}\).- Parameters:
channel – quantum channel \(\mathcal{E}\).
target (optional) – quantum channel \(\mathcal{U}\). If
None
, target is the Identity channel. Defaults toNone
.check_unitary (bool, optional) – if
True
, checks if one of the input channels is unitary. Default:False
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Process fidelity between channel \(\mathcal{E}\) and target unitary channel \(\mathcal{U}\).
- Return type:
Gate error#
- qibo.quantum_info.gate_error(channel, target=None, check_unitary: bool = False, backend=None)#
Gate error between a quantum
channel
\(\mathcal{E}\) and atarget
unitary channel \(U\), which is defined as\[E(\mathcal{E}, \mathcal{U}) = 1 - F_{\text{avg}}(\mathcal{E}, \mathcal{U}) \, ,\]where \(F_{\text{avg}}(\mathcal{E}, \mathcal{U})\) is the
qibo.quantum_info.average_gate_fidelity()
.- Parameters:
channel – quantum channel \(\mathcal{E}\).
target (optional) – quantum channel \(\mathcal{U}\). If
None
, target is the Identity channel. Defaults toNone
.check_unitary (bool, optional) – if
True
, checks if one of the input channels is unitary. Default:False
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Gate error between
channel
\(\mathcal{E}\) andtarget
\(\mathcal{U}\).- Return type:
Diamond Norm#
- qibo.quantum_info.diamond_norm(channel, target=None, **kwargs)#
Calculates the diamond norm \(\|\mathcal{E}\|_{\diamond}\) of
channel
\(\mathcal{E}\), which is given by\[\|\mathcal{E}\|_{\diamond} = \max_{\rho} \, \| \left(\mathcal{E} \otimes I_{d^{2}}\right)(\rho) \|_{1} \, ,\]where \(I_{d^{2}}\) is the \(d^{2} \times d^{2}\) Identity operator, \(d = 2^{n}\), \(n\) is the number of qubits, and \(\|\cdot\|_{1}\) denotes the trace norm.
If a
target
channel \(\Lambda\) is specified, then it calculates \(\| \mathcal{E} - \Lambda\|_{\diamond}\).Example
from qibo.quantum_info import diamond_norm, random_unitary, to_choi nqubits = 1 dim = 2**nqubits unitary = random_unitary(dim) unitary = to_choi(unitary, order="row") unitary_2 = random_unitary(dim) unitary_2 = to_choi(unitary_2, order="row") dnorm = diamond_norm(unitary, unitary_2)
- Parameters:
channel (ndarray) – row-vectorized Choi representation of a quantum channel.
target (ndarray, optional) – row-vectorized Choi representation of a target quantum channel. Defaults to
None
.kwargs – optional arguments to pass to CVXPY solver. For more information, please visit CVXPY’s API documentation.
- Returns:
diamond norm of either
channel
orchannel - target
.- Return type:
Note
This function requires the optional CVXPY package to be installed.
Meyer-Wallach entanglement#
- qibo.quantum_info.meyer_wallach_entanglement(circuit, backend=None)#
Computes the Meyer-Wallach entanglement Q of the circuit,
\[Q(\theta) = 1 - \frac{1}{N} \, \sum_{k} \, \text{tr}\left(\rho_{k^{2}}(\theta)\right) \, .\]- Parameters:
circuit (
qibo.models.Circuit
) – Parametrized circuit.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Meyer-Wallach entanglement.
- Return type:
Entanglement capability#
- qibo.quantum_info.entangling_capability(circuit, samples: int, backend=None)#
Returns the entangling capability \(\text{Ent}\) of a parametrized circuit, which is average Meyer-Wallach entanglement Q of the circuit, i.e.
\[\text{Ent} = \frac{2}{S}\sum_{k}Q_k \, ,\]where \(S\) is the number of samples.
- Parameters:
circuit (
qibo.models.Circuit
) – Parametrized circuit.samples (int) – number of samples to estimate the integral.
backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Entangling capability.
- Return type:
Expressibility of parameterized quantum circuits#
- qibo.quantum_info.expressibility(circuit, t: int, samples: int, backend=None)#
Returns the expressibility \(\|A\|_{HS}\) of a parametrized circuit, where
\[A = \int_{\text{Haar}} d\psi \, \left(|\psi\rangle\right.\left. \langle\psi|\right)^{\otimes t} - \int_{\Theta} d\psi \, \left(|\psi_{\theta}\rangle\right.\left. \langle\psi_{\theta}|\right)^{\otimes t}\]- Parameters:
circuit (
qibo.models.Circuit
) – Parametrized circuit.t (int) – power that defines the \(t\)-design.
samples (int) – number of samples to estimate the integrals.
backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Entangling capability.
- Return type:
Random Ensembles#
Functions that can generate random quantum objects.
Random Gaussian matrix#
- qibo.quantum_info.random_gaussian_matrix(dims: int, rank: int | None = None, mean: float = 0, stddev: float = 1, seed=None, backend=None)#
Generates a random Gaussian Matrix.
Gaussian matrices are matrices where each entry is sampled from a Gaussian probability distribution
with mean \(\mu\) and standard deviation \(\sigma\).
- Parameters:
dims (int) – dimension of the matrix.
rank (int, optional) – rank of the matrix. If
None
, thenrank == dims
. Default:None
.mean (float, optional) – mean of the Gaussian distribution. Defaults to 0.
stddev (float, optional) – standard deviation of the Gaussian distribution. Defaults to
1
.seed (int or
numpy.random.Generator
, optional) – Either a generator of random numbers or a fixed seed to initialize a generator. IfNone
, initializes a generator with a random seed. Default:None
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Random Gaussian matrix with dimensions
(dims, rank)
.- Return type:
ndarray
Random Hermitian matrix#
- qibo.quantum_info.random_hermitian(dims: int, semidefinite: bool = False, normalize: bool = False, seed=None, backend=None)#
Generates a random Hermitian matrix \(H\), i.e. a random matrix such that \(H = H^{\dagger}.\)
- Parameters:
dims (int) – dimension of the matrix.
semidefinite (bool, optional) – if
True
, returns a Hermitian matrix that is also positive semidefinite. Defaults toFalse
.normalize (bool, optional) – if
True
andsemidefinite=False
, returns a Hermitian matrix with eigenvalues in the interval \([-1, \, 1]\). IfTrue
andsemidefinite=True
, interval is \([0, \, 1]\). Defaults toFalse
.seed (int or
numpy.random.Generator
, optional) – Either a generator of random numbers or a fixed seed to initialize a generator. IfNone
, initializes a generator with a random seed. Defaults toNone
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Hermitian matrix \(H\) with dimensions
(dims, dims)
.- Return type:
ndarray
Random unitary matrix#
- qibo.quantum_info.random_unitary(dims: int, measure: str | None = None, seed=None, backend=None)#
Returns a random Unitary operator \(U\), i.e. a random operator such that \(U^{-1} = U^{\dagger}\).
- Parameters:
dims (int) – dimension of the matrix.
measure (str, optional) – probability measure in which to sample the unitary from. If
None
, functions returns \(\exp{(-i \, H)}\), where \(H\) is a Hermitian operator. If"haar"
, returns an Unitary matrix sampled from the Haar measure. Defaults toNone
.seed (int or
numpy.random.Generator
, optional) – Either a generator of random numbers or a fixed seed to initialize a generator. IfNone
, initializes a generator with a random seed. Defaults toNone
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Unitary matrix \(U\) with dimensions
(dims, dims)
.- Return type:
ndarray
Random quantum channel#
- qibo.quantum_info.random_quantum_channel(dims: int, representation: str = 'liouville', measure: str | None = None, order: str = 'row', normalize: bool = False, precision_tol: float | None = None, seed=None, backend=None)#
Creates a random superoperator from an unitary operator in one of the supported superoperator representations.
- Parameters:
dims (int) – dimension of the unitary operator.
representation (str, optional) – If
"chi"
, returns a random channel in the Chi representation. If"choi"
, returns channel in Choi representation. If"kraus"
, returns Kraus representation of channel. If"liouville"
, returns Liouville representation. If"pauli"
, returns Pauli-Liouville representation. If “pauli-<pauli_order>” or “chi-<pauli_order>”, (e.g. “pauli-IZXY”), returns it in the Pauli basis with the corresponding order of single-qubit Pauli elements (seeqibo.quantum_info.pauli_basis()
). Defaults to"liouville"
.measure (str, optional) – probability measure in which to sample the unitary from. If
None
, functions returns \(\exp{(-i \, H)}\), where \(H\) is a Hermitian operator. If"haar"
, returns an Unitary matrix sampled from the Haar measure. Defaults toNone
.order (str, optional) – If
"row"
, vectorization is performed row-wise. If"column"
, vectorization is performed column-wise. If"system"
, a block-vectorization is performed. Defaults to"row"
.normalize (bool, optional) – used when
representation="chi"
orrepresentation="pauli"
. IfTrue
assumes the normalized Pauli basis. IfFalse
, it assumes unnormalized Pauli basis. Defaults toFalse
.precision_tol (float, optional) – if
representation="kraus"
, it is the precision tolerance for eigenvalues found in the spectral decomposition problem. Any eigenvalue \(\lambda <\)precision_tol
is set to 0 (zero). IfNone
,precision_tol
defaults toqibo.config.PRECISION_TOL=1e-8
. Defaults toNone
.seed (int or
numpy.random.Generator
, optional) – Either a generator of random numbers or a fixed seed to initialize a generator. IfNone
, initializes a generator with a random seed. Defaults toNone
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Superoperator representation of a random unitary gate.
- Return type:
ndarray
Random statevector#
- qibo.quantum_info.random_statevector(dims: int, haar: bool = False, seed=None, backend=None)#
Creates a random statevector \(\ket{\psi}\).
\[\ket{\psi} = \sum_{k = 0}^{d - 1} \, \sqrt{p_{k}} \, e^{i \phi_{k}} \, \ket{k} \, ,\]where \(d\) is
dims
, and \(p_{k}\) and \(\phi_{k}\) are, respectively, the probability and phase corresponding to the computational basis state \(\ket{k}\).- Parameters:
dims (int) – dimension of the matrix.
haar (bool, optional) – if
True
, statevector is created by sampling a Haar random unitary \(U_{\text{haar}}\) and acting with it on a random computational basis state \(\ket{k}\), i.e. \(\ket{\psi} = U_{\text{haar}} \ket{k}\). Defaults toFalse
.seed (int or
numpy.random.Generator
, optional) – Either a generator of random numbers or a fixed seed to initialize a generator. IfNone
, initializes a generator with a random seed. Defaults toNone
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Random statevector \(\ket{\psi}\).
- Return type:
ndarray
Random density matrix#
- qibo.quantum_info.random_density_matrix(dims: int, rank: int | None = None, pure: bool = False, metric: str = 'Hilbert-Schmidt', basis: str | None = None, normalize: bool = False, seed=None, backend=None)#
Creates a random density matrix \(\rho\). If
pure=True
,\[\rho = \ketbra{\psi}{\psi} \, ,\]where \(\ket{\psi}\) is a
qibo.quantum_info.random_statevector()
. Ifpure=False
, then\[\rho = \sum_{k} \, p_{k} \, \ketbra{\psi_{k}}{\psi_{k}} \, .\]is a mixed state.
- Parameters:
dims (int) – dimension of the matrix.
rank (int, optional) – rank of the matrix. If
None
, thenrank == dims
. Defaults toNone
.pure (bool, optional) – if
True
, returns a pure state. Defaults toFalse
.metric (str, optional) – metric to sample the density matrix from. Options:
"Hilbert-Schmidt"
and"Bures"
. Defaults to"Hilbert-Schmidt"
.basis (str, optional) – if
None
, returns random density matrix in the computational basis. If"pauli-<pauli_order>"
, (e.g."pauli-IZXY"
), returns it in the Pauli basis with the corresponding order of single-qubit Pauli elements (seeqibo.quantum_info.pauli_basis()
). Defaults toNone
.normalize (bool, optional) – if
True
andbasis="pauli-<pauli-order>"
, returns random density matrix in the normalized Pauli basis. IfFalse
andbasis="pauli-<pauli-order>"
, returns state in the unnormalized Pauli basis. Defaults toFalse
.seed (int or
numpy.random.Generator
, optional) – Either a generator of random numbers or a fixed seed to initialize a generator. IfNone
, initializes a generator with a random seed. Defaults toNone
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Random density matrix \(\rho\).
- Return type:
ndarray
Random Clifford#
- qibo.quantum_info.random_clifford(nqubits: int, return_circuit: bool = True, seed=None, backend=None)#
Generates a random \(n\)-qubit Clifford operator, where \(n\) is
nqubits
. For the mathematical details, see Reference [1].- Parameters:
nqubits (int) – number of qubits.
return_circuit (bool, optional) – if
True
, returns aqibo.models.Circuit
object. IfFalse
, returns anndarray
object. Defaults toFalse
.seed (int or
numpy.random.Generator
, optional) – Either a generator of random numbers or a fixed seed to initialize a generator. IfNone
, initializes a generator with a random seed. Defaults toNone
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Random Clifford operator.
- Return type:
(ndarray or
qibo.models.Circuit
)
- Reference:
S. Bravyi and D. Maslov, Hadamard-free circuits expose the structure of the Clifford group. arXiv:2003.09412 [quant-ph].
Random Pauli#
- qibo.quantum_info.random_pauli(qubits, depth: int, max_qubits: int | None = None, subset: list | None = None, return_circuit: bool = True, seed=None, backend=None)#
Creates random Pauli operator(s).
Pauli operators are sampled from the single-qubit Pauli set \(\{I, \, X, \, Y, \, Z\}\).
- Parameters:
qubits (int or list or ndarray) – if
int
andmax_qubits=None
, the number of qubits. Ifint
andmax_qubits != None
, qubit index in which the Pauli sequence will act. Iflist
orndarray
, indexes of the qubits for the Pauli sequence to act.depth (int) – length of the sequence of Pauli gates.
max_qubits (int, optional) – total number of qubits in the circuit. If
None
,max_qubits = max(qubits)
. Defaults toNone
.subset (list, optional) – list containing a subset of the 4 single-qubit Pauli operators. If
None
, defaults to the complete set. Defaults toNone
.return_circuit (bool, optional) – if
True
, returns aqibo.models.Circuit
object. IfFalse
, returns anndarray
with shape (qubits, depth, 2, 2) that contains all Pauli matrices that were sampled. Defaults toTrue
.seed (int or
numpy.random.Generator
, optional) – Either a generator of random numbers or a fixed seed to initialize a generator. IfNone
, initializes a generator with a random seed. Defaults toNone
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
all sampled Pauli operators.
- Return type:
(ndarray or
qibo.models.Circuit
)
Random Pauli Hamiltonian#
- qibo.quantum_info.random_pauli_hamiltonian(nqubits: int, max_eigenvalue: int | float | None = None, normalize: bool = False, pauli_order: str = 'IXYZ', seed=None, backend=None)#
Generates a random Hamiltonian in the Pauli basis.
- Parameters:
nqubits (int) – number of qubits.
max_eigenvalue (int or float, optional) – fixes the value of the largest eigenvalue. Defaults to
None
.normalize (bool, optional) – If
True
, fixes the gap of the Hamiltonian as1.0
. Moreover, ifTrue
, thenmax_eigenvalue
must be> 1.0
. Defaults toFalse
.pauli_order (str, optional) – corresponds to the order of 4 single-qubit Pauli elements in the basis. Defaults to “IXYZ”.
seed (int or
numpy.random.Generator
, optional) – Either a generator of random numbers or a fixed seed to initialize a generator. IfNone
, initializes a generator with a random seed. Defaults toNone
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Hamiltonian in the Pauli basis and its corresponding eigenvalues.
- Return type:
tuple(ndarray, ndarray)
Random stochastic matrix#
- qibo.quantum_info.random_stochastic_matrix(dims: int, bistochastic: bool = False, diagonally_dominant: bool = False, precision_tol: float | None = None, max_iterations: int | None = None, seed=None, backend=None)#
Creates a random stochastic matrix.
- Parameters:
dims (int) – dimension of the matrix.
bistochastic (bool, optional) – if
True
, matrix is row- and column-stochastic. IfFalse
, matrix is row-stochastic. Defaults toFalse
.diagonally_dominant (bool, optional) – if
True
, matrix is strictly diagonally dominant. Defaults toFalse
.precision_tol (float, optional) – tolerance level for how much each probability distribution can deviate from summing up to
1.0
. IfNone
, it defaults toqibo.config.PRECISION_TOL
. Defaults toNone
.max_iterations (int, optional) – when
bistochastic=True
, maximum number of iterations used to normalize all rows and columns simultaneously. IfNone
, defaults toqibo.config.MAX_ITERATIONS
. Defaults toNone
.seed (int or
numpy.random.Generator
, optional) – Either a generator of random numbers or a fixed seed to initialize a generator. IfNone
, initializes a statevectorgenerator with a random seed. Defaults toNone
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
a random stochastic matrix.
- Return type:
ndarray
Superoperator Transformations#
Functions used to convert superoperators among their possible representations. For more in-depth theoretical description of the representations and transformations, we direct the reader to Wood, Biamonte, and Cory, Quant. Inf. Comp. 15, 0579-0811 (2015).
Vectorization#
- qibo.quantum_info.vectorization(state, order: str = 'row', backend=None)#
Returns state \(\rho\) in its Liouville representation \(|\rho\rangle\rangle\).
If
order="row"
, then:\[|\rho\rangle\rangle = \sum_{k, l} \, \rho_{kl} \, \ket{k} \otimes \ket{l}\]If
order="column"
, then:\[|\rho\rangle\rangle = \sum_{k, l} \, \rho_{kl} \, \ket{l} \otimes \ket{k}\]- Parameters:
state – state vector or density matrix.
order (str, optional) – If
"row"
, vectorization is performed row-wise. If"column"
, vectorization is performed column-wise. If"system"
, a block-vectorization is performed. Defaults to"row"
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Liouville representation of
state
.- Return type:
ndarray
Note
Due to numpy
limitations on handling transposition of tensors,
this function will not work when the number of qubits \(n\)
is such that \(n > 16\).
Unvectorization#
- qibo.quantum_info.unvectorization(state, order: str = 'row', backend=None)#
Returns state \(\rho\) from its Liouville representation \(|\rho\rangle\rangle\). This operation is the inverse function of
vectorization()
, i.e.\[\begin{split}\begin{align} \rho &= \text{unvectorization}(|\rho\rangle\rangle) \nonumber \\ &= \text{unvectorization}(\text{vectorization}(\rho)) \nonumber \end{align}\end{split}\]- Parameters:
state – quantum state in Liouville representation.
order (str, optional) – If
"row"
, unvectorization is performed row-wise. If"column"
, unvectorization is performed column-wise. If"system"
, system-wise vectorization is performed. Defaults to"row"
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Density matrix of
state
.- Return type:
ndarray
Note
Due to numpy
limitations on handling transposition of tensors,
this function will not work when the number of qubits \(n\)
is such that \(n > 16\).
To Choi#
- qibo.quantum_info.to_choi(channel, order: str = 'row', backend=None)#
Converts quantum
channel
\(U\) to its Choi representation \(\Lambda\).\[\Lambda = | U \rangle\rangle \langle\langle U | \, ,\]where \(| \cdot \rangle\rangle\) is the
qibo.quantum_info.vectorization()
operation.- Parameters:
channel (ndarray) – quantum channel.
order (str, optional) – If
"row"
, vectorization is performed row-wise. If"column"
, vectorization is performed column-wise. If"system"
, a block-vectorization is performed. Default is"row"
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
quantum channel in its Choi representation.
- Return type:
ndarray
To Liouville#
- qibo.quantum_info.to_liouville(channel, order: str = 'row', backend=None)#
Converts quantum
channel
\(U\) to its Liouville representation \(\mathcal{E}\). It uses the Choi representation as an intermediate step.- Parameters:
channel (ndarray) – quantum channel.
order (str, optional) – If
"row"
, vectorization is performed row-wise. If"column"
, vectorization is performed column-wise. If"system"
, a block-vectorization is performed. Default is"row"
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
quantum channel in its Liouville representation.
- Return type:
ndarray
To Pauli-Liouville#
- qibo.quantum_info.to_pauli_liouville(channel, normalize: bool = False, order: str = 'row', pauli_order: str = 'IXYZ', backend=None)#
Converts quantum
channel
\(U\) to its Pauli-Liouville representation \(\mathcal{E}\). It uses the Liouville representation as an intermediate step.- Parameters:
channel (ndarray) – quantum channel.
normalize (bool, optional) – If
True
superoperator is returned in the normalized Pauli basis. IfFalse
, it is returned in the unnormalized Pauli basis. Defaults toFalse
.order (str, optional) – If
"row"
, vectorization is performed row-wise. If"column"
, vectorization is performed column-wise. If"system"
, a block-vectorization is performed. Default is"row"
.pauli_order (str, optional) – corresponds to the order of 4 single-qubit Pauli elements. Default is “IXYZ”.
backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
quantum channel in its Pauli-Liouville representation.
- Return type:
ndarray
To Chi#
- qibo.quantum_info.to_chi(channel, normalize: bool = False, order: str = 'row', pauli_order: str = 'IXYZ', backend=None)#
Converts quantum
channel
\(U\) to its \(\chi\)-representation.- Parameters:
channel (ndarray) – quantum channel.
normalize (bool, optional) – If
True
superoperator is returned in the normalized Pauli basis. IfFalse
, it is returned in the unnormalized Pauli basis. Defaults toFalse
.order (str, optional) – If
"row"
, vectorization is performed row-wise. If"column"
, vectorization is performed column-wise. If"system"
, a block-vectorization is performed. Default is"row"
.pauli_order (str, optional) – corresponds to the order of 4 single-qubit Pauli elements. Default is “IXYZ”.
backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
quantum channel in its \(\chi\)-representation.
- Return type:
ndarray
Choi to Liouville#
- qibo.quantum_info.choi_to_liouville(choi_super_op, order: str = 'row', backend=None)#
Converts Choi representation \(\Lambda\) of quantum channel to its Liouville representation \(\mathcal{E}\).
If
order="row"
, then:\[\Lambda_{\alpha\beta, \, \gamma\delta} \mapsto \Lambda_{\alpha\gamma, \, \beta\delta} \equiv \mathcal{E}\]If
order="column"
, then:\[\Lambda_{\alpha\beta, \, \gamma\delta} \mapsto \Lambda_{\delta\beta, \, \gamma\alpha} \equiv \mathcal{E}\]- Parameters:
choi_super_op – Choi representation of quantum channel.
order (str, optional) – If
"row"
, reshuffling is performed with respect to row-wise vectorization. If"column"
, reshuffling is performed with respect to column-wise vectorization. If"system"
, operator is converted to a representation based on row vectorization, reshuffled, and then converted back to its representation with respect to system-wise vectorization. Defaults to"row"
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Liouville representation of quantum channel.
- Return type:
ndarray
Choi to Pauli-Liouville#
- qibo.quantum_info.choi_to_pauli(choi_super_op, normalize: bool = False, order: str = 'row', pauli_order: str = 'IXYZ', backend=None)#
Converts Choi representation \(\Lambda\) of a quantum channel to its Pauli-Liouville representation.
- Parameters:
choi_super_op (ndarray) – superoperator in the Choi representation.
normalize (bool, optional) – If
True
superoperator is returned in the normalized Pauli basis. IfFalse
, it is returned in the unnormalized Pauli basis. Defaults toFalse
.order (str, optional) – If
"row"
, it assumeschoi_super_op
is in row-vectorization. If"column"
, it assumes column-vectorization. Defaults to"row"
.pauli_order (str, optional) – corresponds to the order of 4 single-qubit Pauli elements. Defaults to “IXYZ”.
backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
superoperator in the Pauli-Liouville representation.
- Return type:
ndarray
Choi to Kraus#
- qibo.quantum_info.superoperator_transformations.choi_to_kraus(choi_super_op, precision_tol: float | None = None, order: str = 'row', validate_cp: bool = True, backend=None)#
Converts Choi representation \(\Lambda\) of a quantum channel \(\mathcal{E}\) into Kraus operators \(\{ K_{\alpha} \}_{\alpha}\).
If \(\mathcal{E}\) is a completely positive (CP) map, then
\[\Lambda = \sum_{\alpha} \, \lambda_{\alpha}^{2} \, |\tilde{K}_{\alpha}\rangle\rangle \langle\langle \tilde{K}_{\alpha}| \, .\]This is the spectral decomposition of \(\Lambda\), Hence, the set \(\{\lambda_{\alpha}, \, \tilde{K}_{\alpha}\}_{\alpha}\) is found by diagonalization of \(\Lambda\). The Kraus operators \(\{K_{\alpha}\}_{\alpha}\) are defined as
\[K_{\alpha} = \lambda_{\alpha} \, \text{unvectorization}(|\tilde{K}_{\alpha}\rangle\rangle) \, .\]If \(\mathcal{E}\) is not CP, then spectral composition is replaced by a singular value decomposition (SVD), i.e.
\[\Lambda = U \, S \, V^{\dagger} \, ,\]where \(U\) is a \(d^{2} \times d^{2}\) unitary matrix, \(S\) is a \(d^{2} \times d^{2}\) positive diagonal matrix containing the singular values of \(\Lambda\), and \(V\) is a \(d^{2} \times d^{2}\) unitary matrix. The Kraus coefficients are replaced by the square root of the singular values, and \(U\) (\(V\)) determine the left-generalized (right-generalized) Kraus operators.
- Parameters:
choi_super_op – Choi representation of a quantum channel.
precision_tol (float, optional) – Precision tolerance for eigenvalues found in the spectral decomposition problem. Any eigenvalue \(\lambda <\)
precision_tol
is set to 0 (zero). IfNone
,precision_tol
defaults toqibo.config.PRECISION_TOL=1e-8
. Defaults toNone
.order (str, optional) – If
"row"
, reshuffling is performed with respect to row-wise vectorization. If"column"
, reshuffling is performed with respect to column-wise vectorization. If"system"
, operator is converted to a representation based on row vectorization, reshuffled, and then converted back to its representation with respect to system-wise vectorization. Defaults to"row"
.validate_cp (bool, optional) – If
True
, checks ifchoi_super_op
is a completely positive map. IfFalse
, it assumes thatchoi_super_op
is completely positive (and Hermitian). Defaults toTrue
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
The set \(\{K_{\alpha}, \, \lambda_{\alpha} \}_{\alpha}\) of Kraus operators representing the quantum channel and their respective coefficients. If map is non-CP, then function returns the set \(\{ \{K_{L}, \, K_{R}\}_{\alpha}, \, \lambda_{\alpha} \}_{\alpha}\), with the left- and right-generalized Kraus operators as well as the square root of their corresponding singular values.
- Return type:
tuple(ndarray, ndarray)
Note
Due to the spectral decomposition subroutine in this function, the resulting Kraus operators \(\{K_{\alpha}\}_{\alpha}\) might contain global phases. That implies these operators are not exactly equal to the “true” Kraus operators \(\{K_{\alpha}^{(\text{ideal})}\}_{\alpha}\). However, since these are global phases, the operators’ actions are the same, i.e.
Note
User can set validate_cp=False
in order to speed up execution by not checking if
input map choi_super_op
is completely positive (CP) and Hermitian. However, that may
lead to erroneous outputs if choi_super_op
is not guaranteed to be CP. We advise users
to either set this flag carefully or leave it in its default setting (validate_cp=True
).
Choi to Chi-matrix#
- qibo.quantum_info.choi_to_chi(choi_super_op, normalize: bool = False, order: str = 'row', pauli_order: str = 'IXYZ', backend=None)#
Converts Choi representation \(\Lambda\) of quantum channel to its \(\chi\)-matrix representation.
\[\chi = \text{liouville_to_pauli}(\Lambda)\]- Parameters:
choi_super_op – Choi representation of a quantum channel.
normalize (bool, optional) – If
True
assumes the normalized Pauli basis. IfFalse
, it assumes unnormalized Pauli basis. Defaults toFalse
.order (str, optional) – If
"row"
, reshuffling is performed with respect to row-wise vectorization. If"column"
, reshuffling is performed with respect to column-wise vectorization. If"system"
, operator is converted to a representation based on row vectorization, reshuffled, and then converted back to its representation with respect to system-wise vectorization. Defaults to"row"
.pauli_order (str, optional) – corresponds to the order of 4 single-qubit Pauli elements. Defaults to “IXYZ”.
backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Chi-matrix representation of the quantum channel.
- Return type:
ndarray
Choi to Stinespring#
- qibo.quantum_info.choi_to_stinespring(choi_super_op, precision_tol: float | None = None, order: str = 'row', validate_cp: bool = True, nqubits: int | None = None, initial_state_env=None, backend=None)#
Converts Choi representation \(\Lambda\) of quantum channel to its Stinespring representation \(U_{0}\). It uses the Kraus representation as an intermediate step.
- Parameters:
choi_super_op – Choi representation of a quantum channel.
precision_tol (float, optional) – Precision tolerance for eigenvalues found in the spectral decomposition problem. Any eigenvalue \(\lambda <\)
precision_tol
is set to 0 (zero). IfNone
,precision_tol
defaults toqibo.config.PRECISION_TOL=1e-8
. Defaults toNone
.order (str, optional) – If
"row"
, reshuffling is performed with respect to row-wise vectorization. If"column"
, reshuffling is performed with respect to column-wise vectorization. If"system"
, operator is converted to a representation based on row vectorization, reshuffled, and then converted back to its representation with respect to system-wise vectorization. Defaults to"row"
.validate_cp (bool, optional) – If
True
, checks ifchoi_super_op
is a completely positive map. IfFalse
, it assumes thatchoi_super_op
is completely positive (and Hermitian). Defaults toTrue
.nqubits (int, optional) – total number of qubits in the system that is interacting with the environment. Must be equal or greater than the number of qubits
kraus_ops
acts on. IfNone
, defaults to the number of qubits inkraus_ops
. Defauts toNone
.initial_state_env (ndarray, optional) – statevector representing the initial state of the enviroment. If
None
, it assumes the environment in its ground state. Defaults toNone
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Choi representation of quantum channel.
- Return type:
ndarray
Kraus to Choi#
- qibo.quantum_info.kraus_to_choi(kraus_ops, order: str = 'row', backend=None)#
Converts Kraus representation \(\{K_{\alpha}\}_{\alpha}\) of quantum channel to its Choi representation \(\Lambda\).
\[\Lambda = \sum_{\alpha} \, |K_{\alpha}\rangle\rangle \langle\langle K_{\alpha}|\]- Parameters:
kraus_ops (list) – List of Kraus operators as pairs
(qubits, Ak)
wherequbits
refers the qubit ids that \(A_k\) acts on and \(A_k\) is the corresponding matrix as anp.ndarray
.order (str, optional) – If
"row"
, reshuffling is performed with respect to row-wise vectorization. If"column"
, reshuffling is performed with respect to column-wise vectorization. If"system"
, operator is converted to a representation based on row vectorization, reshuffled, and then converted back to its representation with respect to system-wise vectorization. Defaults to"row"
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Choi representation of the Kraus channel.
- Return type:
ndarray
Kraus to Liouville#
- qibo.quantum_info.kraus_to_liouville(kraus_ops, order: str = 'row', backend=None)#
Converts from Kraus representation \(\{K_{\alpha}\}_{\alpha}\) of quantum channel to its Liouville representation \(\mathcal{E}\). It uses the Choi representation as an intermediate step.
\[\mathcal{E} = \text{choi_to_liouville}(\text{kraus_to_choi} (\{K_{\alpha}\}_{\alpha}))\]- Parameters:
kraus_ops (list) – List of Kraus operators as pairs
(qubits, Ak)
wherequbits
refers the qubit ids that \(A_k\) acts on and \(A_k\) is the corresponding matrix as anp.ndarray
.order (str, optional) – If
"row"
, reshuffling is performed with respect to row-wise vectorization. If"column"
, reshuffling is performed with respect to column-wise vectorization. If"system"
, operator is converted to a representation based on row vectorization, reshuffled, and then converted back to its representation with respect to system-wise vectorization. Defaults to"row"
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Liouville representation of quantum channel.
- Return type:
ndarray
Kraus to Pauli-Liouville#
- qibo.quantum_info.kraus_to_pauli(kraus_ops, normalize: bool = False, order: str = 'row', pauli_order: str = 'IXYZ', backend=None)#
Converts Kraus representation \(\{K_{\alpha}\}_{\alpha}\) of a quantum channel to its Pauli-Liouville representation.
- Parameters:
kraus_ops (list) – List of Kraus operators as pairs
(qubits, Ak)
wherequbits
refers the qubit ids that \(A_k\) acts on and \(A_k\) is the corresponding matrix as anp.ndarray
.normalize (bool, optional) – If
True
superoperator is returned in the normalized Pauli basis. IfFalse
, it is returned in the unnormalized Pauli basis. Defaults toFalse
.order (str, optional) – If
"row"
, intermediate step for Choi representation is done in row-vectorization. If"column"
, step is done in column-vectorization. If"system"
, block-vectorization is performed. Defaults to"row"
.pauli_order (str, optional) – corresponds to the order of 4 single-qubit Pauli elements. Defaults to “IXYZ”.
backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
superoperator in the Pauli-Liouville representation.
- Return type:
ndarray
Kraus to Chi-matrix#
- qibo.quantum_info.kraus_to_chi(kraus_ops, normalize: bool = False, order: str = 'row', pauli_order: str = 'IXYZ', backend=None)#
Convert Kraus representation \(\{K_{\alpha}\}_{\alpha}\) of quantum channel to its \(\chi\)-matrix representation.
\[\chi = \sum_{\alpha} \, |c_{\alpha}\rangle\rangle \langle\langle c_{\alpha}|,\]where \(|c_{\alpha}\rangle\rangle \cong |K_{\alpha}\rangle\rangle\) in Pauli-Liouville basis.
- Parameters:
kraus_ops (list) – List of Kraus operators as pairs
(qubits, Ak)
wherequbits
refers the qubit ids that \(A_k\) acts on and \(A_k\) is the corresponding matrix as anp.ndarray
.normalize (bool, optional) – If
True
assumes the normalized Pauli basis. IfFalse
, it assumes unnormalized Pauli basis. Defaults toFalse
.order (str, optional) – If
"row"
, reshuffling is performed with respect to row-wise vectorization. If"column"
, reshuffling is performed with respect to column-wise vectorization. If"system"
, operator is converted to a representation based on row vectorization, reshuffled, and then converted back to its representation with respect to system-wise vectorization. Defaults to"row"
.pauli_order (str, optional) – corresponds to the order of 4 single-qubit Pauli elements in the Pauli basis. Defaults to “IXYZ”.
backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Chi-matrix representation of the Kraus channel.
- Return type:
ndarray
Kraus to Stinespring#
- qibo.quantum_info.kraus_to_stinespring(kraus_ops, nqubits: int | None = None, initial_state_env=None, backend=None)#
Converts Kraus representation \(\{K_{\alpha}\}_{\alpha}\) of quantum channel to its Stinespring representation \(U_{0}\), i.e.
\[U_{0} = \sum_{\alpha} \, K_{\alpha} \otimes \ketbra{\alpha}{v_{0}} \, ,\]where \(\ket{v_{0}}\) is the initial state of the environment (
initial_state_env
), \(D\) is the dimension of the environment’s Hilbert space, and \(\{\ket{\alpha} \, : \, \alpha = 0, 1, \cdots, D - 1 \}\) is an orthonormal basis for the environment’s space.- Parameters:
kraus_ops (list) – List of Kraus operators as pairs
(qubits, Ak)
wherequbits
refers the qubit ids that \(A_k\) acts on and \(A_k\) is the corresponding matrix as anp.ndarray
.nqubits (int, optional) – total number of qubits in the system that is interacting with the environment. Must be equal or greater than the number of qubits
kraus_ops
acts on. IfNone
, defaults to the number of qubits inkraus_ops
. Defauts toNone
.initial_state_env (ndarray, optional) – statevector representing the initial state of the enviroment. If
None
, it assumes the environment in its ground state. Defaults toNone
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Stinespring representation (restricted unitary) of the Kraus channel.
- Return type:
ndarray
Liouville to Choi#
- qibo.quantum_info.liouville_to_choi(super_op, order: str = 'row', backend=None)#
Converts Liouville representation of quantum channel \(\mathcal{E}\) to its Choi representation \(\Lambda\). Indexing \(\mathcal{E}\) as \(\mathcal{E}_{\alpha\beta, \, \gamma\delta} \,\,\), then
If
order="row"
:\[\Lambda = \sum_{k, l} \, \ketbra{k}{l} \otimes \mathcal{E}(\ketbra{k}{l}) \equiv \mathcal{E}_{\alpha\gamma, \, \beta\delta}\]If
order="column"
, then:\[\Lambda = \sum_{k, l} \, \mathcal{E}(\ketbra{k}{l}) \otimes \ketbra{k}{l} \equiv \mathcal{E}_{\delta\beta, \, \gamma\alpha}\]- Parameters:
super_op – Liouville representation of quantum channel.
order (str, optional) – If
"row"
, reshuffling is performed with respect to row-wise vectorization. If"column"
, reshuffling is performed with respect to column-wise vectorization. If"system"
, operator is converted to a representation based on row vectorization, reshuffled, and then converted back to its representation with respect to system-wise vectorization. Defaults to"row"
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Choi representation of quantum channel.
- Return type:
ndarray
Liouville to Pauli-Liouville#
- qibo.quantum_info.liouville_to_pauli(super_op, normalize: bool = False, order: str = 'row', pauli_order: str = 'IXYZ', backend=None)#
Converts Liouville representation \(\mathcal{E}\) of a quantum channel to its Pauli-Liouville representation.
- Parameters:
super_op (ndarray) – superoperator in the Liouville representation._
normalize (bool, optional) – If
True
superoperator is returned in the normalized Pauli basis. IfFalse
, it is returned in the unnormalized Pauli basis. Defaults toFalse
.order (str, optional) – If
"row"
, it assumessuper_op
is in row-vectorization. If"column"
, it assumes column-vectorization. If"system"
, it assumes block-vectorization. Defaults to"row"
.pauli_order (str, optional) – corresponds to the order of 4 single-qubit Pauli elements in the basis. Defaults to “IXYZ”.
backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
superoperator in the Pauli-Liouville representation.
- Return type:
ndarray
Liouville to Kraus#
- qibo.quantum_info.liouville_to_kraus(super_op, precision_tol: float | None = None, order: str = 'row', backend=None)#
Converts Liouville representation \(\mathcal{E}\) of a quantum channel to its Kraus representation \(\{K_{\alpha}\}_{\alpha}\). It uses the Choi representation as an intermediate step.
\[\{K_{\alpha}, \, \lambda_{\alpha}\}_{\alpha} = \text{choi_to_kraus}(\text{liouville_to_choi}(\mathcal{E}))\]- Parameters:
super_op (ndarray) – Liouville representation of quantum channel.
precision_tol (float, optional) – Precision tolerance for eigenvalues found in the spectral decomposition problem. Any eigenvalue \(\lambda < \text{precision_tol}\) is set to 0 (zero). If
None
,precision_tol
defaults toqibo.config.PRECISION_TOL=1e-8
. Defaults to None.order (str, optional) – If
"row"
, reshuffling is performed with respect to row-wise vectorization. If"column"
, reshuffling is performed with respect to column-wise vectorization. If"system"
, operator is converted to a representation based on row vectorization, reshuffled, and then converted back to its representation with respect to system-wise vectorization. Defaults to"row"
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Kraus operators of quantum channel and their respective coefficients.
- Return type:
(ndarray, ndarray)
Note
Due to the spectral decomposition subroutine in this function, the resulting Kraus operators \(\{K_{\alpha}\}_{\alpha}\) might contain global phases. That implies these operators are not exactly equal to the “true” Kraus operators \(\{K_{\alpha}^{(\text{ideal})}\}_{\alpha}\). However, since these are global phases, the operators’ actions are the same, i.e.
Liouville to Chi-matrix#
- qibo.quantum_info.liouville_to_chi(super_op, normalize: bool = False, order: str = 'row', pauli_order: str = 'IXYZ', backend=None)#
Converts Liouville representation of quantum channel \(\mathcal{E}\) to its \(\chi\)-matrix representation. It uses the Choi representation as an intermediate step.
\[\chi = \text{liouville_to_pauli}(\text{liouville_to_choi}(\mathcal{E}))\]- Parameters:
super_op – Liouville representation of quantum channel.
normalize (bool, optional) – If
True
assumes the normalized Pauli basis. IfFalse
, it assumes unnormalized Pauli basis. Defaults toFalse
.order (str, optional) – If
"row"
, reshuffling is performed with respect to row-wise vectorization. If"column"
, reshuffling is performed with respect to column-wise vectorization. If"system"
, operator is converted to a representation based on row vectorization, reshuffled, and then converted back to its representation with respect to system-wise vectorization. Defaults to"row"
.pauli_order (str, optional) – corresponds to the order of 4 single-qubit Pauli elements in the basis. Defaults to “IXYZ”.
backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Chi-matrix representation of quantum channel.
- Return type:
ndarray
Liouville to Stinespring#
- qibo.quantum_info.liouville_to_stinespring(super_op, order: str = 'row', precision_tol: float | None = None, validate_cp: bool = True, nqubits: int | None = None, initial_state_env=None, backend=None)#
Converts Liouville representation \(\mathcal{E}\) of quantum channel to its Stinespring representation \(U_{0}\). It uses the Choi representation \(\Lambda\) as intermediate step.
- Parameters:
super_op – Liouville representation of quantum channel.
order (str, optional) – If
"row"
, reshuffling is performed with respect to row-wise vectorization. If"column"
, reshuffling is performed with respect to column-wise vectorization. If"system"
, operator is converted to a representation based on row vectorization, reshuffled, and then converted back to its representation with respect to system-wise vectorization. Defaults to"row"
.precision_tol (float, optional) – Precision tolerance for eigenvalues found in the spectral decomposition problem. Any eigenvalue \(\lambda <\)
precision_tol
is set to 0 (zero). IfNone
,precision_tol
defaults toqibo.config.PRECISION_TOL=1e-8
. Defaults toNone
.validate_cp (bool, optional) – If
True
, checks ifchoi_super_op
is a completely positive map. IfFalse
, it assumes thatchoi_super_op
is completely positive (and Hermitian). Defaults toTrue
.nqubits (int, optional) – total number of qubits in the system that is interacting with the environment. Must be equal or greater than the number of qubits
kraus_ops
acts on. IfNone
, defaults to the number of qubits inkraus_ops
. Defauts toNone
.initial_state_env (ndarray, optional) – statevector representing the initial state of the enviroment. If
None
, it assumes the environment in its ground state. Defaults toNone
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Stinespring representation of quantum channel.
- Return type:
ndarray
Pauli-Liouville to Liouville#
- qibo.quantum_info.pauli_to_liouville(pauli_op, normalize: bool = False, order: str = 'row', pauli_order: str = 'IXYZ', backend=None)#
Converts Pauli-Liouville representation of a quantum channel to its Liouville representation \(\mathcal{E}\).
- Parameters:
pauli_op (ndarray) – Pauli-Liouville representation of a quantum channel.
normalize (bool, optional) – If
True
assumespauli_op
is represented in the normalized Pauli basis. IfFalse
, it assumes unnormalized Pauli basis. Defaults toFalse
.order (str, optional) – If
"row"
, returns Liouville representation in row-vectorization. If"column"
, returns column-vectorized superoperator. If"system"
, superoperator will be in block-vectorization. Defaults to"row"
.pauli_order (str, optional) – corresponds to the order of 4 single-qubit Pauli elements. Defaults to “IXYZ”.
backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
superoperator in the Liouville representation.
- Return type:
ndarray
Pauli-Liouville to Choi#
- qibo.quantum_info.pauli_to_choi(pauli_op, normalize: bool = False, order: str = 'row', pauli_order: str = 'IXYZ', backend=None)#
Converts Pauli-Liouville representation of a quantum channel to its Choi representation \(\Lambda\).
- Parameters:
pauli_op (ndarray) – superoperator in the Pauli-Liouville representation.
normalize (bool, optional) – If
True
assumespauli_op
is represented in the normalized Pauli basis. IfFalse
, it assumes unnormalized Pauli basis. Defaults toFalse
.order (str, optional) – If
"row"
, returns Choi representation in row-vectorization. If"column"
, returns column-vectorized superoperator. Defaults to"row"
.pauli_order (str, optional) – corresponds to the order of 4 single-qubit Pauli elements. Defaults to “IXYZ”.
backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Choi representation of the superoperator.
- Return type:
ndarray
Pauli-Liouville to Kraus#
- qibo.quantum_info.pauli_to_kraus(pauli_op, normalize: bool = False, order: str = 'row', pauli_order: str = 'IXYZ', precision_tol: float | None = None, backend=None)#
Converts Pauli-Liouville representation of a quantum channel to its Kraus representation \(\{K_{\alpha}\}_{\alpha}\).
- Parameters:
pauli_op (ndarray) – superoperator in the Pauli-Liouville representation.
normalize (bool, optional) – If
True
assumespauli_op
is represented in the normalized Pauli basis. IfFalse
, it assumes unnormalized Pauli basis. Defaults toFalse
.order (str, optional) – vectorization order of the Liouville and Choi intermediate steps. If
"row"
, row-vectorizationcis used for both representations. If"column"
, column-vectorization is used. Defaults to"row"
.pauli_order (str, optional) – corresponds to the order of 4 single-qubit Pauli elements. Defaults to “IXYZ”.
precision_tol (float, optional) – Precision tolerance for eigenvalues found in the spectral decomposition problem. Any eigenvalue \(\lambda <\)
precision_tol
is set to 0 (zero). IfNone
,precision_tol
defaults toqibo.config.PRECISION_TOL=1e-8
. Defaults toNone
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Kraus operators and their coefficients.
- Return type:
(ndarray, ndarray)
Pauli-Liouville to Chi-matrix#
- qibo.quantum_info.pauli_to_chi(pauli_op, normalize: bool = False, order: str = 'row', pauli_order: str = 'IXYZ', backend=None)#
Converts Pauli-Liouville representation of a quantum channel to its \(\chi\)-matrix representation.
- Parameters:
pauli_op (ndarray) – superoperator in the Pauli-Liouville representation.
normalize (bool, optional) – If
True
assumespauli_op
is represented in the normalized Pauli basis. IfFalse
, it assumes unnormalized Pauli basis. Defaults toFalse
.order (str, optional) – If
"row"
, returns Choi representation in row-vectorization. If"column"
, returns column-vectorized superoperator. Defaults to"row"
.pauli_order (str, optional) – corresponds to the order of 4 single-qubit Pauli elements. Defaults to “IXYZ”.
backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Chi-matrix representation of the quantum channel.
- Return type:
ndarray
Pauli-Liouville to Stinespring#
- qibo.quantum_info.pauli_to_stinespring(pauli_op, normalize: bool = False, order: str = 'row', pauli_order: str = 'IXYZ', precision_tol: float | None = None, validate_cp: bool = True, nqubits: int | None = None, initial_state_env=None, backend=None)#
Converts Pauli-Liouville representation \(\mathcal{E}_{P}\) of quantum channel to its Stinespring representation \(U_{0}\). It uses the Liouville representation \(\mathcal{E}\) as intermediate step.
- Parameters:
pauli_op (ndarray) – Pauli-Liouville representation of a quantum channel.
normalize (bool, optional) – If
True
assumespauli_op
is represented in the normalized Pauli basis. IfFalse
, it assumes unnormalized Pauli basis. Defaults toFalse
.order (str, optional) – If
"row"
, returns Liouville representation in row-vectorization. If"column"
, returns column-vectorized superoperator. If"system"
, superoperator will be in block-vectorization. Defaults to"row"
.pauli_order (str, optional) – corresponds to the order of 4 single-qubit Pauli elements. Defaults to “IXYZ”.
precision_tol (float, optional) – Precision tolerance for eigenvalues found in the spectral decomposition problem. Any eigenvalue \(\lambda <\)
precision_tol
is set to 0 (zero). IfNone
,precision_tol
defaults toqibo.config.PRECISION_TOL=1e-8
. Defaults toNone
.validate_cp (bool, optional) – If
True
, checks ifchoi_super_op
is a completely positive map. IfFalse
, it assumes thatchoi_super_op
is completely positive (and Hermitian). Defaults toTrue
.nqubits (int, optional) – total number of qubits in the system that is interacting with the environment. Must be equal or greater than the number of qubits
kraus_ops
acts on. IfNone
, defaults to the number of qubits inkraus_ops
. Defauts toNone
.initial_state_env (ndarray, optional) – statevector representing the initial state of the enviroment. If
None
, it assumes the environment in its ground state. Defaults toNone
.backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Stinestring representation of quantum channel.
- Return type:
ndarray
Chi-matrix to Choi#
- qibo.quantum_info.chi_to_choi(chi_matrix, normalize: bool = False, order: str = 'row', pauli_order: str = 'IXYZ', backend=None)#
Convert the \(\chi\)-matrix representation of a quantum channel to its Choi representation \(\Lambda\).
\[\Lambda = \text{pauli_to_liouville}(\chi)\]- Parameters:
chi_matrix – Chi-matrix representation of quantum channel.
normalize (bool, optional) – If
True
assumes the normalized Pauli basis. IfFalse
, it assumes unnormalized Pauli basis. Defaults toFalse
.order (str, optional) – If
"row"
, reshuffling is performed with respect to row-wise vectorization. If"column"
, reshuffling is performed with respect to column-wise vectorization. If"system"
, operator is converted to a representation based on row vectorization, reshuffled, and then converted back to its representation with respect to system-wise vectorization. Defaults to"row"
.pauli_order (str, optional) – corresponds to the order of 4 single-qubit Pauli elements. Defaults to “IXYZ”.
backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Choi representation of quantum channel.
- Return type:
ndarray
Chi-matrix to Liouville#
- qibo.quantum_info.chi_to_liouville(chi_matrix, normalize: bool = False, order: str = 'row', pauli_order: str = 'IXYZ', backend=None)#
Converts the \(\chi\)-matrix representation of a quantum channel to its Liouville representation \(\mathcal{E}\).
\[\mathcal{E} = \text{pauli_to_liouville}(\text{choi_to_liouville}(\chi))\]- Parameters:
chi_matrix – Chi-matrix representation of quantum channel.
normalize (bool, optional) – If
True
assumes the normalized Pauli basis. IfFalse
, it assumes unnormalized Pauli basis. Defaults toFalse
.order (str, optional) – If
"row"
, reshuffling is performed with respect to row-wise vectorization. If"column"
, reshuffling is performed with respect to column-wise vectorization. If"system"
, operator is converted to a representation based on row vectorization, reshuffled, and then converted back to its representation with respect to system-wise vectorization. Defaults to"row"
.pauli_order (str, optional) – corresponds to the order of 4 single-qubit Pauli elements. Defaults to “IXYZ”.
backend (
qibo.backends.abstract.Backend
, optional) – backend to be used in the execution. IfNone
, it usesqibo.backends.GlobalBackend
. Defaults toNone
.
- Returns:
Liouville representation of quantum channel.
- Return type:
ndarray