Skip to content

Commit

Permalink
batch of changes
Browse files Browse the repository at this point in the history
  • Loading branch information
renatomello committed Oct 31, 2024
1 parent 0fda301 commit ac06dce
Show file tree
Hide file tree
Showing 6 changed files with 56 additions and 46 deletions.
2 changes: 1 addition & 1 deletion doc/source/code-examples/advancedexamples.rst
Original file line number Diff line number Diff line change
Expand Up @@ -787,7 +787,7 @@ that is supported by Tensorflow, such as defining
and using the `Sequential model API
<https://www.tensorflow.org/api_docs/python/tf/keras/Sequential>`_ to train them.

Similarly, ``pytorch`` supports `automatic differentiation
Similarly, ``pytorch`` `supports automatic differentiation
<https://pytorch.org/tutorials/beginner/basics/autogradqs_tutorFor%20example%20tial.html>`_.
The following script optimizes the parameters of the variational circuit of the first example
using the ``pytorch`` framework.
Expand Down
30 changes: 16 additions & 14 deletions src/qibo/gates/measurements.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ def __init__(
register_name: Optional[str] = None,
collapse: bool = False,
basis: Union[Gate, str] = Z,
p0: Optional["ProbsType"] = None,
p1: Optional["ProbsType"] = None,
p0: Optional["ProbsType"] = None, # type: ignore
p1: Optional["ProbsType"] = None, # type: ignore
):
super().__init__()
self.name = "measure"
Expand Down Expand Up @@ -119,7 +119,7 @@ def raw(self) -> dict:

