qiboml.models#
Submodules#
qiboml.models.encoding#
- class qiboml.models.encoding.QuantumEncoding(nqubits: int, qubits: Optional[tuple[int]] = None, density_matrix: Optional[bool] = False, _circuit: Circuit = None)[source]#
Bases:
ABCAbstract Encoder class.
- Parameters:
- _circuit: Circuit = None#
- abstract __call__(x: ndarray[tuple[int, ...], dtype[_ScalarType_co]]) Circuit[source]#
Abstract call method.
- property circuit: Circuit#
Internal initialized circuit.
- property differentiable: bool#
Whether the encoder is differentiable. If
Truethe gradient w.r.t. the inputs is calculated, otherwise it is automatically set to zero.
- _abc_impl = <_abc._abc_data object>#
- class qiboml.models.encoding.PhaseEncoding(nqubits: int, qubits: Optional[tuple[int]] = None, density_matrix: Optional[bool] = False, _circuit: qibo.models.circuit.Circuit = None, encoding_gate: type = <factory>)[source]#
Bases:
QuantumEncoding- __call__(x: ndarray[tuple[int, ...], dtype[_ScalarType_co]]) Circuit[source]#
Construct the circuit encoding the
xdata in the chosen encoding gate.- Parameters:
x (ndarray) – the input real data to encode in rotation angles.
- Returns:
the constructed
qibo.Circuit.- Return type:
(Circuit)
- _abc_impl = <_abc._abc_data object>#
- _circuit: Circuit = None#
- property circuit: Circuit#
Internal initialized circuit.
- class qiboml.models.encoding.BinaryEncoding(nqubits: int, qubits: Optional[tuple[int]] = None, density_matrix: Optional[bool] = False, _circuit: Circuit = None)[source]#
Bases:
QuantumEncoding- __call__(x: ndarray[tuple[int, ...], dtype[_ScalarType_co]]) Circuit[source]#
Construct the circuit encoding the
xbinary data in someRXrotation gates with angles either \(\pi\) (for ones) or 0 (for zeros).- Parameters:
x (ndarray) – the input binary data.
- Returns:
the constructed
qibo.Circuit.- Return type:
(Circuit)
- property differentiable: bool#
Whether the encoder is differentiable. If
Truethe gradient w.r.t. the inputs is calculated, otherwise it is automatically set to zero.
- _abc_impl = <_abc._abc_data object>#
- _circuit: Circuit = None#
- property circuit: Circuit#
Internal initialized circuit.
qiboml.models.ansatze#
- qiboml.models.ansatze.hardware_efficient(nqubits: int, qubits: Optional[tuple[int]] = None, nlayers: int = 1, single_block: Optional[Circuit] = None, entangling_block: Optional[Circuit] = None, entangling_gate: str = 'CNOT', architecture: str = 'diagonal', closed_boundary: bool = True, seed: Optional[Union[int, Generator]] = None, backend=None, **kwargs) Circuit[source]#
Create a hardware-efficient ansatz with custom single-qubit layers and entangling blocks.
- Parameters:
nqubits (int) – Number of qubits \(n\) in the ansatz.
qubits (tuple[int], optional) – Qubit indexes to apply the ansatz to. If
None, the ansatz is applied to all qubits from \(0\) to \(nqubits-1\). Defaults toNone.nlayers (int, optional) – Number of layers (single-qubit + entangling per layer). Defaults to \(1\).
single_block (Circuit, optional) – \(1\)-qubit circuit applied to each qubit.
None (If) –
:param defaults to a block with
qibo.gates.RYand: :paramqibo.gates.RZgates with Haar-random sampled phases. Defaults toNone.: :param entangling_block: \(n\)-qubit entangling circuit. Defaults toNone. :type entangling_block: Circuit, optional :param entangling_gate: Only used ifentangling_blockis
None. Two-qubit gate to be used in the entangling layer ifentangling_blockis not provided. Ifentangling_gateis a parametrized gate, all phases are initialized as \(0.0\). Defaults to"CNOT".- Parameters:
architecture (str, optional) – Only used if
entangling_blockisNone. Architecture of the entangling layer. In alphabetical order, options are:"diagonal","even_layer","next_nearest","odd_layer","pyramid","shifted","v", and"x". The"x"architecture is only defined for an even number of qubits. Defaults to"diagonal".closed_boundary (bool, optional) – Only used if
entangling_blockisNone. IfTrueandarchitecture not in ["pyramid", "v", "x"], adds a closed-boundary condition to the entangling layer. 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. Default:None.backend (
qibo.backends.abstract.Backend, optional) – backend to be used in the execution. IfNone, it uses the current backend. Defaults toNone.kwargs (dict, optional) – Additional arguments used to initialize a Circuit object. For details, see the documentation of
qibo.models.circuit.Circuit.
- Returns:
Constructed hardware-efficient ansatz.
- Return type:
qibo.models.circuit.Circuit
- qiboml.models.ansatze.HardwareEfficient(nqubits: int, qubits: Optional[tuple[int]] = None, nlayers: int = 1, single_block: Optional[Circuit] = None, entangling_block: Optional[Circuit] = None, entangling_gate: str = 'CNOT', architecture: str = 'diagonal', closed_boundary: bool = True, seed: Optional[Union[int, Generator]] = None, backend=None, **kwargs) Circuit#
Create a hardware-efficient ansatz with custom single-qubit layers and entangling blocks.
- Parameters:
nqubits (int) – Number of qubits \(n\) in the ansatz.
qubits (tuple[int], optional) – Qubit indexes to apply the ansatz to. If
None, the ansatz is applied to all qubits from \(0\) to \(nqubits-1\). Defaults toNone.nlayers (int, optional) – Number of layers (single-qubit + entangling per layer). Defaults to \(1\).
single_block (Circuit, optional) – \(1\)-qubit circuit applied to each qubit.
None (If) –
:param defaults to a block with
qibo.gates.RYand: :paramqibo.gates.RZgates with Haar-random sampled phases. Defaults toNone.: :param entangling_block: \(n\)-qubit entangling circuit. Defaults toNone. :type entangling_block: Circuit, optional :param entangling_gate: Only used ifentangling_blockis
None. Two-qubit gate to be used in the entangling layer ifentangling_blockis not provided. Ifentangling_gateis a parametrized gate, all phases are initialized as \(0.0\). Defaults to"CNOT".- Parameters:
architecture (str, optional) – Only used if
entangling_blockisNone. Architecture of the entangling layer. In alphabetical order, options are:"diagonal","even_layer","next_nearest","odd_layer","pyramid","shifted","v", and"x". The"x"architecture is only defined for an even number of qubits. Defaults to"diagonal".closed_boundary (bool, optional) – Only used if
entangling_blockisNone. IfTrueandarchitecture not in ["pyramid", "v", "x"], adds a closed-boundary condition to the entangling layer. 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. Default:None.backend (
qibo.backends.abstract.Backend, optional) – backend to be used in the execution. IfNone, it uses the current backend. Defaults toNone.kwargs (dict, optional) – Additional arguments used to initialize a Circuit object. For details, see the documentation of
qibo.models.circuit.Circuit.
- Returns:
Constructed hardware-efficient ansatz.
- Return type:
qibo.models.circuit.Circuit
- qiboml.models.ansatze.brickwork_givens(nqubits: int, weight: int, full_hwp: bool = False, **kwargs)[source]#
Create a Hamming-weight-preserving circuit based on brickwork layers of two-qubit Givens rotations.
- Parameters:
nqubits (int) – Total number of qubits.
weight (int) – Hamming weight to be encoded.
full_hwp (bool, optional) – If
False, returns circuit with the necessaryqibo.gates.Xgates included to generate the initial Hamming weight to be preserved. IfTrue, circuit does not include theqibo.gates.Xgates. Defaults toFalse.kwargs (dict, optional) – Additional arguments used to initialize a Circuit object. For details, see the documentation of
qibo.models.circuit.Circuit.
- Returns:
Hamming-weight-preserving brickwork circuit.
- Return type:
qibo.models.circuit.Circuit
References
1. B. T. Gard, L. Zhu1, G. S. Barron, N. J. Mayhall, S. E. Economou, and Edwin Barnes, Efficient symmetry-preserving state preparation circuits for the variational quantum eigensolver algorithm, npj Quantum Information (2020) 6:10.
qiboml.models.decoding#
- class qiboml.models.decoding.QuantumDecoding(nqubits: int, qubits: Optional[tuple[int]] = None, wire_names: Optional[Union[tuple[int], tuple[str]]] = None, nshots: Optional[int] = None, backend: Optional[Backend] = None, transpiler: Optional[Passes] = None, noise_model: Optional[NoiseModel] = None, density_matrix: Optional[bool] = False, _circuit: Circuit = None)[source]#
Bases:
objectAbstract decoder class.
- Parameters:
nqubits (int) – total number of qubits.
qubits (tuple[int], optional) – set of qubits it acts on, by default
range(nqubits).wire_names (tuple[int] | tuple[str], optional) – names to be given to the wires, this has to have
lenequal tonqubits. Additionally, this is mostly useful when executing on hardware to select which qubits to make use of. Namely, if the chip has qubits named:` ("a", "b", "c", "d") `and we wish to deploy a two qubits circuit on the first and last qubits you have to build it as:` decoding = QuantumDecoding(nqubits=2, wire_names=("a", "d")) `nshots (int, optional) – number of shots used for circuit execution and sampling.
backend (Backend, optional) – backend used for computation, by default the globally-set backend is used.
transpiler (Passes, optional) – transpiler to run before circuit execution, by default no transpilation is performed on the circuit (
transpiler=None).noise_model (NoiseModel) – a
NoiseModelof Qibo, which is applied to the given circuit to perform noisy simulations. In case a transpiler is passed, the noise model is applied to the transpiled circuit. Default isNoneand no noise is added.density_matrix (bool) – if
True, density matrix simulation is performed instead of state-vector simulation.
- _circuit: Circuit = None#
- __call__(x: Circuit) Union[CircuitResult, QuantumState, MeasurementOutcomes][source]#
Combine the input circuir with the internal one and execute them with the internal backend.
- Parameters:
x (Circuit) – input circuit.
- Returns:
the execution
qibo.resultobject.- Return type:
(CircuitResult | QuantumState | MeasurementOutcomes)
- preprocessing(x: Circuit) Circuit[source]#
Perform some preprocessing on the input circuit to run with the settings specified by the decoder. In detail, transpilation and noise application on the input circuit is performed.
- align_circuits(x: Circuit)[source]#
Align some attributes of the input circuit with the internal one, e.g. sets the density_matrix and wire_names.
- transpile(x: Circuit) Circuit[source]#
Transpile a given circuit
xusing the instructions provided by thetranspilerattribute.
- property circuit: Circuit#
A copy of the internal circuit.
- Returns:
a copy of the internal circuit.
- Return type:
(Circuit)
- set_backend(backend: Backend)[source]#
Set the internal backend.
- Parameters:
backend (Backend) – backend to be set.
- property output_shape#
The shape of the decoded outputs.
- property analytic: bool#
Whether the decoder is analytic, i.e. the gradient is ananlytically computable, or not (e.g. if sampling is involved).
- Returns:
TrueifnshotsisNone,Falseotherwise.- Return type:
(bool)
- class qiboml.models.decoding.Probabilities(nqubits: int, qubits: Optional[tuple[int]] = None, wire_names: Optional[Union[tuple[int], tuple[str]]] = None, nshots: Optional[int] = None, backend: Optional[Backend] = None, transpiler: Optional[Passes] = None, noise_model: Optional[NoiseModel] = None, density_matrix: Optional[bool] = False, _circuit: Circuit = None)[source]#
Bases:
QuantumDecodingThe probabilities decoder.
- __call__(x: Circuit) ndarray[tuple[int, ...], dtype[_ScalarType_co]][source]#
Computes the final state probabilities.
- Parameters:
x (Circuit) – input circuit.
- Returns:
the final probabilities.
- Return type:
(ndarray)
- property analytic: bool#
Whether the decoder is analytic, i.e. the gradient is ananlytically computable, or not (e.g. if sampling is involved).
- Returns:
TrueifnshotsisNone,Falseotherwise.- Return type:
(bool)
- _align_density_matrix(x: Circuit)#
Share the density matrix attribute with the input circuit.
- _align_wire_names(x: Circuit)#
Share the wire names with the input circuit.
- _circuit: Circuit = None#
- _temporary_nshots(nshots)#
Context manager to execute the decoder with a custom number of shots.
- align_circuits(x: Circuit)#
Align some attributes of the input circuit with the internal one, e.g. sets the density_matrix and wire_names.
- apply_noise(x: Circuit) Circuit#
Apply the decoder
noise_modelto the target circuit.
- property circuit: Circuit#
A copy of the internal circuit.
- Returns:
a copy of the internal circuit.
- Return type:
(Circuit)
- preprocessing(x: Circuit) Circuit#
Perform some preprocessing on the input circuit to run with the settings specified by the decoder. In detail, transpilation and noise application on the input circuit is performed.
- set_backend(backend: Backend)#
Set the internal backend.
- Parameters:
backend (Backend) – backend to be set.
- transpile(x: Circuit) Circuit#
Transpile a given circuit
xusing the instructions provided by thetranspilerattribute.
- class qiboml.models.decoding.Expectation(nqubits: int, qubits: Optional[tuple[int]] = None, wire_names: Optional[Union[tuple[int], tuple[str]]] = None, nshots: Optional[int] = None, backend: Optional[Backend] = None, transpiler: Optional[Passes] = None, noise_model: Optional[NoiseModel] = None, density_matrix: Optional[bool] = False, _circuit: Circuit = None, observable: Union[ndarray[tuple[int, ...], dtype[_ScalarType_co]], Hamiltonian] = None, mitigation_config: Optional[Dict[str, Any]] = None, calibrator: None = None)[source]#
Bases:
QuantumDecodingThe expectation value decoder.
- Parameters:
observable (Hamiltonian | ndarray) – the observable to calculate the expectation value of, by default \(Z_0 + Z_1 + ... + Z_n\) is used.
mitigation_config (dict) –
configuration of the real-time quantum error mitigation method in case it is desired. The real-time quantum error mitigation algorithm is proposed in https://arxiv.org/abs/2311.05680 and consists in performing a real-time check of the reliability of a learned mitigation map. This is done by constructing a reference error-sensitive Clifford circuit, which preserves the size of the original, target one. When the decoder is called, the reliability of the mitigation map is checked by computing a simple metric \(D = |E_{\rm noisy} - E_{\rm mitigated}|\). If the metric is found exceeding an arbitrary threshold value \(\delta\), then a chosen data-driven error mitigation technique is executed to retrieve the mitigation map. To successfully check the reliability of the mitigation map or computing the map itself, it is recommended to use a number of shots which leads to a statistical noise (due to measurements) \(\varepsilon << \delta\). For this reason, the real-time error mitigation algorithm can be customized by passing also a min_iterations argument, which will define the minimum number of decoding calls which have to happen before the mitigation map check is performed. An example of real-time error mitigation configuration is:
mitigation_config = { "threshold": 2e-1, "min_iterations": 500, "method": "CDR", "method_kwargs": {"n_training_samples": 100, "nshots": 10000}, }
The given example is performing real-time error mitigation with the request of computing the mitigation map via Clifford Data Regression whenever the reference expectation value differs from the mitigated one of \(\delta > 0.2\). This check is performed every 500 iterations and, in case it is required, the mitigation map is computed executing circuits with nshots=10000.
- __call__(x: Circuit) ndarray[tuple[int, ...], dtype[_ScalarType_co]][source]#
Execute the input circuit and calculate the expectation value of the internal observable on the final state.
- Parameters:
x (Circuit) – input Circuit.
- Returns:
the calculated expectation value.
- Return type:
(ndarray)
- set_backend(backend: Backend)[source]#
Set the internal and observable’s backends.
- Parameters:
backend (Backend) – backend to be set.
- _align_density_matrix(x: Circuit)#
Share the density matrix attribute with the input circuit.
- _align_wire_names(x: Circuit)#
Share the wire names with the input circuit.
- _circuit: Circuit = None#
- _temporary_nshots(nshots)#
Context manager to execute the decoder with a custom number of shots.
- align_circuits(x: Circuit)#
Align some attributes of the input circuit with the internal one, e.g. sets the density_matrix and wire_names.
- property analytic: bool#
Whether the decoder is analytic, i.e. the gradient is ananlytically computable, or not (e.g. if sampling is involved).
- Returns:
TrueifnshotsisNone,Falseotherwise.- Return type:
(bool)
- apply_noise(x: Circuit) Circuit#
Apply the decoder
noise_modelto the target circuit.
- property circuit: Circuit#
A copy of the internal circuit.
- Returns:
a copy of the internal circuit.
- Return type:
(Circuit)
- preprocessing(x: Circuit) Circuit#
Perform some preprocessing on the input circuit to run with the settings specified by the decoder. In detail, transpilation and noise application on the input circuit is performed.
- transpile(x: Circuit) Circuit#
Transpile a given circuit
xusing the instructions provided by thetranspilerattribute.
- class qiboml.models.decoding.State(nqubits: int, qubits: Optional[tuple[int]] = None, wire_names: Optional[Union[tuple[int], tuple[str]]] = None, nshots: Optional[int] = None, backend: Optional[Backend] = None, transpiler: Optional[Passes] = None, noise_model: Optional[NoiseModel] = None, density_matrix: Optional[bool] = False, _circuit: Circuit = None)[source]#
Bases:
QuantumDecodingThe state decoder.
- __call__(x: Circuit) ndarray[tuple[int, ...], dtype[_ScalarType_co]][source]#
Compute the final state of the input circuit and separates it in its real and imaginary parts stacked on top of each other.
- Parameters:
x (Circuit) – input Circuit.
- Returns:
the final state.
- Return type:
(ndarray)
- property analytic: bool#
Whether the decoder is analytic, i.e. the gradient is ananlytically computable, or not (e.g. if sampling is involved).
- Returns:
TrueifnshotsisNone,Falseotherwise.- Return type:
(bool)
- _align_density_matrix(x: Circuit)#
Share the density matrix attribute with the input circuit.
- _align_wire_names(x: Circuit)#
Share the wire names with the input circuit.
- _circuit: Circuit = None#
- _temporary_nshots(nshots)#
Context manager to execute the decoder with a custom number of shots.
- align_circuits(x: Circuit)#
Align some attributes of the input circuit with the internal one, e.g. sets the density_matrix and wire_names.
- apply_noise(x: Circuit) Circuit#
Apply the decoder
noise_modelto the target circuit.
- property circuit: Circuit#
A copy of the internal circuit.
- Returns:
a copy of the internal circuit.
- Return type:
(Circuit)
- preprocessing(x: Circuit) Circuit#
Perform some preprocessing on the input circuit to run with the settings specified by the decoder. In detail, transpilation and noise application on the input circuit is performed.
- set_backend(backend: Backend)#
Set the internal backend.
- Parameters:
backend (Backend) – backend to be set.
- transpile(x: Circuit) Circuit#
Transpile a given circuit
xusing the instructions provided by thetranspilerattribute.
- class qiboml.models.decoding.Samples(nqubits: int, qubits: Optional[tuple[int]] = None, wire_names: Optional[Union[tuple[int], tuple[str]]] = None, nshots: Optional[int] = None, backend: Optional[Backend] = None, transpiler: Optional[Passes] = None, noise_model: Optional[NoiseModel] = None, density_matrix: Optional[bool] = False, _circuit: Circuit = None)[source]#
Bases:
QuantumDecodingThe samples decoder.
- __call__(x: Circuit) ndarray[tuple[int, ...], dtype[_ScalarType_co]][source]#
Sample the final state of the circuit.
- Parameters:
x (Circuit) – input Circuit.
- Returns:
Generated samples.
- Return type:
ndarray
- property analytic: bool#
Whether the decoder is analytic, i.e. the gradient is ananlytically computable, or not (e.g. if sampling is involved).
- Returns:
TrueifnshotsisNone,Falseotherwise.- Return type:
(bool)
- _align_density_matrix(x: Circuit)#
Share the density matrix attribute with the input circuit.
- _align_wire_names(x: Circuit)#
Share the wire names with the input circuit.
- _circuit: Circuit = None#
- _temporary_nshots(nshots)#
Context manager to execute the decoder with a custom number of shots.
- align_circuits(x: Circuit)#
Align some attributes of the input circuit with the internal one, e.g. sets the density_matrix and wire_names.
- apply_noise(x: Circuit) Circuit#
Apply the decoder
noise_modelto the target circuit.
- property circuit: Circuit#
A copy of the internal circuit.
- Returns:
a copy of the internal circuit.
- Return type:
(Circuit)
- preprocessing(x: Circuit) Circuit#
Perform some preprocessing on the input circuit to run with the settings specified by the decoder. In detail, transpilation and noise application on the input circuit is performed.
- set_backend(backend: Backend)#
Set the internal backend.
- Parameters:
backend (Backend) – backend to be set.
- transpile(x: Circuit) Circuit#
Transpile a given circuit
xusing the instructions provided by thetranspilerattribute.
- class qiboml.models.decoding.VariationalQuantumLinearSolver(nqubits: int, qubits: Optional[tuple[int]] = None, wire_names: Optional[Union[tuple[int], tuple[str]]] = None, nshots: Optional[int] = None, backend: Optional[Backend] = None, transpiler: Optional[Passes] = None, noise_model: Optional[NoiseModel] = None, density_matrix: Optional[bool] = False, _circuit: Circuit = None, *, target_state: ndarray[tuple[int, ...], dtype[_ScalarType_co]], A: ndarray[tuple[int, ...], dtype[_ScalarType_co]])[source]#
Bases:
QuantumDecodingDecoder for the Variational Quantum Linear Solver (VQLS).
- Parameters:
target_state (ndarray) – Target solution vector \(\ket{b}\).
A (ndarray) – The matrix
Ain the linear system \(A \, \ket{x} = \ket{b}\).
- Reference:
C. Bravo-Prieto, R. LaRose, M. Cerezo, Y. Subasi, L. Cincio, and P. J. Coles, Variational quantum linear solver, Quantum 7, 1188 (2023).
- __call__(circuit: Circuit)[source]#
Combine the input circuir with the internal one and execute them with the internal backend.
- Parameters:
x (Circuit) – input circuit.
- Returns:
the execution
qibo.resultobject.- Return type:
(CircuitResult | QuantumState | MeasurementOutcomes)
- property analytic: bool#
Whether the decoder is analytic, i.e. the gradient is ananlytically computable, or not (e.g. if sampling is involved).
- Returns:
TrueifnshotsisNone,Falseotherwise.- Return type:
(bool)
- _align_density_matrix(x: Circuit)#
Share the density matrix attribute with the input circuit.
- _align_wire_names(x: Circuit)#
Share the wire names with the input circuit.
- _circuit: Circuit = None#
- _temporary_nshots(nshots)#
Context manager to execute the decoder with a custom number of shots.
- align_circuits(x: Circuit)#
Align some attributes of the input circuit with the internal one, e.g. sets the density_matrix and wire_names.
- apply_noise(x: Circuit) Circuit#
Apply the decoder
noise_modelto the target circuit.
- property circuit: Circuit#
A copy of the internal circuit.
- Returns:
a copy of the internal circuit.
- Return type:
(Circuit)
- preprocessing(x: Circuit) Circuit#
Perform some preprocessing on the input circuit to run with the settings specified by the decoder. In detail, transpilation and noise application on the input circuit is performed.
- set_backend(backend: Backend)#
Set the internal backend.
- Parameters:
backend (Backend) – backend to be set.
- transpile(x: Circuit) Circuit#
Transpile a given circuit
xusing the instructions provided by thetranspilerattribute.
- qiboml.models.decoding._real_time_mitigation_check(decoder: Expectation, x: Circuit)[source]#
Helper function to execute the real time mitigation check and, if necessary, to compute the reference circuit expectation value.
- qiboml.models.decoding._check_or_recompute_map(decoder: Expectation, x: Circuit)[source]#
Helper function to recompute the mitigation map.