@staticmethod
def _get_bitflip_tuple(
qubits: Tuple[int, ...], probs: "ProbsType"
qubits: Tuple[int, ...], probs: "ProbsType" # type: ignore
) -> Tuple[float, ...]:
if isinstance(probs, float):
if probs < 0 or probs > 1: # pragma: no cover
Expand All @@ -146,7 +146,7 @@ def _get_bitflip_tuple(

raise_error(TypeError, f"Invalid type {probs} of bitflip map.")

def _get_bitflip_map(self, p: Optional["ProbsType"] = None) -> Dict[int, float]:
def _get_bitflip_map(self, p: Optional["ProbsType"] = None) -> Dict[int, float]: # type: ignore
"""Creates dictionary with bitflip probabilities."""
if p is None:
return {q: 0 for q in self.qubits}
Expand All @@ -163,8 +163,8 @@ def add(self, 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
by the :class:`qibo.models.Circuit`.
The user is not supposed to use this method and a ``ValueError`` is
raised if he does so.
Args:
Expand Down Expand Up @@ -232,22 +232,24 @@ def on_qubits(self, qubit_map) -> "Gate":
and preserving the measurement result register.
Args:
qubit_map (int): Dictionary mapping original qubit indices to new ones.
qubit_map (dict): Dictionary mapping original qubit indices to new ones.
Returns:
A :class:`qibo.gates.Gate.M` object of the original gate
type targeting the given qubits.
:class:`qibo.gates.Gate.M`: object of the original gate type targeting
the given qubits.
Example:
.. testcode::
from qibo import models, gates
from qibo import Circuit, gates
measurement = gates.M(0, 1)
c = models.Circuit(3)
c.add(measurement.on_qubits({0: 0, 1: 2}))
assert c.queue[0].result is measurement.result
c.draw()
circuit = Circuit(3)
circuit.add(measurement.on_qubits({0: 0, 1: 2}))
assert circuit.queue[0].result is measurement.result
circuit.draw()
.. testoutput::
q0: ─M─
Expand Down
2 changes: 1 addition & 1 deletion src/qibo/hamiltonians/adiabatic.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ def circuit(self, dt, accelerators=None, t=0):
t (float): Time that the Hamiltonian should be calculated.
Returns:
A :class:`qibo.models.Circuit` implementing the Trotterized evolution.
:class:`qibo.models.Circuit`: Circuit implementing the Trotterized evolution.
"""
from qibo import Circuit # pylint: disable=import-outside-toplevel
from qibo.hamiltonians.terms import ( # pylint: disable=import-outside-toplevel
Expand Down
44 changes: 23 additions & 21 deletions src/qibo/models/circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,16 +345,17 @@ def on_qubits(self, *qubits):
.. testcode::
from qibo import gates, models
from qibo import Circuit, gates
# 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)))
small_circuit = Circuit(4)
small_circuit.add(gates.RX(i, theta=0.1) for i in range(4))
small_circuit.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)))
large_circuit = Circuit(8)
large_circuit.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)))
large_circuit.add(smallc.on_qubits(*range(0, 8, 2)))
"""
if len(qubits) != self.nqubits:
raise_error(
Expand Down Expand Up @@ -384,7 +385,7 @@ def light_cone(self, *qubits):
qubits (int): Qubit ids that the observable has support on.
Returns:
circuit (qibo.models.Circuit): Circuit that contains only
circuit (:class:`qibo.models.Circuit`): 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
Expand Down Expand Up @@ -977,14 +978,15 @@ def fuse(self, max_qubits=2):
Example:
.. testcode::
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)])
from qibo import Circuit, gates
circuit = Circuit(2)
circuit.add([gates.H(0), gates.H(1)])
circuit.add(gates.CNOT(0, 1))
circuit.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
fused_circuit = circuit.fuse()
# now ``fused_circuit`` contains a single ``FusedGate`` that is
# equivalent to applying the five original gates
"""
if self.accelerators: # pragma: no cover
Expand Down Expand Up @@ -1207,19 +1209,19 @@ def from_qasm(cls, qasm_code, accelerators=None, density_matrix=False):
.. testcode::
from qibo import gates, models
from qibo import Circuit, gates
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)
circuit = 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_2 = Circuit(2)
circuit_2.add(gates.H(0))
circuit_2.add(gates.H(1))
circuit_2.add(gates.CNOT(0, 1))
"""
parser = QASMParser()
return parser.to_circuit(qasm_code, accelerators, density_matrix)
Expand Down
4 changes: 2 additions & 2 deletions src/qibo/models/error_mitigation.py
Original file line number Diff line number Diff line change
Expand Up @@ -821,7 +821,7 @@ def get_expectation_val_with_readout_mitigation(
Applies readout error mitigation to the given circuit and observable.
Args:
circuit (qibo.models.Circuit): input circuit.
circuit (:class:`qibo.models.Circuit`): input circuit.
observable (:class:`qibo.hamiltonians.Hamiltonian/:class:`qibo.hamiltonians.SymbolicHamiltonian`): The observable to be measured.
noise_model (qibo.models.noise.Noise, optional): the noise model to be applied. Defaults to ``None``.
nshots (int, optional): the number of shots for the circuit execution. Defaults to :math:`10000`.
Expand Down Expand Up @@ -1163,7 +1163,7 @@ def _execute_circuit(circuit, qubit_map, noise_model=None, nshots=10000, backend
Helper function to execute the given circuit with the specified parameters.
Args:
circuit (qibo.models.Circuit): input circuit.
circuit (:class:`qibo.models.Circuit`): input circuit.
qubit_map (list): the qubit map. If ``None``, a list of range of circuit's qubits is used. Defaults to ``None``.
noise_model (qibo.models.noise.Noise, optional): The noise model to be applied. Defaults to ``None``.
nshots (int): the number of shots for the circuit execution. Defaults to :math:`10000`..
Expand Down
20 changes: 13 additions & 7 deletions src/qibo/models/qcnn.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
""" This module implements a Quantum Convolutional Neural Network (QCNN) for classification tasks. The QCNN model was originally proposed in: arXiv:1810.03787 <https://arxiv.org/abs/1810.03787>_ for the identification of quantum phases.
""" This module implements a Quantum Convolutional Neural Network (QCNN) for classification tasks.
The QCNN model was originally proposed in: arXiv:1810.03787 <https://arxiv.org/abs/1810.03787>_
for the identification of quantum phases.
The QuantumCNN class in this module provides methods to construct the QCNN.
"""
Expand All @@ -14,27 +16,31 @@ class QuantumCNN:
"""
Model that implements and trains a variational quantum convolutional network (QCNN) for
classification tasks.
The QCNN model was originally proposed in: `arXiv:1810.03787 <https://arxiv.org/abs/1810.03787>`_
for the identification of quantum phases.
The QCNN model was originally proposed in: `arXiv:1810.03787
<https://arxiv.org/abs/1810.03787>`_ for the identification of quantum phases.
Args:
nqubits (int): number of qubits of the input states. Currently supports powers of 2.
nlayers (int): number of convolutional and pooling layers.
nclasses (int): number of classes to be classified. Default setting of 2 (phases).
params: initial list of variational parameters. If not provided, all parameters
will be initialized to zero.
twoqubitansatz (:class:`qibo.models.Circuit`): a two qubit ansatz that can be input by the user to form the two qubit ansatz used in the convolutional circuit.
twoqubitansatz (:class:`qibo.models.Circuit`): a two qubit ansatz that can be input by
the user to form the two qubit ansatz used in the convolutional circuit.
Example:
.. testcode::
import math
import numpy as np
import random
import qibo
import numpy as np
from qibo import set_backend
from qibo.models.qcnn import QuantumCNN
set_backend("numpy")
qibo.set_backend("numpy")
data = np.random.rand(16)
data = data / np.linalg.norm(data)
data = [data]
Expand Down

0 comments on commit ac06dce

Please sign in to comment.