repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/Qiskit/feedback
Qiskit
# Install qiskit-terra=0.21 to use group_commuting() # ! pip install qiskit-terra=0.21 from collections import defaultdict from numbers import Number from typing import Dict from collections import defaultdict import numpy as np import retworkx as rx from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.custom_iterator import CustomIterator from qiskit.quantum_info.operators.mixins import GroupMixin, LinearMixin from qiskit.quantum_info.operators.symplectic.base_pauli import BasePauli from qiskit.quantum_info.operators.symplectic.pauli import Pauli from qiskit.quantum_info.operators.symplectic.pauli_table import PauliTable from qiskit.quantum_info.operators.symplectic.stabilizer_table import StabilizerTable from qiskit.quantum_info.operators.linear_op import LinearOp from qiskit.utils.deprecation import deprecate_function # if version incompativility occurs in terra 0.21, set PauliList and SparsePauliOp class below. class PauliList(BasePauli, LinearMixin, GroupMixin): r"""List of N-qubit Pauli operators. This class is an efficient representation of a list of :class:`Pauli` operators. It supports 1D numpy array indexing returning a :class:`Pauli` for integer indexes or a :class:`PauliList` for slice or list indices. **Initialization** A PauliList object can be initialized in several ways. ``PauliList(list[str])`` where strings are same representation with :class:`~qiskit.quantum_info.Pauli`. ``PauliList(Pauli) and PauliList(list[Pauli])`` where Pauli is :class:`~qiskit.quantum_info.Pauli`. ``PauliList.from_symplectic(z, x, phase)`` where ``z`` and ``x`` are 2 dimensional boolean ``numpy.ndarrays`` and ``phase`` is an integer in ``[0, 1, 2, 3]``. For example, .. jupyter-execute:: import numpy as np from qiskit.quantum_info import Pauli, PauliList # 1. init from list[str] pauli_list = PauliList(["II", "+ZI", "-iYY"]) print("1. ", pauli_list) pauli1 = Pauli("iXI") pauli2 = Pauli("iZZ") # 2. init from Pauli print("2. ", PauliList(pauli1)) # 3. init from list[Pauli] print("3. ", PauliList([pauli1, pauli2])) # 4. init from np.ndarray z = np.array([[True, True], [False, False]]) x = np.array([[False, True], [True, False]]) phase = np.array([0, 1]) pauli_list = PauliList.from_symplectic(z, x, phase) print("4. ", pauli_list) **Data Access** The individual Paulis can be accessed and updated using the ``[]`` operator which accepts integer, lists, or slices for selecting subsets of PauliList. If integer is given, it returns Pauli not PauliList. .. jupyter-execute:: pauli_list = PauliList(["XX", "ZZ", "IZ"]) print("Integer: ", repr(pauli_list[1])) print("List: ", repr(pauli_list[[0, 2]])) print("Slice: ", repr(pauli_list[0:2])) **Iteration** Rows in the Pauli table can be iterated over like a list. Iteration can also be done using the label or matrix representation of each row using the :meth:`label_iter` and :meth:`matrix_iter` methods. """ # Set the max number of qubits * paulis before string truncation __truncate__ = 2000 def __init__(self, data): """Initialize the PauliList. Args: data (Pauli or list): input data for Paulis. If input is a list each item in the list must be a Pauli object or Pauli str. Raises: QiskitError: if input array is invalid shape. Additional Information: The input array is not copied so multiple Pauli tables can share the same underlying array. """ if isinstance(data, BasePauli): base_z, base_x, base_phase = data._z, data._x, data._phase elif isinstance(data, StabilizerTable): # Conversion from legacy StabilizerTable base_z, base_x, base_phase = self._from_array(data.Z, data.X, 2 * data.phase) elif isinstance(data, PauliTable): # Conversion from legacy PauliTable base_z, base_x, base_phase = self._from_array(data.Z, data.X) else: # Conversion as iterable of Paulis base_z, base_x, base_phase = self._from_paulis(data) # Initialize BasePauli super().__init__(base_z, base_x, base_phase) # --------------------------------------------------------------------- # Representation conversions # --------------------------------------------------------------------- @property def settings(self): """Return settings.""" return {"data": self.to_labels()} def __array__(self, dtype=None): """Convert to numpy array""" # pylint: disable=unused-argument shape = (len(self),) + 2 * (2**self.num_qubits,) ret = np.zeros(shape, dtype=complex) for i, mat in enumerate(self.matrix_iter()): ret[i] = mat return ret @staticmethod def _from_paulis(data): """Construct a PauliList from a list of Pauli data. Args: data (iterable): list of Pauli data. Returns: PauliList: the constructed PauliList. Raises: QiskitError: If the input list is empty or contains invalid Pauli strings. """ if not isinstance(data, (list, tuple, set, np.ndarray)): data = [data] num_paulis = len(data) if num_paulis == 0: raise QiskitError("Input Pauli list is empty.") paulis = [] for i in data: if not isinstance(i, Pauli): paulis.append(Pauli(i)) else: paulis.append(i) num_qubits = paulis[0].num_qubits base_z = np.zeros((num_paulis, num_qubits), dtype=bool) base_x = np.zeros((num_paulis, num_qubits), dtype=bool) base_phase = np.zeros(num_paulis, dtype=int) for i, pauli in enumerate(paulis): base_z[i] = pauli._z base_x[i] = pauli._x base_phase[i] = pauli._phase return base_z, base_x, base_phase def __repr__(self): """Display representation.""" return self._truncated_str(True) def __str__(self): """Print representation.""" return self._truncated_str(False) def _truncated_str(self, show_class): stop = self._num_paulis if self.__truncate__: max_paulis = self.__truncate__ // self.num_qubits if self._num_paulis > max_paulis: stop = max_paulis labels = [str(self[i]) for i in range(stop)] prefix = "PauliList(" if show_class else "" tail = ")" if show_class else "" if stop != self._num_paulis: suffix = ", ...]" + tail else: suffix = "]" + tail list_str = np.array2string( np.array(labels), threshold=stop + 1, separator=", ", prefix=prefix, suffix=suffix ) return prefix + list_str[:-1] + suffix def __eq__(self, other): """Entrywise comparison of Pauli equality.""" if not isinstance(other, PauliList): other = PauliList(other) if not isinstance(other, BasePauli): return False return self._eq(other) def equiv(self, other): """Entrywise comparison of Pauli equivalence up to global phase. Args: other (PauliList or Pauli): a comparison object. Returns: np.ndarray: An array of True or False for entrywise equivalence of the current table. """ if not isinstance(other, PauliList): other = PauliList(other) return np.all(self.z == other.z, axis=1) & np.all(self.x == other.x, axis=1) # --------------------------------------------------------------------- # Direct array access # --------------------------------------------------------------------- @property def phase(self): """Return the phase exponent of the PauliList.""" # Convert internal ZX-phase convention to group phase convention return np.mod(self._phase - self._count_y(), 4) @phase.setter def phase(self, value): # Convert group phase convetion to internal ZX-phase convention self._phase[:] = np.mod(value + self._count_y(), 4) @property def x(self): """The x array for the symplectic representation.""" return self._x @x.setter def x(self, val): self._x[:] = val @property def z(self): """The z array for the symplectic representation.""" return self._z @z.setter def z(self, val): self._z[:] = val # --------------------------------------------------------------------- # Size Properties # --------------------------------------------------------------------- @property def shape(self): """The full shape of the :meth:`array`""" return self._num_paulis, self.num_qubits @property def size(self): """The number of Pauli rows in the table.""" return self._num_paulis def __len__(self): """Return the number of Pauli rows in the table.""" return self._num_paulis # --------------------------------------------------------------------- # Pauli Array methods # --------------------------------------------------------------------- def __getitem__(self, index): """Return a view of the PauliList.""" # Returns a view of specified rows of the PauliList # This supports all slicing operations the underlying array supports. if isinstance(index, tuple): if len(index) == 1: index = index[0] elif len(index) > 2: raise IndexError(f"Invalid PauliList index {index}") # Row-only indexing if isinstance(index, (int, np.integer)): # Single Pauli return Pauli( BasePauli( self._z[np.newaxis, index], self._x[np.newaxis, index], self._phase[np.newaxis, index], ) ) elif isinstance(index, (slice, list, np.ndarray)): # Sub-Table view return PauliList(BasePauli(self._z[index], self._x[index], self._phase[index])) # Row and Qubit indexing return PauliList((self._z[index], self._x[index], 0)) def __setitem__(self, index, value): """Update PauliList.""" if isinstance(index, tuple): if len(index) == 1: index = index[0] elif len(index) > 2: raise IndexError(f"Invalid PauliList index {index}") # Modify specified rows of the PauliList if not isinstance(value, PauliList): value = PauliList(value) self._z[index] = value._z self._x[index] = value._x if not isinstance(index, tuple): # Row-only indexing self._phase[index] = value._phase else: # Row and Qubit indexing self._phase[index[0]] += value._phase self._phase %= 4 def delete(self, ind, qubit=False): """Return a copy with Pauli rows deleted from table. When deleting qubits the qubit index is the same as the column index of the underlying :attr:`X` and :attr:`Z` arrays. Args: ind (int or list): index(es) to delete. qubit (bool): if True delete qubit columns, otherwise delete Pauli rows (Default: False). Returns: PauliList: the resulting table with the entries removed. Raises: QiskitError: if ind is out of bounds for the array size or number of qubits. """ if isinstance(ind, int): ind = [ind] # Row deletion if not qubit: if max(ind) >= len(self): raise QiskitError( "Indices {} are not all less than the size" " of the PauliList ({})".format(ind, len(self)) ) z = np.delete(self._z, ind, axis=0) x = np.delete(self._x, ind, axis=0) phase = np.delete(self._phase, ind) return PauliList(BasePauli(z, x, phase)) # Column (qubit) deletion if max(ind) >= self.num_qubits: raise QiskitError( "Indices {} are not all less than the number of" " qubits in the PauliList ({})".format(ind, self.num_qubits) ) z = np.delete(self._z, ind, axis=1) x = np.delete(self._x, ind, axis=1) # Use self.phase, not self._phase as deleting qubits can change the # ZX phase convention return PauliList.from_symplectic(z, x, self.phase) def insert(self, ind, value, qubit=False): """Insert Pauli's into the table. When inserting qubits the qubit index is the same as the column index of the underlying :attr:`X` and :attr:`Z` arrays. Args: ind (int): index to insert at. value (PauliList): values to insert. qubit (bool): if True delete qubit columns, otherwise delete Pauli rows (Default: False). Returns: PauliList: the resulting table with the entries inserted. Raises: QiskitError: if the insertion index is invalid. """ if not isinstance(ind, int): raise QiskitError("Insert index must be an integer.") if not isinstance(value, PauliList): value = PauliList(value) # Row insertion size = self._num_paulis if not qubit: if ind > size: raise QiskitError( "Index {} is larger than the number of rows in the" " PauliList ({}).".format(ind, size) ) base_z = np.insert(self._z, ind, value._z, axis=0) base_x = np.insert(self._x, ind, value._x, axis=0) base_phase = np.insert(self._phase, ind, value._phase) return PauliList(BasePauli(base_z, base_x, base_phase)) # Column insertion if ind > self.num_qubits: raise QiskitError( "Index {} is greater than number of qubits" " in the PauliList ({})".format(ind, self.num_qubits) ) if len(value) == 1: # Pad blocks to correct size value_x = np.vstack(size * [value.x]) value_z = np.vstack(size * [value.z]) value_phase = np.vstack(size * [value.phase]) elif len(value) == size: # Blocks are already correct size value_x = value.x value_z = value.z value_phase = value.phase else: # Blocks are incorrect size raise QiskitError( "Input PauliList must have a single row, or" " the same number of rows as the Pauli Table" " ({}).".format(size) ) # Build new array by blocks z = np.hstack([self.z[:, :ind], value_z, self.z[:, ind:]]) x = np.hstack([self.x[:, :ind], value_x, self.x[:, ind:]]) phase = self.phase + value_phase return PauliList.from_symplectic(z, x, phase) def argsort(self, weight=False, phase=False): """Return indices for sorting the rows of the table. The default sort method is lexicographic sorting by qubit number. By using the `weight` kwarg the output can additionally be sorted by the number of non-identity terms in the Pauli, where the set of all Pauli's of a given weight are still ordered lexicographically. Args: weight (bool): Optionally sort by weight if True (Default: False). phase (bool): Optionally sort by phase before weight or order (Default: False). Returns: array: the indices for sorting the table. """ # Get order of each Pauli using # I => 0, X => 1, Y => 2, Z => 3 x = self.x z = self.z order = 1 * (x & ~z) + 2 * (x & z) + 3 * (~x & z) phases = self.phase # Optionally get the weight of Pauli # This is the number of non identity terms if weight: weights = np.sum(x | z, axis=1) # To preserve ordering between successive sorts we # are use the 'stable' sort method indices = np.arange(self._num_paulis) # Initial sort by phases sort_inds = phases.argsort(kind="stable") indices = indices[sort_inds] order = order[sort_inds] if phase: phases = phases[sort_inds] if weight: weights = weights[sort_inds] # Sort by order for i in range(self.num_qubits): sort_inds = order[:, i].argsort(kind="stable") order = order[sort_inds] indices = indices[sort_inds] if weight: weights = weights[sort_inds] if phase: phases = phases[sort_inds] # If using weights we implement a sort by total number # of non-identity Paulis if weight: sort_inds = weights.argsort(kind="stable") indices = indices[sort_inds] phases = phases[sort_inds] # If sorting by phase we perform a final sort by the phase value # of each pauli if phase: indices = indices[phases.argsort(kind="stable")] return indices def sort(self, weight=False, phase=False): """Sort the rows of the table. The default sort method is lexicographic sorting by qubit number. By using the `weight` kwarg the output can additionally be sorted by the number of non-identity terms in the Pauli, where the set of all Pauli's of a given weight are still ordered lexicographically. **Example** Consider sorting all a random ordering of all 2-qubit Paulis .. jupyter-execute:: from numpy.random import shuffle from qiskit.quantum_info.operators import PauliList # 2-qubit labels labels = ['II', 'IX', 'IY', 'IZ', 'XI', 'XX', 'XY', 'XZ', 'YI', 'YX', 'YY', 'YZ', 'ZI', 'ZX', 'ZY', 'ZZ'] # Shuffle Labels shuffle(labels) pt = PauliList(labels) print('Initial Ordering') print(pt) # Lexicographic Ordering srt = pt.sort() print('Lexicographically sorted') print(srt) # Weight Ordering srt = pt.sort(weight=True) print('Weight sorted') print(srt) Args: weight (bool): optionally sort by weight if True (Default: False). phase (bool): Optionally sort by phase before weight or order (Default: False). Returns: PauliList: a sorted copy of the original table. """ return self[self.argsort(weight=weight, phase=phase)] def unique(self, return_index=False, return_counts=False): """Return unique Paulis from the table. **Example** .. jupyter-execute:: from qiskit.quantum_info.operators import PauliList pt = PauliList(['X', 'Y', '-X', 'I', 'I', 'Z', 'X', 'iZ']) unique = pt.unique() print(unique) Args: return_index (bool): If True, also return the indices that result in the unique array. (Default: False) return_counts (bool): If True, also return the number of times each unique item appears in the table. Returns: PauliList: unique the table of the unique rows. unique_indices: np.ndarray, optional The indices of the first occurrences of the unique values in the original array. Only provided if ``return_index`` is True. unique_counts: np.array, optional The number of times each of the unique values comes up in the original array. Only provided if ``return_counts`` is True. """ # Check if we need to stack the phase array if np.any(self._phase != self._phase[0]): # Create a single array of Pauli's and phases for calling np.unique on # so that we treat different phased Pauli's as unique array = np.hstack([self._z, self._x, self.phase.reshape((self.phase.shape[0], 1))]) else: # All Pauli's have the same phase so we only need to sort the array array = np.hstack([self._z, self._x]) # Get indexes of unique entries if return_counts: _, index, counts = np.unique(array, return_index=True, return_counts=True, axis=0) else: _, index = np.unique(array, return_index=True, axis=0) # Sort the index so we return unique rows in the original array order sort_inds = index.argsort() index = index[sort_inds] unique = PauliList(BasePauli(self._z[index], self._x[index], self._phase[index])) # Concatinate return tuples ret = (unique,) if return_index: ret += (index,) if return_counts: ret += (counts[sort_inds],) if len(ret) == 1: return ret[0] return ret # --------------------------------------------------------------------- # BaseOperator methods # --------------------------------------------------------------------- def tensor(self, other): """Return the tensor product with each Pauli in the list. Args: other (PauliList): another PauliList. Returns: PauliList: the list of tensor product Paulis. Raises: QiskitError: if other cannot be converted to a PauliList, does not have either 1 or the same number of Paulis as the current list. """ if not isinstance(other, PauliList): other = PauliList(other) return PauliList(super().tensor(other)) def expand(self, other): """Return the expand product of each Pauli in the list. Args: other (PauliList): another PauliList. Returns: PauliList: the list of tensor product Paulis. Raises: QiskitError: if other cannot be converted to a PauliList, does not have either 1 or the same number of Paulis as the current list. """ if not isinstance(other, PauliList): other = PauliList(other) if len(other) not in [1, len(self)]: raise QiskitError( "Incompatible PauliLists. Other list must " "have either 1 or the same number of Paulis." ) return PauliList(super().expand(other)) def compose(self, other, qargs=None, front=False, inplace=False): """Return the composition self∘other for each Pauli in the list. Args: other (PauliList): another PauliList. qargs (None or list): qubits to apply dot product on (Default: None). front (bool): If True use `dot` composition method [default: False]. inplace (bool): If True update in-place (default: False). Returns: PauliList: the list of composed Paulis. Raises: QiskitError: if other cannot be converted to a PauliList, does not have either 1 or the same number of Paulis as the current list, or has the wrong number of qubits for the specified qargs. """ if qargs is None: qargs = getattr(other, "qargs", None) if not isinstance(other, PauliList): other = PauliList(other) if len(other) not in [1, len(self)]: raise QiskitError( "Incompatible PauliLists. Other list must " "have either 1 or the same number of Paulis." ) return PauliList(super().compose(other, qargs=qargs, front=front, inplace=inplace)) # pylint: disable=arguments-differ def dot(self, other, qargs=None, inplace=False): """Return the composition other∘self for each Pauli in the list. Args: other (PauliList): another PauliList. qargs (None or list): qubits to apply dot product on (Default: None). inplace (bool): If True update in-place (default: False). Returns: PauliList: the list of composed Paulis. Raises: QiskitError: if other cannot be converted to a PauliList, does not have either 1 or the same number of Paulis as the current list, or has the wrong number of qubits for the specified qargs. """ return self.compose(other, qargs=qargs, front=True, inplace=inplace) def _add(self, other, qargs=None): """Append two PauliLists. If ``qargs`` are specified the other operator will be added assuming it is identity on all other subsystems. Args: other (PauliList): another table. qargs (None or list): optional subsystems to add on (Default: None) Returns: PauliList: the concatenated list self + other. """ if qargs is None: qargs = getattr(other, "qargs", None) if not isinstance(other, PauliList): other = PauliList(other) self._op_shape._validate_add(other._op_shape, qargs) base_phase = np.hstack((self._phase, other._phase)) if qargs is None or (sorted(qargs) == qargs and len(qargs) == self.num_qubits): base_z = np.vstack([self._z, other._z]) base_x = np.vstack([self._x, other._x]) else: # Pad other with identity and then add padded = BasePauli( np.zeros((other.size, self.num_qubits), dtype=bool), np.zeros((other.size, self.num_qubits), dtype=bool), np.zeros(other.size, dtype=int), ) padded = padded.compose(other, qargs=qargs, inplace=True) base_z = np.vstack([self._z, padded._z]) base_x = np.vstack([self._x, padded._x]) return PauliList(BasePauli(base_z, base_x, base_phase)) def _multiply(self, other): """Multiply each Pauli in the list by a phase. Args: other (complex or array): a complex number in [1, -1j, -1, 1j] Returns: PauliList: the list of Paulis other * self. Raises: QiskitError: if the phase is not in the set [1, -1j, -1, 1j]. """ return PauliList(super()._multiply(other)) def conjugate(self): """Return the conjugate of each Pauli in the list.""" return PauliList(super().conjugate()) def transpose(self): """Return the transpose of each Pauli in the list.""" return PauliList(super().transpose()) def adjoint(self): """Return the adjoint of each Pauli in the list.""" return PauliList(super().adjoint()) def inverse(self): """Return the inverse of each Pauli in the list.""" return PauliList(super().adjoint()) # --------------------------------------------------------------------- # Utility methods # --------------------------------------------------------------------- def commutes(self, other, qargs=None): """Return True for each Pauli that commutes with other. Args: other (PauliList): another PauliList operator. qargs (list): qubits to apply dot product on (default: None). Returns: bool: True if Pauli's commute, False if they anti-commute. """ if qargs is None: qargs = getattr(other, "qargs", None) if not isinstance(other, BasePauli): other = PauliList(other) return super().commutes(other, qargs=qargs) def anticommutes(self, other, qargs=None): """Return True if other Pauli that anticommutes with other. Args: other (PauliList): another PauliList operator. qargs (list): qubits to apply dot product on (default: None). Returns: bool: True if Pauli's anticommute, False if they commute. """ return np.logical_not(self.commutes(other, qargs=qargs)) def commutes_with_all(self, other): """Return indexes of rows that commute other. If other is a multi-row Pauli list the returned vector indexes rows of the current PauliList that commute with *all* Pauli's in other. If no rows satisfy the condition the returned array will be empty. Args: other (PauliList): a single Pauli or multi-row PauliList. Returns: array: index array of the commuting rows. """ return self._commutes_with_all(other) def anticommutes_with_all(self, other): """Return indexes of rows that commute other. If other is a multi-row Pauli list the returned vector indexes rows of the current PauliList that anti-commute with *all* Pauli's in other. If no rows satisfy the condition the returned array will be empty. Args: other (PauliList): a single Pauli or multi-row PauliList. Returns: array: index array of the anti-commuting rows. """ return self._commutes_with_all(other, anti=True) def _commutes_with_all(self, other, anti=False): """Return row indexes that commute with all rows in another PauliList. Args: other (PauliList): a PauliList. anti (bool): if True return rows that anti-commute, otherwise return rows that commute (Default: False). Returns: array: index array of commuting or anti-commuting row. """ if not isinstance(other, PauliList): other = PauliList(other) comms = self.commutes(other[0]) (inds,) = np.where(comms == int(not anti)) for pauli in other[1:]: comms = self[inds].commutes(pauli) (new_inds,) = np.where(comms == int(not anti)) if new_inds.size == 0: # No commuting rows return new_inds inds = inds[new_inds] return inds def evolve(self, other, qargs=None, frame="h"): r"""Evolve the Pauli by a Clifford. This returns the Pauli :math:`P^\prime = C.P.C^\dagger`. By choosing the parameter frame='s', this function returns the Schrödinger evolution of the Pauli :math:`P^\prime = C.P.C^\dagger`. This option yields a faster calculation. Args: other (Pauli or Clifford or QuantumCircuit): The Clifford operator to evolve by. qargs (list): a list of qubits to apply the Clifford to. frame (string): 'h' for Heisenberg or 's' for Schrödinger framework. Returns: Pauli: the Pauli :math:`C.P.C^\dagger`. Raises: QiskitError: if the Clifford number of qubits and qargs don't match. """ from qiskit.circuit import Instruction, QuantumCircuit from qiskit.quantum_info.operators.symplectic.clifford import Clifford if qargs is None: qargs = getattr(other, "qargs", None) if not isinstance(other, (BasePauli, Instruction, QuantumCircuit, Clifford)): # Convert to a PauliList other = PauliList(other) return PauliList(super().evolve(other, qargs=qargs, frame=frame)) def to_labels(self, array=False): r"""Convert a PauliList to a list Pauli string labels. For large PauliLists converting using the ``array=True`` kwarg will be more efficient since it allocates memory for the full Numpy array of labels in advance. .. list-table:: Pauli Representations :header-rows: 1 * - Label - Symplectic - Matrix * - ``"I"`` - :math:`[0, 0]` - :math:`\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}` * - ``"X"`` - :math:`[1, 0]` - :math:`\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}` * - ``"Y"`` - :math:`[1, 1]` - :math:`\begin{bmatrix} 0 & -i \\ i & 0 \end{bmatrix}` * - ``"Z"`` - :math:`[0, 1]` - :math:`\begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}` Args: array (bool): return a Numpy array if True, otherwise return a list (Default: False). Returns: list or array: The rows of the PauliList in label form. """ if (self.phase == 1).any(): prefix_len = 2 elif (self.phase > 0).any(): prefix_len = 1 else: prefix_len = 0 str_len = self.num_qubits + prefix_len ret = np.zeros(self.size, dtype=f"<U{str_len}") iterator = self.label_iter() for i in range(self.size): ret[i] = next(iterator) if array: return ret return ret.tolist() def to_matrix(self, sparse=False, array=False): r"""Convert to a list or array of Pauli matrices. For large PauliLists converting using the ``array=True`` kwarg will be more efficient since it allocates memory a full rank-3 Numpy array of matrices in advance. .. list-table:: Pauli Representations :header-rows: 1 * - Label - Symplectic - Matrix * - ``"I"`` - :math:`[0, 0]` - :math:`\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}` * - ``"X"`` - :math:`[1, 0]` - :math:`\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}` * - ``"Y"`` - :math:`[1, 1]` - :math:`\begin{bmatrix} 0 & -i \\ i & 0 \end{bmatrix}` * - ``"Z"`` - :math:`[0, 1]` - :math:`\begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}` Args: sparse (bool): if True return sparse CSR matrices, otherwise return dense Numpy arrays (Default: False). array (bool): return as rank-3 numpy array if True, otherwise return a list of Numpy arrays (Default: False). Returns: list: A list of dense Pauli matrices if `array=False` and `sparse=False`. list: A list of sparse Pauli matrices if `array=False` and `sparse=True`. array: A dense rank-3 array of Pauli matrices if `array=True`. """ if not array: # We return a list of Numpy array matrices return list(self.matrix_iter(sparse=sparse)) # For efficiency we also allow returning a single rank-3 # array where first index is the Pauli row, and second two # indices are the matrix indices dim = 2**self.num_qubits ret = np.zeros((self.size, dim, dim), dtype=complex) iterator = self.matrix_iter(sparse=sparse) for i in range(self.size): ret[i] = next(iterator) return ret # --------------------------------------------------------------------- # Custom Iterators # --------------------------------------------------------------------- def label_iter(self): """Return a label representation iterator. This is a lazy iterator that converts each row into the string label only as it is used. To convert the entire table to labels use the :meth:`to_labels` method. Returns: LabelIterator: label iterator object for the PauliList. """ class LabelIterator(CustomIterator): """Label representation iteration and item access.""" def __repr__(self): return f"<PauliList_label_iterator at {hex(id(self))}>" def __getitem__(self, key): return self.obj._to_label(self.obj._z[key], self.obj._x[key], self.obj._phase[key]) return LabelIterator(self) def matrix_iter(self, sparse=False): """Return a matrix representation iterator. This is a lazy iterator that converts each row into the Pauli matrix representation only as it is used. To convert the entire table to matrices use the :meth:`to_matrix` method. Args: sparse (bool): optionally return sparse CSR matrices if True, otherwise return Numpy array matrices (Default: False) Returns: MatrixIterator: matrix iterator object for the PauliList. """ class MatrixIterator(CustomIterator): """Matrix representation iteration and item access.""" def __repr__(self): return f"<PauliList_matrix_iterator at {hex(id(self))}>" def __getitem__(self, key): return self.obj._to_matrix( self.obj._z[key], self.obj._x[key], self.obj._phase[key], sparse=sparse ) return MatrixIterator(self) # --------------------------------------------------------------------- # Class methods # --------------------------------------------------------------------- @classmethod def from_symplectic(cls, z, x, phase=0): """Construct a PauliList from a symplectic data. Args: z (np.ndarray): 2D boolean Numpy array. x (np.ndarray): 2D boolean Numpy array. phase (np.ndarray or None): Optional, 1D integer array from Z_4. Returns: PauliList: the constructed PauliList. """ base_z, base_x, base_phase = cls._from_array(z, x, phase) return cls(BasePauli(base_z, base_x, base_phase)) def _noncommutation_graph(self, qubit_wise): """Create an edge list representing the non-commutation graph (Pauli Graph). An edge (i, j) is present if i and j are not commutable. Args: qubit_wise (bool): whether the commutation rule is applied to the whole operator, or on a per-qubit basis. Returns: List[Tuple(int,int)]: A list of pairs of indices of the PauliList that are not commutable. """ # convert a Pauli operator into int vector where {I: 0, X: 2, Y: 3, Z: 1} mat1 = np.array( [op.z + 2 * op.x for op in self], dtype=np.int8, ) mat2 = mat1[:, None] qubit_commutation_mat = (mat1 * mat2) * (mat1 - mat2) # adjacency_mat[i, j] is True if an edge (i, j) is present, i.e. i and j are non-commuting if qubit_wise: adjacency_mat = np.logical_or.reduce(qubit_commutation_mat, axis=2) else: adjacency_mat = np.logical_xor.reduce(qubit_commutation_mat, axis=2) # convert into list where tuple elements are non-commuting operators return list(zip(*np.where(np.triu(adjacency_mat, k=1)))) def _create_graph(self, qubit_wise): """Transform measurement operator grouping problem into graph coloring problem Args: qubit_wise (bool): whether the commutation rule is applied to the whole operator, or on a per-qubit basis. Returns: retworkx.PyGraph: A class of undirected graphs """ edges = self._noncommutation_graph(qubit_wise) graph = rx.PyGraph() graph.add_nodes_from(range(self.size)) graph.add_edges_from_no_data(edges) return graph def group_qubit_wise_commuting(self): """Partition a PauliList into sets of mutually qubit-wise commuting Pauli strings. Returns: List[PauliList]: List of PauliLists where each PauliList contains commutable Pauli operators. """ return self.group_commuting(qubit_wise=True) def group_commuting(self, qubit_wise=False): """Partition a PauliList into sets of commuting Pauli strings. Args: qubit_wise (bool): whether the commutation rule is applied to the whole operator, or on a per-qubit basis. For example: .. code-block:: python >>> op = PauliList(["XX", "YY", "IZ", "ZZ"]) >>> op.group_commuting() [PauliList(['XX', 'YY']), PauliList(['IZ', 'ZZ'])] >>> op.group_commuting(qubit_wise=True) [PauliList(['XX']), PauliList(['YY']), PauliList(['IZ', 'ZZ'])] Returns: List[PauliList]: List of PauliLists where each PauliList contains commuting Pauli operators. """ graph = self._create_graph(qubit_wise) # Keys in coloring_dict are nodes, values are colors coloring_dict = rx.graph_greedy_color(graph) groups = defaultdict(list) for idx, color in coloring_dict.items(): groups[color].append(idx) return [self[group] for group in groups.values()] class SparsePauliOp(LinearOp): """Sparse N-qubit operator in a Pauli basis representation. This is a sparse representation of an N-qubit matrix :class:`~qiskit.quantum_info.Operator` in terms of N-qubit :class:`~qiskit.quantum_info.PauliList` and complex coefficients. It can be used for performing operator arithmetic for hundred of qubits if the number of non-zero Pauli basis terms is sufficiently small. The Pauli basis components are stored as a :class:`~qiskit.quantum_info.PauliList` object and can be accessed using the :attr:`~SparsePauliOp.paulis` attribute. The coefficients are stored as a complex Numpy array vector and can be accessed using the :attr:`~SparsePauliOp.coeffs` attribute. """ def __init__(self, data, coeffs=None, *, ignore_pauli_phase=False, copy=True): """Initialize an operator object. Args: data (PauliList or SparsePauliOp or PauliTable or Pauli or list or str): Pauli list of terms. A list of Pauli strings or a Pauli string is also allowed. coeffs (np.ndarray): complex coefficients for Pauli terms. .. note:: If ``data`` is a :obj:`~SparsePauliOp` and ``coeffs`` is not ``None``, the value of the ``SparsePauliOp.coeffs`` will be ignored, and only the passed keyword argument ``coeffs`` will be used. ignore_pauli_phase (bool): if true, any ``phase`` component of a given :obj:`~PauliList` will be assumed to be zero. This is more efficient in cases where a :obj:`~PauliList` has been constructed purely for this object, and it is already known that the phases in the ZX-convention are zero. It only makes sense to pass this option when giving :obj:`~PauliList` data. (Default: False) copy (bool): copy the input data if True, otherwise assign it directly, if possible. (Default: True) Raises: QiskitError: If the input data or coeffs are invalid. """ if ignore_pauli_phase and not isinstance(data, PauliList): raise QiskitError("ignore_pauli_list=True is only valid with PauliList data") if isinstance(data, SparsePauliOp): if coeffs is None: coeffs = data.coeffs data = data._pauli_list # `SparsePauliOp._pauli_list` is already compatible with the internal ZX-phase # convention. See `BasePauli._from_array` for the internal ZX-phase convention. ignore_pauli_phase = True pauli_list = PauliList(data.copy() if copy and hasattr(data, "copy") else data) if coeffs is None: coeffs = np.ones(pauli_list.size, dtype=complex) else: coeffs = np.array(coeffs, copy=copy, dtype=complex) if ignore_pauli_phase: # Fast path used in copy operations, where the phase of the PauliList is already known # to be zero. This path only works if the input data is compatible with the internal # ZX-phase convention. self._pauli_list = pauli_list self._coeffs = coeffs else: # move the phase of `pauli_list` to `self._coeffs` phase = pauli_list.phase self._coeffs = np.asarray((-1j) ** phase * coeffs, dtype=complex) pauli_list._phase = np.mod(pauli_list._phase - phase, 4) self._pauli_list = pauli_list if self._coeffs.shape != (self._pauli_list.size,): raise QiskitError( "coeff vector is incorrect shape for number" " of Paulis {} != {}".format(self._coeffs.shape, self._pauli_list.size) ) # Initialize LinearOp super().__init__(num_qubits=self._pauli_list.num_qubits) def __array__(self, dtype=None): if dtype: return np.asarray(self.to_matrix(), dtype=dtype) return self.to_matrix() def __repr__(self): prefix = "SparsePauliOp(" pad = len(prefix) * " " return "{}{},\n{}coeffs={})".format( prefix, self.paulis.to_labels(), pad, np.array2string(self.coeffs, separator=", "), ) def __eq__(self, other): """Entrywise comparison of two SparsePauliOp operators""" return ( super().__eq__(other) and self.coeffs.shape == other.coeffs.shape and np.allclose(self.coeffs, other.coeffs) and self.paulis == other.paulis ) def equiv(self, other): """Check if two SparsePauliOp operators are equivalent. Args: other (SparsePauliOp): an operator object. Returns: bool: True if the operator is equivalent to ``self``. """ if not super().__eq__(other): return False return np.allclose((self - other).simplify().coeffs, [0]) @property def settings(self) -> Dict: """Return settings.""" return {"data": self._pauli_list, "coeffs": self._coeffs} # --------------------------------------------------------------------- # Data accessors # --------------------------------------------------------------------- @property def size(self): """The number of Pauli of Pauli terms in the operator.""" return self._pauli_list.size def __len__(self): """Return the size.""" return self.size # pylint: disable=bad-docstring-quotes @property @deprecate_function( "The SparsePauliOp.table method is deprecated as of Qiskit Terra 0.19.0 " "and will be removed no sooner than 3 months after the releasedate. " "Use SparsePauliOp.paulis method instead.", ) def table(self): """DEPRECATED - Return the the PauliTable.""" return PauliTable(np.column_stack((self.paulis.x, self.paulis.z))) @table.setter @deprecate_function( "The SparsePauliOp.table method is deprecated as of Qiskit Terra 0.19.0 " "and will be removed no sooner than 3 months after the releasedate. " "Use SparsePauliOp.paulis method instead.", ) def table(self, value): if not isinstance(value, PauliTable): value = PauliTable(value) self._pauli_list = PauliList(value) @property def paulis(self): """Return the the PauliList.""" return self._pauli_list @paulis.setter def paulis(self, value): if not isinstance(value, PauliList): value = PauliList(value) self._pauli_list = value @property def coeffs(self): """Return the Pauli coefficients.""" return self._coeffs @coeffs.setter def coeffs(self, value): """Set Pauli coefficients.""" self._coeffs[:] = value def __getitem__(self, key): """Return a view of the SparsePauliOp.""" # Returns a view of specified rows of the PauliList # This supports all slicing operations the underlying array supports. if isinstance(key, (int, np.integer)): key = [key] return SparsePauliOp(self.paulis[key], self.coeffs[key]) def __setitem__(self, key, value): """Update SparsePauliOp.""" # Modify specified rows of the PauliList if not isinstance(value, SparsePauliOp): value = SparsePauliOp(value) self.paulis[key] = value.paulis self.coeffs[key] = value.coeffs # --------------------------------------------------------------------- # LinearOp Methods # --------------------------------------------------------------------- def conjugate(self): # Conjugation conjugates phases and also Y.conj() = -Y # Hence we need to multiply conjugated coeffs by -1 # for rows with an odd number of Y terms. # Find rows with Ys ret = self.transpose() ret._coeffs = ret._coeffs.conj() return ret def transpose(self): # The only effect transposition has is Y.T = -Y # Hence we need to multiply coeffs by -1 for rows with an # odd number of Y terms. ret = self.copy() minus = (-1) ** np.mod(np.sum(ret.paulis.x & ret.paulis.z, axis=1), 2) ret._coeffs *= minus return ret def adjoint(self): # Pauli's are self adjoint, so we only need to # conjugate the phases ret = self.copy() ret._coeffs = ret._coeffs.conj() return ret def compose(self, other, qargs=None, front=False): if qargs is None: qargs = getattr(other, "qargs", None) if not isinstance(other, SparsePauliOp): other = SparsePauliOp(other) # Validate composition dimensions and qargs match self._op_shape.compose(other._op_shape, qargs, front) if qargs is not None: x1, z1 = self.paulis.x[:, qargs], self.paulis.z[:, qargs] else: x1, z1 = self.paulis.x, self.paulis.z x2, z2 = other.paulis.x, other.paulis.z num_qubits = other.num_qubits # This method is the outer version of `BasePauli.compose`. # `x1` and `z1` have shape `(self.size, num_qubits)`. # `x2` and `z2` have shape `(other.size, num_qubits)`. # `x1[:, no.newaxis]` results in shape `(self.size, 1, num_qubits)`. # `ar = ufunc(x1[:, np.newaxis], x2)` will be in shape `(self.size, other.size, num_qubits)`. # So, `ar.reshape((-1, num_qubits))` will be in shape `(self.size * other.size, num_qubits)`. # Ref: https://numpy.org/doc/stable/user/theory.broadcasting.html phase = np.add.outer(self.paulis._phase, other.paulis._phase).reshape(-1) if front: q = np.logical_and(x1[:, np.newaxis], z2).reshape((-1, num_qubits)) else: q = np.logical_and(z1[:, np.newaxis], x2).reshape((-1, num_qubits)) # `np.mod` will be applied to `phase` in `SparsePauliOp.__init__` phase = phase + 2 * np.sum(q, axis=1) x3 = np.logical_xor(x1[:, np.newaxis], x2).reshape((-1, num_qubits)) z3 = np.logical_xor(z1[:, np.newaxis], z2).reshape((-1, num_qubits)) if qargs is None: pauli_list = PauliList(BasePauli(z3, x3, phase)) else: x4 = np.repeat(self.paulis.x, other.size, axis=0) z4 = np.repeat(self.paulis.z, other.size, axis=0) x4[:, qargs] = x3 z4[:, qargs] = z3 pauli_list = PauliList(BasePauli(z4, x4, phase)) # note: the following is a faster code equivalent to # `coeffs = np.kron(self.coeffs, other.coeffs)` # since `self.coeffs` and `other.coeffs` are both 1d arrays. coeffs = np.multiply.outer(self.coeffs, other.coeffs).ravel() return SparsePauliOp(pauli_list, coeffs, copy=False) def tensor(self, other): if not isinstance(other, SparsePauliOp): other = SparsePauliOp(other) return self._tensor(self, other) def expand(self, other): if not isinstance(other, SparsePauliOp): other = SparsePauliOp(other) return self._tensor(other, self) @classmethod def _tensor(cls, a, b): paulis = a.paulis.tensor(b.paulis) coeffs = np.kron(a.coeffs, b.coeffs) return SparsePauliOp(paulis, coeffs, copy=False) def _add(self, other, qargs=None): if qargs is None: qargs = getattr(other, "qargs", None) if not isinstance(other, SparsePauliOp): other = SparsePauliOp(other) self._op_shape._validate_add(other._op_shape, qargs) paulis = self.paulis._add(other.paulis, qargs=qargs) coeffs = np.hstack((self.coeffs, other.coeffs)) return SparsePauliOp(paulis, coeffs, ignore_pauli_phase=True, copy=False) def _multiply(self, other): if not isinstance(other, Number): raise QiskitError("other is not a number") if other == 0: # Check edge case that we deleted all Paulis # In this case we return an identity Pauli with a zero coefficient paulis = PauliList.from_symplectic( np.zeros((1, self.num_qubits), dtype=bool), np.zeros((1, self.num_qubits), dtype=bool), ) coeffs = np.array([0j]) return SparsePauliOp(paulis, coeffs, ignore_pauli_phase=True, copy=False) # Otherwise we just update the phases return SparsePauliOp( self.paulis.copy(), other * self.coeffs, ignore_pauli_phase=True, copy=False ) # --------------------------------------------------------------------- # Utility Methods # --------------------------------------------------------------------- def is_unitary(self, atol=None, rtol=None): """Return True if operator is a unitary matrix. Args: atol (float): Optional. Absolute tolerance for checking if coefficients are zero (Default: 1e-8). rtol (float): Optional. relative tolerance for checking if coefficients are zero (Default: 1e-5). Returns: bool: True if the operator is unitary, False otherwise. """ # Get default atol and rtol if atol is None: atol = self.atol if rtol is None: rtol = self.rtol # Compose with adjoint val = self.compose(self.adjoint()).simplify() # See if the result is an identity return ( val.size == 1 and np.isclose(val.coeffs[0], 1.0, atol=atol, rtol=rtol) and not np.any(val.paulis.x) and not np.any(val.paulis.z) ) def simplify(self, atol=None, rtol=None): """Simplify PauliList by combining duplicates and removing zeros. Args: atol (float): Optional. Absolute tolerance for checking if coefficients are zero (Default: 1e-8). rtol (float): Optional. relative tolerance for checking if coefficients are zero (Default: 1e-5). Returns: SparsePauliOp: the simplified SparsePauliOp operator. """ # Get default atol and rtol if atol is None: atol = self.atol if rtol is None: rtol = self.rtol # Filter non-zero coefficients non_zero = np.logical_not(np.isclose(self.coeffs, 0, atol=atol, rtol=rtol)) paulis_x = self.paulis.x[non_zero] paulis_z = self.paulis.z[non_zero] nz_coeffs = self.coeffs[non_zero] # Pack bool vectors into np.uint8 vectors by np.packbits array = np.packbits(paulis_x, axis=1) * 256 + np.packbits(paulis_z, axis=1) indexes, inverses = unordered_unique(array) if np.all(non_zero) and indexes.shape[0] == array.shape[0]: # No zero operator or duplicate operator return self.copy() coeffs = np.zeros(indexes.shape[0], dtype=complex) np.add.at(coeffs, inverses, nz_coeffs) # Delete zero coefficient rows is_zero = np.isclose(coeffs, 0, atol=atol, rtol=rtol) # Check edge case that we deleted all Paulis # In this case we return an identity Pauli with a zero coefficient if np.all(is_zero): x = np.zeros((1, self.num_qubits), dtype=bool) z = np.zeros((1, self.num_qubits), dtype=bool) coeffs = np.array([0j], dtype=complex) else: non_zero = np.logical_not(is_zero) non_zero_indexes = indexes[non_zero] x = paulis_x[non_zero_indexes] z = paulis_z[non_zero_indexes] coeffs = coeffs[non_zero] return SparsePauliOp( PauliList.from_symplectic(z, x), coeffs, ignore_pauli_phase=True, copy=False ) def chop(self, tol=1e-14): """Set real and imaginary parts of the coefficients to 0 if ``< tol`` in magnitude. For example, the operator representing ``1+1e-17j X + 1e-17 Y`` with a tolerance larger than ``1e-17`` will be reduced to ``1 X`` whereas :meth:`.SparsePauliOp.simplify` would return ``1+1e-17j X``. If a both the real and imaginary part of a coefficient is 0 after chopping, the corresponding Pauli is removed from the operator. Args: tol (float): The absolute tolerance to check whether a real or imaginary part should be set to 0. Returns: SparsePauliOp: This operator with chopped coefficients. """ realpart_nonzero = np.abs(self.coeffs.real) > tol imagpart_nonzero = np.abs(self.coeffs.imag) > tol remaining_indices = np.logical_or(realpart_nonzero, imagpart_nonzero) remaining_real = realpart_nonzero[remaining_indices] remaining_imag = imagpart_nonzero[remaining_indices] if len(remaining_real) == 0: # if no Paulis are left x = np.zeros((1, self.num_qubits), dtype=bool) z = np.zeros((1, self.num_qubits), dtype=bool) coeffs = np.array([0j], dtype=complex) else: coeffs = np.zeros(np.count_nonzero(remaining_indices), dtype=complex) coeffs.real[remaining_real] = self.coeffs.real[realpart_nonzero] coeffs.imag[remaining_imag] = self.coeffs.imag[imagpart_nonzero] x = self.paulis.x[remaining_indices] z = self.paulis.z[remaining_indices] return SparsePauliOp( PauliList.from_symplectic(z, x), coeffs, ignore_pauli_phase=True, copy=False ) @staticmethod def sum(ops): """Sum of SparsePauliOps. This is a specialized version of the builtin ``sum`` function for SparsePauliOp with smaller overhead. Args: ops (list[SparsePauliOp]): a list of SparsePauliOps. Returns: SparsePauliOp: the SparsePauliOp representing the sum of the input list. Raises: QiskitError: if the input list is empty. QiskitError: if the input list includes an object that is not SparsePauliOp. QiskitError: if the numbers of qubits of the objects in the input list do not match. """ if len(ops) == 0: raise QiskitError("Input list is empty") if not all(isinstance(op, SparsePauliOp) for op in ops): raise QiskitError("Input list includes an object that is not SparsePauliOp") for other in ops[1:]: ops[0]._op_shape._validate_add(other._op_shape) z = np.vstack([op.paulis.z for op in ops]) x = np.vstack([op.paulis.x for op in ops]) phase = np.hstack([op.paulis._phase for op in ops]) pauli_list = PauliList(BasePauli(z, x, phase)) coeffs = np.hstack([op.coeffs for op in ops]) return SparsePauliOp(pauli_list, coeffs, ignore_pauli_phase=True, copy=False) # --------------------------------------------------------------------- # Additional conversions # --------------------------------------------------------------------- @staticmethod def from_operator(obj, atol=None, rtol=None): """Construct from an Operator objector. Note that the cost of this construction is exponential as it involves taking inner products with every element of the N-qubit Pauli basis. Args: obj (Operator): an N-qubit operator. atol (float): Optional. Absolute tolerance for checking if coefficients are zero (Default: 1e-8). rtol (float): Optional. relative tolerance for checking if coefficients are zero (Default: 1e-5). Returns: SparsePauliOp: the SparsePauliOp representation of the operator. Raises: QiskitError: if the input operator is not an N-qubit operator. """ # Get default atol and rtol if atol is None: atol = SparsePauliOp.atol if rtol is None: rtol = SparsePauliOp.rtol if not isinstance(obj, Operator): obj = Operator(obj) # Check dimension is N-qubit operator num_qubits = obj.num_qubits if num_qubits is None: raise QiskitError("Input Operator is not an N-qubit operator.") data = obj.data # Index of non-zero basis elements inds = [] # Non-zero coefficients coeffs = [] # Non-normalized basis factor denom = 2**num_qubits # Compute coefficients from basis basis = pauli_basis(num_qubits, pauli_list=True) for i, mat in enumerate(basis.matrix_iter()): coeff = np.trace(mat.dot(data)) / denom if not np.isclose(coeff, 0, atol=atol, rtol=rtol): inds.append(i) coeffs.append(coeff) # Get Non-zero coeff PauliList terms paulis = basis[inds] return SparsePauliOp(paulis, coeffs, copy=False) @staticmethod def from_list(obj): """Construct from a list of Pauli strings and coefficients. For example, the 5-qubit Hamiltonian .. math:: H = Z_1 X_4 + 2 Y_0 Y_3 can be constructed as .. code-block:: python # via tuples and the full Pauli string op = SparsePauliOp.from_list([("XIIZI", 1), ("IYIIY", 2)]) Args: obj (Iterable[Tuple[str, complex]]): The list of 2-tuples specifying the Pauli terms. Returns: SparsePauliOp: The SparsePauliOp representation of the Pauli terms. Raises: QiskitError: If the list of Paulis is empty. """ obj = list(obj) # To convert zip or other iterable size = len(obj) # number of Pauli terms if size == 0: raise QiskitError("Input Pauli list is empty.") # determine the number of qubits num_qubits = len(obj[0][0]) coeffs = np.zeros(size, dtype=complex) labels = np.zeros(size, dtype=f"<U{num_qubits}") for i, item in enumerate(obj): labels[i] = item[0] coeffs[i] = item[1] paulis = PauliList(labels) return SparsePauliOp(paulis, coeffs, copy=False) @staticmethod def from_sparse_list(obj, num_qubits): """Construct from a list of local Pauli strings and coefficients. Each list element is a 3-tuple of a local Pauli string, indices where to apply it, and a coefficient. For example, the 5-qubit Hamiltonian .. math:: H = Z_1 X_4 + 2 Y_0 Y_3 can be constructed as .. code-block:: python # via triples and local Paulis with indices op = SparsePauliOp.from_sparse_list([("ZX", [1, 4], 1), ("YY", [0, 3], 2)], num_qubits=5) # equals the following construction from "dense" Paulis op = SparsePauliOp.from_list([("XIIZI", 1), ("IYIIY", 2)]) Args: obj (Iterable[Tuple[str, List[int], complex]]): The list 3-tuples specifying the Paulis. num_qubits (int): The number of qubits of the operator. Returns: SparsePauliOp: The SparsePauliOp representation of the Pauli terms. Raises: QiskitError: If the list of Paulis is empty. QiskitError: If the number of qubits is incompatible with the indices of the Pauli terms. """ obj = list(obj) # To convert zip or other iterable size = len(obj) # number of Pauli terms if size == 0: raise QiskitError("Input Pauli list is empty.") coeffs = np.zeros(size, dtype=complex) labels = np.zeros(size, dtype=f"<U{num_qubits}") for i, (paulis, indices, coeff) in enumerate(obj): # construct the full label based off the non-trivial Paulis and indices label = ["I"] * num_qubits for pauli, index in zip(paulis, indices): if index >= num_qubits: raise QiskitError( f"The number of qubits ({num_qubits}) is smaller than a required index {index}." ) label[~index] = pauli labels[i] = "".join(label) coeffs[i] = coeff paulis = PauliList(labels) return SparsePauliOp(paulis, coeffs, copy=False) def to_list(self, array=False): """Convert to a list Pauli string labels and coefficients. For operators with a lot of terms converting using the ``array=True`` kwarg will be more efficient since it allocates memory for the full Numpy array of labels in advance. Args: array (bool): return a Numpy array if True, otherwise return a list (Default: False). Returns: list or array: List of pairs (label, coeff) for rows of the PauliList. """ # Dtype for a structured array with string labels and complex coeffs pauli_labels = self.paulis.to_labels(array=True) labels = np.zeros(self.size, dtype=[("labels", pauli_labels.dtype), ("coeffs", "c16")]) labels["labels"] = pauli_labels labels["coeffs"] = self.coeffs if array: return labels return labels.tolist() def to_matrix(self, sparse=False): """Convert to a dense or sparse matrix. Args: sparse (bool): if True return a sparse CSR matrix, otherwise return dense Numpy array (Default: False). Returns: array: A dense matrix if `sparse=False`. csr_matrix: A sparse matrix in CSR format if `sparse=True`. """ mat = None for i in self.matrix_iter(sparse=sparse): if mat is None: mat = i else: mat += i return mat def to_operator(self): """Convert to a matrix Operator object""" return Operator(self.to_matrix()) # --------------------------------------------------------------------- # Custom Iterators # --------------------------------------------------------------------- def label_iter(self): """Return a label representation iterator. This is a lazy iterator that converts each term in the SparsePauliOp into a tuple (label, coeff). To convert the entire table to labels use the :meth:`to_labels` method. Returns: LabelIterator: label iterator object for the PauliTable. """ class LabelIterator(CustomIterator): """Label representation iteration and item access.""" def __repr__(self): return f"<SparsePauliOp_label_iterator at {hex(id(self))}>" def __getitem__(self, key): coeff = self.obj.coeffs[key] pauli = self.obj.paulis.label_iter()[key] return (pauli, coeff) return LabelIterator(self) def matrix_iter(self, sparse=False): """Return a matrix representation iterator. This is a lazy iterator that converts each term in the SparsePauliOp into a matrix as it is used. To convert to a single matrix use the :meth:`to_matrix` method. Args: sparse (bool): optionally return sparse CSR matrices if True, otherwise return Numpy array matrices (Default: False) Returns: MatrixIterator: matrix iterator object for the PauliList. """ class MatrixIterator(CustomIterator): """Matrix representation iteration and item access.""" def __repr__(self): return f"<SparsePauliOp_matrix_iterator at {hex(id(self))}>" def __getitem__(self, key): coeff = self.obj.coeffs[key] mat = self.obj.paulis[key].to_matrix(sparse) return coeff * mat return MatrixIterator(self) def _create_graph(self, qubit_wise): """Transform measurement operator grouping problem into graph coloring problem Args: qubit_wise (bool): whether the commutation rule is applied to the whole operator, or on a per-qubit basis. Returns: retworkx.PyGraph: A class of undirected graphs """ edges = self.paulis._noncommutation_graph(qubit_wise) graph = rx.PyGraph() graph.add_nodes_from(range(self.size)) graph.add_edges_from_no_data(edges) return graph def group_commuting(self, qubit_wise=False): """Partition a SparsePauliOp into sets of commuting Pauli strings. Args: qubit_wise (bool): whether the commutation rule is applied to the whole operator, or on a per-qubit basis. For example: .. code-block:: python >>> op = SparsePauliOp.from_list([("XX", 2), ("YY", 1), ("IZ",2j), ("ZZ",1j)]) >>> op.group_commuting() [SparsePauliOp(["IZ", "ZZ"], coeffs=[0.+2.j, 0.+1j]), SparsePauliOp(["XX", "YY"], coeffs=[2.+0.j, 1.+0.j])] >>> op.group_commuting(qubit_wise=True) [SparsePauliOp(['XX'], coeffs=[2.+0.j]), SparsePauliOp(['YY'], coeffs=[1.+0.j]), SparsePauliOp(['IZ', 'ZZ'], coeffs=[0.+2.j, 0.+1.j])] Returns: List[SparsePauliOp]: List of SparsePauliOp where each SparsePauliOp contains commuting Pauli operators. """ graph = self._create_graph(qubit_wise) # Keys in coloring_dict are nodes, values are colors coloring_dict = rx.graph_greedy_color(graph) groups = defaultdict(list) for idx, color in coloring_dict.items(): groups[color].append(idx) return [self[group] for group in groups.values()] # ibm-quantum-spring-challenge-2022/exercise4/04.quantum_chemistry.ipynb from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import ElectronicStructureMoleculeDriver, ElectronicStructureDriverType molecule = Molecule( # coordinates are given in Angstrom geometry=[ ["O", [0.0, 0.0, 0.0]], ["H", [0.758602, 0.0, 0.504284]], ["H", [0.758602, 0.0, -0.504284]] ], multiplicity=1, # = 2*spin + 1 charge=0, ) driver = ElectronicStructureMoleculeDriver( molecule=molecule, basis="sto3g", driver_type=ElectronicStructureDriverType.PYSCF, ) properties = driver.run() from qiskit_nature.transformers.second_quantization.electronic import ActiveSpaceTransformer # Check the occupation of the spin orbitals PN_property = properties.get_property("ParticleNumber") print(PN_property) # Define the active space around the Fermi level # (selected automatically around the HOMO and LUMO, ordered by energy) transformer = ActiveSpaceTransformer( num_electrons=2, #how many electrons we have in our active space num_molecular_orbitals=2, #how many orbitals we have in our active space ) # We can hand-pick the MOs to be included in the AS # (in case they are not exactly around the Fermi level) # transformer = ActiveSpaceTransformer( # num_electrons=2, #how amny electrons we have in our active space # num_molecular_orbitals=2, #how many orbitals we have in our active space # active_orbitals=[4,7], #We are specifically choosing MO number 4 (occupied with two electrons) and 7 (empty) # ) from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem problem = ElectronicStructureProblem(driver, [transformer]) second_q_ops = problem.second_q_ops() # this calls driver.run() internally hamiltonian = second_q_ops[0] print(hamiltonian) from qiskit_nature.mappers.second_quantization import ParityMapper, BravyiKitaevMapper, JordanWignerMapper from qiskit_nature.converters.second_quantization import QubitConverter # Setup the mapper and qubit converter mapper_type = 'JordanWignerMapper' if mapper_type == 'ParityMapper': mapper = ParityMapper() elif mapper_type == 'JordanWignerMapper': mapper = JordanWignerMapper() elif mapper_type == 'BravyiKitaevMapper': mapper = BravyiKitaevMapper() converter = QubitConverter(mapper) qubit_op = converter.convert(hamiltonian) print(qubit_op) print("No-grouping (Active Space)") print("\n", f"Number of Measurement is {len(qubit_op)}") print("Qubit-wise grouping") measure_group = PauliList(qubit_op.primitive.paulis).group_commuting(qubit_wise=True) for group in measure_group: print(group) print("\n", f"Number of Measurement is {len(measure_group)}") print("General grouping") measure_group = PauliList(qubit_op.primitive.paulis).group_commuting() for group in measure_group: print(group) print("\n", f"Number of Measurement is {len(measure_group)}") problem = ElectronicStructureProblem(driver, []) second_q_ops = problem.second_q_ops() # this calls driver.run() internally hamiltonian = second_q_ops[0] # print(hamiltonian) converter = QubitConverter(mapper) qubit_op = converter.convert(hamiltonian) print(qubit_op) print("No-grouping (Active Space)") print("\n", f"Number of Measurement is {len(qubit_op)}") print("Qubit-wise grouping") measure_group = PauliList(qubit_op.primitive.paulis).group_commuting(qubit_wise=True) print("\n", f"Number of Measurement is {len(measure_group)}\n") for group in measure_group: print(group) print("General grouping") measure_group = PauliList(qubit_op.primitive.paulis).group_commuting() print("\n", f"Number of Measurement is {len(measure_group)}\n") for group in measure_group: print(group)
https://github.com/Slope86/QiskitExtension
Slope86
import math from qiskit_extension.quantum_circuit2 import QuantumCircuit2 as qc2 from qiskit_extension.state_vector2 import StateVector2 as sv2 # Create a 4bits quantum circuit circ_init = qc2(4) # Make ground state qubit(0,1) and qubit(2,3) entangled into two EPR pairs circ_init.h([0,2]) circ_init.cx([0,2],[1,3]) # Display the circuit circ_init.show_circ() # Put the ground state into the circuit we build in previous step, and get two EPR pairs state_EPR = sv2(circ_init) # Show state state_EPR.show_state() circ_Bell_measure = qc2(4) circ_Bell_measure.cx(1,2) circ_Bell_measure.h(1) # Bell measurement on qubits(1,2), and store the four possible states as a list after measurement # list[0b00]=state after measurement result is 00, # list[0b01]=state after measurement result is 01, # ... list_state_EPR_after_Bell_measure = state_EPR.evolve(circ_Bell_measure).measure([1,2]) # Show the four possible states after the Bell measurement # Display format: (|00> indicates the measured state, followed by a colon indicating [the remaining state after measurement result is 00]) # |00>: 1/2|0> + 1/2|1> ... state_EPR.evolve(circ_Bell_measure).show_measure([1,2]) # Get the state after measuring, and the measurement result is 01 state_before_correction = list_state_EPR_after_Bell_measure[0b01] # Show the state before correction state_before_correction.show_state(hide=[1,2]) # Correction circuit (measurement result is 01, so perform Pauli-X on qubit 3) circ_correction = qc2(4) circ_correction.x(3) # Put state_before_correction into the correction circuit, get the state after correction state_after_correction = state_before_correction.evolve(circ_correction) # Show corrected state, make sure that entangled swap successful state_after_correction.show_state(hide=[1,2])
https://github.com/lzylili/grovers-algo
lzylili
#Import libraries from qiskit import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import * from qiskit.providers.ibmq import least_busy import math # Initializing circuit: define as 2 qubits q = QuantumRegister(2, 'q') c = ClassicalRegister(2, 'c') # Create the quantum circuit qc = QuantumCircuit(q,c) ## Step 1: Apply a Hadarmard gate to all qubits qc.h(q) ## Step 2: Implement the Oracle circuit for state |11> + Grover diffusion qc.cz(q[1],q[0]) qc.barrier(q) qc.h(q) qc.x(q) qc.cz(q[1],q[0]) qc.x(q) qc.h(q) qc.barrier(q) qc.draw(output='mpl') ## Don't forget about the measurement gates! qc.measure(q[0],c[0]) qc.measure(q[1],c[1]) qc.draw(output='mpl') ## Step 4: Run on backend simulator and print results simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend = simulator, shots = 2048).result() counts = result.get_counts() print('RESULT: ',counts,'\n') from qiskit.tools.visualization import plot_histogram plot_histogram(counts) ## Step 4: Run on real device from IBM - load account and get least busy backend provider = IBMQ.load_account() device = least_busy(provider.backends(simulator=False)) print("Running on current least busy device: ", device) from qiskit.tools.monitor import job_monitor job = execute(qc, backend=device, shots=1024, max_credits=10) job_monitor(job, interval = 2) ## Print results from device from IBM results = job.result() answer = results.get_counts(qc) plot_histogram(answer) pi = math.pi # Initializing circuit: define as 3 qubits q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') # Create the quantum circuit qc = QuantumCircuit(q,c) ## Step 1: Apply a Hadarmard gate to all qubits qc.h(q) ## Step 2: Implement the Oracle circuit for state |111> + Grover diffusion qc.cz(q[2],q[0]) qc.barrier(q) qc.h(q) qc.x(q) qc.barrier(q) qc.cx(q[1],q[0]) qc.z(q[0]),-pi/4 qc.cx(q[2],q[0]) qc.z(q[0]),pi/4 qc.cx(q[1],q[0]) qc.z(q[0]),-pi/4 qc.barrier(q) qc.cx(q[2],q[0]) qc.z(q[0]),pi/4 qc.z(q[1]),pi/4 qc.barrier(q) qc.cx(q[2],q[1]) qc.z(q[1]),-pi/4 qc.cx(q[2],q[1]) qc.z(q[2]),pi/4 qc.barrier(q) qc.x(q) qc.h(q) qc.barrier(q) qc.draw(output='mpl') ## Don't forget about the measurement gates! qc.measure(q[0],c[0]) qc.measure(q[1],c[1]) qc.measure(q[2],c[2]) qc.draw(output='mpl') ## Step 4: Run on backend simulator and print results simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend = simulator, shots = 2048).result() counts = result.get_counts() print('RESULT: ',counts,'\n') from qiskit.tools.visualization import plot_histogram plot_histogram(counts) ## Note: accuracy of this implementation is not 100% (may need to run a couple iterations before achieving desired result) ## Step 4: Run on real device from IBM - load account and get least busy backend provider = IBMQ.load_account() device = least_busy(provider.backends(simulator=False)) print("Running on current least busy device: ", device) from qiskit.tools.monitor import job_monitor job = execute(qc, backend=device, shots=1024, max_credits=10) job_monitor(job, interval = 2) ## Print results from device from IBM results = job.result() answer = results.get_counts(qc) plot_histogram(answer) # Initializing circuit: define as 2 qubits q = QuantumRegister(4, 'q') c = ClassicalRegister(4, 'c') # Create the quantum circuit qc = QuantumCircuit(q,c) ## Step 1: Apply a Hadarmard gate to all qubits qc.h(q) ## Step 2: Implement the Oracle circuit for state |111> + Grover diffusion qc.cz(q[3],q[0]) qc.barrier(q) qc.h(q) qc.x(q) qc.barrier(q) qc.h(q[1]) qc.cx(q[2],q[1]) qc.tdg(q[1]) qc.cx(q[3],q[1]) qc.t(q[1]) qc.cx(q[2],q[1]) qc.tdg(q[1]) qc.cx(q[3],q[1]) qc.barrier(q) qc.t(q[1]) qc.tdg(q[2]) qc.h(q[1]) qc.barrier(q) qc.h(q[2]) qc.h(q[3]) qc.cx(q[3],q[2]) qc.h(q[2]) qc.h(q[3]) qc.tdg(q[2]) qc.barrier(q) qc.h(q[2]) qc.h(q[3]) qc.cx(q[3],q[2]) qc.h(q[2]) qc.h(q[3]) qc.s(q[2]) qc.t(q[3]) qc.barrier(q) qc.cx(q[1],q[0]) qc.t(q[0]) qc.cx(q[1],q[0]) qc.tdg(q[0]) qc.tdg(q[1]) qc.h(q[1]) qc.cx(q[2],q[1]) qc.tdg(q[1]) qc.cx(q[3],q[1]) qc.t(q[1]) qc.cx(q[2],q[1]) qc.tdg(q[1]) qc.cx(q[3],q[1]) qc.t(q[1]) qc.tdg(q[2]) qc.h(q[1]) qc.barrier(q) qc.h(q[2]) qc.h(q[3]) qc.cx(q[3],q[2]) qc.h(q[2]) qc.h(q[3]) qc.tdg(q[2]) qc.barrier(q) qc.h(q[2]) qc.h(q[3]) qc.cx(q[3],q[2]) qc.h(q[2]) qc.h(q[3]) qc.s(q[2]) qc.t(q[3]) qc.barrier(q) qc.cx(q[1],q[0]) qc.tdg(q[0]) qc.cx(q[1],q[0]) qc.t(q[0]) qc.t(q[1]) qc.barrier(q) qc.h(q[2]) qc.h(q[3]) qc.cx(q[3],q[2]) qc.h(q[2]) qc.h(q[3]) qc.cx(q[1],q[0]) qc.h(q[0]) qc.h(q[1]) qc.cx(q[1],q[0]) qc.h(q[0]) qc.h(q[1]) qc.cx(q[1],q[0]) qc.h(q[0]) qc.h(q[1]) qc.barrier(q) qc.cx(q[2],q[1]) qc.u1(pi/8,q[1]) qc.cx(q[2],q[1]) qc.u1(-pi/8,q[1]) qc.u1(pi/8,q[2]) qc.barrier(q) qc.h(q[2]) qc.h(q[3]) qc.cx(q[3],q[2]) qc.h(q[2]) qc.h(q[3]) qc.cx(q[2],q[1]) qc.u1(pi/8,q[1]) qc.cx(q[2],q[1]) qc.u1(pi/8,q[1]) qc.u1(pi/8,q[2]) qc.cx(q[3],q[1]) qc.u1(-pi/8,q[1]) qc.cx(q[3],q[1]) qc.u1(pi/8,q[1]) qc.u1(pi/8,q[3]) qc.barrier(q) qc.cx(q[1],q[0]) qc.h(q[0]) qc.h(q[1]) qc.cx(q[1],q[0]) qc.h(q[0]) qc.h(q[1]) qc.cx(q[1],q[0]) qc.h(q[0]) qc.h(q[1]) qc.barrier(q) qc.x(q) qc.h(q) qc.barrier(q) qc.draw(output='mpl') ## Don't forget about the measurement gates! qc.measure(q[0],c[0]) qc.measure(q[1],c[1]) qc.measure(q[2],c[2]) qc.measure(q[3],c[3]) qc.draw(output='mpl') ## Step 4: Run on backend simulator and print results simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend = simulator, shots = 2048).result() counts = result.get_counts() print('RESULT: ',counts,'\n') from qiskit.tools.visualization import plot_histogram plot_histogram(counts) ## Note: accuracy of this implementation not 100% (may need to run a couple iterations before achieving desired result) ## Step 4: Run on real device from IBM - load account and get least busy backend provider = IBMQ.load_account() device = least_busy(provider.backends(simulator=False)) print("Running on current least busy device: ", device) from qiskit.tools.monitor import job_monitor job = execute(qc, backend=device, shots=1024, max_credits=10) job_monitor(job, interval = 2) ## Print results from device from IBM results = job.result() answer = results.get_counts(qc) plot_histogram(answer)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) qc.draw('mpl')
https://github.com/Hayatto9217/Qiskit11
Hayatto9217
pip install qiskit-aer import numpy as np from qiskit import QuantumCircuit from qiskit import Aer, transpile from qiskit.tools.visualization import plot_histogram, plot_state_city import qiskit.quantum_info as pi Aer.backends() simulator = Aer.get_backend('aer_simulator') circ = QuantumCircuit(2) circ.h(0) circ.cx(0,1) circ.measure_all() simulator = Aer.get_backend('aer_simulator') circ =transpile(circ, simulator) result =simulator.run(circ).result() counts =result.get_counts(circ) plot_histogram(counts, title= "Bell-State counts") result =simulator.run(circ,shots=10, memory=True).result() memory =result.get_memory(circ) print(memory) shots = 10000 sim_stabilizer = Aer.get_backend('aer_simulator_stabilizer') job_stabilizer = sim_stabilizer.run(circ, shots=shots) counts_stabilizer = job_stabilizer.result().get_counts(0) sim_statevector = Aer.get_backend('aer_simulator_statevector') job_statevector =sim_statevector.run(circ, shots=shots) counts_statevector = job_statevector.result().get_counts(0) sim_density = Aer.get_backend('aer_simulator_density_matrix') job_density = sim_density.run(circ, shots=shots) counts_density = job_density.result().get_counts(0) sim_mps = Aer.get_backend('aer_simulator_matrix_product_state') job_mps = sim_mps.run(circ, shots=shots) counts_mps =job_mps.result().get_counts(0) plot_histogram([counts_stabilizer, counts_statevector, counts_density, counts_mps], title='Counts for different simulation methods', legend=['stabilizer', 'statevector', 'density_matrix', 'matrix_product_state']) from qiskit_aer import AerError try: simulator_gpu = Aer.get_backend('aer_simulator') simulator_gpu.set_options(device='GPU') except AerError as e: print(e) simulator = Aer.get_backend('aer_simulator_statevector') simulator.set_options(precision='single') result =simulator.run(circ).result() counts =result.get_counts(circ) print(counts) circ = QuantumCircuit(2) circ.h(0) circ.cx(0, 1) circ.save_statevector() simulator = Aer.get_backend('aer_simulator') circ =transpile(circ, simulator) result =simulator.run(circ).result() statevector= result.get_statevector(circ) plot_state_city(statevector,title='Bell state') steps = 5 circ = QuantumCircuit(1) for i in range(steps): circ.save_statevector(label=f'psi_{i}') circ.rx(i * np.pi / steps, 0) circ.save_statevector(label=f'psi_{steps}') simulator = Aer.get_backend('aer_simulator') circ =transpile(circ, simulator) result =simulator.run(circ).result() data =result.data(0) data # Generate a random statevector num_qubits = 2 psi = random_statevector(2 ** num_qubits, seed=100) # Set initial state to generated statevector circ = QuantumCircuit(num_qubits) circ.set_statevector(psi) circ.save_state() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get saved data result = simulator.run(circ).result() result.data(0) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# This is a comment # A comment is used for explanations/descriptions/etc. # Comments do not affect the programs # let's define an integer variable named a a = 5 # let's print its value print(a) # let's define three integer variables named a, b, and c a = 2 b = 4 c = a + b # summation of a and b # let's print their values together print(a,b,c) # a single space will automatically appears in between # let's print their values in reverse order print(c,b,a) # let's print their summation and multiplication print(a+b+c,a*b*c) # let's define variables with string/text values hw = "hello world" # we can use double quotes hqw = 'hello quantum world' # we can use single quotes # let's print them print(hw) print(hqw) # let's print them together by inserting another string in between print(hw,"and",hqw) # let's concatenate a few strings d = "Hello " + 'World' + " but " + 'Quantum' + "World" # let's print the result print(d) # let's print numeric and string values together print("a =",a,", b =",b,", a+b =",a+b) # let's subtract two numbers d = a-b print(a,b,d) # let's divide two numbers d = a/b print(a,b,d) # let's divide two integers over integers # the result is always an integer with possible integer remainder d = 33 // 6 print(d) # reminder/mod operator r = 33 % 6 # 33 mod 6 = 3 # or when 33 is divided by 6 over integers, the reminder is 3 # 33 = 5 * 6 + 3 # let's print the result print(r) # Booleen variables t = True f = False # let's print their values print(t,f) # print their negations print(not t) print("the negation of",t,"is",not t) print(not f) print("the negation of",f,"is",not f) # define a float variable d = -3.4444 # let's print its value and its square print(d, d * d) e = (23*13) - (11 * 15) print(e) # we can use more than one variable # left is the variable for the left part of the expression # we start with the multiplication inside the parathesis left = 34*11 # we continue with the substruction inside the parathesis # we reuse the variable named left left = 123 - left # we reuse left again for the multiplication with -3 left = -3 * left # right is the variable for the right part of the expression # we use the same idea here right = 23 * 15 right = 5 + right right = 4 * right # at the end, we use left for the result left = left + right # let's print the result print(left) # # your solution is here # # # your solution is here # # # your solution is here #
https://github.com/rohitgit1/Quantum-Computing-Summer-School
rohitgit1
# import SymPy and define symbols import sympy as sp sp.init_printing(use_unicode=True) wr = sp.Symbol('\omega_r') # resonator frequency wq = sp.Symbol('\omega_q') # qubit frequency g = sp.Symbol('g', real=True) # vacuum Rabi coupling Delta = sp.Symbol('Delta', real=True) # wr - wq; defined later # import operator relations and define them from sympy.physics.quantum.boson import BosonOp a = BosonOp('a') # resonator photon annihilation operator from sympy.physics.quantum import pauli, Dagger, Commutator from sympy.physics.quantum.operatorordering import normal_ordered_form # Pauli matrices sx = pauli.SigmaX() sy = pauli.SigmaY() sz = pauli.SigmaZ() # qubit raising and lowering operators splus = pauli.SigmaPlus() sminus = pauli.SigmaMinus() # define J-C Hamiltonian in terms of diagonal and non-block diagonal terms H0 = wr*Dagger(a)*a - (1/2)*wq*sz; H1 = 0 H2 = g*(Dagger(a)*sminus + a*splus); HJC = H0 + H1 + H2; HJC # print # using the above method for finding the ansatz eta = Commutator(H0, H2); eta pauli.qsimplify_pauli(normal_ordered_form(eta.doit().expand())) A = sp.Symbol('A') B = sp.Symbol('B') eta = A * Dagger(a) * sminus - B * a * splus; pauli.qsimplify_pauli(normal_ordered_form(Commutator(H0, eta).doit().expand())) H2 S1 = eta.subs(A, g/Delta) S1 = S1.subs(B, g/Delta); S1.factor() Heff = H0 + H1 + 0.5*pauli.qsimplify_pauli(normal_ordered_form(Commutator(H2, S1).doit().expand())).simplify(); Heff from qiskit.tools.jupyter import * from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') backend = provider.get_backend('ibmq_armonk') backend_config = backend.configuration() assert backend_config.open_pulse, "Backend doesn't support Pulse" dt = backend_config.dt print(f"Sampling time: {dt*1e9} ns") backend_defaults = backend.defaults() import numpy as np # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 us = 1.0e-6 # Microseconds ns = 1.0e-9 # Nanoseconds # We will find the qubit frequency for the following qubit. qubit = 0 # The sweep will be centered around the estimated qubit frequency. center_frequency_Hz = backend_defaults.qubit_freq_est[qubit] # The default frequency is given in Hz # warning: this will change in a future release print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.") # scale factor to remove factors of 10 from the data scale_factor = 1e-14 # We will sweep 40 MHz around the estimated frequency frequency_span_Hz = 40 * MHz # in steps of 1 MHz. frequency_step_Hz = 1 * MHz # We will sweep 20 MHz above and 20 MHz below the estimated frequency frequency_min = center_frequency_Hz - frequency_span_Hz / 2 frequency_max = center_frequency_Hz + frequency_span_Hz / 2 # Construct an np array of the frequencies for our experiment frequencies_GHz = np.arange(frequency_min / GHz, frequency_max / GHz, frequency_step_Hz / GHz) print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz \ in steps of {frequency_step_Hz / MHz} MHz.") from qiskit import pulse # This is where we access all of our Pulse features! inst_sched_map = backend_defaults.instruction_schedule_map measure = inst_sched_map.get('measure', qubits=[qubit]) x_pulse = inst_sched_map.get('x', qubits=[qubit]) ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Create the base schedule # Start with drive pulse acting on the drive channel schedule = pulse.Schedule(name='Frequency sweep') schedule += x_pulse # The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration schedule += measure << schedule.duration # Create the frequency settings for the sweep (MUST BE IN HZ) frequencies_Hz = frequencies_GHz*GHz schedule_frequencies = [{drive_chan: freq} for freq in frequencies_Hz] schedule.draw(label=True, scaling=0.8) from qiskit import assemble frequency_sweep_program = assemble(schedule, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=schedule_frequencies) # RUN the job on a real device #job = backend.run(rabi_experiment_program) #print(job.job_id()) #from qiskit.tools.monitor import job_monitor #job_monitor(job) # OR retreive result from previous run job = backend.retrieve_job('5ef3b081fbc24b001275b03b') frequency_sweep_results = job.result() import matplotlib.pyplot as plt plt.style.use('dark_background') sweep_values = [] for i in range(len(frequency_sweep_results.results)): # Get the results from the ith experiment res = frequency_sweep_results.get_memory(i)*scale_factor # Get the results for `qubit` from this experiment sweep_values.append(res[qubit]) plt.scatter(frequencies_GHz, np.real(sweep_values), color='white') # plot real part of sweep values plt.xlim([min(frequencies_GHz), max(frequencies_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured signal [a.u.]") plt.show() from scipy.optimize import curve_fit def fit_function(x_values, y_values, function, init_params): fitparams, conv = curve_fit(function, x_values, y_values, init_params) y_fit = function(x_values, *fitparams) return fitparams, y_fit fit_params, y_fit = fit_function(frequencies_GHz, np.real(sweep_values), lambda x, A, q_freq, B, C: (A / np.pi) * (B / ((x - q_freq)**2 + B**2)) + C, [5, 4.975, 1, 3] # initial parameters for curve_fit ) plt.scatter(frequencies_GHz, np.real(sweep_values), color='white') plt.plot(frequencies_GHz, y_fit, color='red') plt.xlim([min(frequencies_GHz), max(frequencies_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() # Create the schedules for 0 and 1 schedule_0 = pulse.Schedule(name='0') schedule_0 += measure schedule_1 = pulse.Schedule(name='1') schedule_1 += x_pulse schedule_1 += measure << schedule_1.duration schedule_0.draw() schedule_1.draw() frequency_span_Hz = 320 * kHz frequency_step_Hz = 8 * kHz center_frequency_Hz = backend_defaults.meas_freq_est[qubit] print(f"Qubit {qubit} has an estimated readout frequency of {center_frequency_Hz / GHz} GHz.") frequency_min = center_frequency_Hz - frequency_span_Hz / 2 frequency_max = center_frequency_Hz + frequency_span_Hz / 2 frequencies_GHz = np.arange(frequency_min / GHz, frequency_max / GHz, frequency_step_Hz / GHz) print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz\ in steps of {frequency_step_Hz / MHz} MHz.") num_shots_per_frequency = 2048 frequencies_Hz = frequencies_GHz*GHz schedule_los = [{meas_chan: freq} for freq in frequencies_Hz] cavity_sweep_0 = assemble(schedule_0, backend=backend, meas_level=1, meas_return='avg', shots=num_shots_per_frequency, schedule_los=schedule_los) cavity_sweep_1 = assemble(schedule_1, backend=backend, meas_level=1, meas_return='avg', shots=num_shots_per_frequency, schedule_los=schedule_los) # RUN the job on a real device #job_0 = backend.run(cavity_sweep_0) #job_monitor(job_0) #job_0.error_message() #job_1 = backend.run(cavity_sweep_1) #job_monitor(job_1) #job_1.error_message() # OR retreive result from previous run job_0 = backend.retrieve_job('5efa5b447c0d6800137fff1c') job_1 = backend.retrieve_job('5efa6b2720eee10013be46b4') cavity_sweep_0_results = job_0.result() cavity_sweep_1_results = job_1.result() scale_factor = 1e-14 sweep_values_0 = [] for i in range(len(cavity_sweep_0_results.results)): res_0 = cavity_sweep_0_results.get_memory(i)*scale_factor sweep_values_0.append(res_0[qubit]) sweep_values_1 = [] for i in range(len(cavity_sweep_1_results.results)): res_1 = cavity_sweep_1_results.get_memory(i)*scale_factor sweep_values_1.append(res_1[qubit]) plotx = frequencies_Hz/kHz ploty_0 = np.abs(sweep_values_0) ploty_1 = np.abs(sweep_values_1) plt.plot(plotx, ploty_0, color='blue', marker='.') # plot real part of sweep values plt.plot(plotx, ploty_1, color='red', marker='.') # plot real part of sweep values plt.legend([r'$\vert0\rangle$', r'$\vert1\rangle$']) plt.grid() plt.xlabel("Frequency [kHz]") plt.ylabel("Measured signal [a.u.]") plt.yscale('log') plt.show()
https://github.com/abbarreto/qiskit4
abbarreto
https://github.com/JouziP/MQITE
JouziP
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 5 16:33:48 2022 @author: pejmanjouzdani """ # from SimulateMQITE.log_config import logger import numpy as np import pandas as pd from qiskit import QuantumCircuit, transpile from qiskit import Aer class AmplitudeClass: def __init__(self, circ_U, circ_UQU, Q, shots_amplitude, eta, significant_figures, machine_precision=10): self.Q = Q self.circ_U = circ_U self.circ_UQU = circ_UQU self.shots_amplitude = shots_amplitude self.eta = eta self.significant_figures = significant_figures self.machine_precision = machine_precision ############################ OUTPUTS #################### |cj|^2 and js upto significant digits self.df_count = self.getIndexsFromExecute(self.circ_UQU, self.shots_amplitude) ### keep eta of them -> {|c_j|} = df_ampl ### the j's and c_j's from shots and observed bit string --> NO state vector self.df_ampl = self.getAmplitudes( pd.DataFrame.copy(self.df_count), self.eta ) @staticmethod def getIndexsFromExecute(circ_UQU, shots, backend = 'qasm_simulator'): pass ''' appends classical wires to record measurements execute the circuit 'shots' time returns the observed bit-strings and distributions (counts) [AerSimulator('aer_simulator'), AerSimulator('aer_simulator_statevector'), AerSimulator('aer_simulator_density_matrix'), AerSimulator('aer_simulator_stabilizer'), AerSimulator('aer_simulator_matrix_product_state'), AerSimulator('aer_simulator_extended_stabilizer'), AerSimulator('aer_simulator_unitary'), AerSimulator('aer_simulator_superop'), QasmSimulator('qasm_simulator'), StatevectorSimulator('statevector_simulator'), UnitarySimulator('unitary_simulator'), PulseSimulator('pulse_simulator')] ''' ### check if shots are type and value correct if not isinstance(shots, int): raise TypeError('shots must be an integer') if shots<1 or shots>10**8: raise ValueError('Number of shots is either less than 1 or larger than 10^8') ### check if backend is correct simulator = Aer.get_backend(backend) ### check the circ Value and Type ### Building measurment circuit num_qubits = circ_UQU.num_qubits circ_meas = QuantumCircuit(num_qubits, num_qubits) circ_meas = circ_meas.compose(circ_UQU) circ_meas.measure( [q for q in range(num_qubits)], [q for q in range(num_qubits)] ) compiled_circuit = transpile(circ_meas, simulator) job = simulator.run(compiled_circuit, shots=shots) result = job.result() counts = result.get_counts(compiled_circuit) ### Using Pandas dataframe to organize df_count = pd.DataFrame([counts.int_outcomes()]).T df_count.columns=['n_j'] return df_count @staticmethod def getAmplitudes(df_count,eta ): ''' return the |c_j| of the most largest amplitudes ''' chi = df_count.sum()['n_j'] df_count = df_count/chi df_ampl = df_count.apply(lambda x: np.sqrt(x)) df_ampl.columns=['|c_j|'] return df_ampl if __name__=='__main__': pass from qiskit import QuantumCircuit ################################################################ ################################################################ ##################### FOR TEST ####################### ################################################################ ################################################################ ################################################################ from BasicFunctions.getRandomQ import getRandomQ from BasicFunctions.getRandomU import getRandomU from BasicFunctions.getQCirc import getQCirc from BasicFunctions.getUQUCirc import getUQUCirc ################################################################ ################################################################ seed = 1253 np.random.seed(seed) ################################################################ ################################################################ nspins = 12 num_layers =2 num_itr =1 machine_precision = 10 shots_amplitude = 100 eta = 100 significant_figures = 2#np.log10(np.sqrt(shots_amplitude)).astype(int) TestLevel = 0 circ_U = getRandomU(nspins, num_layers) Q = getRandomQ(nspins) circ_UQ = getQCirc(circ_U, Q) circ_UQU = getUQUCirc(circ_U, circ_UQ) ################################# TEST ###### Constructor myAmplObj = AmplitudeClass( circ_U, circ_UQU, Q, shots_amplitude, eta, significant_figures, machine_precision=10) print(myAmplObj.df_count) print(myAmplObj.df_ampl)
https://github.com/Hayatto9217/Qiskit4
Hayatto9217
import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import BasicAer from qiskit.compiler import transpile from qiskit.quantum_info.operators import Operator, Pauli from qiskit.quantum_info import process_fidelity from qiskit.extensions import RXGate, XGate, CXGate #Operator create XX = Operator([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]]) XX # Operater propaty XX.data input_dim, output_dim = XX.dim input_dim, output_dim #InputとOutputの関数でサブシステムの追跡可能 op = Operator(np.random.rand(2 ** 1, 2 ** 2)) print('Input dimensions:', op.input_dims()) print('Output dimesions:', op.output_dims()) #6*6の行列場合 op = Operator(np.random.rand(6, 6)) print('Input dimensions:', op.input_dims()) print('Output dimensions:', op.output_dims()) #初期化時に手動でして可能 op = Operator(np.random.rand(2 ** 1, 2 ** 3), input_dims=[8]) print('Input dimensions:', op.input_dims()) print('Output dimensions:', op.output_dims()) # Specify system is a qubit and qutrit op = Operator(np.random.rand(6, 6), input_dims=[2, 3], output_dims=[2, 3]) print('Input dimensions:', op.input_dims()) print('Output dimensions:', op.output_dims()) print('Dimension of input system 0:', op.input_dims([0])) print('Dimension of iutput system 1:', op.input_dims([1])) #Pauliオブジェクトからオペレーターに変換 pauliXX = Pauli('XX') Operator(pauliXX) #Gateオブジェクトからオペレータに変換 Operator(CXGate()) #parameterized gateオブジェクトからオペレータに変換 Operator(RXGate(np.pi / 2)) #QuantumCircuitオブジェクトからオペレータに変換 circ = QuantumCircuit(10) circ.h(0) for j in range(1, 10): circ.cx(j-1, j) Operator(circ) #回路にオペレータ利用 XX = Operator(Pauli('XX')) circ = QuantumCircuit(2,2) circ.append(XX, [0,1]) circ.measure([0,1],[0,1]) circ.draw('mpl') backend = BasicAer.get_backend('qasm_simulator') circ =transpile(circ, backend, basis_gates=['u1', 'u2', 'u3', 'cx']) job =backend.run(circ) job.result().get_counts(0) circ2 = QuantumCircuit(2,2) circ2.append(Pauli('YY'),[0, 1]) circ2.measure([0,1], [0,1]) circ2.draw() #単一量子ビットオペレータの場合 A = Operator(Pauli('X')) B = Operator(Pauli('Z')) A.tensor(B) #順序が逆になるテンソル積 A = Operator(Pauli('X')) B = Operator(Pauli('Z')) A.expand(B) A = Operator(Pauli('X')) B = Operator(Pauli('Z')) A.compose(B) #順番を逆にする役割 A = Operator(Pauli('X')) B = Operator(Pauli('Z')) A.compose(B, front= True) #Compose XZと3-qubit indetity op = Operator(np.eye(2 ** 3)) XZ = Operator(Pauli('XZ')) op.compose(XZ, qargs=[0,2]) op.is_unitary() #Compose YXと前のオペレータ op = Operator(np.eye(2 ** 4)) YX = Operator(Pauli('YX')) op.compose(XZ, qargs= [0,2], front=True) op.is_unitary() #標準な線形オペレータ(非ユニタリー性) XX = Operator(Pauli('XX')) YY = Operator(Pauli('YY')) ZZ = Operator(Pauli('ZZ')) op = 0.5 * (XX + YY -6 * ZZ) op op.is_unitary() Operator(np.eye(2)).compose([[0,1],[1,0]]) #Operatorの近似的チェック法 Operator(Pauli('X'))!= Operator(XGate()) Operator(XGate()) != np.exp(1j * 0.5) * Operator(XGate()) op_a = Operator(XGate()) op_b = np.exp(1j * 1) * Operator(XGate()) F = process_fidelity(op_a, op_b) print('Process fidelity =', F) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) def udd10_pos(j): return np.sin(np.pi*j/(2*10 + 2))**2 with pulse.build() as udd_sched: pulse.play(x90, d0) with pulse.align_func(duration=300, func=udd10_pos): for _ in range(10): pulse.play(x180, d0) pulse.play(x90, d0) udd_sched.draw()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_optimization.problems import QuadraticProgram # define a problem qp = QuadraticProgram() qp.binary_var("x") qp.integer_var(name="y", lowerbound=-1, upperbound=4) qp.maximize(quadratic={("x", "y"): 1}) qp.linear_constraint({"x": 1, "y": -1}, "<=", 0) print(qp.prettyprint()) from qiskit_optimization.algorithms import CplexOptimizer, GurobiOptimizer cplex_result = CplexOptimizer().solve(qp) gurobi_result = GurobiOptimizer().solve(qp) print("cplex") print(cplex_result.prettyprint()) print() print("gurobi") print(gurobi_result.prettyprint()) result = CplexOptimizer(disp=True, cplex_parameters={"threads": 1, "timelimit": 0.1}).solve(qp) print(result.prettyprint()) from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit_aer import Aer from qiskit.algorithms.minimum_eigensolvers import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler meo = MinimumEigenOptimizer(QAOA(sampler=Sampler(), optimizer=COBYLA(maxiter=100))) result = meo.solve(qp) print(result.prettyprint()) print("\ndisplay the best 5 solution samples") for sample in result.samples[:5]: print(sample) # docplex model from docplex.mp.model import Model docplex_model = Model("docplex") x = docplex_model.binary_var("x") y = docplex_model.integer_var(-1, 4, "y") docplex_model.maximize(x * y) docplex_model.add_constraint(x <= y) docplex_model.prettyprint() # gurobi model import gurobipy as gp gurobipy_model = gp.Model("gurobi") x = gurobipy_model.addVar(vtype=gp.GRB.BINARY, name="x") y = gurobipy_model.addVar(vtype=gp.GRB.INTEGER, lb=-1, ub=4, name="y") gurobipy_model.setObjective(x * y, gp.GRB.MAXIMIZE) gurobipy_model.addConstr(x - y <= 0) gurobipy_model.update() gurobipy_model.display() from qiskit_optimization.translators import from_docplex_mp, from_gurobipy qp = from_docplex_mp(docplex_model) print("QuadraticProgram obtained from docpblex") print(qp.prettyprint()) print("-------------") print("QuadraticProgram obtained from gurobipy") qp2 = from_gurobipy(gurobipy_model) print(qp2.prettyprint()) from qiskit_optimization.translators import to_gurobipy, to_docplex_mp gmod = to_gurobipy(from_docplex_mp(docplex_model)) print("convert docplex to gurobipy via QuadraticProgram") gmod.display() dmod = to_docplex_mp(from_gurobipy(gurobipy_model)) print("\nconvert gurobipy to docplex via QuadraticProgram") print(dmod.export_as_lp_string()) ind_mod = Model("docplex") x = ind_mod.binary_var("x") y = ind_mod.integer_var(-1, 2, "y") z = ind_mod.integer_var(-1, 2, "z") ind_mod.maximize(3 * x + y - z) ind_mod.add_indicator(x, y >= z, 1) print(ind_mod.export_as_lp_string()) qp = from_docplex_mp(ind_mod) result = meo.solve(qp) # apply QAOA to QuadraticProgram print("QAOA") print(result.prettyprint()) print("-----\nCPLEX") print(ind_mod.solve()) # apply CPLEX directly to the Docplex model import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/sergiogh/qpirates-qiskit-notebooks
sergiogh
import pennylane as qml from pennylane import numpy as np graph = [(0, 1), (0, 3), (1, 2), (2, 3), (3, 4), (1, 4), (4, 5)] n_wires = len(graph) # unitary operator U_B with parameter beta def U_B(beta): for wire in range(n_wires): qml.RX(2 * beta, wires=wire) # unitary operator U_C with parameter gamma def U_C(gamma): for edge in graph: wire1 = edge[0] wire2 = edge[1] qml.CNOT(wires=[wire1, wire2]) qml.RZ(gamma, wires=wire2) qml.CNOT(wires=[wire1, wire2]) def comp_basis_measurement(wires): n_wires = len(wires) return qml.Hermitian(np.diag(range(2 ** n_wires)), wires=wires) dev = qml.device("default.qubit", wires=n_wires, analytic=True, shots=1) pauli_z = [[1, 0], [0, -1]] pauli_z_2 = np.kron(pauli_z, pauli_z) @qml.qnode(dev) def circuit(gammas, betas, edge=None, n_layers=1): # apply Hadamards to get the n qubit |+> state for wire in range(n_wires): qml.Hadamard(wires=wire) # p instances of unitary operators for i in range(n_layers): U_C(gammas[i]) U_B(betas[i]) if edge is None: # measurement phase return qml.sample(comp_basis_measurement(range(n_wires))) # during the optimization phase we are evaluating a term # in the objective using expval return qml.expval(qml.Hermitian(pauli_z_2, wires=edge)) def qaoa_maxcut(n_layers=1): print("\np={:d}".format(n_layers)) # initialize the parameters near zero init_params = 0.01 * np.random.rand(2, n_layers) # minimize the negative of the objective function def objective(params): gammas = params[0] betas = params[1] neg_obj = 0 for edge in graph: # objective for the MaxCut problem neg_obj -= 0.5 * (1 - circuit(gammas, betas, edge=edge, n_layers=n_layers)) return neg_obj # initialize optimizer: Adagrad works well empirically opt = qml.AdagradOptimizer(stepsize=0.5) # optimize parameters in objective params = init_params steps = 30 for i in range(steps): params = opt.step(objective, params) if (i + 1) % 5 == 0: print("Objective after step {:5d}: {: .7f}".format(i + 1, -objective(params))) # sample measured bitstrings 100 times bit_strings = [] n_samples = 100 for i in range(0, n_samples): bit_strings.append(int(circuit(params[0], params[1], edge=None, n_layers=n_layers))) # print optimal parameters and most frequently sampled bitstring counts = np.bincount(np.array(bit_strings)) most_freq_bit_string = np.argmax(counts) print("Optimized (gamma, beta) vectors:\n{}".format(params[:, :n_layers])) print("Most frequently sampled bit string is: {:04b}".format(most_freq_bit_string)) return -objective(params), bit_strings # perform qaoa on our graph with p=1,2 and # keep the bitstring sample lists bitstrings1 = qaoa_maxcut(n_layers=1)[1] bitstrings2 = qaoa_maxcut(n_layers=2)[1] bitstrings3 = qaoa_maxcut(n_layers=3)[1] import matplotlib.pyplot as plt xticks = range(0, 16) xtick_labels = list(map(lambda x: format(x, "08b"), xticks)) bins = np.arange(0, 17) - 0.5 fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(10, 4)) plt.subplot(1, 3, 1) plt.title("n_layers=1") plt.xlabel("bitstrings") plt.ylabel("freq.") plt.xticks(xticks, xtick_labels, rotation="vertical") plt.hist(bitstrings1, bins=bins) plt.subplot(1, 3, 2) plt.title("n_layers=2") plt.xlabel("bitstrings") plt.ylabel("freq.") plt.xticks(xticks, xtick_labels, rotation="vertical") plt.hist(bitstrings2, bins=bins) plt.subplot(1, 3, 3) plt.title("n_layers=3") plt.xlabel("bitstrings") plt.ylabel("freq.") plt.xticks(xticks, xtick_labels, rotation="vertical") plt.hist(bitstrings3, bins=bins) plt.tight_layout() plt.show()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module # pylint: disable=attribute-defined-outside-init,unsubscriptable-object from qiskit import converters from qiskit import qasm from .utils import random_circuit class ConverterBenchmarks: params = ([1, 2, 5, 8, 14, 20, 32, 53], [8, 128, 2048, 8192]) param_names = ["n_qubits", "depth"] timeout = 600 def setup(self, n_qubits, depth): seed = 42 # NOTE: Remove the benchmarks larger than 20x2048 and 14x8192, this is # a tradeoff for speed of benchmarking, creating circuits this size # takes more time than is worth it for benchmarks that take a couple # seconds if n_qubits >= 20: if depth >= 2048: raise NotImplementedError elif n_qubits == 14: if depth > 2048: raise NotImplementedError self.qc = random_circuit(n_qubits, depth, measure=True, conditional=True, seed=seed) self.dag = converters.circuit_to_dag(self.qc) self.qasm = qasm.Qasm(data=self.qc.qasm()).parse() def time_circuit_to_dag(self, *_): converters.circuit_to_dag(self.qc) def time_circuit_to_instruction(self, *_): converters.circuit_to_instruction(self.qc) def time_dag_to_circuit(self, *_): converters.dag_to_circuit(self.dag) def time_ast_to_circuit(self, *_): converters.ast_to_dag(self.qasm)
https://github.com/pranavdurai10/quantum-gates
pranavdurai10
''' /////////////////////////////////////////////////////////////////////////// Code written by Pranav Durai for Quantum Computer on 30.05.2023 @ 22:30:05 Component: Hadamard Gate Framework: Qiskit 0.43.0 /////////////////////////////////////////////////////////////////////////// ''' # Import necessary libraries from qiskit import QuantumCircuit, Aer, execute # Create a quantum circuit with one qubit circuit = QuantumCircuit(1) # Apply Hadamard gate to the qubit circuit.h(0) # Measure the qubit circuit.measure_all() # Simulate the circuit using the local Aer simulator simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=1) # Get the result result = job.result() counts = result.get_counts(circuit) # Print the measurement outcome print("Measurement outcome:", list(counts.keys())[0])
https://github.com/nmoran/qiskit-qdrift-quid19
nmoran
#!/usr/bin/env python3 """ Script to run different qiskit Quantum Phase Estimation methods for comparison Adapted from notebook at https://github.com/Qiskit/qiskit-community-tutorials/blob/master/chemistry/h2_iqpe.ipynb """ import time import numpy as np import argparse import sys import logging import os import copy from qiskit import BasicAer from qiskit.aqua import QuantumInstance, AquaError from qiskit.aqua.operators import Z2Symmetries from qiskit.aqua.operators.op_converter import to_weighted_pauli_operator from qiskit.aqua.algorithms.single_sample import IQPE from qiskit.aqua.algorithms.single_sample import QPE from qiskit.aqua.components.iqfts import Standard from qiskit.aqua.algorithms.classical import ExactEigensolver from qiskit.chemistry import FermionicOperator from qiskit.chemistry.aqua_extensions.components.initial_states import HartreeFock from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry import set_qiskit_chemistry_logging from qiskit.aqua.components.initial_states import Custom from IQPEHack import IQPEHack def compute_energy(i, distance, algorithm, first_atom='H', sim='statevector_simulator', error=0.1, runs=20): """ Compute the ground state energy given a distance, method and params """ try: driver = PySCFDriver( atom='{} .0 .0 .0; H .0 .0 {}'.format(first_atom, distance), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g' ) except: raise AquaError('PYSCF driver does not appear to be installed') molecule = driver.run() qubit_mapping = 'parity' fer_op = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) qubit_op = Z2Symmetries.two_qubit_reduction(to_weighted_pauli_operator(fer_op.mapping(map_type=qubit_mapping, threshold=1e-10)), 2) energy_std = 0.0 exact_eigensolver = ExactEigensolver(qubit_op, k=1) exact_result = exact_eigensolver.run() gs_state = Custom(qubit_op.num_qubits, state_vector=exact_result['eigvecs'][0]) if algorithm.lower() == 'exacteigensolver': reference_energy = exact_result['energy'] energy = exact_result['energy'] elif algorithm.lower() == 'iqpe': num_particles = molecule.num_alpha + molecule.num_beta two_qubit_reduction = True num_orbitals = qubit_op.num_qubits + (2 if two_qubit_reduction else 0) num_time_slices = 2 num_iterations = 8 #state_in = HartreeFock(qubit_op.num_qubits, num_orbitals, # num_particles, qubit_mapping, two_qubit_reduction) iqpe = IQPE(qubit_op, gs_state, num_time_slices, num_iterations, expansion_mode='trotter', expansion_order=1, shallow_circuit_concat=True) backend = BasicAer.get_backend(sim) quantum_instance = QuantumInstance(backend) result = iqpe.run(quantum_instance) energy = result['energy'] elif algorithm.lower() == 'iqpe_hack': num_particles = molecule.num_alpha + molecule.num_beta two_qubit_reduction = True num_orbitals = qubit_op.num_qubits + (2 if two_qubit_reduction else 0) num_time_slices = 1 num_iterations = 8 num_runs = runs energy_samples = np.empty(num_runs) for runs in range(num_runs): state_in = HartreeFock(qubit_op.num_qubits, num_orbitals, num_particles, qubit_mapping, two_qubit_reduction) qubit_op = Z2Symmetries.two_qubit_reduction(to_weighted_pauli_operator(fer_op.mapping(map_type=qubit_mapping, threshold=1e-10)), 2) iqpe = IQPEHack(qubit_op.copy(), gs_state, num_time_slices, num_iterations, expansion_mode='trotter', expansion_order=1, shallow_circuit_concat=True, error=error) backend = BasicAer.get_backend(sim) quantum_instance = QuantumInstance(backend) result = iqpe.run(quantum_instance) energy_samples[runs] = result['energy'] energy = np.mean(energy_samples) energy_std = np.std(energy_samples) elif algorithm.lower() == 'qpe': num_particles = molecule.num_alpha + molecule.num_beta two_qubit_reduction = True num_orbitals = qubit_op.num_qubits + (2 if two_qubit_reduction else 0) num_time_slices = 10 iqft = Standard(qubit_op.num_qubits) state_in = HartreeFock(qubit_op.num_qubits, num_orbitals, num_particles, qubit_mapping, two_qubit_reduction) qpe = QPE(qubit_op, gs_state, iqft, num_time_slices, num_ancillae=4, expansion_mode='trotter', expansion_order=1, shallow_circuit_concat=True) backend = BasicAer.get_backend(sim) quantum_instance = QuantumInstance(backend) result = qpe.run(quantum_instance) energy = result['energy'] else: raise AquaError('Unrecognized algorithm.') return i, distance, energy + molecule.nuclear_repulsion_energy, molecule.hf_energy, energy_std if __name__ == '__main__': # Create parser with args to control behaviour parser = argparse.ArgumentParser() parser.add_argument('-r', '--no-ref', action='store_true', help='Do not calculate reference values using exact eigensolver.') parser.add_argument('-q', '--qpe', action='store_true', help='Also use QPE algorithm.') parser.add_argument('-n', '--no-hack', action='store_true', help='Do not attempt to use the modified IQPE.') parser.add_argument('-i', '--include-standard-iqpe', action='store_true', help='Include the standard IQPE method.') parser.add_argument('-s', '--steps', type=int, default=10, help='Number of distance steps to use between 0.5 and 1.0 (default=10).') parser.add_argument('-f', '--first_atom', default='H', help='The first atom (default=H).') parser.add_argument('-e', '--error', type=float, default=0.1, help='The error to use for qdrift IQPE (default=0.1).') parser.add_argument('-m', '--runs', type=int, default=20, help='The number of runs to do of stochastic algorithms to gather statistics (default=20).') parser.add_argument('--id', type=str, default='', help='Identifying string to use in output filenames.') parser.add_argument('-v', '--verbose', action='store_true') # parse command line args opts = parser.parse_args(sys.argv[1:]) # if verbose flag set verbosity level if opts.verbose: set_qiskit_chemistry_logging(logging.INFO) logging.basicConfig(level=logging.INFO) algorithms = [] if not opts.no_hack: algorithms.append('iqpe_hack') if not opts.no_ref: algorithms.append('exacteigensolver') if opts.include_standard_iqpe: algorithms.append('iqpe') if opts.qpe: algorithms.append('qpe') start = 0.5 # Start distance by = 1.0 # How much to increase distance by steps = opts.steps # Number of steps to increase by energies = {} energy_stds = {} hf_energies = np.empty(steps) distances = np.empty(steps) logging.info(f'Running for algorithms {algorithms} and {steps} steps...') start_time = time.time() for j in range(len(algorithms)): algorithm = algorithms[j] energies[algorithm] = np.empty(steps) energy_stds[algorithm] = np.empty(steps) for i in range(steps): d = start + i*by/steps result = compute_energy( i, d, algorithm, opts.first_atom, error=opts.error, runs=opts.runs ) i, d, energy, hf_energy, energy_error = result energies[algorithm][i] = energy energy_stds[algorithm][i] = energy_error hf_energies[i] = hf_energy distances[i] = d print(' --- complete') print('Distances: ', distances) print('Energies:', energies) print('Energy Stds:', energy_stds) print('Hartree-Fock energies:', hf_energies) print("--- %s seconds ---" % (time.time() - start_time)) import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.plot(distances, hf_energies, label='Hartree-Fock', alpha=0.5, marker='+') for algorithm, es in energies.items(): plt.errorbar(distances, es, yerr=energy_stds[algorithm], label=algorithm, alpha=0.5, marker='+') plt.xlabel('Interatomic distance') plt.ylabel('Energy') plt.title(f'{opts.first_atom}-H Ground State Energy') if opts.id == '': plt.legend(loc='upper right') filename = 'energies_0.png' i = 0 while os.path.exists(f'energies_{i}.png'): i += 1 filename = f'energies_{i}.png' else: filename = f'energies_{opts.id}.png' plt.savefig(filename) # we plot energy difference with reference energy if present if 'exacteigensolver' in energies: plt.figure() plt.plot(distances, hf_energies - energies['exacteigensolver'], label='Hartree-Fock', alpha=0.5, marker='+') for algorithm, es in energies.items(): if algorithm != 'exacteigensolver': plt.plot(distances, es - energies['exacteigensolver'], label=algorithm, alpha=0.5, marker='+') plt.xlabel('Interatomic distance') plt.ylabel('Energy - Energy ref') plt.title(f'{opts.first_atom}-H Ground State Energy') plt.legend(loc='upper right') if opts.id == '': filename = 'energy_diffs_0.png' i = 0 while os.path.exists(f'energy_diffs_{i}.png'): i += 1 filename = f'energy_diffs_{i}.png' else: filename = f'energy_diffs_{opts.id}.png' plt.savefig(filename)
https://github.com/qiskit-community/qiskit-toqm
qiskit-community
import unittest import qiskit_toqm.native as toqm class TestTOQM(unittest.TestCase): def test_version(self): self.assertEqual(toqm.__version__, "0.1.0") def test_basic(self): num_q = 4 gates = [ toqm.GateOp(0, "cx", 0, 1), toqm.GateOp(1, "cx", 0, 2), toqm.GateOp(2, "cx", 0, 3), toqm.GateOp(3, "cx", 1, 2), toqm.GateOp(4, "cx", 1, 3), toqm.GateOp(5, "cx", 2, 3) ] coupling = toqm.CouplingMap(5, {(0, 1), (0, 2), (1, 2), (2, 3), (2, 4), (3, 4)}) q = toqm.DefaultQueue() exp = toqm.DefaultExpander() cf = toqm.CXFrontier() lat = toqm.Latency_1_2_6() fs = [toqm.HashFilter(), toqm.HashFilter2()] nms = [] mapper = toqm.ToqmMapper(q, exp, cf, lat, nms, fs, -1) mapper.setRetainPopped(0) result = mapper.run(gates, num_q, coupling) # Print result for g in result.scheduledGates: print(f"{g.gateOp.type} ", end='') if g.physicalControl >= 0: print(f"q[{g.physicalControl}],", end='') print(f"q[{g.physicalTarget}]; ", end='') print(f"//cycle: {g.cycle}", end='') if (g.gateOp.type.lower() != "swap"): print(f" //{g.gateOp.type} ", end='') if g.gateOp.control >= 0: print(f"q[{g.gateOp.control}],", end='') print(f"q[{g.gateOp.target}]; ", end='') print()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, execute from qiskit.visualization import plot_error_map from qiskit.providers.fake_provider import FakeVigoV2 backend = FakeVigoV2() plot_error_map(backend)
https://github.com/rishikhurana2/FourQuantumAlgorithms
rishikhurana2
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>) out of four possible values.""" #import numpy and plot library import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector # import basic plot tools from qiskit.visualization import plot_histogram # define variables, 1) initialize qubits to zero n = 2 grover_circuit = QuantumCircuit(n) #define initialization function def initialize_s(qc, qubits): '''Apply a H-gate to 'qubits' in qc''' for q in qubits: qc.h(q) return qc ### begin grovers circuit ### #2) Put qubits in equal state of superposition grover_circuit = initialize_s(grover_circuit, [0,1]) # 3) Apply oracle reflection to marked instance x_0 = 3, (|11>) grover_circuit.cz(0,1) statevec = job_sim.result().get_statevector() from qiskit_textbook.tools import vector2latex vector2latex(statevec, pretext="|\\psi\\rangle =") # 4) apply additional reflection (diffusion operator) grover_circuit.h([0,1]) grover_circuit.z([0,1]) grover_circuit.cz(0,1) grover_circuit.h([0,1]) # 5) measure the qubits grover_circuit.measure_all() # Load IBM Q account and get the least busy backend device provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) from qiskit.tools.monitor import job_monitor job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) #highest amplitude should correspond with marked value x_0 (|11>)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test for the converter dag dependency to circuit and circuit to dag dependency V2.""" import unittest from qiskit.converters.dagdependency_to_circuit import dagdependency_to_circuit from qiskit.converters.circuit_to_dagdependency_v2 import _circuit_to_dagdependency_v2 from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from test import QiskitTestCase # pylint: disable=wrong-import-order class TestCircuitToDAGDependencyV2(QiskitTestCase): """Test QuantumCircuit to DAGDependencyV2.""" def test_circuit_and_dag_canonical(self): """Check convert to dag dependency and back""" qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit_in = QuantumCircuit(qr, cr) circuit_in.h(qr[0]) circuit_in.h(qr[1]) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.x(qr[0]).c_if(cr, 0x3) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.measure(qr[2], cr[2]) dag_dependency = _circuit_to_dagdependency_v2(circuit_in) circuit_out = dagdependency_to_circuit(dag_dependency) self.assertEqual(circuit_out, circuit_in) def test_calibrations(self): """Test that calibrations are properly copied over.""" circuit_in = QuantumCircuit(1) circuit_in.add_calibration("h", [0], None) self.assertEqual(len(circuit_in.calibrations), 1) dag_dependency = _circuit_to_dagdependency_v2(circuit_in) self.assertEqual(len(dag_dependency.calibrations), 1) circuit_out = dagdependency_to_circuit(dag_dependency) self.assertEqual(len(circuit_out.calibrations), 1) def test_metadata(self): """Test circuit metadata is preservered through conversion.""" meta_dict = {"experiment_id": "1234", "execution_number": 4} qr = QuantumRegister(2) circuit_in = QuantumCircuit(qr, metadata=meta_dict) circuit_in.h(qr[0]) circuit_in.cx(qr[0], qr[1]) circuit_in.measure_all() dag_dependency = _circuit_to_dagdependency_v2(circuit_in) self.assertEqual(dag_dependency.metadata, meta_dict) circuit_out = dagdependency_to_circuit(dag_dependency) self.assertEqual(circuit_out.metadata, meta_dict) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/carstenblank/dc-qiskit-stochastics
carstenblank
# Copyright 2018-2022 Carsten Blank # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import sys from typing import List, Optional import numpy as np import qiskit from qiskit import QuantumCircuit from qiskit.providers.models import QasmBackendConfiguration from qiskit.qobj import Qobj from qiskit.transpiler import PassManager from dc_quantum_scheduling import PreparedExperiment, FinishedExperiment from qiskit.utils.mitigation import CompleteMeasFitter, complete_meas_cal from . import qobj_mapping, get_default_pass_manager LOG = logging.getLogger(__name__) def create_qobj(circuits: List[QuantumCircuit], pass_manager: PassManager, qobj_id, other_arguments, transpiler_target_backend): circuits_assembled = [pass_manager.run(qc) for qc in circuits] config: QasmBackendConfiguration = transpiler_target_backend.configuration() max_shots = config.max_shots max_experiments = config.max_experiments if hasattr(config, 'max_experiments') else sys.maxsize shots = other_arguments.get('shots', max_shots) other_arguments['shots'] = shots mapping_matrix: np.array = qobj_mapping(shots, max_shots, max_experiments, len(circuits_assembled)) shots_per_experiment = int(shots / mapping_matrix.shape[1]) LOG.debug(mapping_matrix) number_of_qobj: int = np.max(mapping_matrix) + 1 LOG.info(f'For #{len(circuits_assembled)} evaluations each {shots} on the device {transpiler_target_backend.name()} ' f'with max shots {max_shots} and max no. of experiments per Qobj {max_experiments} ' f'there are #{number_of_qobj} of Qobj needed. Assembling the circuits now.') qobj_list: List[Qobj] = [] circuit_list: List[List[QuantumCircuit]] = [[] for i in range(number_of_qobj)] for row_no, qc in enumerate(circuits_assembled): indices = mapping_matrix[row_no] for i, qobj_id in enumerate(indices): qobj_circuits = circuit_list[qobj_id] qobj_circuits.append(qc) LOG.info(f'Assembled circuits, now building a list of Qobj.') for i, cc in enumerate(circuit_list): qobj_id_i = f'{qobj_id}--{i}' LOG.info(f'Assembling circuits for Qobj #{i} with shots {shots_per_experiment} and id {qobj_id_i}.') qobj = qiskit.compiler.assemble(cc, shots=shots_per_experiment, max_credits=shots_per_experiment * 5, qobj_id=qobj_id_i) qobj_list.append(qobj) return qobj_list def interpret_output(finished_experiment: FinishedExperiment, meas_fitter: Optional[CompleteMeasFitter] = None) -> CompleteMeasFitter: if meas_fitter is not None: return meas_fitter qubit_list = finished_experiment.parameters['qubit_list'] state_labels = finished_experiment.parameters['state_labels'] # Get results cal_results = [] for qobj_index in range(len(finished_experiment.qobj_list)): r = finished_experiment.to_result(qobj_index) cal_results.append(r) # Calculate the calibration matrix with the noise model return CompleteMeasFitter(cal_results, state_labels, qubit_list=qubit_list, circlabel='mcal') def create_error_mitigation_experiment(exp: PreparedExperiment) -> PreparedExperiment: # def calculate_error_mitigation_matrix(self, backend: Optional[Union[IBMQBackend, AerBackend]] = None): # Get the measured qubits measured_qubits = set([e.instructions[-1].qubits[0] for q in exp.qobj_list for e in q.experiments]) LOG.info(f'Qubits measured are {measured_qubits}') # Generate the calibration circuits qr = qiskit.QuantumRegister(exp.transpiler_backend.configuration().n_qubits) qubit_list = list(measured_qubits) meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qr, circlabel='mcal') _, pm = get_default_pass_manager(exp.transpiler_backend, exp.parameters) external_id = f'{exp.external_id}-error_mitigation' qobj_list = create_qobj(meas_calibs, pass_manager=pm, qobj_id=external_id, other_arguments=exp.parameters, transpiler_target_backend=exp.transpiler_backend ) return PreparedExperiment( external_id=f'{exp.external_id}-error_mitigation', tags=exp.tags + ['error mitigation'], qobj_list=qobj_list, arguments=[], transpiler_backend=exp.transpiler_backend, parameters={ 'qubit_list': qubit_list, 'state_labels': state_labels, **exp.parameters, }, callback=interpret_output )
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
%pip install qiskit import math, cmath from typing import List Matrix = List[List[complex]] def create_empty_matrix(rows, columns): # Create an empty matrix filled with 0s matrix = [[0] * columns for _ in range(rows)] return matrix def matrix_add(a, b): # Get the size of the matrices rows = len(a) columns = len(a[0]) # Create an empty matrix to store the result c = create_empty_matrix(rows, columns) # Perform element-wise addition of matrices for i in range(rows): for j in range(columns): c[i][j] = a[i][j] + b[i][j] return c A = [[1, 2, 3], [4, 5, 6]] B = [[7, 8, 9], [10, 11, 12]] result = matrix_add(A, B) print(result) # Output: [[8, 10, 12], # [14, 16, 18]] def scalar_mult(x, a): # Get the size of the matrix rows = len(a) columns = len(a[0]) # Create a new matrix to store the result result = create_empty_matrix(rows, columns) # Perform scalar multiplication for i in range(rows): for j in range(columns): # Access element of the matrix element = a[i][j] # Compute the scalar multiplication and store it in the result matrix result[i][j] = x * element return result x = 2 A = [[1, 2, 3], [4, 5, 6]] result = scalar_mult(x, A) print(result) # Output: [[2, 4, 6], # [8, 10, 12]] def matrix_mult(a, b): # Get the dimensions of matrices a and b rows_a = len(a) cols_a = len(a[0]) rows_b = len(b) cols_b = len(b[0]) # Check if the matrices can be multiplied if cols_a != rows_b: raise ValueError("Matrices cannot be multiplied. Invalid dimensions.") # Create a new matrix to store the result result = create_empty_matrix(rows_a, cols_b) # Perform matrix multiplication for i in range(rows_a): for j in range(cols_b): for k in range(cols_a): # Access elements from matrices a and b element_a = a[i][k] element_b = b[k][j] # Compute the product and accumulate it in the result matrix result[i][j] += element_a * element_b return result A = [[1, 2, 3], [4, 5, 6]] B = [[7, 8], [9, 10], [11, 12]] result = matrix_mult(A, B) print(result) # Output: [[58, 64], # [139, 154]] def determinant(a): # Get the dimension of the matrix n = len(a) # Check if the matrix is square if n != len(a[0]): raise ValueError("Matrix must be square.") # Base case: for a 1x1 matrix, return the single element as the determinant if n == 1: return a[0][0] # Recursive case: calculate the determinant using cofactor expansion det = 0 for j in range(n): # Create a submatrix without the first row and the j-th column submatrix = [[a[i][col] for col in range(n) if col != j] for i in range(1, n)] # Calculate the determinant of the submatrix recursively sub_det = determinant(submatrix) # Calculate the cofactor by multiplying the element with (-1)^(1+j) cofactor = (-1) ** (1 + j) * sub_det # Accumulate the cofactors to compute the determinant det += a[0][j] * cofactor return det def matrix_inverse(a): # Get the dimensions of the matrix n = len(a) # Check if the matrix is square if n != len(a[0]): raise ValueError("Matrix must be square.") # Calculate the determinant of the matrix det = determinant(a) # Check if the matrix is invertible (non-zero determinant) if det == 0: raise ValueError("Matrix is not invertible.") # Create an empty matrix to store the inverse inverse = create_empty_matrix(n, n) # Calculate the matrix of minors for i in range(n): for j in range(n): # Create a submatrix without the i-th row and j-th column submatrix = [[a[row][col] for col in range(n) if col != j] for row in range(n) if row != i] # Calculate the determinant of the submatrix minor = determinant(submatrix) # Calculate the cofactor by multiplying the determinant with (-1)^(i+j) cofactor = (-1) ** (i + j) * minor # Calculate the element of the inverse matrix inverse[j][i] = cofactor / det return inverse A = [[1, 3, 3], [4, 5, 6], [7,8,9]] result = matrix_inverse(A) print(result) def transpose(a): # Get the dimensions of the matrix rows = len(a) columns = len(a[0]) # Create an empty matrix to store the transpose transposed = create_empty_matrix(columns, rows) # Fill in the transposed matrix with elements from the original matrix for i in range(rows): for j in range(columns): transposed[j][i] = a[i][j] return transposed A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] A_transposed = transpose(A) print(A_transposed) # Output: [[1, 4, 7], # [2, 5, 8], # [3, 6, 9]] def conjugate(a): # Get the dimensions of the matrix rows = len(a) columns = len(a[0]) # Create an empty matrix to store the conjugate conjugated = create_empty_matrix(rows, columns) # Fill in the conjugated matrix with conjugates of elements from the original matrix for i in range(rows): for j in range(columns): element = a[i][j] conjugated[i][j] = complex(element.real, -element.imag) return conjugated A = [[1+2j, 2+3j], [3+4j, 4+5j]] A_conjugated = conjugate(A) print(A_conjugated) # Output: [[1-2j, 2-3j], # [3-4j, 4-5j]] def adjoint(a): # Get the dimensions of the matrix rows = len(a) columns = len(a[0]) # Create an empty matrix to store the adjoint adjointed = create_empty_matrix(columns, rows) # Fill in the adjointed matrix with conjugates of elements from the original matrix for i in range(rows): for j in range(columns): element = a[i][j] adjointed[j][i] = complex(element.real, -element.imag) return adjointed A = [[1+2j, 2+3j], [3+4j, 4+5j]] A_adjointed = adjoint(A) print(A_adjointed) # Output: [[1-2j, 3-4j], # [2-3j, 4-5j]] def inner_prod(v, w): # Check if the vectors have the same length if len(v) != len(w): raise ValueError("Vectors must have the same length") inner_product = 0 for i in range(len(v)): inner_product += v[i] * w[i].conjugate() return inner_product v = [1+2j, 3+4j, 5+6j] w = [7+8j, 9+10j, 11+12j] result = inner_prod(v, w) print(result) import math def normalize(v): # Calculate the magnitude of the vector magnitude = math.sqrt(sum(abs(element)**2 for element in v)) # Check if the magnitude is zero if magnitude == 0: raise ValueError("Cannot normalize a zero vector") # Divide each element of the vector by the magnitude normalized = [element / magnitude for element in v] return normalized v = [1+2j, 3+4j, 5+6j] normalized_v = normalize(v) print(normalized_v) def outer_prod(v, w): # Get the lengths of the vectors len_v = len(v) len_w = len(w) # Create an empty matrix to store the outer product matrix = [[0] * len_w for _ in range(len_v)] # Calculate the outer product for i in range(len_v): for j in range(len_w): matrix[i][j] = v[i] * w[j] return matrix v = [1+2j, 3+4j, 5+6j] w = [7+8j, 9+10j, 11+12j] result = outer_prod(v, w) print(result) def tensor_prod(A, B): # Get the dimensions of matrices A and B rows_A, cols_A = len(A), len(A[0]) rows_B, cols_B = len(B), len(B[0]) # Calculate the dimensions of the resulting tensor product matrix rows_result = rows_A * rows_B cols_result = cols_A * cols_B # Create an empty matrix to store the tensor product result = [[0] * cols_result for _ in range(rows_result)] # Calculate the tensor product for i in range(rows_A): for j in range(cols_A): for m in range(rows_B): for n in range(cols_B): result[i * rows_B + m][j * cols_B + n] = A[i][j] * B[m][n] return result A = [[1+2j, 3+4j], [5+6j, 7+8j]] B = [[9+10j, 11+12j], [13+14j, 15+16j]] result = tensor_prod(A, B) print(result) import numpy as np def eigenvalue_eigenvector(A): # Convert the matrix A to a numpy array A = np.array(A) # Calculate the eigenvalues and eigenvectors using numpy's eig function eigen_vals, eigen_vecs = np.linalg.eig(A) # Return the eigenvalues and eigenvectors as a tuple return eigen_vals, eigen_vecs A = [[1, 2], [3, 4]] eigen_vals, eigen_vecs = eigenvalue_eigenvector(A) print("Eigenvalues:", eigen_vals) print("Eigenvectors:") for i, vec in enumerate(eigen_vecs.T): print("Eigenvalue:", eigen_vals[i]) print("Eigenvector:", vec)
https://github.com/hkhetawat/QArithmetic
hkhetawat
# Import the Qiskit SDK from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, Aer from QArithmetic import sub_ripple_ex # Input N N = 4 a = QuantumRegister(N) b = QuantumRegister(N) s = QuantumRegister(N+1) ca = ClassicalRegister(N) cb = ClassicalRegister(N) cs = ClassicalRegister(N+1) qc = QuantumCircuit(a, b, s, ca, cb, cs) # Input Superposition # a = 1110 qc.x(a[1]) qc.x(a[2]) qc.x(a[3]) # b = 1011 qc.x(b[0]) qc.x(b[1]) qc.x(b[3]) sub_ripple_ex(qc, a, b, s, N) qc.measure(a, ca) qc.measure(b, cb) qc.measure(s, cs) backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc))
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """HamiltonianGate tests""" import numpy as np from numpy.testing import assert_allclose import qiskit from qiskit.extensions.hamiltonian_gate import HamiltonianGate, UnitaryGate from qiskit.extensions.exceptions import ExtensionError from qiskit.test import QiskitTestCase from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Parameter from qiskit.quantum_info import Operator from qiskit.converters import circuit_to_dag, dag_to_circuit class TestHamiltonianGate(QiskitTestCase): """Tests for the HamiltonianGate class.""" def test_set_matrix(self): """Test instantiation""" hamiltonian = HamiltonianGate([[0, 1], [1, 0]], 1) self.assertEqual(hamiltonian.num_qubits, 1) def test_set_matrix_raises(self): """test non-unitary""" with self.assertRaises(ExtensionError): HamiltonianGate([[1, 0], [1, 1]], 1) def test_complex_time_raises(self): """test non-unitary""" with self.assertRaises(ExtensionError): HamiltonianGate([[1, 0], [1, 1]], 1j) def test_conjugate(self): """test conjugate""" ham = HamiltonianGate([[0, 1j], [-1j, 2]], np.pi / 4) np.testing.assert_array_almost_equal(ham.conjugate().to_matrix(), np.conj(ham.to_matrix())) def test_transpose(self): """test transpose""" ham = HamiltonianGate([[15, 1j], [-1j, -2]], np.pi / 7) np.testing.assert_array_almost_equal( ham.transpose().to_matrix(), np.transpose(ham.to_matrix()) ) def test_adjoint(self): """test adjoint operation""" ham = HamiltonianGate([[3, 4j], [-4j, -0.2]], np.pi * 0.143) np.testing.assert_array_almost_equal( ham.adjoint().to_matrix(), np.transpose(np.conj(ham.to_matrix())) ) class TestHamiltonianCircuit(QiskitTestCase): """Hamiltonian gate circuit tests.""" def test_1q_hamiltonian(self): """test 1 qubit hamiltonian""" qr = QuantumRegister(1, "q0") cr = ClassicalRegister(1, "c0") qc = QuantumCircuit(qr, cr) matrix = np.zeros((2, 2)) qc.x(qr[0]) theta = Parameter("theta") qc.append(HamiltonianGate(matrix, theta), [qr[0]]) qc = qc.bind_parameters({theta: 1}) # test of text drawer self.log.info(qc) dag = circuit_to_dag(qc) dag_nodes = dag.named_nodes("hamiltonian") self.assertTrue(len(dag_nodes) == 1) dnode = dag_nodes[0] self.assertIsInstance(dnode.op, HamiltonianGate) self.assertEqual(dnode.qargs, tuple(qc.qubits)) assert_allclose(dnode.op.to_matrix(), np.eye(2)) def test_error_and_deprecation_warning_on_qasm(self): """test that an error is thrown if the method `qasm` is called.""" matrix = np.zeros((2, 2)) hamiltonian_gate = HamiltonianGate(data=matrix, time=1) with self.assertRaises(ExtensionError): with self.assertWarns(DeprecationWarning): hamiltonian_gate.qasm() def test_2q_hamiltonian(self): """test 2 qubit hamiltonian""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) matrix = Operator.from_label("XY") qc.x(qr[0]) theta = Parameter("theta") uni2q = HamiltonianGate(matrix, theta) qc.append(uni2q, [qr[0], qr[1]]) qc2 = qc.bind_parameters({theta: -np.pi / 2}) dag = circuit_to_dag(qc2) nodes = dag.two_qubit_ops() self.assertEqual(len(nodes), 1) dnode = nodes[0] self.assertIsInstance(dnode.op, HamiltonianGate) self.assertEqual(dnode.qargs, (qr[0], qr[1])) # Equality based on Pauli exponential identity np.testing.assert_array_almost_equal(dnode.op.to_matrix(), 1j * matrix.data) qc3 = dag_to_circuit(dag) self.assertEqual(qc2, qc3) def test_3q_hamiltonian(self): """test 3 qubit hamiltonian on non-consecutive bits""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) qc.x(qr[0]) matrix = Operator.from_label("XZY") theta = Parameter("theta") uni3q = HamiltonianGate(matrix, theta) qc.append(uni3q, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) # test of text drawer self.log.info(qc) qc = qc.bind_parameters({theta: -np.pi / 2}) dag = circuit_to_dag(qc) nodes = dag.multi_qubit_ops() self.assertEqual(len(nodes), 1) dnode = nodes[0] self.assertIsInstance(dnode.op, HamiltonianGate) self.assertEqual(dnode.qargs, (qr[0], qr[1], qr[3])) np.testing.assert_almost_equal(dnode.op.to_matrix(), 1j * matrix.data) def test_qobj_with_hamiltonian(self): """test qobj output with hamiltonian""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) qc.rx(np.pi / 4, qr[0]) matrix = Operator.from_label("XIZ") theta = Parameter("theta") uni = HamiltonianGate(matrix, theta, label="XIZ") qc.append(uni, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) qc = qc.bind_parameters({theta: np.pi / 2}) qobj = qiskit.compiler.assemble(qc) instr = qobj.experiments[0].instructions[1] self.assertEqual(instr.name, "hamiltonian") # Also test label self.assertEqual(instr.label, "XIZ") np.testing.assert_array_almost_equal( np.array(instr.params[0]).astype(np.complex64), matrix.data ) def test_decomposes_into_correct_unitary(self): """test 2 qubit hamiltonian""" qc = QuantumCircuit(2) matrix = Operator.from_label("XY") theta = Parameter("theta") uni2q = HamiltonianGate(matrix, theta) qc.append(uni2q, [0, 1]) qc = qc.bind_parameters({theta: -np.pi / 2}).decompose() decomposed_ham = qc.data[0].operation self.assertEqual(decomposed_ham, UnitaryGate(Operator.from_label("XY")))
https://github.com/bawejagb/Quantum_Computing
bawejagb
#Import Libraries from qiskit import QuantumCircuit, transpile, Aer, assemble from qiskit.providers.aer import QasmSimulator from qiskit.visualization import plot_bloch_multivector, plot_histogram from qiskit.visualization import array_to_latex, plot_state_qsphere # Use Aer's qasm_simulator simulator = QasmSimulator() # Create a Quantum Circuit acting on the q register circuit = QuantumCircuit(2, 2) # Add a H gate on qubit 0 circuit.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1 circuit.cx(0, 1) # Draw the circuit circuit.draw(output='mpl') # Let's get the result: svsim=Aer.get_backend('aer_simulator') circuit.save_statevector() qobj = assemble(circuit) result = svsim.run(qobj).result() # Print the statevector neatly: final_state = result.get_statevector() array_to_latex(final_state, prefix="\\text{Statevector = }") #Plot Sphere plot_state_qsphere(final_state) # Map the quantum measurement to the classical bits circuit.measure([0,1], [0,1]) # Draw the circuit circuit.draw(output='mpl') # compile the circuit down to low-level QASM instructions compiled_circuit = transpile(circuit, simulator) # Execute the circuit on the qasm simulator job = simulator.run(compiled_circuit, shots=1000) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(compiled_circuit) print("\nTotal count for 00 and 11 are:",counts) #Plot histogram of result plot_histogram(counts)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the Unroller pass""" from numpy import pi from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.extensions.simulator import Snapshot from qiskit.transpiler.passes import Unroller from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.quantum_info import Operator from qiskit.test import QiskitTestCase from qiskit.exceptions import QiskitError from qiskit.circuit import Parameter, Qubit, Clbit from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate from qiskit.transpiler.target import Target class TestUnroller(QiskitTestCase): """Tests the Unroller pass.""" def test_basic_unroll(self): """Test decompose a single H into u2.""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) dag = circuit_to_dag(circuit) pass_ = Unroller(["u2"]) unrolled_dag = pass_.run(dag) op_nodes = unrolled_dag.op_nodes() self.assertEqual(len(op_nodes), 1) self.assertEqual(op_nodes[0].name, "u2") def test_basic_unroll_target(self): """Test decompose a single H into U2 from target.""" qc = QuantumCircuit(1) qc.h(0) target = Target(num_qubits=1) phi = Parameter("phi") lam = Parameter("lam") target.add_instruction(U2Gate(phi, lam)) dag = circuit_to_dag(qc) pass_ = Unroller(target=target) unrolled_dag = pass_.run(dag) op_nodes = unrolled_dag.op_nodes() self.assertEqual(len(op_nodes), 1) self.assertEqual(op_nodes[0].name, "u2") def test_unroll_toffoli(self): """Test unroll toffoli on multi regs to h, t, tdg, cx.""" qr1 = QuantumRegister(2, "qr1") qr2 = QuantumRegister(1, "qr2") circuit = QuantumCircuit(qr1, qr2) circuit.ccx(qr1[0], qr1[1], qr2[0]) dag = circuit_to_dag(circuit) pass_ = Unroller(["h", "t", "tdg", "cx"]) unrolled_dag = pass_.run(dag) op_nodes = unrolled_dag.op_nodes() self.assertEqual(len(op_nodes), 15) for node in op_nodes: self.assertIn(node.name, ["h", "t", "tdg", "cx"]) def test_unroll_1q_chain_conditional(self): """Test unroll chain of 1-qubit gates interrupted by conditional.""" qr = QuantumRegister(1, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr) circuit.tdg(qr) circuit.z(qr) circuit.t(qr) circuit.ry(0.5, qr) circuit.rz(0.3, qr) circuit.rx(0.1, qr) circuit.measure(qr, cr) circuit.x(qr).c_if(cr, 1) circuit.y(qr).c_if(cr, 1) circuit.z(qr).c_if(cr, 1) dag = circuit_to_dag(circuit) pass_ = Unroller(["u1", "u2", "u3"]) unrolled_dag = pass_.run(dag) # Pick up -1 * 0.3 / 2 global phase for one RZ -> U1. ref_circuit = QuantumCircuit(qr, cr, global_phase=-0.3 / 2) ref_circuit.append(U2Gate(0, pi), [qr[0]]) ref_circuit.append(U1Gate(-pi / 4), [qr[0]]) ref_circuit.append(U1Gate(pi), [qr[0]]) ref_circuit.append(U1Gate(pi / 4), [qr[0]]) ref_circuit.append(U3Gate(0.5, 0, 0), [qr[0]]) ref_circuit.append(U1Gate(0.3), [qr[0]]) ref_circuit.append(U3Gate(0.1, -pi / 2, pi / 2), [qr[0]]) ref_circuit.measure(qr[0], cr[0]) ref_circuit.append(U3Gate(pi, 0, pi), [qr[0]]).c_if(cr, 1) ref_circuit.append(U3Gate(pi, pi / 2, pi / 2), [qr[0]]).c_if(cr, 1) ref_circuit.append(U1Gate(pi), [qr[0]]).c_if(cr, 1) ref_dag = circuit_to_dag(ref_circuit) self.assertEqual(unrolled_dag, ref_dag) def test_unroll_no_basis(self): """Test when a given gate has no decompositions.""" qr = QuantumRegister(1, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr) dag = circuit_to_dag(circuit) pass_ = Unroller(basis=[]) with self.assertRaises(QiskitError): pass_.run(dag) def test_simple_unroll_parameterized_without_expressions(self): """Verify unrolling parameterized gates without expressions.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) theta = Parameter("theta") qc.rz(theta, qr[0]) dag = circuit_to_dag(qc) unrolled_dag = Unroller(["u1", "u3", "cx"]).run(dag) expected = QuantumCircuit(qr, global_phase=-theta / 2) expected.append(U1Gate(theta), [qr[0]]) self.assertEqual(circuit_to_dag(expected), unrolled_dag) def test_simple_unroll_parameterized_with_expressions(self): """Verify unrolling parameterized gates with expressions.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) theta = Parameter("theta") phi = Parameter("phi") sum_ = theta + phi qc.rz(sum_, qr[0]) dag = circuit_to_dag(qc) unrolled_dag = Unroller(["u1", "u3", "cx"]).run(dag) expected = QuantumCircuit(qr, global_phase=-sum_ / 2) expected.append(U1Gate(sum_), [qr[0]]) self.assertEqual(circuit_to_dag(expected), unrolled_dag) def test_definition_unroll_parameterized(self): """Verify that unrolling complex gates with parameters does not raise.""" qr = QuantumRegister(2) qc = QuantumCircuit(qr) theta = Parameter("theta") qc.append(CU1Gate(theta), [qr[1], qr[0]]) qc.append(CU1Gate(theta * theta), [qr[0], qr[1]]) dag = circuit_to_dag(qc) out_dag = Unroller(["u1", "cx"]).run(dag) self.assertEqual(out_dag.count_ops(), {"u1": 6, "cx": 4}) def test_unrolling_parameterized_composite_gates(self): """Verify unrolling circuits with parameterized composite gates.""" qr1 = QuantumRegister(2) subqc = QuantumCircuit(qr1) theta = Parameter("theta") subqc.rz(theta, qr1[0]) subqc.cx(qr1[0], qr1[1]) subqc.rz(theta, qr1[1]) # Expanding across register with shared parameter qr2 = QuantumRegister(4) qc = QuantumCircuit(qr2) qc.append(subqc.to_instruction(), [qr2[0], qr2[1]]) qc.append(subqc.to_instruction(), [qr2[2], qr2[3]]) dag = circuit_to_dag(qc) out_dag = Unroller(["u1", "u3", "cx"]).run(dag) # Pick up -1 * theta / 2 global phase four twice (once for each RZ -> P # in each of the two sub_instr instructions). expected = QuantumCircuit(qr2, global_phase=-1 * 4 * theta / 2.0) expected.append(U1Gate(theta), [qr2[0]]) expected.cx(qr2[0], qr2[1]) expected.append(U1Gate(theta), [qr2[1]]) expected.append(U1Gate(theta), [qr2[2]]) expected.cx(qr2[2], qr2[3]) expected.append(U1Gate(theta), [qr2[3]]) self.assertEqual(circuit_to_dag(expected), out_dag) # Expanding across register with shared parameter qc = QuantumCircuit(qr2) phi = Parameter("phi") gamma = Parameter("gamma") qc.append(subqc.to_instruction({theta: phi}), [qr2[0], qr2[1]]) qc.append(subqc.to_instruction({theta: gamma}), [qr2[2], qr2[3]]) dag = circuit_to_dag(qc) out_dag = Unroller(["u1", "u3", "cx"]).run(dag) expected = QuantumCircuit(qr2, global_phase=-1 * (2 * phi + 2 * gamma) / 2.0) expected.append(U1Gate(phi), [qr2[0]]) expected.cx(qr2[0], qr2[1]) expected.append(U1Gate(phi), [qr2[1]]) expected.append(U1Gate(gamma), [qr2[2]]) expected.cx(qr2[2], qr2[3]) expected.append(U1Gate(gamma), [qr2[3]]) self.assertEqual(circuit_to_dag(expected), out_dag) def test_unrolling_preserves_qregs_order(self): """Test unrolling a gate preseveres it's definition registers order""" qr = QuantumRegister(2, "qr1") qc = QuantumCircuit(qr) qc.cx(1, 0) gate = qc.to_gate() qr2 = QuantumRegister(2, "qr2") qc2 = QuantumCircuit(qr2) qc2.append(gate, qr2) dag = circuit_to_dag(qc2) out_dag = Unroller(["cx"]).run(dag) expected = QuantumCircuit(qr2) expected.cx(1, 0) self.assertEqual(circuit_to_dag(expected), out_dag) def test_unrolling_nested_gates_preserves_qregs_order(self): """Test unrolling a nested gate preseveres it's definition registers order.""" qr = QuantumRegister(2, "qr1") qc = QuantumCircuit(qr) qc.cx(1, 0) gate_level_1 = qc.to_gate() qr2 = QuantumRegister(2, "qr2") qc2 = QuantumCircuit(qr2) qc2.append(gate_level_1, [1, 0]) qc2.cp(pi, 1, 0) gate_level_2 = qc2.to_gate() qr3 = QuantumRegister(2, "qr3") qc3 = QuantumCircuit(qr3) qc3.append(gate_level_2, [1, 0]) qc3.cu(pi, pi, pi, 0, 1, 0) gate_level_3 = qc3.to_gate() qr4 = QuantumRegister(2, "qr4") qc4 = QuantumCircuit(qr4) qc4.append(gate_level_3, [0, 1]) dag = circuit_to_dag(qc4) out_dag = Unroller(["cx", "cp", "cu"]).run(dag) expected = QuantumCircuit(qr4) expected.cx(1, 0) expected.cp(pi, 0, 1) expected.cu(pi, pi, pi, 0, 1, 0) self.assertEqual(circuit_to_dag(expected), out_dag) def test_unrolling_global_phase_1q(self): """Test unrolling a circuit with global phase in a composite gate.""" circ = QuantumCircuit(1, global_phase=pi / 2) circ.x(0) circ.h(0) v = circ.to_gate() qc = QuantumCircuit(1) qc.append(v, [0]) dag = circuit_to_dag(qc) out_dag = Unroller(["cx", "x", "h"]).run(dag) qcd = dag_to_circuit(out_dag) self.assertEqual(Operator(qc), Operator(qcd)) def test_unrolling_global_phase_nested_gates(self): """Test unrolling a nested gate preseveres global phase.""" qc = QuantumCircuit(1, global_phase=pi) qc.x(0) gate = qc.to_gate() qc = QuantumCircuit(1) qc.append(gate, [0]) gate = qc.to_gate() qc = QuantumCircuit(1) qc.append(gate, [0]) dag = circuit_to_dag(qc) out_dag = Unroller(["x", "u"]).run(dag) qcd = dag_to_circuit(out_dag) self.assertEqual(Operator(qc), Operator(qcd)) def test_if_simple(self): """Test a simple if statement unrolls correctly.""" qubits = [Qubit(), Qubit()] clbits = [Clbit(), Clbit()] qc = QuantumCircuit(qubits, clbits) qc.h(0) qc.measure(0, 0) with qc.if_test((clbits[0], 0)): qc.x(0) qc.h(0) qc.measure(0, 1) with qc.if_test((clbits[1], 0)): qc.h(1) qc.cx(1, 0) dag = circuit_to_dag(qc) unrolled_dag = Unroller(["u", "cx"]).run(dag) expected = QuantumCircuit(qubits, clbits) expected.u(pi / 2, 0, pi, 0) expected.measure(0, 0) with expected.if_test((clbits[0], 0)): expected.u(pi, 0, pi, 0) expected.u(pi / 2, 0, pi, 0) expected.measure(0, 1) with expected.if_test((clbits[1], 0)): expected.u(pi / 2, 0, pi, 1) expected.cx(1, 0) expected_dag = circuit_to_dag(expected) self.assertEqual(unrolled_dag, expected_dag) def test_if_else_simple(self): """Test a simple if-else statement unrolls correctly.""" qubits = [Qubit(), Qubit()] clbits = [Clbit(), Clbit()] qc = QuantumCircuit(qubits, clbits) qc.h(0) qc.measure(0, 0) with qc.if_test((clbits[0], 0)) as else_: qc.x(0) with else_: qc.z(0) qc.h(0) qc.measure(0, 1) with qc.if_test((clbits[1], 0)) as else_: qc.h(1) qc.cx(1, 0) with else_: qc.h(0) qc.cx(0, 1) dag = circuit_to_dag(qc) unrolled_dag = Unroller(["u", "cx"]).run(dag) expected = QuantumCircuit(qubits, clbits) expected.u(pi / 2, 0, pi, 0) expected.measure(0, 0) with expected.if_test((clbits[0], 0)) as else_: expected.u(pi, 0, pi, 0) with else_: expected.u(0, 0, pi, 0) expected.u(pi / 2, 0, pi, 0) expected.measure(0, 1) with expected.if_test((clbits[1], 0)) as else_: expected.u(pi / 2, 0, pi, 1) expected.cx(1, 0) with else_: expected.u(pi / 2, 0, pi, 0) expected.cx(0, 1) expected_dag = circuit_to_dag(expected) self.assertEqual(unrolled_dag, expected_dag) def test_nested_control_flow(self): """Test unrolling nested control flow blocks.""" qr = QuantumRegister(2) cr1 = ClassicalRegister(1) cr2 = ClassicalRegister(1) cr3 = ClassicalRegister(1) qc = QuantumCircuit(qr, cr1, cr2, cr3) with qc.for_loop(range(3)): with qc.while_loop((cr1, 0)): qc.x(0) with qc.while_loop((cr2, 0)): qc.y(0) with qc.while_loop((cr3, 0)): qc.z(0) dag = circuit_to_dag(qc) unrolled_dag = Unroller(["u", "cx"]).run(dag) expected = QuantumCircuit(qr, cr1, cr2, cr3) with expected.for_loop(range(3)): with expected.while_loop((cr1, 0)): expected.u(pi, 0, pi, 0) with expected.while_loop((cr2, 0)): expected.u(pi, pi / 2, pi / 2, 0) with expected.while_loop((cr3, 0)): expected.u(0, 0, pi, 0) expected_dag = circuit_to_dag(expected) self.assertEqual(unrolled_dag, expected_dag) def test_parameterized_angle(self): """Test unrolling with parameterized angle""" qc = QuantumCircuit(1) index = Parameter("index") with qc.for_loop((0, 0.5 * pi), index) as param: qc.rx(param, 0) dag = circuit_to_dag(qc) unrolled_dag = Unroller(["u", "cx"]).run(dag) expected = QuantumCircuit(1) with expected.for_loop((0, 0.5 * pi), index) as param: expected.u(param, -pi / 2, pi / 2, 0) expected_dag = circuit_to_dag(expected) self.assertEqual(unrolled_dag, expected_dag) class TestUnrollAllInstructions(QiskitTestCase): """Test unrolling a circuit containing all standard instructions.""" def setUp(self): super().setUp() qr = self.qr = QuantumRegister(3, "qr") cr = self.cr = ClassicalRegister(3, "cr") self.circuit = QuantumCircuit(qr, cr) self.ref_circuit = QuantumCircuit(qr, cr) self.pass_ = Unroller(basis=["u3", "cx", "id"]) def compare_dags(self): """compare dags in class tests""" dag = circuit_to_dag(self.circuit) unrolled_dag = self.pass_.run(dag) ref_dag = circuit_to_dag(self.ref_circuit) self.assertEqual(unrolled_dag, ref_dag) def test_unroll_crx(self): """test unroll crx""" # qr_1: ─────■───── qr_1: ─────────────────■─────────────────────■───────────────────── # ┌────┴────┐ = ┌─────────────┐┌─┴─┐┌───────────────┐┌─┴─┐┌─────────────────┐ # qr_2: ┤ Rx(0.5) ├ qr_2: ┤ U3(0,0,π/2) ├┤ X ├┤ U3(-0.25,0,0) ├┤ X ├┤ U3(0.25,-π/2,0) ├ # └─────────┘ └─────────────┘└───┘└───────────────┘└───┘└─────────────────┘ self.circuit.crx(0.5, 1, 2) self.ref_circuit.append(U3Gate(0, 0, pi / 2), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(-0.25, 0, 0), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(0.25, -pi / 2, 0), [2]) self.compare_dags() def test_unroll_cry(self): """test unroll cry""" # qr_1: ─────■───── qr_1: ──────────────────■─────────────────────■── # ┌────┴────┐ = ┌──────────────┐┌─┴─┐┌───────────────┐┌─┴─┐ # qr_2: ┤ Ry(0.5) ├ qr_2: ┤ U3(0.25,0,0) ├┤ X ├┤ U3(-0.25,0,0) ├┤ X ├ # └─────────┘ └──────────────┘└───┘└───────────────┘└───┘ self.circuit.cry(0.5, 1, 2) self.ref_circuit.append(U3Gate(0.25, 0, 0), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(-0.25, 0, 0), [2]) self.ref_circuit.cx(1, 2) self.compare_dags() def test_unroll_ccx(self): """test unroll ccx""" # qr_0: ──■── qr_0: ──────────────────────────────────────■──────────────────────» # │ │ » # qr_1: ──■── = qr_1: ─────────────────■────────────────────┼───────────────────■──» # ┌─┴─┐ ┌─────────────┐┌─┴─┐┌──────────────┐┌─┴─┐┌─────────────┐┌─┴─┐» # qr_2: ┤ X ├ qr_2: ┤ U3(π/2,0,π) ├┤ X ├┤ U3(0,0,-π/4) ├┤ X ├┤ U3(0,0,π/4) ├┤ X ├» # └───┘ └─────────────┘└───┘└──────────────┘└───┘└─────────────┘└───┘» # « ┌─────────────┐ # «qr_0: ──────────────────■─────────■───────┤ U3(0,0,π/4) ├───■── # « ┌─────────────┐ │ ┌─┴─┐ ├─────────────┴┐┌─┴─┐ # «qr_1: ┤ U3(0,0,π/4) ├───┼───────┤ X ├─────┤ U3(0,0,-π/4) ├┤ X ├ # « ├─────────────┴┐┌─┴─┐┌────┴───┴────┐├─────────────┬┘└───┘ # «qr_2: ┤ U3(0,0,-π/4) ├┤ X ├┤ U3(0,0,π/4) ├┤ U3(π/2,0,π) ├────── # « └──────────────┘└───┘└─────────────┘└─────────────┘ self.circuit.ccx(0, 1, 2) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [2]) self.ref_circuit.cx(0, 2) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [1]) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [2]) self.ref_circuit.cx(0, 2) self.ref_circuit.cx(0, 1) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [0]) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [1]) self.ref_circuit.cx(0, 1) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2]) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2]) self.compare_dags() def test_unroll_ch(self): """test unroll ch""" # qr_0: ──■── qr_0: ───────────────────────────────────────────────■──────────────────» # ┌─┴─┐ = ┌─────────────┐┌─────────────┐┌─────────────┐┌─┴─┐┌──────────────┐» # qr_2: ┤ H ├ qr_2: ┤ U3(0,0,π/2) ├┤ U3(π/2,0,π) ├┤ U3(0,0,π/4) ├┤ X ├┤ U3(0,0,-π/4) ├» # └───┘ └─────────────┘└─────────────┘└─────────────┘└───┘└──────────────┘» # « # «qr_0: ─────────────────────────────── # « ┌─────────────┐┌──────────────┐ # «qr_2: ┤ U3(π/2,0,π) ├┤ U3(0,0,-π/2) ├ # « └─────────────┘└──────────────┘ self.circuit.ch(0, 2) self.ref_circuit.append(U3Gate(0, 0, pi / 2), [2]) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2]) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2]) self.ref_circuit.cx(0, 2) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [2]) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2]) self.ref_circuit.append(U3Gate(0, 0, -pi / 2), [2]) self.compare_dags() def test_unroll_crz(self): """test unroll crz""" # qr_1: ─────■───── qr_1: ──────────────────■─────────────────────■── # ┌────┴────┐ = ┌──────────────┐┌─┴─┐┌───────────────┐┌─┴─┐ # qr_2: ┤ Rz(0.5) ├ qr_2: ┤ U3(0,0,0.25) ├┤ X ├┤ U3(0,0,-0.25) ├┤ X ├ # └─────────┘ └──────────────┘└───┘└───────────────┘└───┘ self.circuit.crz(0.5, 1, 2) self.ref_circuit.append(U3Gate(0, 0, 0.25), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(0, 0, -0.25), [2]) self.ref_circuit.cx(1, 2) def test_unroll_cswap(self): """test unroll cswap""" # ┌───┐ » # qr_0: ─X─ qr_0: ┤ X ├─────────────────■────────────────────────────────────────■──» # │ └─┬─┘ │ │ » # qr_1: ─■─ = qr_1: ──┼───────────────────┼────────────────────■───────────────────┼──» # │ │ ┌─────────────┐┌─┴─┐┌──────────────┐┌─┴─┐┌─────────────┐┌─┴─┐» # qr_2: ─X─ qr_2: ──■──┤ U3(π/2,0,π) ├┤ X ├┤ U3(0,0,-π/4) ├┤ X ├┤ U3(0,0,π/4) ├┤ X ├» # └─────────────┘└───┘└──────────────┘└───┘└─────────────┘└───┘» # « ┌─────────────┐ ┌───┐ ┌──────────────┐┌───┐┌───┐ # «qr_0: ┤ U3(0,0,π/4) ├───────────┤ X ├─────┤ U3(0,0,-π/4) ├┤ X ├┤ X ├ # « └─────────────┘ └─┬─┘ ├─────────────┬┘└─┬─┘└─┬─┘ # «qr_1: ──────────────────■─────────■───────┤ U3(0,0,π/4) ├───■────┼── # « ┌──────────────┐┌─┴─┐┌─────────────┐├─────────────┤ │ # «qr_2: ┤ U3(0,0,-π/4) ├┤ X ├┤ U3(0,0,π/4) ├┤ U3(π/2,0,π) ├────────■── # « └──────────────┘└───┘└─────────────┘└─────────────┘ self.circuit.cswap(1, 0, 2) self.ref_circuit.cx(2, 0) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2]) self.ref_circuit.cx(0, 2) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2]) self.ref_circuit.cx(0, 2) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [0]) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.cx(1, 0) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [0]) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [1]) self.ref_circuit.cx(1, 0) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2]) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2]) self.ref_circuit.cx(2, 0) self.compare_dags() def test_unroll_cu1(self): """test unroll cu1""" # ┌──────────────┐ # qr_0: ─■──────── qr_0: ┤ U3(0,0,0.05) ├──■─────────────────────■────────────────── # │U1(0.1) = └──────────────┘┌─┴─┐┌───────────────┐┌─┴─┐┌──────────────┐ # qr_2: ─■──────── qr_2: ────────────────┤ X ├┤ U3(0,0,-0.05) ├┤ X ├┤ U3(0,0,0.05) ├ # └───┘└───────────────┘└───┘└──────────────┘ self.circuit.append(CU1Gate(0.1), [0, 2]) self.ref_circuit.append(U3Gate(0, 0, 0.05), [0]) self.ref_circuit.cx(0, 2) self.ref_circuit.append(U3Gate(0, 0, -0.05), [2]) self.ref_circuit.cx(0, 2) self.ref_circuit.append(U3Gate(0, 0, 0.05), [2]) self.compare_dags() def test_unroll_cu3(self): """test unroll cu3""" # ┌──────────────┐ # q_1: ────────■──────── q_1: ─┤ U3(0,0,0.05) ├──■────────────────────────■─────────────────── # ┌───────┴───────┐ = ┌┴──────────────┤┌─┴─┐┌──────────────────┐┌─┴─┐┌───────────────┐ # q_2: ┤ U3(0.2,0.1,0) ├ q_2: ┤ U3(0,0,-0.05) ├┤ X ├┤ U3(-0.1,0,-0.05) ├┤ X ├┤ U3(0.1,0.1,0) ├ # └───────────────┘ └───────────────┘└───┘└──────────────────┘└───┘└───────────────┘ self.circuit.append(CU3Gate(0.2, 0.1, 0.0), [1, 2]) self.ref_circuit.append(U3Gate(0, 0, 0.05), [1]) self.ref_circuit.append(U3Gate(0, 0, -0.05), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(-0.1, 0, -0.05), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(0.1, 0.1, 0), [2]) self.compare_dags() def test_unroll_cx(self): """test unroll cx""" self.circuit.cx(1, 0) self.ref_circuit.cx(1, 0) self.compare_dags() def test_unroll_cy(self): """test unroll cy""" # qr_1: ──■── qr_1: ──────────────────■───────────────── # ┌─┴─┐ = ┌──────────────┐┌─┴─┐┌─────────────┐ # qr_2: ┤ Y ├ qr_2: ┤ U3(0,0,-π/2) ├┤ X ├┤ U3(0,0,π/2) ├ # └───┘ └──────────────┘└───┘└─────────────┘ self.circuit.cy(1, 2) self.ref_circuit.append(U3Gate(0, 0, -pi / 2), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(0, 0, pi / 2), [2]) self.compare_dags() def test_unroll_cz(self): """test unroll cz""" # ┌─────────────┐┌───┐┌─────────────┐ # qr_0: ─■─ qr_0: ┤ U3(π/2,0,π) ├┤ X ├┤ U3(π/2,0,π) ├ # │ = └─────────────┘└─┬─┘└─────────────┘ # qr_2: ─■─ qr_2: ─────────────────■───────────────── self.circuit.cz(2, 0) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [0]) self.ref_circuit.cx(2, 0) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [0]) self.compare_dags() def test_unroll_h(self): """test unroll h""" self.circuit.h(1) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [1]) self.compare_dags() def test_unroll_i(self): """test unroll i""" self.circuit.i(0) self.ref_circuit.i(0) self.compare_dags() def test_unroll_rx(self): """test unroll rx""" self.circuit.rx(0.1, 0) self.ref_circuit.append(U3Gate(0.1, -pi / 2, pi / 2), [0]) self.compare_dags() def test_unroll_ry(self): """test unroll ry""" self.circuit.ry(0.2, 1) self.ref_circuit.append(U3Gate(0.2, 0, 0), [1]) self.compare_dags() def test_unroll_rz(self): """test unroll rz""" self.circuit.rz(0.3, 2) self.ref_circuit.global_phase = -1 * 0.3 / 2 self.ref_circuit.append(U3Gate(0, 0, 0.3), [2]) self.compare_dags() def test_unroll_rzz(self): """test unroll rzz""" # global phase: 5.9832 # ┌───┐┌─────────────┐┌───┐ # qr_0: ─■──────── qr_0: ┤ X ├┤ U3(0,0,0.6) ├┤ X ├ # │ZZ(0.6) = └─┬─┘└─────────────┘└─┬─┘ # qr_1: ─■──────── qr_1: ──■───────────────────■── self.circuit.rzz(0.6, 1, 0) self.ref_circuit.global_phase = -1 * 0.6 / 2 self.ref_circuit.cx(1, 0) self.ref_circuit.append(U3Gate(0, 0, 0.6), [0]) self.ref_circuit.cx(1, 0) self.compare_dags() def test_unroll_s(self): """test unroll s""" self.circuit.s(0) self.ref_circuit.append(U3Gate(0, 0, pi / 2), [0]) self.compare_dags() def test_unroll_sdg(self): """test unroll sdg""" self.circuit.sdg(1) self.ref_circuit.append(U3Gate(0, 0, -pi / 2), [1]) self.compare_dags() def test_unroll_swap(self): """test unroll swap""" # ┌───┐ # qr_1: ─X─ qr_1: ──■──┤ X ├──■── # │ = ┌─┴─┐└─┬─┘┌─┴─┐ # qr_2: ─X─ qr_2: ┤ X ├──■──┤ X ├ # └───┘ └───┘ self.circuit.swap(1, 2) self.ref_circuit.cx(1, 2) self.ref_circuit.cx(2, 1) self.ref_circuit.cx(1, 2) self.compare_dags() def test_unroll_t(self): """test unroll t""" self.circuit.t(2) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2]) self.compare_dags() def test_unroll_tdg(self): """test unroll tdg""" self.circuit.tdg(0) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [0]) self.compare_dags() def test_unroll_u1(self): """test unroll u1""" self.circuit.append(U1Gate(0.1), [1]) self.ref_circuit.append(U3Gate(0, 0, 0.1), [1]) self.compare_dags() def test_unroll_u2(self): """test unroll u2""" self.circuit.append(U2Gate(0.2, -0.1), [0]) self.ref_circuit.append(U3Gate(pi / 2, 0.2, -0.1), [0]) self.compare_dags() def test_unroll_u3(self): """test unroll u3""" self.circuit.append(U3Gate(0.3, 0.0, -0.1), [2]) self.ref_circuit.append(U3Gate(0.3, 0.0, -0.1), [2]) self.compare_dags() def test_unroll_x(self): """test unroll x""" self.circuit.x(2) self.ref_circuit.append(U3Gate(pi, 0, pi), [2]) self.compare_dags() def test_unroll_y(self): """test unroll y""" self.circuit.y(1) self.ref_circuit.append(U3Gate(pi, pi / 2, pi / 2), [1]) self.compare_dags() def test_unroll_z(self): """test unroll z""" self.circuit.z(0) self.ref_circuit.append(U3Gate(0, 0, pi), [0]) self.compare_dags() def test_unroll_snapshot(self): """test unroll snapshot""" num_qubits = self.circuit.num_qubits instr = Snapshot("0", num_qubits=num_qubits) self.circuit.append(instr, range(num_qubits)) self.ref_circuit.append(instr, range(num_qubits)) self.compare_dags() def test_unroll_measure(self): """test unroll measure""" self.circuit.measure(self.qr, self.cr) self.ref_circuit.measure(self.qr, self.cr) self.compare_dags()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can set a color for all the bars. from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_paulivec qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = Statevector(qc) plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import WeightedAdder, LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = (r - 0.5 * vol**2) * T + np.log(S) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2 / 2) variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=list(zip(low, high))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_T^1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_T^2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 3.5 # map strike price from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price = ( (strike_price - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = 2 * (2**num_uncertainty_qubits - 1) - mapped_strike_price basket_objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar = AncillaRegister(max(n_aux, basket_objective.num_ancillas), "work") # additional qubits objective_index = u.num_qubits basket_option = QuantumCircuit(qr_state, qr_obj, ar_sum, ar) basket_option.append(u, qr_state) basket_option.append(agg, qr_state[:] + ar_sum[:] + ar[:n_aux]) basket_option.append(basket_objective, ar_sum[:] + qr_obj[:] + ar[: basket_objective.num_ancillas]) print(basket_option.draw()) print("objective qubit index", objective_index) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = np.linspace(sum(low), sum(high)) y = np.maximum(0, x - strike_price) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Sum of Spot Prices ($S_T^1 + S_T^2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) exact_value = np.dot( u.probabilities[sum_values >= strike_price], sum_values[sum_values >= strike_price] - strike_price, ) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = basket_option.num_qubits - basket_option.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(basket_option, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) basket_option_measure = basket_option.measure_all(inplace=False) sampler = Sampler() job = sampler.run(basket_option_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = ( basket_objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=basket_option, objective_qubits=[objective_index], post_processing=basket_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value: \t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-dell-runtime
qiskit-community
from dell_runtime import DellRuntimeProvider import os provider = DellRuntimeProvider() provider.remote(os.getenv("SERVER_URL")) provider.runtime.programs() provider.runtime.pprint_programs() RUNTIME_PROGRAM = """ from qiskit.compiler import transpile, schedule def main( backend, user_messenger, circuits, **kwargs, ): user_messenger.publish({'results': 'intermittently'}) circuits = transpile( circuits, ) if not isinstance(circuits, list): circuits = [circuits] # Compute raw results result = backend.run(circuits, **kwargs).result() user_messenger.publish({'results': 'finally'}) user_messenger.publish(result.to_dict(), final=True) print("job complete successfully") """ RUNTIME_PROGRAM_METADATA = { "max_execution_time": 600, "description": "Qiskit test program" } program_id = provider.runtime.upload_program(RUNTIME_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA) proglist = provider.runtime.programs() proglist program_id provider.runtime.pprint_programs(refresh=True) from qiskit import QuantumCircuit, execute, transpile qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) program_inputs = { 'circuits': qc, } job = provider.runtime.run(program_id, options=None, inputs=program_inputs) result = job.result(timeout=120) job.status()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt import numpy as np from qiskit.circuit import ParameterVector from qiskit.circuit.library import TwoLocal from qiskit.quantum_info import Statevector from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.applications.estimation import EuropeanCallPricing from qiskit_finance.circuit.library import NormalDistribution # Set upper and lower data values bounds = np.array([0.0, 7.0]) # Set number of qubits used in the uncertainty model num_qubits = 3 # Load the trained circuit parameters g_params = [0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225] # Set an initial state for the generator circuit init_dist = NormalDistribution(num_qubits, mu=1.0, sigma=1.0, bounds=bounds) # construct the variational form var_form = TwoLocal(num_qubits, "ry", "cz", entanglement="circular", reps=1) # keep a list of the parameters so we can associate them to the list of numerical values # (otherwise we need a dictionary) theta = var_form.ordered_parameters # compose the generator circuit, this is the circuit loading the uncertainty model g_circuit = init_dist.compose(var_form) # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 2 # set the approximation scaling for the payoff function c_approx = 0.25 # Evaluate trained probability distribution values = [ bounds[0] + (bounds[1] - bounds[0]) * x / (2**num_qubits - 1) for x in range(2**num_qubits) ] uncertainty_model = g_circuit.assign_parameters(dict(zip(theta, g_params))) amplitudes = Statevector.from_instruction(uncertainty_model).data x = np.array(values) y = np.abs(amplitudes) ** 2 # Sample from target probability distribution N = 100000 log_normal = np.random.lognormal(mean=1, sigma=1, size=N) log_normal = np.round(log_normal) log_normal = log_normal[log_normal <= 7] log_normal_samples = [] for i in range(8): log_normal_samples += [np.sum(log_normal == i)] log_normal_samples = np.array(log_normal_samples / sum(log_normal_samples)) # Plot distributions plt.bar(x, y, width=0.2, label="trained distribution", color="royalblue") plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.grid() plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15) plt.ylabel("Probability ($\%$)", size=15) plt.plot( log_normal_samples, "-o", color="deepskyblue", label="target distribution", linewidth=4, markersize=12, ) plt.legend(loc="best") plt.show() # Evaluate payoff for different distributions payoff = np.array([0, 0, 0, 1, 2, 3, 4, 5]) ep = np.dot(log_normal_samples, payoff) print("Analytically calculated expected payoff w.r.t. the target distribution: %.4f" % ep) ep_trained = np.dot(y, payoff) print("Analytically calculated expected payoff w.r.t. the trained distribution: %.4f" % ep_trained) # Plot exact payoff function (evaluated on the grid of the trained uncertainty model) x = np.array(values) y_strike = np.maximum(0, x - strike_price) plt.plot(x, y_strike, "ro-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Spot Price", size=15) plt.ylabel("Payoff", size=15) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.show() # construct circuit for payoff function european_call_pricing = EuropeanCallPricing( num_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=bounds, uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % ep_trained) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/minnukota381/Quantum-Computing-Qiskit
minnukota381
import numpy as np a = np.array([2, 6]) b = np.array([3, 10]) print("Vectors :") print("a = ", a) print("\nb = ", b) print("\nInner product of vectors a and b =") print(np.inner(a, b)) print("---------------------------------------") x = np.array([[2, 3, 4], [3, 2, 9]]) y = np.array([[1, 5, 0], [5, 10, 3]]) print("\nMatrices :") print("x =", x) print("\ny =", y) print("\nInner product of matrices x and y =") print(np.inner(x, y))
https://github.com/martynscn/Masters-Thesis-on-Quantum-Cryptography
martynscn
# This code has been adapted and modified from IBM Qiskit 2021 and # uses the constant optimized modular exponentiation circuit for mod 15 as contained # in https://arxiv.org/abs/1202.6614. import numpy as np import math from decimal import * import matplotlib.pyplot as plt from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.visualization import plot_histogram from qiskit import Aer, transpile, assemble import pandas as pd from fractions import Fraction # # import math # from math import gcd # from numpy.random import randint # # # from decimal import * print("Imports Successful") from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" def my_mod(a,n): getcontext().prec = 27 return round((Decimal(a)/Decimal(n) - Decimal(a)//Decimal(n) ) * n) def constant_optimized_modular_exponentation_modulus15(a, power): if a not in [2,7,8,11,13]: raise ValueError("'a' must be 2,7,8,11 or 13") U = QuantumCircuit(4) for iteration in range(power): if a in [2,13]: U.swap(0,1) U.swap(1,2) U.swap(2,3) if a in [7,8]: U.swap(2,3) U.swap(1,2) U.swap(0,1) if a == 11: U.swap(1,3) U.swap(0,2) if a in [7,11,13]: for q in range(4): U.x(q) U = U.to_gate() U.name = "%i^%i mod 15" % (a, power) control_U = U.control() return control_U def inverse_qft(n): circuit = QuantumCircuit(n) for i in range(n//2): circuit.swap(i, n-1-i) for j in range(n): for m in range(j): circuit.cp(-np.pi/float(2**(j-m)), m, j) circuit.h(j) circuit.name = "QFT†" return circuit N = 15 a = 7 n_count = 8 counting_register = QuantumRegister(size = n_count, name = "counting_register") acting_register = QuantumRegister(size = 4, name="acting_register") classic_register = ClassicalRegister(size = n_count, name="classic_register") qc = QuantumCircuit(counting_register, acting_register ,classic_register) initial_state = [1,0] for q in range(8): qc.initialize(initial_state, q) qc.draw(output = 'mpl', filename = "Step0") for q in range(n_count): qc.h(q) qc.draw(output = 'mpl', filename = "Step1") qc.x(3+n_count) qc.draw(output = 'mpl', filename = "Step1b") for q in range(n_count): qc.append(constant_optimized_modular_exponentation_modulus15(a, 2**q), [q] + [i+n_count for i in range(4)]) qc.measure(range(n_count,n_count + 4), range(4)) qc.barrier() qc.draw(output = 'mpl', filename = "Step2") qc.append(inverse_qft(n_count), range(n_count)) qc.draw(output = 'mpl', filename = "Step3") # Measure circuit qc.measure(range(n_count), range(n_count)) qc.draw(output = 'mpl', filename = "Step4") qasm_sim = Aer.get_backend('qasm_simulator') t_qc = transpile(qc, qasm_sim) qobj = assemble(t_qc) results = qasm_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) rows, measured_phases = [], [] for output in counts: decimal = int(output, 2) phase = decimal/(2**n_count) measured_phases.append(phase) rows.append([f"{output}(bin) = {decimal:>3}(dec)", f"{decimal}/{2**n_count} = {phase:.2f}"]) headers=["Register Output", "Phase"] df = pd.DataFrame(rows, columns=headers) df rows = [] for phase in measured_phases: frac = Fraction(phase).limit_denominator(15) rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator]) headers=["Phase", "Fraction", "Guess for r"] df = pd.DataFrame(rows, columns=headers) my_period_r = max(df["Guess for r"]) print("My period (r) is %i" % my_period_r) # Confirm that the period is 4 xvals = np.arange(N) xvals = [x.item() for x in xvals] yvals = [my_mod(a**x, N) for x in xvals] fig, ax = plt.subplots(); ax.plot(xvals, yvals, linewidth=1, linestyle='dotted', marker='x'); ax.set(xlabel='$x$', ylabel='$%i^x$ mod $%i$' % (a, N), title="Example of Periodic Function in Shor's Algorithm"); try: r = yvals[1:].index(1) +1 plt.annotate(s = '', xy=(0,1), xytext=(r,1), arrowprops=dict(arrowstyle='<->')); plt.annotate(s = '$r=%i$' % r, xy=(r/3,1.5)); except ValueError: print('Could not find a period') first_shared_factor = math.gcd((7**(int(my_period_r/2)) + 1), 15) first_shared_factor second_shared_factor = math.gcd((7**(int(my_period_r/2)) - 1), 15) second_shared_factor %qiskit_copyright
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import numpy as np from qiskit import QuantumRegister, QuantumCircuit from qiskit.aqua.components.variational_forms import VariationalForm class RY(VariationalForm): """Layers of Y rotations followed by entangling gates.""" CONFIGURATION = { 'name': 'RY', 'description': 'RY Variational Form', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'ry_schema', 'type': 'object', 'properties': { 'depth': { 'type': 'integer', 'default': 3, 'minimum': 0 }, 'entanglement': { 'type': 'string', 'default': 'full', 'oneOf': [ {'enum': ['full', 'linear']} ] }, 'entangler_map': { 'type': ['array', 'null'], 'default': None }, 'entanglement_gate': { 'type': 'string', 'default': 'cz', 'oneOf': [ {'enum': ['cz', 'cx']} ] }, 'skip_unentangled_qubits': { 'type': 'boolean', 'default': False } }, 'additionalProperties': False }, 'depends': [ { 'pluggable_type': 'initial_state', 'default': { 'name': 'ZERO', } }, ], } def __init__(self, num_qubits, depth=3, entangler_map=None, entanglement='full', initial_state=None, entanglement_gate='cz', skip_unentangled_qubits=False): """Constructor. Args: num_qubits (int) : number of qubits depth (int) : number of rotation layers entangler_map (list[list]): describe the connectivity of qubits, each list describes [source, target], or None for full entanglement. Note that the order is the list is the order of applying the two-qubit gate. entanglement (str): 'full' or 'linear' initial_state (InitialState): an initial state object entanglement_gate (str): cz or cx skip_unentangled_qubits (bool): skip the qubits not in the entangler_map """ self.validate(locals()) super().__init__() self._num_qubits = num_qubits self._depth = depth if entangler_map is None: self._entangler_map = VariationalForm.get_entangler_map(entanglement, num_qubits) else: self._entangler_map = VariationalForm.validate_entangler_map(entangler_map, num_qubits) # determine the entangled qubits all_qubits = [] for src, targ in self._entangler_map: all_qubits.extend([src, targ]) self._entangled_qubits = sorted(list(set(all_qubits))) self._initial_state = initial_state self._entanglement_gate = entanglement_gate self._skip_unentangled_qubits = skip_unentangled_qubits # for the first layer self._num_parameters = len(self._entangled_qubits) if self._skip_unentangled_qubits \ else self._num_qubits # for repeated block self._num_parameters += len(self._entangled_qubits) * depth self._bounds = [(-np.pi, np.pi)] * self._num_parameters def construct_circuit(self, parameters, q=None): """ Construct the variational form, given its parameters. Args: parameters (numpy.ndarray): circuit parameters. q (QuantumRegister): Quantum Register for the circuit. Returns: QuantumCircuit: a quantum circuit with given `parameters` Raises: ValueError: the number of parameters is incorrect. """ if len(parameters) != self._num_parameters: raise ValueError('The number of parameters has to be {}'.format(self._num_parameters)) if q is None: q = QuantumRegister(self._num_qubits, name='q') if self._initial_state is not None: circuit = self._initial_state.construct_circuit('circuit', q) else: circuit = QuantumCircuit(q) param_idx = 0 for qubit in range(self._num_qubits): if not self._skip_unentangled_qubits or qubit in self._entangled_qubits: circuit.u3(parameters[param_idx], 0.0, 0.0, q[qubit]) # ry param_idx += 1 for block in range(self._depth): circuit.barrier(q) for src, targ in self._entangler_map: if self._entanglement_gate == 'cz': circuit.u2(0.0, np.pi, q[targ]) # h circuit.cx(q[src], q[targ]) circuit.u2(0.0, np.pi, q[targ]) # h else: circuit.cx(q[src], q[targ]) circuit.barrier(q) for qubit in self._entangled_qubits: circuit.u3(parameters[param_idx], 0.0, 0.0, q[qubit]) # ry param_idx += 1 circuit.barrier(q) return circuit
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.735", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) problem = driver.run() print(problem) hamiltonian = problem.hamiltonian coefficients = hamiltonian.electronic_integrals print(coefficients.alpha) second_q_op = hamiltonian.second_q_op() print(second_q_op) hamiltonian.nuclear_repulsion_energy # NOT included in the second_q_op above problem.molecule problem.reference_energy problem.num_particles problem.num_spatial_orbitals problem.basis problem.properties problem.properties.particle_number problem.properties.angular_momentum problem.properties.magnetization problem.properties.electronic_dipole_moment from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms import GroundStateEigensolver from qiskit_nature.second_q.mappers import JordanWignerMapper solver = GroundStateEigensolver( JordanWignerMapper(), NumPyMinimumEigensolver(), ) result = solver.solve(problem) print(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the Check CNOT direction pass""" import unittest from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler.passes import CheckCXDirection from qiskit.transpiler import CouplingMap from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase class TestCheckCNotDirection(QiskitTestCase): """ Tests the CheckCXDirection pass with CX gates""" def test_trivial_map(self): """ Trivial map in a circuit without entanglement qr0:---[H]--- qr1:---[H]--- qr2:---[H]--- CouplingMap map: None """ qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.h(qr) coupling = CouplingMap() dag = circuit_to_dag(circuit) pass_ = CheckCXDirection(coupling) pass_.run(dag) self.assertTrue(pass_.property_set['is_direction_mapped']) def test_true_direction(self): """ Mapped is easy to check qr0:---.--[H]--.-- | | qr1:--(+)------|-- | qr2:----------(+)- CouplingMap map: [1]<-[0]->[2] """ qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.h(qr[0]) circuit.cx(qr[0], qr[2]) coupling = CouplingMap([[0, 1], [0, 2]]) dag = circuit_to_dag(circuit) pass_ = CheckCXDirection(coupling) pass_.run(dag) self.assertTrue(pass_.property_set['is_direction_mapped']) def test_true_direction_in_same_layer(self): """ Two CXs distance_qubits 1 to each other, in the same layer qr0:--(+)-- | qr1:---.--- qr2:--(+)-- | qr3:---.--- CouplingMap map: [0]->[1]->[2]->[3] """ qr = QuantumRegister(4, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[2], qr[3]) coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) dag = circuit_to_dag(circuit) pass_ = CheckCXDirection(coupling) pass_.run(dag) self.assertTrue(pass_.property_set['is_direction_mapped']) def test_wrongly_mapped(self): """ Needs [0]-[1] in a [0]--[2]--[1] qr0:--(+)-- | qr1:---.--- CouplingMap map: [0]->[2]->[1] """ qr = QuantumRegister(2, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) coupling = CouplingMap([[0, 2], [2, 1]]) dag = circuit_to_dag(circuit) pass_ = CheckCXDirection(coupling) pass_.run(dag) self.assertFalse(pass_.property_set['is_direction_mapped']) def test_true_direction_undirected(self): """ Mapped but with wrong direction qr0:--(+)-[H]--.-- | | qr1:---.-------|-- | qr2:----------(+)- CouplingMap map: [1]<-[0]->[2] """ qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.h(qr[0]) circuit.cx(qr[2], qr[0]) coupling = CouplingMap([[0, 1], [0, 2]]) dag = circuit_to_dag(circuit) pass_ = CheckCXDirection(coupling) pass_.run(dag) self.assertFalse(pass_.property_set['is_direction_mapped']) def test_false_direction_in_same_layer_undirected(self): """ Two CXs in the same layer, but one is wrongly directed qr0:--(+)-- | qr1:---.--- qr2:---.--- | qr3:--(+)-- CouplingMap map: [0]->[1]->[2]->[3] """ qr = QuantumRegister(4, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[3], qr[2]) coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) dag = circuit_to_dag(circuit) pass_ = CheckCXDirection(coupling) pass_.run(dag) self.assertFalse(pass_.property_set['is_direction_mapped']) class TestCheckCNotDirectionBarrier(QiskitTestCase): """ Tests the CheckCNotDirection pass with Swap gates""" def test_2q_barrier(self): """ A 2q barrier should be ignored qr0:--|-- | qr1:--|-- CouplingMap map: None """ qr = QuantumRegister(2, 'qr') circuit = QuantumCircuit(qr) circuit.barrier(qr[0], qr[1]) coupling = CouplingMap() dag = circuit_to_dag(circuit) pass_ = CheckCXDirection(coupling) pass_.run(dag) self.assertTrue(pass_.property_set['is_direction_mapped']) if __name__ == '__main__': unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.735", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) es_problem = driver.run() from qiskit_nature.second_q.mappers import JordanWignerMapper mapper = JordanWignerMapper() from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver numpy_solver = NumPyMinimumEigensolver() from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit_nature.second_q.circuit.library import HartreeFock, UCCSD ansatz = UCCSD( es_problem.num_spatial_orbitals, es_problem.num_particles, mapper, initial_state=HartreeFock( es_problem.num_spatial_orbitals, es_problem.num_particles, mapper, ), ) vqe_solver = VQE(Estimator(), ansatz, SLSQP()) vqe_solver.initial_point = [0.0] * ansatz.num_parameters from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.circuit.library import TwoLocal tl_circuit = TwoLocal( rotation_blocks=["h", "rx"], entanglement_blocks="cz", entanglement="full", reps=2, parameter_prefix="y", ) another_solver = VQE(Estimator(), tl_circuit, SLSQP()) from qiskit_nature.second_q.algorithms import GroundStateEigensolver calc = GroundStateEigensolver(mapper, vqe_solver) res = calc.solve(es_problem) print(res) calc = GroundStateEigensolver(mapper, numpy_solver) res = calc.solve(es_problem) print(res) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.drivers import GaussianForcesDriver from qiskit_nature.second_q.mappers import DirectMapper from qiskit_nature.second_q.problems import HarmonicBasis driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") basis = HarmonicBasis([2, 2, 2, 2]) vib_problem = driver.run(basis=basis) vib_problem.hamiltonian.truncation_order = 2 mapper = DirectMapper() solver_without_filter = NumPyMinimumEigensolver() solver_with_filter = NumPyMinimumEigensolver( filter_criterion=vib_problem.get_default_filter_criterion() ) gsc_wo = GroundStateEigensolver(mapper, solver_without_filter) result_wo = gsc_wo.solve(vib_problem) gsc_w = GroundStateEigensolver(mapper, solver_with_filter) result_w = gsc_w.solve(vib_problem) print(result_wo) print("\n\n") print(result_w) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/apozas/qaoa-color
apozas
from functools import reduce from itertools import product from qiskit import BasicAer, QuantumRegister, ClassicalRegister from qiskit_aqua import QuantumInstance from qiskit_aqua import Operator, run_algorithm from qiskit.quantum_info import Pauli from qiskit_aqua.components.optimizers import COBYLA from qiskit_aqua.algorithms import QAOA import numpy as np import qutip as qt from qiskit_aqua.components.initial_states import Custom edges = [(0, 1), (1, 2), (2, 3)] colors = 4 vertices = max(reduce(lambda x, y: x + y, [list(edge) for edge in edges])) + 1 logcolors = int(np.log2(colors)) n_qubits = int(vertices * logcolors) zr = np.zeros(n_qubits) ws = np.eye(n_qubits) up = qt.basis(2, 0) dn = qt.basis(2, 1) cost_operator = reduce( lambda x, y: x + y, [ Operator([[1, (Pauli(ws[logcolors*v1 + j, :], zr) *Pauli(ws[logcolors*v2 + j, :], zr))]]) for (v1, v2), j in product(edges, range(logcolors)) ] ) cobyla = COBYLA() cobyla.set_options(maxiter=250) p = 2 # steps of QAOA constrained = QAOA(cost_operator, cobyla, p) backend = BasicAer.get_backend('statevector_simulator') seed = 50 constrained.random_seed = seed quantum_instance = QuantumInstance(backend=backend, seed=seed, seed_mapper=seed) result = constrained.run(quantum_instance) result['eigvals'] result['opt_params'] result['eigvecs']
https://github.com/we-taper/qiskit-pyzx
we-taper
import qiskit %matplotlib inline qiskit.__qiskit_version__ import math len = 3 q_r = qiskit.QuantumRegister(len, 'q') c_r = qiskit.ClassicalRegister(len, 'c') q_c = qiskit.QuantumCircuit(q_r, c_r) q_c.u3(-1.23096,0,0, q_r[0]); q_c.u3(math.pi/4,0,0, q_r[1]); q_c.cx(q_r[0],q_r[2]); q_c.z(q_r[2]); q_c.h(q_r[2]); q_c.cx(q_r[1],q_r[2]); q_c.z(q_r[2]); q_c.u3(math.pi/4,0,0, q_r[1]); q_c.h(q_r[2]); q_c.cx(q_r[1],q_r[2]); #q_c.barrier() q_c.measure(q_r,c_r) q_c.draw(output='latex', line_length=300, scale=0.5) sim = qiskit.BasicAer.get_backend('qasm_simulator') job = qiskit.execute(q_c, backend = sim, shots = 1000) res = job.result().get_counts() print(res) qiskit.visualization.plot_histogram(res) print(q_c.qasm())
https://github.com/weiT1993/qiskit_helper_functions
weiT1993
import sys from qiskit import Aer, execute from quantum_circuit_generator.generators import gen_hwea n = 6 circ = gen_hwea(n, 1) print(circ) simulator = Aer.get_backend("statevector_simulator") result = execute(circ, simulator).result() sv = result.get_statevector(circ) print(sv) # entanglement measure def sgn_star(n, i): if n == 2: return 1 i_binary = "{:b}".format(i) Ni = 0 for char in i_binary: if char == "1": Ni += 1 if i >= 0 and i <= 2 ** (n - 3) - 1: return (-1) ** Ni elif i >= 2 ** (n - 3) and i <= 2 ** (n - 2) - 1: return (-1) ** (n + Ni) else: print("i out of range for sgn*") sys.exit(2) def tau(a, n): istar = 0 for i in range(0, 2 ** (n - 2)): istar_term = sgn_star(n, i) * ( a[2 * i] * a[(2**n - 1) - 2 * i] - a[2 * i + 1] * a[(2**n - 2) - 2 * i] ) istar += istar_term return 2 * abs(istar) print(tau(sv, n))
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
import sys import os current_dir = os.getcwd() sys.path.append(current_dir) from quantum_circuit import QuantumCircuit # import qiskit.providers.fake_provider from qiskit.transpiler import CouplingMap import qiskit_ibm_runtime.fake_provider from Backend.backend import Backend class FakeBackend(Backend): def __init__(self, backend_name : str) -> None: self.backend = FakeBackend.get_ibm_fake_backend(backend_name=backend_name) @staticmethod def get_ibm_fake_backend_name_list() -> list[str]: ibm_dir = dir(qiskit_ibm_runtime.fake_provider) return [val for val in ibm_dir if '__' not in val and 'Fake' in val] @staticmethod def get_ibm_fake_backend(backend_name : str): try: return getattr(qiskit_ibm_runtime.fake_provider, backend_name)() except: pass fake_backend_name = FakeBackend.get_ibm_fake_backend_name_list() for backend in fake_backend_name: backend = FakeBackend.get_ibm_fake_backend(backend) if backend is not None: try: if backend.name == backend_name: return backend except: pass return None @staticmethod def get_ibm_fake_backend_names_with_limit(min_qubit : int = 1, max_qubit: int = float('inf')) -> list[str]: limited_backend = [] fake_backend_name = FakeBackend.get_ibm_fake_backend_name_list() for backend in fake_backend_name: backend = FakeBackend.get_ibm_fake_backend(backend) if backend is not None: try: num_qubit = backend.num_qubits if num_qubit >= min_qubit and num_qubit <= max_qubit: limited_backend.append(backend.name) except: pass return limited_backend if __name__ == "__main__": print(FakeBackend.get_ibm_fake_backend_name_list()) backend = FakeBackend('fake_auckland') qc = QuantumCircuit(2) qc.x(0) qc.h(1) qc.measure_all() print(qc.draw()) job = backend.run(qc) print(job.result()) qc_transpile = backend.traspile_qiskit(qc)[0] print(qc_transpile.draw()) job = backend.run(qc_transpile) print(job.result())
https://github.com/JackHidary/quantumcomputingbook
JackHidary
# install cirq !pip install cirq==0.5 --quiet import cirq import numpy as np import sympy import matplotlib.pyplot as plt print(cirq.google.Bristlecone) a = cirq.NamedQubit("a") b = cirq.NamedQubit("b") gamma = 0.3 # Put your own value here. circuit = cirq.Circuit.from_ops(cirq.ZZ(a,b)**gamma) print(circuit) cirq.unitary(circuit).round(2) test_matrix = np.array([[np.exp(-1j*np.pi*gamma/2),0, 0, 0], [0, np.exp(1j*np.pi*gamma/2), 0, 0], [0, 0, np.exp(1j*np.pi*gamma/2), 0], [0, 0, 0,np.exp(-1j*np.pi*gamma/2)]]) cirq.testing.assert_allclose_up_to_global_phase(test_matrix, cirq.unitary(circuit), atol=1e-5) a = cirq.NamedQubit("a") gamma = 0.3 # Put your own value here. h = 1.3 # Put your own value here. circuit = cirq.Circuit.from_ops(cirq.Z(a)**(gamma*h)) print(circuit) print(cirq.unitary(circuit).round(2)) test_matrix = np.array([[np.exp(-1j*np.pi*gamma*h/2),0], [0, np.exp(1j*np.pi*gamma*h/2)]]) cirq.testing.assert_allclose_up_to_global_phase(test_matrix, cirq.unitary(circuit), atol=1e-5) n_cols = 3 n_rows = 3 h = 0.5*np.ones((n_rows,n_cols)) # Arranging the qubits in a list-of-lists like this makes them easy to refer to later. qubits = [[cirq.GridQubit(i,j) for j in range(n_cols)] for i in range(n_rows)] def beta_layer(beta): """Generator for U(beta, B) layer (mixing layer) of QAOA""" for row in qubits: for qubit in row: yield cirq.X(qubit)**beta def gamma_layer(gamma, h): """Generator for U(gamma, C) layer of QAOA Args: gamma: Float variational parameter for the circuit h: Array of floats of external magnetic field values """ for i in range(n_rows): for j in range(n_cols): if i < n_rows-1: yield cirq.ZZ(qubits[i][j], qubits[i+1][j])**gamma if j < n_cols-1: yield cirq.ZZ(qubits[i][j], qubits[i][j+1])**gamma yield cirq.Z(qubits[i][j])**(gamma*h[i,j]) qaoa = cirq.Circuit() qaoa.append(cirq.H.on_each(*[q for row in qubits for q in row])) # YOUR CODE HERE print(qaoa) qaoa = cirq.Circuit() gamma = sympy.Symbol('g') beta = sympy.Symbol('b') qaoa.append(cirq.H.on_each(*[q for row in qubits for q in row])) qaoa.append(gamma_layer(gamma,h)) qaoa.append(beta_layer(beta)) print(qaoa) def energy_from_wavefunction(wf, h): """Computes the energy-per-site of the Ising Model directly from the a given wavefunction. Args: wf: Array of size 2**(n_rows*n_cols) specifying the wavefunction. h: Array of shape (n_rows, n_cols) giving the magnetic field values. Returns: energy: Float equal to the expectation value of the energy per site """ n_sites = n_rows*n_cols # Z is an array of shape (n_sites, 2**n_sites). Each row consists of the # 2**n_sites non-zero entries in the operator that is the Pauli-Z matrix on # one of the qubits times the identites on the other qubits. The # (i*n_cols + j)th row corresponds to qubit (i,j). Z = np.array([(-1)**(np.arange(2**n_sites) >> i) for i in range(n_sites-1,-1,-1)]) # Create the operator corresponding to the interaction energy summed over all # nearest-neighbor pairs of qubits ZZ_filter = np.zeros_like(wf, dtype=float) for i in range(n_rows): for j in range(n_cols): if i < n_rows-1: ZZ_filter += Z[i*n_cols + j]*Z[(i+1)*n_cols + j] if j < n_cols-1: ZZ_filter += Z[i*n_cols + j]*Z[i*n_cols + (j+1)] energy_operator = -ZZ_filter - h.reshape(n_sites).dot(Z) # Expectation value of the energy divided by the number of sites return np.sum(np.abs(wf)**2 * energy_operator) / n_sites def energy_from_params(gamma, beta, qaoa, h): sim = cirq.Simulator() params = cirq.ParamResolver({'g':gamma, 'b':beta}) wf = sim.simulate(qaoa, param_resolver = params).final_state return energy_from_wavefunction(wf, h) %%time grid_size = 50 gamma_max = 2 beta_max = 2 energies = np.zeros((grid_size,grid_size)) for i in range(grid_size): for j in range(grid_size): energies[i,j] = energy_from_params(i*gamma_max/grid_size, j*beta_max/grid_size, qaoa, h) plt.ylabel('gamma') plt.xlabel('beta') plt.title('Energy as a Function of Parameters') plt.imshow(energies, extent = (0,beta_max,gamma_max,0)); def gradient_energy(gamma, beta, qaoa, h): """Uses a symmetric difference to calulate the gradient.""" eps = 10**-3 # Try different values of the discretization parameter # Gamma-component of the gradient grad_g = energy_from_params(gamma + eps, beta, qaoa, h) grad_g -= energy_from_params(gamma - eps, beta, qaoa, h) grad_g /= 2*eps # Beta-compoonent of the gradient grad_b = energy_from_params(gamma, beta + eps, qaoa, h) grad_b -= energy_from_params(gamma, beta - eps, qaoa, h) grad_b /= 2*eps return grad_g, grad_b gamma, beta = 0.2, 0.7 # Try different initializations eta = 10**-2 # Try adjusting the learning rate. for i in range(151): grad_g, grad_b = gradient_energy(gamma, beta, qaoa, h) gamma -= eta*grad_g beta -= eta*grad_b if not i%25: print('Step: {} Energy: {}'.format(i, energy_from_params(gamma, beta, qaoa, h))) print('Learned gamma: {} Learned beta: {}'.format(gamma, beta, qaoa, h)) measurement_circuit = qaoa.copy() measurement_circuit.append(cirq.measure(*[qubit for row in qubits for qubit in row],key='m')) measurement_circuit num_reps = 10**3 # Try different numbers of repetitions gamma, beta = 0.2,0.25 # Try different values of the parameters simulator = cirq.Simulator() params = cirq.ParamResolver({'g':gamma, 'b':beta}) result = simulator.run(measurement_circuit, param_resolver = params, repetitions=num_reps) def compute_energy(meas, h): Z_vals = 1-2*meas.reshape(n_rows,n_cols) energy = 0 for i in range(n_rows): for j in range(n_cols): if i < n_rows-1: energy -= Z_vals[i, j]*Z_vals[i+1, j] if j < n_cols-1: energy -= Z_vals[i, j]*Z_vals[i, j+1] energy -= h[i,j]*Z_vals[i,j] return energy/(n_rows*n_cols) hist = result.histogram(key='m') num = 10 probs = [v/result.repetitions for _,v in hist.most_common(num)] configs = [c for c,_ in hist.most_common(num)] plt.title('Probability of {} Most Common Outputs'.format(num)) plt.bar([x for x in range(len(probs))],probs) plt.show() meas = [[int(s) for s in ''.join([str(b) for b in bin(k)[2:]]).zfill(n_rows*n_cols)] for k in configs] costs = [compute_energy(np.array(m), h) for m in meas] plt.title('Energy of {} Most Common Outputs'.format(num)) plt.bar([x for x in range(len(costs))],costs) plt.show() print('Fraction of outputs displayed: {}'.format(np.sum(probs).round(2)))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import FakeVigo backend = FakeVigo() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) # Virtual -> physical # 0 -> 3 # 1 -> 4 # 2 -> 2 my_ghz = transpile(ghz, backend, initial_layout=[3, 4, 2]) plot_circuit_layout(my_ghz, backend)
https://github.com/QPower-Research/QPowerAlgo
QPower-Research
import numpy as np from numpy import pi # importing Qiskit from qiskit import QuantumCircuit, transpile, assemble, Aer from qiskit.visualization import plot_histogram, plot_bloch_multivector qc = QuantumCircuit(3) qc.h(2) qc.cp(pi/2, 1, 2) qc.cp(pi/4, 0, 2) qc.h(1) qc.cp(pi/2, 0, 1) qc.h(0) qc.swap(0, 2) qc.draw() def qft_rotations(circuit, n): if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) qft_rotations(circuit, n) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft(circuit, n): qft_rotations(circuit, n) swap_registers(circuit, n) return circuit qc = QuantumCircuit(4) qft(qc,4) qc.draw() # Create the circuit qc = QuantumCircuit(3) # Encode the state 5 (101 in binary) qc.x(0) qc.x(2) qc.draw() sim = Aer.get_backend("aer_simulator") qc_init = qc.copy() qc_init.save_statevector() statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) qft(qc, 3) qc.draw() qc.save_statevector() statevector = sim.run(qc).result().get_statevector() plot_bloch_multivector(statevector)
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Copyright Alpine Quantum Technologies GmbH 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # mypy: disable-error-code="no-untyped-def" """Quickstart example on using the Estimator primitive. This examples uses a variational quantum eigensolver (VQE) to find the ground state energy of a Hamiltonian. """ from collections.abc import Sequence from qiskit import QuantumCircuit from qiskit.circuit.library import TwoLocal from qiskit.primitives import BaseEstimator from qiskit.quantum_info import SparsePauliOp from qiskit.quantum_info.operators.base_operator import BaseOperator from scipy.optimize import minimize from qiskit_aqt_provider import AQTProvider from qiskit_aqt_provider.primitives import AQTEstimator # Select an execution backend provider = AQTProvider("ACCESS_TOKEN") backend = provider.get_backend("offline_simulator_no_noise") # Instantiate an estimator on the execution backend estimator = AQTEstimator(backend) # Set the transpiler's optimization level estimator.set_transpile_options(optimization_level=3) # Specify the problem Hamiltonian hamiltonian = SparsePauliOp.from_list( [ ("II", -1.052373245772859), ("IZ", 0.39793742484318045), ("ZI", -0.39793742484318045), ("ZZ", -0.01128010425623538), ("XX", 0.18093119978423156), ] ) # Define the VQE Ansatz, initial point, and cost function ansatz = TwoLocal(num_qubits=2, rotation_blocks="ry", entanglement_blocks="cz") initial_point = [0] * 8 def cost_function( params: Sequence[float], ansatz: QuantumCircuit, hamiltonian: BaseOperator, estimator: BaseEstimator, ) -> float: """Cost function for the VQE. Return the estimated expectation value of the Hamiltonian on the state prepared by the Ansatz circuit. """ return float(estimator.run(ansatz, hamiltonian, parameter_values=params).result().values[0]) # Run the VQE using the SciPy minimizer routine result = minimize( cost_function, initial_point, args=(ansatz, hamiltonian, estimator), method="cobyla" ) # Print the found minimum eigenvalue print(result.fun)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 12345 from qiskit_machine_learning.datasets import ad_hoc_data adhoc_dimension = 2 train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data( training_size=20, test_size=5, n=adhoc_dimension, gap=0.3, plot_data=False, one_hot=False, include_sample_total=True, ) import matplotlib.pyplot as plt import numpy as np def plot_features(ax, features, labels, class_label, marker, face, edge, label): # A train plot ax.scatter( # x coordinate of labels where class is class_label features[np.where(labels[:] == class_label), 0], # y coordinate of labels where class is class_label features[np.where(labels[:] == class_label), 1], marker=marker, facecolors=face, edgecolors=edge, label=label, ) def plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total): plt.figure(figsize=(5, 5)) plt.ylim(0, 2 * np.pi) plt.xlim(0, 2 * np.pi) plt.imshow( np.asmatrix(adhoc_total).T, interpolation="nearest", origin="lower", cmap="RdBu", extent=[0, 2 * np.pi, 0, 2 * np.pi], ) # A train plot plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "A train") # B train plot plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B train") # A test plot plot_features(plt, test_features, test_labels, 0, "s", "b", "w", "A test") # B test plot plot_features(plt, test_features, test_labels, 1, "o", "r", "w", "B test") plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0) plt.title("Ad hoc dataset") plt.show() plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total) from qiskit.circuit.library import ZZFeatureMap from qiskit.primitives import Sampler from qiskit.algorithms.state_fidelities import ComputeUncompute from qiskit_machine_learning.kernels import FidelityQuantumKernel adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear") sampler = Sampler() fidelity = ComputeUncompute(sampler=sampler) adhoc_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=adhoc_feature_map) from sklearn.svm import SVC adhoc_svc = SVC(kernel=adhoc_kernel.evaluate) adhoc_svc.fit(train_features, train_labels) adhoc_score_callable_function = adhoc_svc.score(test_features, test_labels) print(f"Callable kernel classification test score: {adhoc_score_callable_function}") adhoc_matrix_train = adhoc_kernel.evaluate(x_vec=train_features) adhoc_matrix_test = adhoc_kernel.evaluate(x_vec=test_features, y_vec=train_features) fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].imshow( np.asmatrix(adhoc_matrix_train), interpolation="nearest", origin="upper", cmap="Blues" ) axs[0].set_title("Ad hoc training kernel matrix") axs[1].imshow(np.asmatrix(adhoc_matrix_test), interpolation="nearest", origin="upper", cmap="Reds") axs[1].set_title("Ad hoc testing kernel matrix") plt.show() adhoc_svc = SVC(kernel="precomputed") adhoc_svc.fit(adhoc_matrix_train, train_labels) adhoc_score_precomputed_kernel = adhoc_svc.score(adhoc_matrix_test, test_labels) print(f"Precomputed kernel classification test score: {adhoc_score_precomputed_kernel}") from qiskit_machine_learning.algorithms import QSVC qsvc = QSVC(quantum_kernel=adhoc_kernel) qsvc.fit(train_features, train_labels) qsvc_score = qsvc.score(test_features, test_labels) print(f"QSVC classification test score: {qsvc_score}") print(f"Classification Model | Accuracy Score") print(f"---------------------------------------------------------") print(f"SVC using kernel as a callable function | {adhoc_score_callable_function:10.2f}") print(f"SVC using precomputed kernel matrix | {adhoc_score_precomputed_kernel:10.2f}") print(f"QSVC | {qsvc_score:10.2f}") adhoc_dimension = 2 train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data( training_size=25, test_size=0, n=adhoc_dimension, gap=0.6, plot_data=False, one_hot=False, include_sample_total=True, ) plt.figure(figsize=(5, 5)) plt.ylim(0, 2 * np.pi) plt.xlim(0, 2 * np.pi) plt.imshow( np.asmatrix(adhoc_total).T, interpolation="nearest", origin="lower", cmap="RdBu", extent=[0, 2 * np.pi, 0, 2 * np.pi], ) # A label plot plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "B") # B label plot plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B") plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0) plt.title("Ad hoc dataset for clustering") plt.show() adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear") adhoc_kernel = FidelityQuantumKernel(feature_map=adhoc_feature_map) adhoc_matrix = adhoc_kernel.evaluate(x_vec=train_features) plt.figure(figsize=(5, 5)) plt.imshow(np.asmatrix(adhoc_matrix), interpolation="nearest", origin="upper", cmap="Greens") plt.title("Ad hoc clustering kernel matrix") plt.show() from sklearn.cluster import SpectralClustering from sklearn.metrics import normalized_mutual_info_score adhoc_spectral = SpectralClustering(2, affinity="precomputed") cluster_labels = adhoc_spectral.fit_predict(adhoc_matrix) cluster_score = normalized_mutual_info_score(cluster_labels, train_labels) print(f"Clustering score: {cluster_score}") adhoc_dimension = 2 train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data( training_size=25, test_size=10, n=adhoc_dimension, gap=0.6, plot_data=False, one_hot=False, include_sample_total=True, ) plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total) feature_map = ZZFeatureMap(feature_dimension=2, reps=2, entanglement="linear") qpca_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=feature_map) matrix_train = qpca_kernel.evaluate(x_vec=train_features) matrix_test = qpca_kernel.evaluate(x_vec=test_features, y_vec=test_features) from sklearn.decomposition import KernelPCA kernel_pca_rbf = KernelPCA(n_components=2, kernel="rbf") kernel_pca_rbf.fit(train_features) train_features_rbf = kernel_pca_rbf.transform(train_features) test_features_rbf = kernel_pca_rbf.transform(test_features) kernel_pca_q = KernelPCA(n_components=2, kernel="precomputed") train_features_q = kernel_pca_q.fit_transform(matrix_train) test_features_q = kernel_pca_q.fit_transform(matrix_test) from sklearn.linear_model import LogisticRegression logistic_regression = LogisticRegression() logistic_regression.fit(train_features_q, train_labels) logistic_score = logistic_regression.score(test_features_q, test_labels) print(f"Logistic regression score: {logistic_score}") fig, (q_ax, rbf_ax) = plt.subplots(1, 2, figsize=(10, 5)) plot_features(q_ax, train_features_q, train_labels, 0, "s", "w", "b", "A train") plot_features(q_ax, train_features_q, train_labels, 1, "o", "w", "r", "B train") plot_features(q_ax, test_features_q, test_labels, 0, "s", "b", "w", "A test") plot_features(q_ax, test_features_q, test_labels, 1, "o", "r", "w", "A test") q_ax.set_ylabel("Principal component #1") q_ax.set_xlabel("Principal component #0") q_ax.set_title("Projection of training and test data\n using KPCA with Quantum Kernel") # Plotting the linear separation h = 0.01 # step size in the mesh # create a mesh to plot in x_min, x_max = train_features_q[:, 0].min() - 1, train_features_q[:, 0].max() + 1 y_min, y_max = train_features_q[:, 1].min() - 1, train_features_q[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) predictions = logistic_regression.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot predictions = predictions.reshape(xx.shape) q_ax.contourf(xx, yy, predictions, cmap=plt.cm.RdBu, alpha=0.2) plot_features(rbf_ax, train_features_rbf, train_labels, 0, "s", "w", "b", "A train") plot_features(rbf_ax, train_features_rbf, train_labels, 1, "o", "w", "r", "B train") plot_features(rbf_ax, test_features_rbf, test_labels, 0, "s", "b", "w", "A test") plot_features(rbf_ax, test_features_rbf, test_labels, 1, "o", "r", "w", "A test") rbf_ax.set_ylabel("Principal component #1") rbf_ax.set_xlabel("Principal component #0") rbf_ax.set_title("Projection of training data\n using KernelPCA") plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
mcoggins96
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute,IBMQ from qiskit.tools.monitor import job_monitor import numpy as np IBMQ.enable_account('ENTER API KEY HERE') provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_qasm_simulator') pi = np.pi q = QuantumRegister(1,'q') c = ClassicalRegister(1,'c') circuit = QuantumCircuit(q,c) circuit.ry(pi,q[0]) circuit.measure(q,c) print(circuit) job = execute(circuit, backend, shots=8192) job_monitor(job) counts = job.result().get_counts() print(counts)
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
PavanCyborg
#Assign these values as per your requirements. global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion min_qubits=2 max_qubits=3 skip_qubits=1 max_circuits=3 num_shots=1000 Noise_Inclusion = False saveplots = False Memory_utilization_plot = False gate_counts_plots = True Type_of_Simulator = "FAKEV2" #Inputs are "built_in" or "FAKE" or "FAKEV2" backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends #Change your Specification of Simulator in Declaring Backend Section #By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2() import numpy as np import copy # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error) from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute import time import matplotlib.pyplot as plt # Benchmark Name benchmark_name = "Amplitude Estimation" # Selection of basis gate set for transpilation # Note: selector 1 is a hardware agnostic gate set basis_selector = 1 basis_gates_array = [ [], ['rx', 'ry', 'rz', 'cx'], # a common basis set, default ['cx', 'rz', 'sx', 'x'], # IBM default basis set ['rx', 'ry', 'rxx'], # IonQ default basis set ['h', 'p', 'cx'], # another common basis set ['u', 'cx'] # general unitaries basis gates ] np.random.seed(0) num_gates = 0 depth = 0 def get_QV(backend): import json # Assuming backend.conf_filename is the filename and backend.dirname is the directory path conf_filename = backend.dirname + "/" + backend.conf_filename # Open the JSON file with open(conf_filename, 'r') as file: # Load the JSON data data = json.load(file) # Extract the quantum_volume parameter QV = data.get('quantum_volume', None) return QV def checkbackend(backend_name,Type_of_Simulator): if Type_of_Simulator == "built_in": available_backends = [] for i in Aer.backends(): available_backends.append(i.name) if backend_name in available_backends: platform = backend_name return platform else: print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!") print(f"available backends are : {available_backends}") platform = "qasm_simulator" return platform elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2": import qiskit.providers.fake_provider as fake_backends if hasattr(fake_backends,backend_name) is True: print(f"Backend {backend_name} is available for type {Type_of_Simulator}.") backend_class = getattr(fake_backends,backend_name) backend_instance = backend_class() return backend_instance else: print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!") if Type_of_Simulator == "FAKEV2": backend_class = getattr(fake_backends,"FakeSantiagoV2") else: backend_class = getattr(fake_backends,"FakeSantiago") backend_instance = backend_class() return backend_instance if Type_of_Simulator == "built_in": platform = checkbackend(backend_name,Type_of_Simulator) #By default using "Qasm Simulator" backend = Aer.get_backend(platform) QV_=None print(f"{platform} device is capable of running {backend.num_qubits}") print(f"backend version is {backend.backend_version}") elif Type_of_Simulator == "FAKE": basis_selector = 0 backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting. max_qubits=backend.configuration().n_qubits print(f"{platform} device is capable of running {backend.configuration().n_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") elif Type_of_Simulator == "FAKEV2": basis_selector = 0 if "V2" not in backend_name: backend_name = backend_name+"V2" backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.name +"-" +backend.backend_version max_qubits=backend.num_qubits print(f"{platform} device is capable of running {backend.num_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") else: print("Enter valid Simulator.....") # saved subcircuits circuits for printing A_ = None Q_ = None cQ_ = None QC_ = None QFTI_ = None ############### Circuit Definition def AmplitudeEstimation(num_state_qubits, num_counting_qubits, a, psi_zero=None, psi_one=None): num_qubits = num_state_qubits + 1 + num_counting_qubits qr_state = QuantumRegister(num_state_qubits+1) qr_counting = QuantumRegister(num_counting_qubits) cr = ClassicalRegister(num_counting_qubits) qc = QuantumCircuit(qr_counting, qr_state, cr, name=f"qae-{num_qubits}-{a}") # create the Amplitude Generator circuit A = A_gen(num_state_qubits, a, psi_zero, psi_one) # create the Quantum Operator circuit and a controlled version of it cQ, Q = Ctrl_Q(num_state_qubits, A) # save small example subcircuits for visualization global A_, Q_, cQ_, QFTI_ if (cQ_ and Q_) == None or num_state_qubits <= 6: if num_state_qubits < 9: cQ_ = cQ; Q_ = Q; A_ = A if QFTI_ == None or num_qubits <= 5: if num_qubits < 9: QFTI_ = inv_qft_gate(num_counting_qubits) # Prepare state from A, and counting qubits with H transform qc.append(A, [qr_state[i] for i in range(num_state_qubits+1)]) for i in range(num_counting_qubits): qc.h(qr_counting[i]) repeat = 1 for j in reversed(range(num_counting_qubits)): for _ in range(repeat): qc.append(cQ, [qr_counting[j]] + [qr_state[l] for l in range(num_state_qubits+1)]) repeat *= 2 qc.barrier() # inverse quantum Fourier transform only on counting qubits qc.append(inv_qft_gate(num_counting_qubits), qr_counting) qc.barrier() # measure counting qubits qc.measure([qr_counting[m] for m in range(num_counting_qubits)], list(range(num_counting_qubits))) # save smaller circuit example for display global QC_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc return qc # Construct A operator that takes |0>_{n+1} to sqrt(1-a) |psi_0>|0> + sqrt(a) |psi_1>|1> def A_gen(num_state_qubits, a, psi_zero=None, psi_one=None): if psi_zero==None: psi_zero = '0'*num_state_qubits if psi_one==None: psi_one = '1'*num_state_qubits theta = 2 * np.arcsin(np.sqrt(a)) # Let the objective be qubit index n; state is on qubits 0 through n-1 qc_A = QuantumCircuit(num_state_qubits+1, name=f"A") # takes state to |0>_{n} (sqrt(1-a) |0> + sqrt(a) |1>) qc_A.ry(theta, num_state_qubits) # takes state to sqrt(1-a) |psi_0>|0> + sqrt(a) |0>_{n}|1> qc_A.x(num_state_qubits) for i in range(num_state_qubits): if psi_zero[i]=='1': qc_A.cnot(num_state_qubits,i) qc_A.x(num_state_qubits) # takes state to sqrt(1-a) |psi_0>|0> + sqrt(a) |psi_1>|1> for i in range(num_state_qubits): if psi_one[i]=='1': qc_A.cnot(num_state_qubits,i) return qc_A # Construct the grover-like operator and a controlled version of it def Ctrl_Q(num_state_qubits, A_circ): # index n is the objective qubit, and indexes 0 through n-1 are state qubits qc = QuantumCircuit(num_state_qubits+1, name=f"Q") temp_A = copy.copy(A_circ) A_gate = temp_A.to_gate() A_gate_inv = temp_A.inverse().to_gate() ### Each cycle in Q applies in order: -S_chi, A_circ_inverse, S_0, A_circ # -S_chi qc.x(num_state_qubits) qc.z(num_state_qubits) qc.x(num_state_qubits) # A_circ_inverse qc.append(A_gate_inv, [i for i in range(num_state_qubits+1)]) # S_0 for i in range(num_state_qubits+1): qc.x(i) qc.h(num_state_qubits) qc.mcx([x for x in range(num_state_qubits)], num_state_qubits) qc.h(num_state_qubits) for i in range(num_state_qubits+1): qc.x(i) # A_circ qc.append(A_gate, [i for i in range(num_state_qubits+1)]) # Create a gate out of the Q operator qc.to_gate(label='Q') # and also a controlled version of it Ctrl_Q_ = qc.control(1) # and return both return Ctrl_Q_, qc ############### Inverse QFT Circuit def inv_qft_gate(input_size): global QFTI_, num_gates, depth qr = QuantumRegister(input_size); qc = QuantumCircuit(qr, name="inv_qft") # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in reversed(range(0, input_size)): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # precede with an H gate (applied to all qubits) qc.h(qr[hidx]) num_gates += 1 depth += 1 # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in reversed(range(0, num_crzs)): divisor = 2 ** (num_crzs - j) qc.crz( -math.pi / divisor , qr[hidx], qr[input_size - j - 1]) num_gates += 1 depth += 1 qc.barrier() if QFTI_ == None or input_size <= 5: if input_size < 9: QFTI_= qc return qc # Create an empty noise model noise_parameters = NoiseModel() if Type_of_Simulator == "built_in": # Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5% depol_one_qb_error = 0.05 depol_two_qb_error = 0.005 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx']) # Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0% amp_damp_one_qb_error = 0.0 amp_damp_two_qb_error = 0.0 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx']) # Add reset noise to all single qubit resets reset_to_zero_error = 0.005 reset_to_one_error = 0.005 noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"]) # Add readout error p0given1_error = 0.000 p1given0_error = 0.000 error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]]) noise_parameters.add_all_qubit_readout_error(error_meas) #print(noise_parameters) elif Type_of_Simulator == "FAKE"or"FAKEV2": noise_parameters = NoiseModel.from_backend(backend) #print(noise_parameters) ### Analysis methods to be expanded and eventually compiled into a separate analysis.py file import math, functools def hellinger_fidelity_with_expected(p, q): """ p: result distribution, may be passed as a counts distribution q: the expected distribution to be compared against References: `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ Qiskit Hellinger Fidelity Function """ p_sum = sum(p.values()) q_sum = sum(q.values()) if q_sum == 0: print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0") return 0 p_normed = {} for key, val in p.items(): p_normed[key] = val/p_sum # if p_sum != 0: # p_normed[key] = val/p_sum # else: # p_normed[key] = 0 q_normed = {} for key, val in q.items(): q_normed[key] = val/q_sum total = 0 for key, val in p_normed.items(): if key in q_normed.keys(): total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2 del q_normed[key] else: total += val total += sum(q_normed.values()) # in some situations (error mitigation) this can go negative, use abs value if total < 0: print(f"WARNING: using absolute value in fidelity calculation") total = abs(total) dist = np.sqrt(total)/np.sqrt(2) fidelity = (1-dist**2)**2 return fidelity def polarization_fidelity(counts, correct_dist, thermal_dist=None): """ Combines Hellinger fidelity and polarization rescaling into fidelity calculation used in every benchmark counts: the measurement outcomes after `num_shots` algorithm runs correct_dist: the distribution we expect to get for the algorithm running perfectly thermal_dist: optional distribution to pass in distribution from a uniform superposition over all states. If `None`: generated as `uniform_dist` with the same qubits as in `counts` returns both polarization fidelity and the hellinger fidelity Polarization from: `https://arxiv.org/abs/2008.11294v1` """ num_measured_qubits = len(list(correct_dist.keys())[0]) #print(num_measured_qubits) counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()} # calculate hellinger fidelity between measured expectation values and correct distribution hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist) # to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits if num_measured_qubits > 16: return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity } # if not provided, generate thermal dist based on number of qubits if thermal_dist == None: thermal_dist = uniform_dist(num_measured_qubits) # set our fidelity rescaling value as the hellinger fidelity for a depolarized state floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist) # rescale fidelity result so uniform superposition (random guessing) returns fidelity # rescaled to 0 to provide a better measure of success of the algorithm (polarization) new_floor_fidelity = 0 fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity) return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity } ## Uniform distribution function commonly used def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity): """ Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks fidelity: raw fidelity to rescale floor_fidelity: threshold fidelity which is equivalent to random guessing new_floor_fidelity: what we rescale the floor_fidelity to Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0: 1 -> 1; 0.25 -> 0; 0.5 -> 0.3333; """ rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1 # ensure fidelity is within bounds (0, 1) if rescaled_fidelity < 0: rescaled_fidelity = 0.0 if rescaled_fidelity > 1: rescaled_fidelity = 1.0 return rescaled_fidelity def uniform_dist(num_state_qubits): dist = {} for i in range(2**num_state_qubits): key = bin(i)[2:].zfill(num_state_qubits) dist[key] = 1/(2**num_state_qubits) return dist from matplotlib.patches import Rectangle import matplotlib.cm as cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize from matplotlib.patches import Circle ############### Color Map functions # Create a selection of colormaps from which to choose; default to custom_spectral cmap_spectral = plt.get_cmap('Spectral') cmap_greys = plt.get_cmap('Greys') cmap_blues = plt.get_cmap('Blues') cmap_custom_spectral = None # the default colormap is the spectral map cmap = cmap_spectral cmap_orig = cmap_spectral # current cmap normalization function (default None) cmap_norm = None default_fade_low_fidelity_level = 0.16 default_fade_rate = 0.7 # Specify a normalization function here (default None) def set_custom_cmap_norm(vmin, vmax): global cmap_norm if vmin == vmax or (vmin == 0.0 and vmax == 1.0): print("... setting cmap norm to None") cmap_norm = None else: print(f"... setting cmap norm to [{vmin}, {vmax}]") cmap_norm = Normalize(vmin=vmin, vmax=vmax) # Remake the custom spectral colormap with user settings def set_custom_cmap_style( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): #print("... set custom map style") global cmap, cmap_custom_spectral, cmap_orig cmap_custom_spectral = create_custom_spectral_cmap( fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate) cmap = cmap_custom_spectral cmap_orig = cmap_custom_spectral # Create the custom spectral colormap from the base spectral def create_custom_spectral_cmap( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): # determine the breakpoint from the fade level num_colors = 100 breakpoint = round(fade_low_fidelity_level * num_colors) # get color list for spectral map spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)] #print(fade_rate) # create a list of colors to replace those below the breakpoint # and fill with "faded" color entries (in reverse) low_colors = [0] * breakpoint #for i in reversed(range(breakpoint)): for i in range(breakpoint): # x is index of low colors, normalized 0 -> 1 x = i / breakpoint # get color at this index bc = spectral_colors[i] r0 = bc[0] g0 = bc[1] b0 = bc[2] z0 = bc[3] r_delta = 0.92 - r0 #print(f"{x} {bc} {r_delta}") # compute saturation and greyness ratio sat_ratio = 1 - x #grey_ratio = 1 - x ''' attempt at a reflective gradient if i >= breakpoint/2: xf = 2*(x - 0.5) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (yf + 0.5) else: xf = 2*(0.5 - x) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (0.5 - yf) ''' grey_ratio = 1 - math.pow(x, 1/fade_rate) #print(f" {xf} {yf} ") #print(f" {sat_ratio} {grey_ratio}") r = r0 + r_delta * sat_ratio g_delta = r - g0 b_delta = r - b0 g = g0 + g_delta * grey_ratio b = b0 + b_delta * grey_ratio #print(f"{r} {g} {b}\n") low_colors[i] = (r,g,b,z0) #print(low_colors) # combine the faded low colors with the regular spectral cmap to make a custom version cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:]) #spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)] #for i in range(10): print(spectral_colors[i]) #print("") return cmap_custom_spectral # Make the custom spectral color map the default on module init set_custom_cmap_style() # Arrange the stored annotations optimally and add to plot def anno_volumetric_data(ax, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True): # sort all arrays by the x point of the text (anno_offs) global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos)) x_anno_offs = [a for a,b,c,d,e in all_annos] y_anno_offs = [b for a,b,c,d,e in all_annos] anno_labels = [c for a,b,c,d,e in all_annos] x_annos = [d for a,b,c,d,e in all_annos] y_annos = [e for a,b,c,d,e in all_annos] #print(f"{x_anno_offs}") #print(f"{y_anno_offs}") #print(f"{anno_labels}") for i in range(len(anno_labels)): x_anno = x_annos[i] y_anno = y_annos[i] x_anno_off = x_anno_offs[i] y_anno_off = y_anno_offs[i] label = anno_labels[i] if i > 0: x_delta = abs(x_anno_off - x_anno_offs[i - 1]) y_delta = abs(y_anno_off - y_anno_offs[i - 1]) if y_delta < 0.7 and x_delta < 2: y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6 #x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1 ax.annotate(label, xy=(x_anno+0.0, y_anno+0.1), arrowprops=dict(facecolor='black', shrink=0.0, width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)), xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='baseline', color=(0.2,0.2,0.2), clip_on=True) if saveplots == True: plt.savefig("VolumetricPlotSample.jpg") # Plot one group of data for volumetric presentation def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True, x_size=1.0, y_size=1.0, zorder=1, offset_flag=False, max_depth=0, suppress_low_fidelity=False): # since data may come back out of order, save point at max y for annotation i_anno = 0 x_anno = 0 y_anno = 0 # plot data rectangles low_fidelity_count = True last_y = -1 k = 0 # determine y-axis dimension for one pixel to use for offset of bars that start at 0 (_, dy) = get_pixel_dims(ax) # do this loop in reverse to handle the case where earlier cells are overlapped by later cells for i in reversed(range(len(d_data))): x = depth_index(d_data[i], depth_base) y = float(w_data[i]) f = f_data[i] # each time we star a new row, reset the offset counter # DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars # that represent time starting from 0 secs. We offset by one pixel each and center the group if y != last_y: last_y = y; k = 3 # hardcoded for 8 cells, offset by 3 #print(f"{i = } {x = } {y = }") if max_depth > 0 and d_data[i] > max_depth: #print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}") break; # reject cells with low fidelity if suppress_low_fidelity and f < suppress_low_fidelity_level: if low_fidelity_count: break else: low_fidelity_count = True # the only time this is False is when doing merged gradation plots if do_border == True: # this case is for an array of x_sizes, i.e. each box has different width if isinstance(x_size, list): # draw each of the cells, with no offset if not offset_flag: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder)) # use an offset for y value, AND account for x and width to draw starting at 0 else: ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder)) # this case is for only a single cell else: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size)) # save the annotation point with the largest y value if y >= y_anno: x_anno = x y_anno = y i_anno = i # move the next bar down (if using offset) k -= 1 # if no data rectangles plotted, no need for a label if x_anno == 0 or y_anno == 0: return x_annos.append(x_anno) y_annos.append(y_anno) anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 ) # adjust radius of annotation circle based on maximum width of apps anno_max = 10 if w_max > 10: anno_max = 14 if w_max > 14: anno_max = 18 scale = anno_max / anno_dist # offset of text from end of arrow if scale > 1: x_anno_off = scale * x_anno - x_anno - 0.5 y_anno_off = scale * y_anno - y_anno else: x_anno_off = 0.7 y_anno_off = 0.5 x_anno_off += x_anno y_anno_off += y_anno # print(f"... {xx} {yy} {anno_dist}") x_anno_offs.append(x_anno_off) y_anno_offs.append(y_anno_off) anno_labels.append(label) if do_label: ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2)) x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # init arrays to hold annotation points for label spreading def vplot_anno_init (): global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # Number of ticks on volumetric depth axis max_depth_log = 22 # average transpile factor between base QV depth and our depth based on results from QV notebook QV_transpile_factor = 12.7 # format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1 # (sign handling may be incorrect) def format_number(num, digits=0): if isinstance(num, str): num = float(num) num = float('{:.3g}'.format(abs(num))) sign = '' metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1} for index in metric: num_check = num / metric[index] if num_check >= 1: num = round(num_check, digits) sign = index break numstr = f"{str(num)}" if '.' in numstr: numstr = numstr.rstrip('0').rstrip('.') return f"{numstr}{sign}" # Return the color associated with the spcific value, using color map norm def get_color(value): # if there is a normalize function installed, scale the data if cmap_norm: value = float(cmap_norm(value)) if cmap == cmap_spectral: value = 0.05 + value*0.9 elif cmap == cmap_blues: value = 0.00 + value*1.0 else: value = 0.0 + value*0.95 return cmap(value) # Return the x and y equivalent to a single pixel for the given plot axis def get_pixel_dims(ax): # transform 0 -> 1 to pixel dimensions pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0)) xpix = pixdims[1][0] ypix = pixdims[0][1] #determine x- and y-axis dimension for one pixel dx = (1 / xpix) dy = (1 / ypix) return (dx, dy) ############### Helper functions # return the base index for a circuit depth value # take the log in the depth base, and add 1 def depth_index(d, depth_base): if depth_base <= 1: return d if d == 0: return 0 return math.log(d, depth_base) + 1 # draw a box at x,y with various attributes def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1): value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.5*y_size, zorder=zorder) # draw a circle at x,y with various attributes def circle_at(x, y, value, type=1, fill=True): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Circle((x, y), size/2, alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell edgecolor = ec, facecolor = fc, fill=fill, lw=0.5) def box4_at(x, y, value, type=1, fill=True, alpha=1.0): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.3,0.3,0.3) ec = fc return Rectangle((x - size/8, y - size/2), size/4, size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.1) # Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value def qv_box_at(x, y, qv_width, qv_depth, value, depth_base): #print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}") return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width, edgecolor = (value,value,value), facecolor = (value,value,value), fill=True, lw=1) def bkg_box_at(x, y, value=0.9): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (value,value,value), fill=True, lw=0.5) def bkg_empty_box_at(x, y): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (1.0,1.0,1.0), fill=True, lw=0.5) # Plot the background for the volumetric analysis def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"): if suptitle == None: suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}" QV0 = QV qv_estimate = False est_str = "" if QV == 0: # QV = 0 indicates "do not draw QV background or label" QV = 2048 elif QV < 0: # QV < 0 indicates "add est. to label" QV = -QV qv_estimate = True est_str = " (est.)" if avail_qubits > 0 and max_qubits > avail_qubits: max_qubits = avail_qubits max_width = 13 if max_qubits > 11: max_width = 18 if max_qubits > 14: max_width = 20 if max_qubits > 16: max_width = 24 if max_qubits > 24: max_width = 33 #print(f"... {avail_qubits} {max_qubits} {max_width}") plot_width = 6.8 plot_height = 0.5 + plot_width * (max_width / max_depth_log) #print(f"... {plot_width} {plot_height}") # define matplotlib figure and axis; use constrained layout to fit colorbar to right fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True) plt.suptitle(suptitle) plt.xlim(0, max_depth_log) plt.ylim(0, max_width) # circuit depth axis (x axis) xbasis = [x for x in range(1,max_depth_log)] xround = [depth_base**(x-1) for x in xbasis] xlabels = [format_number(x) for x in xround] ax.set_xlabel('Circuit Depth') ax.set_xticks(xbasis) plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor") # other label options #plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left') #plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor") # circuit width axis (y axis) ybasis = [y for y in range(1,max_width)] yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now ylabels = [str(y) for y in yround] # not used now #ax.set_ylabel('Circuit Width (Number of Qubits)') ax.set_ylabel('Circuit Width') ax.set_yticks(ybasis) #create simple line plot (not used right now) #ax.plot([0, 10],[0, 10]) log2QV = math.log2(QV) QV_width = log2QV QV_depth = log2QV * QV_transpile_factor # show a quantum volume rectangle of QV = 64 e.g. (6 x 6) if QV0 != 0: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base)) else: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base)) # the untranspiled version is commented out - we do not show this by default # also show a quantum volume rectangle un-transpiled # ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base)) # show 2D array of volumetric cells based on this QV_transpiled # DEVNOTE: we use +1 only to make the visuals work; s/b without # Also, the second arg of the min( below seems incorrect, needs correction maxprod = (QV_width + 1) * (QV_depth + 1) for w in range(1, min(max_width, round(QV) + 1)): # don't show VB squares if width greater than known available qubits if avail_qubits != 0 and w > avail_qubits: continue i_success = 0 for d in xround: # polarization factor for low circuit widths maxtest = maxprod / ( 1 - 1 / (2**w) ) # if circuit would fail here, don't draw box if d > maxtest: continue if w * d > maxtest: continue # guess for how to capture how hardware decays with width, not entirely correct # # reduce maxtext by a factor of number of qubits > QV_width # # just an approximation to account for qubit distances # if w > QV_width: # over = w - QV_width # maxtest = maxtest / (1 + (over/QV_width)) # draw a box at this width and depth id = depth_index(d, depth_base) # show vb rectangles; if not showing QV, make all hollow (or less dark) if QV0 == 0: #ax.add_patch(bkg_empty_box_at(id, w)) ax.add_patch(bkg_box_at(id, w, 0.95)) else: ax.add_patch(bkg_box_at(id, w, 0.9)) # save index of last successful depth i_success += 1 # plot empty rectangle after others d = xround[i_success] id = depth_index(d, depth_base) ax.add_patch(bkg_empty_box_at(id, w)) # Add annotation showing quantum volume if QV0 != 0: t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12, horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2), bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1)) # add colorbar to right of plot plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax, shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7)) return ax # Function to calculate circuit depth def calculate_circuit_depth(qc): # Calculate the depth of the circuit depth = qc.depth() return depth def calculate_transpiled_depth(qc,basis_selector): # use either the backend or one of the basis gate sets if basis_selector == 0: qc = transpile(qc, backend) else: basis_gates = basis_gates_array[basis_selector] qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0) transpiled_depth = qc.depth() return transpiled_depth,qc def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title): avg_fidelity_means = [] avg_Hf_fidelity_means = [] avg_num_qubits_values = list(fidelity_data.keys()) # Calculate the average fidelity and Hamming fidelity for each unique number of qubits for num_qubits in avg_num_qubits_values: avg_fidelity = np.average(fidelity_data[num_qubits]) avg_fidelity_means.append(avg_fidelity) avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits]) avg_Hf_fidelity_means.append(avg_Hf_fidelity) return avg_fidelity_means,avg_Hf_fidelity_means list_of_gates = [] def list_of_standardgates(): import qiskit.circuit.library as lib from qiskit.circuit import Gate import inspect # List all the attributes of the library module gate_list = dir(lib) # Filter out non-gate classes (like functions, variables, etc.) gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)] # Get method names from QuantumCircuit circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction) method_names = [name for name, _ in circuit_methods] # Map gate class names to method names gate_to_method = {} for gate in gates: gate_class = getattr(lib, gate) class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name for method in method_names: if method == class_name or method == class_name.replace('cr', 'c-r'): gate_to_method[gate] = method break # Add common operations that are not strictly gates additional_operations = { 'Measure': 'measure', 'Barrier': 'barrier', } gate_to_method.update(additional_operations) for k,v in gate_to_method.items(): list_of_gates.append(v) def update_counts(gates,custom_gates): operations = {} for key, value in gates.items(): operations[key] = value for key, value in custom_gates.items(): if key in operations: operations[key] += value else: operations[key] = value return operations def get_gate_counts(gates,custom_gate_defs): result = gates.copy() # Iterate over the gate counts in the quantum circuit for gate, count in gates.items(): if gate in custom_gate_defs: custom_gate_ops = custom_gate_defs[gate] # Multiply custom gate operations by the count of the custom gate in the circuit for _ in range(count): result = update_counts(result, custom_gate_ops) # Remove the custom gate entry as we have expanded it del result[gate] return result dict_of_qc = dict() custom_gates_defs = dict() # Function to count operations recursively def count_operations(qc): dict_of_qc.clear() circuit_traverser(qc) operations = dict() operations = dict_of_qc[qc.name] del dict_of_qc[qc.name] # print("operations :",operations) # print("dict_of_qc :",dict_of_qc) for keys in operations.keys(): if keys not in list_of_gates: for k,v in dict_of_qc.items(): if k in operations.keys(): custom_gates_defs[k] = v operations=get_gate_counts(operations,custom_gates_defs) custom_gates_defs.clear() return operations def circuit_traverser(qc): dict_of_qc[qc.name]=dict(qc.count_ops()) for i in qc.data: if str(i.operation.name) not in list_of_gates: qc_1 = i.operation.definition circuit_traverser(qc_1) def get_memory(): import resource usage = resource.getrusage(resource.RUSAGE_SELF) max_mem = usage.ru_maxrss/1024 #in MB return max_mem def a_to_bitstring(a, num_counting_qubits): m = num_counting_qubits # solution 1 num1 = round(np.arcsin(np.sqrt(a)) / np.pi * 2**m) num2 = round( (np.pi - np.arcsin(np.sqrt(a))) / np.pi * 2**m) if num1 != num2 and num2 < 2**m and num1 < 2**m: counts = {format(num1, "0"+str(m)+"b"): 0.5, format(num2, "0"+str(m)+"b"): 0.5} else: counts = {format(num1, "0"+str(m)+"b"): 1} return counts def bitstring_to_a(counts, num_counting_qubits): est_counts = {} m = num_counting_qubits precision = int(num_counting_qubits / (np.log2(10))) + 2 for key in counts.keys(): r = counts[key] num = int(key,2) / (2**m) a_est = round((np.sin(np.pi * num) )** 2, precision) if a_est not in est_counts.keys(): est_counts[a_est] = 0 est_counts[a_est] += r return est_counts def a_from_s_int(s_int, num_counting_qubits): theta = s_int * np.pi / (2**num_counting_qubits) precision = int(num_counting_qubits / (np.log2(10))) + 2 a = round(np.sin(theta)**2, precision) return a def analyzer(s_int, num_counting_qubits,counts): secret_int = int(s_int) #print("secret_int = ",secret_int) # calculate expected output histogram a = a_from_s_int(s_int, num_counting_qubits) correct_dist = a_to_bitstring(a, num_counting_qubits) #print("correct_dist=",correct_dist) # generate thermal_dist for polarization calculation thermal_dist = uniform_dist(num_counting_qubits) #print("thermal_dist=",thermal_dist) # convert counts, expectation, and thermal_dist to app form for visibility # app form of correct distribution is measuring amplitude a 100% of the time # app_counts = bitstring_to_a(counts, num_counting_qubits) # app_correct_dist = correct_dist#{a: 1.0} # app_thermal_dist = bitstring_to_a(thermal_dist, num_counting_qubits) return correct_dist,thermal_dist num_state_qubits=1 #(default) not exposed to users def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, num_state_qubits=num_state_qubits): creation_times = [] elapsed_times = [] quantum_times = [] circuit_depths = [] transpiled_depths = [] fidelity_data = {} Hf_fidelity_data = {} numckts = [] mem_usage = [] algorithmic_1Q_gate_counts = [] algorithmic_2Q_gate_counts = [] transpiled_1Q_gate_counts = [] transpiled_2Q_gate_counts = [] print(f"{benchmark_name} Benchmark Program - {platform}") if gate_counts_plots == True: list_of_standardgates() # validate parameters (smallest circuit is 3 qubits) num_state_qubits = max(1, num_state_qubits) if max_qubits < num_state_qubits + 2: print(f"ERROR: AE Benchmark needs at least {num_state_qubits + 2} qubits to run") return min_qubits = max(max(3, min_qubits), num_state_qubits + 2) skip_qubits = max(1, skip_qubits) global qc_o global max_ckts max_ckts = max_circuits global min_qbits,max_qbits,skp_qubits min_qbits = min_qubits max_qbits = max_qubits skp_qubits = skip_qubits print(f"min, max qubits = {min_qubits} {max_qubits}") # Execute Benchmark Program N times for multiple circuit sizes for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): fidelity_data[num_qubits] = [] Hf_fidelity_data[num_qubits] = [] # reset random seed np.random.seed(0) # as circuit width grows, the number of counting qubits is increased num_counting_qubits = num_qubits - num_state_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2 ** (num_counting_qubits), max_circuits) print(f"Executing [{num_circuits}] circuits with num_qubits = {num_qubits}") numckts.append(num_circuits) # determine range of secret strings to loop over if 2**(num_counting_qubits) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(num_counting_qubits), num_circuits, False) for s_int in s_range: print("*********************************************") print(f"qc of {num_qubits} qubits for integer {s_int}") #creation of Quantum Circuit. ts = time.time() a_ = (a_from_s_int(s_int, num_counting_qubits)) qc = AmplitudeEstimation(num_state_qubits, num_counting_qubits, a_) #creation time creation_time = time.time() - ts creation_times.append(creation_time) #print(qc) print(f"creation time = {creation_time*1000} ms") # Calculate gate count for the algorithmic circuit (excluding barriers and measurements) if gate_counts_plots == True: operations = count_operations(qc) n1q = 0; n2q = 0 if operations != None: for key, value in operations.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c") or key.startswith("mc"): n2q += value else: n1q += value algorithmic_1Q_gate_counts.append(n1q) algorithmic_2Q_gate_counts.append(n2q) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc=qc.decompose().decompose().decompose() #print(qc) # Calculate circuit depth depth = calculate_circuit_depth(qc) circuit_depths.append(depth) # Calculate transpiled circuit depth transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector) transpiled_depths.append(transpiled_depth) #print(qc) print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}") if gate_counts_plots == True: # Calculate gate count for the transpiled circuit (excluding barriers and measurements) tr_ops = qc.count_ops() #print("tr_ops = ",tr_ops) tr_n1q = 0; tr_n2q = 0 if tr_ops != None: for key, value in tr_ops.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c"): tr_n2q += value else: tr_n1q += value transpiled_1Q_gate_counts.append(tr_n1q) transpiled_2Q_gate_counts.append(tr_n2q) print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}") print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}") #execution if Type_of_Simulator == "built_in": #To check if Noise is required if Noise_Inclusion == True: noise_model = noise_parameters else: noise_model = None ts = time.time() job = execute(qc, backend, shots=num_shots, noise_model=noise_model) elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" : ts = time.time() job = backend.run(qc,shots=num_shots, noise_model=noise_parameters) #retrieving the result result = job.result() #print(result) #calculating elapsed time elapsed_time = time.time() - ts elapsed_times.append(elapsed_time) # Calculate quantum processing time quantum_time = result.time_taken quantum_times.append(quantum_time) print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms") #counts in result object counts = result.get_counts() s_int = int(s_int) #Correct distribution to compare with counts correct_dist,thermal_dist = analyzer(s_int,num_counting_qubits,counts) #fidelity calculation comparision of counts and correct_dist fidelity_dict = polarization_fidelity(counts, correct_dist,thermal_dist) fidelity_data[num_qubits].append(fidelity_dict['fidelity']) Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity']) #maximum memory utilization (if required) if Memory_utilization_plot == True: max_mem = get_memory() print(f"Maximum Memory Utilized: {max_mem} MB") mem_usage.append(max_mem) print("*********************************************") ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nControlled Quantum Operator 'cQ' ="); print(cQ_ if cQ_ != None else " ... too large!") print("\nQuantum Operator 'Q' ="); print(Q_ if Q_ != None else " ... too large!") print("\nAmplitude Generator 'A' ="); print(A_ if A_ != None else " ... too large!") print("\nInverse QFT Circuit ="); print(QFTI_ if QC_ != None else " ... too large!") return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths, fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) # Execute the benchmark program, accumulate metrics, and calculate circuit depths (creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts, algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run() # Define the range of qubits for the x-axis num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits) print("num_qubits_range =",num_qubits_range) # Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits avg_creation_times = [] avg_elapsed_times = [] avg_quantum_times = [] avg_circuit_depths = [] avg_transpiled_depths = [] avg_1Q_algorithmic_gate_counts = [] avg_2Q_algorithmic_gate_counts = [] avg_1Q_Transpiled_gate_counts = [] avg_2Q_Transpiled_gate_counts = [] max_memory = [] start = 0 for num in numckts: avg_creation_times.append(np.mean(creation_times[start:start+num])) avg_elapsed_times.append(np.mean(elapsed_times[start:start+num])) avg_quantum_times.append(np.mean(quantum_times[start:start+num])) avg_circuit_depths.append(np.mean(circuit_depths[start:start+num])) avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num])) if gate_counts_plots == True: avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num]))) avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num]))) avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num]))) avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num]))) if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num])) start += num # Calculate the fidelity data avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison") # Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits # Add labels to the bars def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"): for rect in rects: height = rect.get_height() ax.annotate(str.format(height), # Formatting to two decimal places xy=(rect.get_x() + rect.get_width() / 2, height / 2), xytext=(0, 0), textcoords="offset points", ha='center', va=va,color=text_color,rotation=90) bar_width = 0.3 # Determine the number of subplots and their arrangement if Memory_utilization_plot and gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30)) # Plotting for both memory utilization and gate counts # ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available elif Memory_utilization_plot: fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30)) # Plotting for memory utilization only # ax1, ax2, ax3, ax6, ax7 are available elif gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30)) # Plotting for gate counts only # ax1, ax2, ax3, ax4, ax5, ax6 are available else: fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30)) # Default plotting # ax1, ax2, ax3, ax6 are available fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16) for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000 avg_creation_times[i] *= 1000 ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue') autolabel(ax1.patches, ax1) ax1.set_xlabel('Number of Qubits') ax1.set_ylabel('Average Creation Time (ms)') ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14) ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000 avg_elapsed_times[i] *= 1000 for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000 avg_quantum_times[i] *= 1000 Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time') Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time') autolabel(Elapsed,ax2,str='{:.1f}') autolabel(Quantum,ax2,str='{:.1f}') ax2.set_xlabel('Number of Qubits') ax2.set_ylabel('Average Time (ms)') ax2.set_title('Average Time vs Number of Qubits') ax2.legend() ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here autolabel(Normalized,ax3,str='{:.2f}') autolabel(Algorithmic,ax3,str='{:.2f}') ax3.set_xlabel('Number of Qubits') ax3.set_ylabel('Average Circuit Depth') ax3.set_title('Average Circuit Depth vs Number of Qubits') ax3.legend() if gate_counts_plots == True: ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_1Q_counts,ax4,str='{}') autolabel(Algorithmic_1Q_counts,ax4,str='{}') ax4.set_xlabel('Number of Qubits') ax4.set_ylabel('Average 1-Qubit Gate Counts') ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits') ax4.legend() ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_2Q_counts,ax5,str='{}') autolabel(Algorithmic_2Q_counts,ax5,str='{}') ax5.set_xlabel('Number of Qubits') ax5.set_ylabel('Average 2-Qubit Gate Counts') ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits') ax5.legend() ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here autolabel(Hellinger,ax6,str='{:.2f}') autolabel(Normalized,ax6,str='{:.2f}') ax6.set_xlabel('Number of Qubits') ax6.set_ylabel('Average Value') ax6.set_title("Fidelity Comparison") ax6.legend() if Memory_utilization_plot == True: ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations") autolabel(ax7.patches, ax7) ax7.set_xlabel('Number of Qubits') ax7.set_ylabel('Maximum Memory Utilized (MB)') ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14) plt.tight_layout(rect=[0, 0, 1, 0.96]) if saveplots == True: plt.savefig("ParameterPlotsSample.jpg") plt.show() # Quantum Volume Plot Suptitle = f"Volumetric Positioning - {platform}" appname=benchmark_name if QV_ == None: QV=2048 else: QV=QV_ depth_base =2 ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity") w_data = num_qubits_range # determine width for circuit w_max = 0 for i in range(len(w_data)): y = float(w_data[i]) w_max = max(w_max, y) d_tr_data = avg_transpiled_depths f_data = avg_f plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
https://github.com/quantum-melbourne/qiskit-challenge-22
quantum-melbourne
# General imports import os import gzip import numpy as np import matplotlib.pyplot as plt from pylab import cm import warnings warnings.filterwarnings("ignore") # scikit-learn imports from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.decomposition import PCA from sklearn.svm import SVC from sklearn.metrics import accuracy_score # Qiskit imports from qiskit import Aer, execute from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2 from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate from qiskit_machine_learning.kernels import QuantumKernel # Load MNIST dataset DATA_PATH = './resources/ch3_part1.npz' data = np.load(DATA_PATH) sample_train = data['sample_train'] labels_train = data['labels_train'] sample_test = data['sample_test'] # Split train data sample_train, sample_val, labels_train, labels_val = train_test_split( sample_train, labels_train, test_size=0.2, random_state=42) # Visualize samples fig = plt.figure() LABELS = [4, 9] num_labels = len(LABELS) for i in range(num_labels): ax = fig.add_subplot(1, num_labels, i+1) img = sample_train[labels_train==LABELS[i]][0].reshape((28, 28)) ax.imshow(img, cmap="Greys") # Standardize ss = StandardScaler() sample_train = ss.fit_transform(sample_train) sample_val = ss.transform(sample_val) sample_test = ss.transform(sample_test) # Reduce dimensions N_DIM = 5 pca = PCA(n_components=N_DIM) sample_train = pca.fit_transform(sample_train) sample_val = pca.transform(sample_val) sample_test = pca.transform(sample_test) # Normalize mms = MinMaxScaler((-1, 1)) sample_train = mms.fit_transform(sample_train) sample_val = mms.transform(sample_val) sample_test = mms.transform(sample_test) # 3 features, depth 2 map_z = ZFeatureMap(feature_dimension=3, reps=2) map_z.decompose().draw('mpl') # 3 features, depth 1, linear entanglement map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='linear') map_zz.decompose().draw('mpl') # 3 features, depth 1, circular entanglement map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='circular') map_zz.decompose().draw('mpl') # 3 features, depth 1 map_pauli = PauliFeatureMap(feature_dimension=3, reps=1, paulis = ['X', 'Y', 'ZZ']) map_pauli.decompose().draw('mpl') twolocal = TwoLocal(num_qubits=3, reps=2, rotation_blocks=['ry','rz'], entanglement_blocks='cx', entanglement='circular', insert_barriers=True) twolocal.decompose().draw('mpl') twolocaln = NLocal(num_qubits=3, reps=2, rotation_blocks=[RYGate(Parameter('a')), RZGate(Parameter('a'))], entanglement_blocks=CXGate(), entanglement='circular', insert_barriers=True) twolocaln.decompose().draw('mpl') print(f'First training data: {sample_train[0]}') encode_map = PauliFeatureMap(feature_dimension=N_DIM, reps=1, paulis = ['X', 'Y', 'ZZ']) encode_circuit = encode_map.bind_parameters(sample_train[0]) encode_circuit.decompose().draw(output='mpl') ############################## # Provide your code here ex3a_fmap = ZZFeatureMap(feature_dimension=5, reps=3, entanglement='circular') ############################## # Check your answer and submit using the following code from qc_grader import grade_ex3a grade_ex3a(ex3a_fmap) pauli_map = PauliFeatureMap(feature_dimension=N_DIM, reps=1, paulis = ['X', 'Y', 'ZZ']) pauli_kernel = QuantumKernel(feature_map=pauli_map, quantum_instance=Aer.get_backend('statevector_simulator')) print(f'First training data : {sample_train[0]}') print(f'Second training data: {sample_train[1]}') pauli_circuit = pauli_kernel.construct_circuit(sample_train[0], sample_train[1]) pauli_circuit.decompose().decompose().draw(output='mpl') backend = Aer.get_backend('qasm_simulator') job = execute(pauli_circuit, backend, shots=8192, seed_simulator=1024, seed_transpiler=1024) counts = job.result().get_counts(pauli_circuit) print(f"Transition amplitude: {counts['0'*N_DIM]/sum(counts.values())}") matrix_train = pauli_kernel.evaluate(x_vec=sample_train) matrix_val = pauli_kernel.evaluate(x_vec=sample_val, y_vec=sample_train) fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].imshow(np.asmatrix(matrix_train), interpolation='nearest', origin='upper', cmap='Blues') axs[0].set_title("training kernel matrix") axs[1].imshow(np.asmatrix(matrix_val), interpolation='nearest', origin='upper', cmap='Reds') axs[1].set_title("validation kernel matrix") plt.show() x = [-0.5, -0.4, 0.3, 0, -0.9] y = [0, -0.7, -0.3, 0, -0.4] ############################## # Provide your code here zz = ZZFeatureMap(feature_dimension=N_DIM, reps=3, entanglement='circular') zz_kernel = QuantumKernel(feature_map=zz, quantum_instance=Aer.get_backend('statevector_simulator')) zz_circuit = zz_kernel.construct_circuit(x, y) backend = Aer.get_backend('qasm_simulator') job = execute(zz_circuit, backend, shots=8192, seed_simulator=1024, seed_transpiler=1024) counts = job.result().get_counts(zz_circuit) ex3b_amp = counts['0'*N_DIM]/sum(counts.values()) ############################## # Check your answer and submit using the following code from qc_grader import grade_ex3b grade_ex3b(ex3b_amp) pauli_svc = SVC(kernel='precomputed') pauli_svc.fit(matrix_train, labels_train) pauli_score = pauli_svc.score(matrix_val, labels_val) print(f'Precomputed kernel classification test score: {pauli_score*100}%') # Load MNIST dataset DATA_PATH = './resources/ch3_part2.npz' data = np.load(DATA_PATH) sample_train = data['sample_train'] labels_train = data['labels_train'] sample_test = data['sample_test'] # Split train data sample_train, sample_val, labels_train, labels_val = train_test_split( sample_train, labels_train, test_size=0.2, random_state=42) # Visualize samples fig = plt.figure() LABELS = [0, 2, 3] num_labels = len(LABELS) for i in range(num_labels): ax = fig.add_subplot(1, num_labels, i+1) img = sample_train[labels_train==LABELS[i]][0].reshape((28, 28)) ax.imshow(img, cmap="Greys") # Standardize standard_scaler = StandardScaler() sample_train = standard_scaler.fit_transform(sample_train) sample_val = standard_scaler.transform(sample_val) sample_test = standard_scaler.transform(sample_test) # Reduce dimensions N_DIM = 5 pca = PCA(n_components=N_DIM) sample_train = pca.fit_transform(sample_train) sample_val = pca.transform(sample_val) sample_test = pca.transform(sample_test) # Normalize min_max_scaler = MinMaxScaler((-1, 1)) sample_train = min_max_scaler.fit_transform(sample_train) sample_val = min_max_scaler.transform(sample_val) sample_test = min_max_scaler.transform(sample_test) labels_train_0 = np.where(labels_train==0, 1, 0) labels_val_0 = np.where(labels_val==0, 1, 0) print(f'Original validation labels: {labels_val}') print(f'Validation labels for 0 vs Rest: {labels_val_0}') labels_train_2 = np.where(labels_train==2, 1, 0) labels_val_2 = np.where(labels_val==2, 1, 0) print(f'Original validation labels: {labels_val}') print(f'Validation labels for 2 vs Rest: {labels_val_2}') labels_train_3 = np.where(labels_train==3, 1, 0) labels_val_3 = np.where(labels_val==3, 1, 0) print(f'Original validation labels: {labels_val}') print(f'Validation labels for 2 vs Rest: {labels_val_3}') pauli_map_0 = ZZFeatureMap(feature_dimension=N_DIM, reps=1, entanglement = 'linear') pauli_kernel_0 = QuantumKernel(feature_map=pauli_map_0, quantum_instance=Aer.get_backend('statevector_simulator')) pauli_svc_0 = SVC(kernel='precomputed', probability=True) matrix_train_0 = pauli_kernel_0.evaluate(x_vec=sample_train) pauli_svc_0.fit(matrix_train_0, labels_train_0) matrix_val_0 = pauli_kernel_0.evaluate(x_vec=sample_val, y_vec=sample_train) pauli_score_0 = pauli_svc_0.score(matrix_val_0, labels_val_0) print(f'Accuracy of discriminating between label 0 and others: {pauli_score_0*100}%') pauli_map_2 = ZZFeatureMap(feature_dimension=N_DIM, reps=1, entanglement='linear') pauli_kernel_2 = QuantumKernel(feature_map=pauli_map_2, quantum_instance=Aer.get_backend('statevector_simulator')) pauli_svc_2 = SVC(kernel='precomputed', probability=True) matrix_train_2 = pauli_kernel_2.evaluate(x_vec=sample_train) pauli_svc_2.fit(matrix_train_2, labels_train_2) matrix_val_2 = pauli_kernel_2.evaluate(x_vec=sample_val, y_vec=sample_train) pauli_score_2 = pauli_svc_2.score(matrix_val_2, labels_val_2) print(f'Accuracy of discriminating between label 2 and others: {pauli_score_2*100}%') pauli_map_3 = ZZFeatureMap(feature_dimension=N_DIM, reps=1, entanglement = 'linear') pauli_kernel_3 = QuantumKernel(feature_map=pauli_map_3, quantum_instance=Aer.get_backend('statevector_simulator')) pauli_svc_3 = SVC(kernel='precomputed', probability=True) matrix_train_3 = pauli_kernel_3.evaluate(x_vec=sample_train) pauli_svc_3.fit(matrix_train_3, labels_train_3) matrix_val_3 = pauli_kernel_3.evaluate(x_vec=sample_val, y_vec=sample_train) pauli_score_3 = pauli_svc_3.score(matrix_val_3, labels_val_3) print(f'Accuracy of discriminating between label 3 and others: {pauli_score_3*100}%') matrix_test_0 = pauli_kernel_0.evaluate(x_vec=sample_test, y_vec=sample_train) pred_0 = pauli_svc_0.predict_proba(matrix_test_0)[:, 1] print(f'Probability of label 0: {np.round(pred_0, 2)}') matrix_test_2 = pauli_kernel_2.evaluate(x_vec=sample_test, y_vec=sample_train) pred_2 = pauli_svc_2.predict_proba(matrix_test_2)[:, 1] print(f'Probability of label 2: {np.round(pred_2, 2)}') matrix_test_3 = pauli_kernel_3.evaluate(x_vec=sample_test, y_vec=sample_train) pred_3 = pauli_svc_3.predict_proba(matrix_test_3)[:, 1] print(f'Probability of label 3: {np.round(pred_3, 2)}') ############################## # Provide your code here pred_2 = pauli_svc_2.predict_proba(matrix_test_2)[:, 1] ############################## ############################## # Provide your code here pred_3 = pauli_svc_3.predict_proba(matrix_test_3)[:, 1] ############################## sample_pred = np.load('./resources/ch3_part2_sub.npy') print(f'Sample prediction: {sample_pred}') pred_2_ex = np.array([0.7]) pred_3_ex = np.array([0.2]) pred_test_ex = np.where((pred_2_ex > pred_3_ex), 2, 3) print(f'Prediction: {pred_test_ex}') pred_2_ex = np.array([0.7, 0.1]) pred_3_ex = np.array([0.2, 0.6]) pred_test_ex = np.where((pred_2_ex > pred_3_ex), 2, 3) print(f'Prediction: {pred_test_ex}') ############################## # Provide your code here prob_0 = np.array(np.round(pred_0,2)) prob_2 = np.array(np.round(pred_2,2)) prob_3 = np.array(np.round(pred_3,2)) def pred(pred_0, pred_2, pred_3): prediction=[] for i in range(len(pred_0)): if pred_0[i]>pred_2[i] and pred_0[i]>pred_3[i]: prediction.append(0) elif pred_2[i]>pred_0[i] and pred_2[i]>pred_3[i]: prediction.append(2) else: prediction.append(3) return np.array(prediction) test = pred(prob_0, prob_2, prob_3) pred_test = np.array(test) print(pred_test) ############################## print(f'Sample prediction: {sample_pred}') # Check your answer and submit using the following code from qc_grader import grade_ex3c grade_ex3c(pred_test, sample_train, standard_scaler, pca, min_max_scaler, pauli_kernel_0, pauli_kernel_2, pauli_kernel_3, pauli_svc_0, pauli_svc_2, pauli_svc_3)
https://github.com/hugosc/quantum-phase-estimation
hugosc
# Import the Qiskit SDK from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import available_backends, execute, register, get_backend, compile from qiskit.tools.visualization import plot_histogram, circuit_drawer import time pi = 3.14159265359 qx_config = { "APItoken": "4c79a44d415dcf5c0c967e7fb488a39c3c6042baacfd60861d6bca9326aeeb64022892979076e63e0bd6c6e007d4ef3d004b697a022bfaf469e8b0a999efdb63", "url":"https://quantumexperience.ng.bluemix.net/api"} register(qx_config['APItoken'], qx_config['url']) available_backends() from qiskit import least_busy least_busy(available_backends({'simulator': False})) # couplingMap = [(0,1),(0,2),(1,2),(2,3),(4,2),(4,3)] couplingMap = [(1,0),(2,0),(2,1),(3,2),(3,4),(4,2)] def cRotation(qc, q, i, j, angle): half_a = angle / 2 if i != 2 and j != 2: swap(qc, q, 2, j) cRotation(qc, q, i, 2, angle) swap(qc, q, 2, j) else: qc.u1(half_a, q[i]) if(j,i) in couplingMap: qc.cx(q[j], q[i]) else: invertCNOT(qc, q, i, j) qc.u1(-half_a, q[i]) if(j,i) in couplingMap: qc.cx(q[j], q[i]) else: invertCNOT(qc, q, i, j) qc.u1(half_a, q[j]) def invertCNOT(qc, q, i, j): qc.h(q[i]) qc.h(q[j]) qc.cx(q[i], q[j]) qc.h(q[i]) qc.h(q[j]) def swap(qc, q, i, j): if i != 2 and j != 2: swap(qc, q, 2, j) swap(qc, q, i, 2) swap(qc, q, 2, j) else: if (i,j) in couplingMap: qc.cx(q[i], q[j]) invertCNOT(qc, q, i, j) qc.cx(q[i], q[j]) else: qc.cx(q[j], q[i]) invertCNOT(qc, q, j, i) qc.cx(q[j], q[i]) def inverse_qft(qc, q, indices): rev = list(reversed(indices)) #swaps need to happen N = len(rev) for i in range(int(N / 2)): j = N - i - 1 swap(qc, q, i, j) for n, i in enumerate(rev): angle = -pi/2**n for j in rev[:n]: cRotation(qc, q, i, j, angle) angle *= 2 qc.h(q[i]) # Create a Quantum Register with 5 qubits. q = QuantumRegister(5) # Create a Classical Register with 5 bits for storing results. c = ClassicalRegister(5) # Create a Quantum Circuit qc = QuantumCircuit(q, c) # Add a H gate on 4 qubits, putting the qubits in superposition. qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) #Put qubit to |1> qc.x(q[4]) cRotation(qc, q, 3, 4, pi/8) cRotation(qc, q, 2, 4, pi/4) cRotation(qc, q, 1, 4, pi/2) cRotation(qc, q, 0, 4, pi) inverse_qft(qc, q, range(4)) qc.measure(q, c) # See a list of available local simulators print("Local backends: ", available_backends({'local': True})) # Compile and run the Quantum circuit on a simulator backend job = execute(qc, "local_qasm_simulator") my_backend = get_backend('ibmqx4') qobj = compile(qc, backend=my_backend, shots=1024) job = my_backend.run(qobj) lapse = 0 interval = 30 while not job.done: print('Status @ {} seconds'.format(interval * lapse)) print(job.status) time.sleep(interval) lapse += 1 print(job.status) result = job.result() counts = result.get_counts() print(result) print(counts) plot_histogram(counts) circuit_drawer(qc) print(qc.qasm())
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.utils import algorithm_globals from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import ( MinimumEigenOptimizer, RecursiveMinimumEigenOptimizer, SolutionSample, OptimizationResultStatus, ) from qiskit_optimization import QuadraticProgram from qiskit.visualization import plot_histogram from typing import List, Tuple import numpy as np # create a QUBO qubo = QuadraticProgram() qubo.binary_var("x") qubo.binary_var("y") qubo.binary_var("z") qubo.minimize(linear=[1, -2, 3], quadratic={("x", "y"): 1, ("x", "z"): -1, ("y", "z"): 2}) print(qubo.prettyprint()) op, offset = qubo.to_ising() print("offset: {}".format(offset)) print("operator:") print(op) qp = QuadraticProgram() qp.from_ising(op, offset, linear=True) print(qp.prettyprint()) algorithm_globals.random_seed = 10598 qaoa_mes = QAOA(sampler=Sampler(), optimizer=COBYLA(), initial_point=[0.0, 0.0]) exact_mes = NumPyMinimumEigensolver() qaoa = MinimumEigenOptimizer(qaoa_mes) # using QAOA exact = MinimumEigenOptimizer(exact_mes) # using the exact classical numpy minimum eigen solver exact_result = exact.solve(qubo) print(exact_result.prettyprint()) qaoa_result = qaoa.solve(qubo) print(qaoa_result.prettyprint()) print("variable order:", [var.name for var in qaoa_result.variables]) for s in qaoa_result.samples: print(s) def get_filtered_samples( samples: List[SolutionSample], threshold: float = 0, allowed_status: Tuple[OptimizationResultStatus] = (OptimizationResultStatus.SUCCESS,), ): res = [] for s in samples: if s.status in allowed_status and s.probability > threshold: res.append(s) return res filtered_samples = get_filtered_samples( qaoa_result.samples, threshold=0.005, allowed_status=(OptimizationResultStatus.SUCCESS,) ) for s in filtered_samples: print(s) fvals = [s.fval for s in qaoa_result.samples] probabilities = [s.probability for s in qaoa_result.samples] np.mean(fvals) np.std(fvals) samples_for_plot = { " ".join(f"{qaoa_result.variables[i].name}={int(v)}" for i, v in enumerate(s.x)): s.probability for s in filtered_samples } samples_for_plot plot_histogram(samples_for_plot) rqaoa = RecursiveMinimumEigenOptimizer(qaoa, min_num_vars=1, min_num_vars_optimizer=exact) rqaoa_result = rqaoa.solve(qubo) print(rqaoa_result.prettyprint()) filtered_samples = get_filtered_samples( rqaoa_result.samples, threshold=0.005, allowed_status=(OptimizationResultStatus.SUCCESS,) ) samples_for_plot = { " ".join(f"{rqaoa_result.variables[i].name}={int(v)}" for i, v in enumerate(s.x)): s.probability for s in filtered_samples } samples_for_plot plot_histogram(samples_for_plot) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.circuit.library import RealAmplitudes from qiskit.algorithms.optimizers import COBYLA from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, SamplingVQE from qiskit.primitives import Sampler from qiskit_optimization.converters import LinearEqualityToPenalty from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit_optimization.translators import from_docplex_mp from qiskit.utils import algorithm_globals import numpy as np import matplotlib.pyplot as plt from docplex.mp.model import Model algorithm_globals.random_seed = 123456 # prepare problem instance n = 6 # number of assets q = 0.5 # risk factor budget = n // 2 # budget penalty = 2 * n # scaling of penalty term # instance from [1] mu = np.array([0.7313, 0.9893, 0.2725, 0.8750, 0.7667, 0.3622]) sigma = np.array( [ [0.7312, -0.6233, 0.4689, -0.5452, -0.0082, -0.3809], [-0.6233, 2.4732, -0.7538, 2.4659, -0.0733, 0.8945], [0.4689, -0.7538, 1.1543, -1.4095, 0.0007, -0.4301], [-0.5452, 2.4659, -1.4095, 3.5067, 0.2012, 1.0922], [-0.0082, -0.0733, 0.0007, 0.2012, 0.6231, 0.1509], [-0.3809, 0.8945, -0.4301, 1.0922, 0.1509, 0.8992], ] ) # or create random instance # mu, sigma = portfolio.random_model(n, seed=123) # expected returns and covariance matrix # create docplex model mdl = Model("portfolio_optimization") x = mdl.binary_var_list(range(n), name="x") objective = mdl.sum([mu[i] * x[i] for i in range(n)]) objective -= q * mdl.sum([sigma[i, j] * x[i] * x[j] for i in range(n) for j in range(n)]) mdl.maximize(objective) mdl.add_constraint(mdl.sum(x[i] for i in range(n)) == budget) # case to qp = from_docplex_mp(mdl) # solve classically as reference opt_result = MinimumEigenOptimizer(NumPyMinimumEigensolver()).solve(qp) print(opt_result.prettyprint()) # we convert the problem to an unconstrained problem for further analysis, # otherwise this would not be necessary as the MinimumEigenSolver would do this # translation automatically linear2penalty = LinearEqualityToPenalty(penalty=penalty) qp = linear2penalty.convert(qp) _, offset = qp.to_ising() # set classical optimizer maxiter = 100 optimizer = COBYLA(maxiter=maxiter) # set variational ansatz ansatz = RealAmplitudes(n, reps=1) m = ansatz.num_parameters # set sampler sampler = Sampler() # run variational optimization for different values of alpha alphas = [1.0, 0.50, 0.25] # confidence levels to be evaluated # dictionaries to store optimization progress and results objectives = {alpha: [] for alpha in alphas} # set of tested objective functions w.r.t. alpha results = {} # results of minimum eigensolver w.r.t alpha # callback to store intermediate results def callback(i, params, obj, stddev, alpha): # we translate the objective from the internal Ising representation # to the original optimization problem objectives[alpha].append(np.real_if_close(-(obj + offset))) # loop over all given alpha values for alpha in alphas: # initialize SamplingVQE using CVaR vqe = SamplingVQE( sampler=sampler, ansatz=ansatz, optimizer=optimizer, aggregation=alpha, callback=lambda i, params, obj, stddev: callback(i, params, obj, stddev, alpha), ) # initialize optimization algorithm based on CVaR-SamplingVQE opt_alg = MinimumEigenOptimizer(vqe) # solve problem results[alpha] = opt_alg.solve(qp) # print results print("alpha = {}:".format(alpha)) print(results[alpha].prettyprint()) print() # plot resulting history of objective values plt.figure(figsize=(10, 5)) plt.plot([0, maxiter], [opt_result.fval, opt_result.fval], "r--", linewidth=2, label="optimum") for alpha in alphas: plt.plot(objectives[alpha], label="alpha = %.2f" % alpha, linewidth=2) plt.legend(loc="lower right", fontsize=14) plt.xlim(0, maxiter) plt.xticks(fontsize=14) plt.xlabel("iterations", fontsize=14) plt.yticks(fontsize=14) plt.ylabel("objective value", fontsize=14) plt.show() # evaluate and sort all objective values objective_values = np.zeros(2**n) for i in range(2**n): x_bin = ("{0:0%sb}" % n).format(i) x = [0 if x_ == "0" else 1 for x_ in reversed(x_bin)] objective_values[i] = qp.objective.evaluate(x) ind = np.argsort(objective_values) # evaluate final optimal probability for each alpha for alpha in alphas: probabilities = np.fromiter( results[alpha].min_eigen_solver_result.eigenstate.binary_probabilities().values(), dtype=float, ) print("optimal probability (alpha = %.2f): %.4f" % (alpha, probabilities[ind][-1:])) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/alejomonbar/Qiskit_Fall_Fest_Mexico_2022
alejomonbar
%pip install yfinance %pip install cplex %pip qiskit_optimization %matplotlib inline import numpy as np import matplotlib.pyplot as plt import pandas as pd from docplex.mp.model import Model colors = plt.cm.tab20(range(20)) label_size = 22 plt.rcParams['xtick.labelsize'] = label_size plt.rcParams['ytick.labelsize'] = label_size plt.rcParams['axes.labelsize'] = label_size plt.rcParams['legend.fontsize'] = label_size plt.rcParams['axes.titlesize'] = label_size stocks_info = {"Stocks":["MSFT", "AAPL", "GOOG", "PFE", "MRNA", "JPM", "C", "XOM", "HAL", "HON"], "Name":["Microsoft", "Apple Inc.", "Alphabet", "Pfizer", "Moderna","JPMorgan Chase", "Citigroup", "ExxonMobil","Halliburton", "Honeywell"], "Sector":3*["Information Technology"] + 2 * ["Health Care"] + 2* ["Financial"] + 2 * ["Energy"]+ ["Industrial"]} pd.DataFrame(stocks_info) import yfinance as yf stocks = stocks_info["Stocks"] tickers = yf.Tickers(stocks) tickers.tickers["AAPL"].history(period="12mo") fig, ax = plt.subplots(2,2, figsize=(24,17)) colors_case = {"Open":colors[0], "High":colors[5], "Low":colors[10], "Close":colors[19]} linestyle = {"Open":"-", "High":"--", "Low":":", "Close":"-."} for case in ["Open", "High","Low", "Close"]: ax[0,0].plot(tickers.tickers["AAPL"].history(period="12mo")[case], color = colors_case[case], linestyle=linestyle[case], label=case) ax[0,0].legend() ax[0,1].plot(tickers.tickers["AAPL"].history(period="12mo")["Volume"], label=case) ax[1,0].plot(tickers.tickers["AAPL"].history(period="12mo")["Dividends"], label=case) ax[1,1].plot(tickers.tickers["AAPL"].history(period="12mo")["Stock Splits"], label=case) names = [["Stock Price", "Volume"], ["Dividends", "Stock Splits"]] for i in range(2): for j in range(2): ax[i,j].set_xlabel("date") ax[i,j].set_ylabel(names[i][j]) ax[i,j].set_title("Apple Inc.") # Price of all the stocks of this example Pt = np.array([tickers.tickers[stock].history(period="12mo")["Close"] for stock in stocks]) mu = (Pt[:,1:] - Pt[:,:-1]) / Pt[:,:-1] plt.figure() plt.plot(mu[0]) plt.xlabel("Days") plt.ylabel(r"$\mu_t$") plt.title("Apple Inc.") N_stocks, N_days = mu.shape sigma = np.zeros((N_stocks, N_stocks)) for i in range(N_stocks-1): for j in range(i, N_stocks): sigma[i,j] = ((mu[i] - mu[i].mean()) * (mu[j] - mu[j].mean())).sum()/(N_time - 1) sigma += sigma.T # sigma = np.cov(mu, varcol=True) fig, ax = plt.subplots(1, 2, figsize=(22,9)) for i in range(N_stocks): ax[0].plot(range(N_days+1), Pt[i], color=colors[i], label=stocks[i]) ax[0].set_xlabel("day") ax[0].set_ylabel("Stock Price [$]") ax[0].legend(loc='upper center', bbox_to_anchor=(0.5, 1.2), ncol=5, fancybox=True, shadow=True) im = ax[1].imshow(sigma, cmap="coolwarm", vmin=-0.0002, vmax=0.0006) fig.colorbar(im) ax[1].set_yticks(range(N_stocks)) ax[1].set_xticks(range(N_stocks)) ax[1].set_xticklabels(stocks, rotation=45) ax[1].set_yticklabels(stocks, rotation=45) ax[1].set_title(r"Covariance Matrix $\Sigma$ associated to the risk") q = 0.1 # Risk aversion Budget = 7 # I can invest in 7 stocks c = N_stocks * [1] # Minimum we can invest in the different assets c_i mdl = Model('Portfolio Optimization') # Binary set of variables that represent the stocks x = np.array(mdl.binary_var_list(N_stocks, name=stocks)) # x vector in numpy array for matrix multiplication # Portfolio optimization function objective_function = mu.mean(axis=1) @ x - q * x.T @ sigma @ x mdl.maximize(objective_function) # Budget constraint mdl.add_constraint(c @ x == Budget, ctname='budget') # Printing the docplex model mdl.prettyprint() sol_docplex = mdl.solve() sol_docplex = {st: int(sol_docplex.get_value(st)) for st in stocks} sol_docplex from qiskit_optimization.translators import from_docplex_mp from qiskit_optimization.runtime import QAOAClient, VQEClient from qiskit.algorithms import VQE, QAOA from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit import Aer # local simulator from qiskit.algorithms.optimizers import SPSA, COBYLA backend = Aer.get_backend("qasm_simulator") qubo = from_docplex_mp(mdl) def optimization_QAOA(qubo, reps=1, optimizer=SPSA(maxiter=50), backend=None, shots=1024, provider=None): intermediate_info = {'nfev': [], 'parameters': [], 'stddev': [], 'mean': [] } def callback(nfev, parameters, mean, stddev): intermediate_info['nfev'].append(nfev) intermediate_info['parameters'].append(parameters) intermediate_info['mean'].append(mean) intermediate_info['stddev'].append(stddev) qaoa_mes = QAOA(optimizer=optimizer, reps=reps, quantum_instance=backend, callback=callback) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(qubo) return result, intermediate_info sol_spsa, info_spsa = optimization_QAOA(qubo, backend=backend) sol_cobyla, info_cobyla = optimization_QAOA(qubo, backend=backend, optimizer=COBYLA()) solutions = {"Stocks":stocks_info["Stocks"], "CPLEX":sol_docplex.values(), "COBYLA":sol_cobyla.x, "SPSA":sol_spsa.x} pd.DataFrame(solutions) plt.figure() plt.plot(info_spsa["nfev"], info_spsa["mean"], label="SPSA", color=colors[5]) plt.plot(info["nfev"], info["mean"], label = "COBYLA", color=colors[10]) plt.legend() plt.xlabel("num func evals") plt.ylabel("Cost func.") from qiskit.circuit.library import TwoLocal ansatz = TwoLocal(N_stocks, rotation_blocks='ry', entanglement_blocks='cz') def Optimization_VQE(qubo, ansatz, optimizer=SPSA(maxiter=50), backend=None, shots=1024): intermediate_info = {'nfev': [], 'parameters': [], 'stddev': [], 'mean': [] } def callback(nfev, parameters, mean, stddev): intermediate_info['nfev'].append(nfev) intermediate_info['parameters'].append(parameters) intermediate_info['mean'].append(mean) intermediate_info['stddev'].append(stddev) vqe_mes = VQE(ansatz=ansatz, quantum_instance=backend, callback=callback, optimizer=optimizer) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(qubo) return result, intermediate_info import qiskit.tools.jupyter %qiskit_version_table
https://github.com/mgg39/qiskit-networks
mgg39
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/qiskit-community/prototype-quantum-kernel-training
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Create a new Covariant Feature Map circuit.""" import copy from typing import Callable, Optional, Union, List, Dict, Any import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import ParameterVector class CovariantFeatureMap(QuantumCircuit): """The Covariant Feature Map circuit. On 3 qubits and a linear entanglement, the circuit is represented by: .. parsed-literal:: ┌──────────────┐ ░ ┌─────────────────┐┌─────────────────┐ q_0: ┤ Ry(θ_par[0]) ├─■─────░─┤ Rz(-2*x_par[1]) ├┤ Rx(-2*x_par[0]) ├ ├──────────────┤ │ ░ ├─────────────────┤├─────────────────┤ q_1: ┤ Ry(θ_par[1]) ├─■──■──░─┤ Rz(-2*x_par[3]) ├┤ Rx(-2*x_par[2]) ├ ├──────────────┤ │ ░ ├─────────────────┤├─────────────────┤ q_2: ┤ Ry(θ_par[2]) ├────■──░─┤ Rz(-2*x_par[5]) ├┤ Rx(-2*x_par[4]) ├ └──────────────┘ ░ └─────────────────┘└─────────────────┘ where θ_par is a vector of trainable feature map parameters and x_par is a vector of data-bound feature map parameters. """ def __init__( self, feature_dimension: int, entanglement: Union[str, List[List[int]], Callable[[int], List[int]]] = None, single_training_parameter: bool = False, name: str = "CovariantFeatureMap", ) -> None: """Create a new Covariant Feature Map circuit. Args: feature_dimension: The number of features insert_barriers: If True, barriers are inserted around the entanglement layer """ if (feature_dimension % 2) != 0: raise ValueError( """ Covariant feature map requires an even number of input features. """ ) self.feature_dimension = feature_dimension self.entanglement = entanglement self.single_training_parameter = single_training_parameter self.training_parameters = None self.input_parameters = None num_qubits = feature_dimension / 2 super().__init__( num_qubits, name=name, ) self._generate_feature_map() @property def settings(self) -> Dict[str, Any]: training_parameters_list = [param for param in self.training_parameters] input_parameters_list = [param for param in self.input_parameters] return { "feature_dimension": self.feature_dimension, "entanglement": self.entanglement, "single_training_parameter": self.single_training_parameter, "training_parameters": training_parameters_list, "input_parameters": input_parameters_list, } def _generate_feature_map(self): # If no entanglement scheme specified, use linear entanglement if self.entanglement is None: self.entanglement = [[i, i + 1] for i in range(self.num_qubits - 1)] # Vector of data parameters input_params = ParameterVector("x_par", self.feature_dimension) # Use a single parameter to rotate each qubit if sharing is desired if self.single_training_parameter: training_params = ParameterVector("\u03B8_par", 1) # Create an initial rotation layer using a single Parameter for i in range(self.num_qubits): self.ry(training_params[0], self.qubits[i]) # Train each qubit's initial rotation individually else: training_params = ParameterVector("\u03B8_par", self.num_qubits) # Create an initial rotation layer of trainable parameters for i in range(self.num_qubits): self.ry(training_params[i], self.qubits[i]) self.training_parameters = training_params self.input_parameters = input_params # Create the entanglement layer for source, target in self.entanglement: self.cz(self.qubits[source], self.qubits[target]) self.barrier() # Create a circuit representation of the data group for i in range(self.num_qubits): self.rz(-2 * input_params[2 * i + 1], self.qubits[i]) self.rx(-2 * input_params[2 * i], self.qubits[i])
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi # the angle of rotation theta = 1 * pi/16 # we read streams of length 8, 16, 24, 32, 40, 48, 56, 64 for i in [8, 16, 24, 32, 40, 48, 56, 64]: # quantum circuit with one qubit and one bit qreg = QuantumRegister(1) creg = ClassicalRegister(1) mycircuit = QuantumCircuit(qreg,creg) # the stream of length i for j in range(i): mycircuit.ry(2*theta,qreg[0]) # apply one rotation for each symbol # we measure after reading the whole stream mycircuit.measure(qreg[0],creg[0]) # execute the circuit 100 times job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(mycircuit) d = i /8 if d % 2 == 0: print(i,"is even multiple of 8") else: print(i,"is odd multiple of 8") print("stream of lenght",i,"->",counts) print() # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange rand = randrange(1, 11) # random number can take any value in between 1-11 theta = (rand * 2* pi)/11 # calculating angle # the streams of lengths from 1 to 11 for i in range(1,12): # quantum circuit with one qubit and one bit qreg = QuantumRegister(1) creg = ClassicalRegister(1) mycircuit = QuantumCircuit(qreg,creg) # the stream of length i for j in range(i): mycircuit.ry(2*theta,qreg[0]) # apply one rotation for each symbol # we measure after reading the whole stream mycircuit.measure(qreg[0],creg[0]) # execute the circuit 1000 times job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1000) counts = job.result().get_counts(mycircuit) print("Length of the Stream",i,"->",counts) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange # for each stream of length from 1 to 10 for i in range(1,11): # we try each angle of the form k*2*pi/11 for k=1,...,10 # we try to find the best k for which we observe 1 the most number_of_one_state = 0 best_k = 1 all_outcomes_for_i = "length "+str(i)+"-> " for k in range(1,11): theta = k*2*pi/11 # quantum circuit with one qubit and one bit qreg = QuantumRegister(1) creg = ClassicalRegister(1) mycircuit = QuantumCircuit(qreg,creg) # the stream of length i for j in range(i): mycircuit.ry(2*theta,qreg[0]) # apply one rotation for each symbol # we measure after reading the whole stream mycircuit.measure(qreg[0],creg[0]) # execute the circuit 10000 times job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=10000) counts = job.result().get_counts(mycircuit) all_outcomes_for_i = all_outcomes_for_i + str(k)+ ":" + str(counts['1']) + " " if int(counts['1']) > number_of_one_state: number_of_one_state = counts['1'] best_k = k print(all_outcomes_for_i) print("for length",i,", the best k is",best_k) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange p = 31 theta1 = (3 * 2 * pi)/p theta2 = (7 * 2 * pi)/p theta3 = (11 * 2 * pi)/p # the streams of lengths from 1 to 30 for i in range(1,30): # Create a circuit with 3 Quantum States qreg = QuantumRegister(3) creg = ClassicalRegister(3) mycircuit = QuantumCircuit(qreg,creg) for j in range(i): # Rotations applied to each symbol number of length times mycircuit.ry(2*theta1,qreg[0]) mycircuit.ry(2*theta2,qreg[1]) mycircuit.ry(2*theta3,qreg[2]) # we measure the system mycircuit.measure(qreg,creg) # execute 1000 times job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots= 1000) counts = job.result().get_counts(mycircuit) # check the number of times state |000> print(counts) if '000' in counts.keys(): c = counts['000'] else: c = 0 # print the result print('000 is observed',c,'times out of',1000) percentange = round(c/1000*100,1) print("the ratio of 000 is ",percentange,"%") print() # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange # randomly picked angles of rotations k1 = randrange(1,31) theta1 = k1*2*pi/31 k2 = randrange(1,31) theta2 = k2*2*pi/31 k3 = randrange(1,31) theta3 = k3*2*pi/31 print("k1 =",k1,"k2 =",k2,"k3 =",k3) print() max_percentange = 0 # we read streams of length from 1 to 30 for i in range(1,31): # quantum circuit with three qubits and three bits qreg = QuantumRegister(3) creg = ClassicalRegister(3) mycircuit = QuantumCircuit(qreg,creg) # the stream of length i for j in range(i): # apply rotations for each symbol mycircuit.ry(2*theta1,qreg[0]) mycircuit.ry(2*theta2,qreg[1]) mycircuit.ry(2*theta3,qreg[2]) # we measure after reading the whole stream mycircuit.measure(qreg,creg) # execute the circuit N times N = 1000 job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=N) counts = job.result().get_counts(mycircuit) # print(counts) if '000' in counts.keys(): c = counts['000'] else: c = 0 print('000 is observed',c,'times out of',N, "for sequence length", i) percentange = round(c/N*100,1) if max_percentange < percentange: max_percentange = percentange print("the ratio of 000 is ",percentange,"%") print() print("max percentage is",max_percentange) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange number_of_qubits = 4 #number_of_qubits = 5 # randomly picked angles of rotations theta = [] for i in range(number_of_qubits): k = randrange(1,31) print("k",str(i),"=",k) theta += [k*2*pi/31] print(theta) # we count the number of zeros zeros = '' for i in range(number_of_qubits): zeros = zeros + '0' print("zeros = ",zeros) print() max_percentange = 0 # we read streams of length from 1 to 30 for i in range(1,31): # quantum circuit with qubits and bits qreg = QuantumRegister(number_of_qubits) creg = ClassicalRegister(number_of_qubits) mycircuit = QuantumCircuit(qreg,creg) # the stream of length i for j in range(i): # apply rotations for each symbol for k in range(number_of_qubits): mycircuit.ry(2*theta[k],qreg[k]) # we measure after reading the whole stream mycircuit.measure(qreg,creg) # execute the circuit N times N = 1000 job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=N) counts = job.result().get_counts(mycircuit) # print(counts) if zeros in counts.keys(): c = counts[zeros] else: c = 0 # print('000 is observed',c,'times out of',N) percentange = round(c/N*100,1) if max_percentange < percentange: max_percentange = percentange # print("the ration of 000 is ",percentange,"%") # print() print("max percentage is",max_percentange)
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) ### removed cx gate ### return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) ### removed h gate ### return qc
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
MonitSharma
import matplotlib.pyplot as plt import pennylane as qml from pennylane import numpy as np np.random.seed(135) def square_loss(targets, predictions): loss = 0 for t, p in zip(targets, predictions): loss += (t - p) ** 2 loss = loss / len(targets) return 0.5*loss degree = 1 # since we are using a single qubit model it would be better to keep it to 1 scaling = 1 # scaling factor for the data coeffs = [0.15 + 0.15j]*degree # coefficient of the non-zero frequencies coeff0 = 0.1 # coefficient of zero frequency def target_function(x): """ Generate a truncated Fourier series, where the data gets re-scaled """ res = coeff0 for idx, coeff in enumerate(coeffs): exponent = np.complex128(scaling * (idx + 1) * x * 1j) conj_coeff = np.conjugate(coeff) res += coeff * np.exp(exponent) + conj_coeff * np.exp(-exponent) return np.real(res) x = np.linspace(-6, 6, 70, requires_grad=False) target_y = np.array([target_function(x_) for x_ in x], requires_grad=False) plt.plot(x, target_y, c='black') plt.scatter(x, target_y, facecolor='white', edgecolor='black') plt.ylim(-1, 1) plt.show(); scaling = 1 dev = qml.device('default.qubit', wires =1) def S(x): """Data encodng circuit block""" qml.RX(scaling * x, wires = 0) def W(theta): """Trainable circuit block""" qml.Rot(theta[0], theta[1], theta[2], wires=0) @qml.qnode(dev) def serial_quantum_model(weights,x): for theta in weights[:-1]: W(theta) S(x) # (L+1)'th unitary W(weights[-1]) return qml.expval(qml.PauliZ(wires=0)) r = 1 # number of times the encoding gets repeated (here equal to the number of layers) weights = 2 * np.pi * np.random.random(size=(r+1, 3), requires_grad=True) # some random initial weights x = np.linspace(-6, 6, 70, requires_grad=False) random_quantum_model_y = [serial_quantum_model(weights, x_) for x_ in x] plt.plot(x, random_quantum_model_y, c='blue') plt.ylim(-1,1) plt.show() print(qml.draw(serial_quantum_model)(weights, x[-1])) def cost(weights, x, y): predictions = [serial_quantum_model(weights, x_) for x_ in x] return square_loss(y, predictions) max_steps = 50 opt = qml.AdamOptimizer(0.3) batch_size = 25 cst = [cost(weights, x, target_y)] # initial cost for step in range(max_steps): # Select batch of data batch_index = np.random.randint(0, len(x), (batch_size,)) x_batch = x[batch_index] y_batch = target_y[batch_index] # Update the weights by one optimizer step weights, _, _ = opt.step(cost, weights, x_batch, y_batch) # Save, and possibly print, the current cost c = cost(weights, x, target_y) cst.append(c) if (step + 1) % 10 == 0: print("Cost at step {0:3}: {1}".format(step + 1, c)) predictions = [serial_quantum_model(weights, x_) for x_ in x] plt.plot(x, target_y, c='black') plt.scatter(x, target_y, facecolor='white', edgecolor='black') plt.plot(x, predictions, c='blue') plt.ylim(-1,1) plt.show(); plt.plot(range(len(cst)), cst) plt.ylabel("Cost") plt.xlabel("Step") plt.ylim(0, 0.23) plt.show(); from pennylane.templates import StronglyEntanglingLayers n_ansatz_layers = 2 n_qubits = 3 dev = qml.device('default.qubit', wires=4) @qml.qnode(dev) def ansatz(weights): StronglyEntanglingLayers(weights, wires=range(n_qubits)) return qml.expval(qml.Identity(wires=0)) weights_ansatz = 2 * np.pi * np.random.random(size=(n_ansatz_layers, n_qubits, 3)) print(qml.draw(ansatz, expansion_strategy="device")(weights_ansatz)) scaling = 1 r = 3 dev = qml.device('default.qubit', wires=r) def S(x): """Data-encoding circuit block.""" for w in range(r): qml.RX(scaling * x, wires=w) def W(theta): """Trainable circuit block.""" StronglyEntanglingLayers(theta, wires=range(r)) @qml.qnode(dev) def parallel_quantum_model(weights, x): W(weights[0]) S(x) W(weights[1]) return qml.expval(qml.PauliZ(wires=0)) trainable_block_layers = 3 weights = 2 * np.pi * np.random.random(size=(2, trainable_block_layers, r, 3), requires_grad=True) x = np.linspace(-6, 6, 70, requires_grad=False) random_quantum_model_y = [parallel_quantum_model(weights, x_) for x_ in x] plt.plot(x, random_quantum_model_y, c='blue') plt.ylim(-1,1) plt.show(); def cost(weights, x, y): predictions = [parallel_quantum_model(weights, x_) for x_ in x] return square_loss(y, predictions) max_steps = 50 opt = qml.AdamOptimizer(0.3) batch_size = 25 cst = [cost(weights, x, target_y)] # initial cost for step in range(max_steps): # select batch of data batch_index = np.random.randint(0, len(x), (batch_size,)) x_batch = x[batch_index] y_batch = target_y[batch_index] # update the weights by one optimizer step weights, _, _ = opt.step(cost, weights, x_batch, y_batch) # save, and possibly print, the current cost c = cost(weights, x, target_y) cst.append(c) if (step + 1) % 10 == 0: print("Cost at step {0:3}: {1}".format(step + 1, c)) predictions = [parallel_quantum_model(weights, x_) for x_ in x] plt.plot(x, target_y, c='black') plt.scatter(x, target_y, facecolor='white', edgecolor='black') plt.plot(x, predictions, c='blue') plt.ylim(-1,1) plt.show(); plt.plot(range(len(cst)), cst) plt.ylabel("Cost") plt.xlabel("Step") plt.show(); def fourier_coefficients(f, K): """ Computes the first 2*K+1 Fourier coefficients of a 2*pi periodic function. """ n_coeffs = 2 * K + 1 t = np.linspace(0, 2 * np.pi, n_coeffs, endpoint=False) y = np.fft.rfft(f(t)) / t.size return y from pennylane.templates import BasicEntanglerLayers scaling = 1 n_qubits = 4 dev = qml.device('default.qubit', wires=n_qubits) def S(x): """Data encoding circuit block.""" for w in range(n_qubits): qml.RX(scaling * x, wires=w) def W(theta): """Trainable circuit block.""" BasicEntanglerLayers(theta, wires=range(n_qubits)) @qml.qnode(dev) def quantum_model(weights, x): W(weights[0]) S(x) W(weights[1]) return qml.expval(qml.PauliZ(wires=0)) n_ansatz_layers = 1 def random_weights(): return 2 * np.pi * np.random.random(size=(2, n_ansatz_layers, n_qubits)) n_coeffs = 5 n_samples = 100 coeffs = [] for i in range(n_samples): weights = random_weights() def f(x): return np.array([quantum_model(weights, x_) for x_ in x]) coeffs_sample = fourier_coefficients(f, n_coeffs) coeffs.append(coeffs_sample) coeffs = np.array(coeffs) coeffs_real = np.real(coeffs) coeffs_imag = np.imag(coeffs) n_coeffs = len(coeffs_real[0]) fig, ax = plt.subplots(1, n_coeffs, figsize=(15, 4)) for idx, ax_ in enumerate(ax): ax_.set_title(r"$c_{}$".format(idx)) ax_.scatter(coeffs_real[:, idx], coeffs_imag[:, idx], s=20, facecolor='white', edgecolor='red') ax_.set_aspect("equal") ax_.set_ylim(-1, 1) ax_.set_xlim(-1, 1) plt.tight_layout(pad=0.5) plt.show(); var = 2 n_ansatz_layers = 1 dev_cv = qml.device('default.gaussian', wires=1) def S(x): qml.Rotation(x, wires=0) def W(theta): """Trainable circuit block.""" for r_ in range(n_ansatz_layers): qml.Displacement(theta[0], theta[1], wires=0) qml.Squeezing(theta[2], theta[3], wires=0) @qml.qnode(dev_cv) def quantum_model(weights, x): W(weights[0]) S(x) W(weights[1]) return qml.expval(qml.X(wires=0)) def random_weights(): return np.random.normal(size=(2, 5 * n_ansatz_layers), loc=0, scale=var) n_coeffs = 5 n_samples = 100 coeffs = [] for i in range(n_samples): weights = random_weights() def f(x): return np.array([quantum_model(weights, x_) for x_ in x]) coeffs_sample = fourier_coefficients(f, n_coeffs) coeffs.append(coeffs_sample) coeffs = np.array(coeffs) coeffs_real = np.real(coeffs) coeffs_imag = np.imag(coeffs) n_coeffs = len(coeffs_real[0]) fig, ax = plt.subplots(1, n_coeffs, figsize=(15, 4)) for idx, ax_ in enumerate(ax): ax_.set_title(r"$c_{}$".format(idx)) ax_.scatter(coeffs_real[:, idx], coeffs_imag[:, idx], s=20, facecolor='white', edgecolor='red') ax_.set_aspect("equal") ax_.set_ylim(-1, 1) ax_.set_xlim(-1, 1) plt.tight_layout(pad=0.5) plt.show();
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# # your code is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi, cos, sin from random import randrange # quantum circuit with three qubits and three bits qreg = QuantumRegister(3) creg = ClassicalRegister(3) mycircuit = QuantumCircuit(qreg,creg) # rotate the first qubit by random angle r = randrange(100) theta = 2*pi*(r/100) # radians print("the picked angle is",r*3.6,"degrees and",theta,"radians") a = cos(theta) b = sin(theta) print("a=",round(a,3),"b=",round(b,3)) print("a*a=",round(a**2,3),"b*b=",round(b**2,3)) print() mycircuit.ry(2*theta,qreg[0]) # creating an entanglement between the second and third qubits mycircuit.h(qreg[1]) mycircuit.cx(qreg[1],qreg[2]) # CNOT operator by Asja on her qubits where the first qubit is the control qubit mycircuit.cx(qreg[0],qreg[1]) # Hadamard operator by Asja on the first qubit mycircuit.h(qreg[0]) # measurement done by Asja mycircuit.measure(qreg[0],creg[0]) mycircuit.measure(qreg[1],creg[1]) # read the state vector job = execute(mycircuit,Aer.get_backend('statevector_simulator')) current_quantum_state=job.result().get_statevector(mycircuit) print("the state vector is") for i in range(len(current_quantum_state)): print(current_quantum_state[i].real) print() # reverse the order def get_state(i): if i==0: return "000" if i==1: return "100" if i==2: return "010" if i==3: return "110" if i==4: return "001" if i==5: return "101" if i==6: return "011" if i==7: return "111" balvis_state = "" for i in range(len(current_quantum_state)): if current_quantum_state[i].real!=0: if abs(current_quantum_state[i].real-a)<0.000001: balvis_state += "+a|"+ get_state(i)+">" elif abs(current_quantum_state[i].real+a)<0.000001: balvis_state += "-a|"+ get_state(i)+">" elif abs(current_quantum_state[i].real-b)<0.000001: balvis_state += "+b|"+ get_state(i)+">" elif abs(current_quantum_state[i].real+b)<0.000001: balvis_state += "-b|"+ get_state(i)+">" print("which is",balvis_state) mycircuit.draw()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeManilaV2 from qiskit import transpile from qiskit.tools.visualization import plot_histogram # Get a fake backend from the fake provider backend = FakeManilaV2() # Create a simple circuit circuit = QuantumCircuit(3) circuit.h(0) circuit.cx(0,1) circuit.cx(0,2) circuit.measure_all() circuit.draw('mpl') # Transpile the ideal circuit to a circuit that can be directly executed by the backend transpiled_circuit = transpile(circuit, backend) transpiled_circuit.draw('mpl') # Run the transpiled circuit using the simulated fake backend job = backend.run(transpiled_circuit) counts = job.result().get_counts() plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_optimization import QuadraticProgram problem = QuadraticProgram("sample") problem.binary_var("x") problem.binary_var("y") problem.maximize(linear={"x": 1, "y": -2}) print(problem.prettyprint()) from qiskit.algorithms import NumPyMinimumEigensolver from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = NumPyMinimumEigensolver() meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = NumPyMinimumEigensolver() meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import MinimumEigenOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) mes = QAOA(optimizer=COBYLA(), quantum_instance=qins) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer shots = 1000 mes = QAOA(sampler=Sampler(), optimizer=COBYLA()) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import MinimumEigenOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) mes = VQE(ansatz=RealAmplitudes(), optimizer=COBYLA(), quantum_instance=qins) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = SamplingVQE(sampler=Sampler(), ansatz=RealAmplitudes(), optimizer=COBYLA()) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Estimator from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = VQE(estimator=Estimator(), ansatz=RealAmplitudes(), optimizer=COBYLA()) try: meo = MinimumEigenOptimizer(min_eigen_solver=mes) except TypeError as ex: print(ex) from qiskit import BasicAer from qiskit.algorithms import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import WarmStartQAOAOptimizer, SlsqpOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) qaoa = QAOA(optimizer=COBYLA(), quantum_instance=qins) optimizer = WarmStartQAOAOptimizer( pre_solver=SlsqpOptimizer(), relax_for_pre_solver=True, qaoa=qaoa, epsilon=0.25 ) result = optimizer.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import WarmStartQAOAOptimizer, SlsqpOptimizer qaoa = QAOA(sampler=Sampler(), optimizer=COBYLA()) optimizer = WarmStartQAOAOptimizer( pre_solver=SlsqpOptimizer(), relax_for_pre_solver=True, qaoa=qaoa, epsilon=0.25 ) result = optimizer.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import GroverOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) optimizer = GroverOptimizer(num_value_qubits=3, num_iterations=3, quantum_instance=qins) result = optimizer.solve(problem) print(result) from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import GroverOptimizer optimizer = GroverOptimizer(num_value_qubits=3, num_iterations=3, sampler=Sampler()) result = optimizer.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit.primitives import Sampler from qiskit_optimization.algorithms import GroverOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) try: optimizer = GroverOptimizer( num_value_qubits=3, num_iterations=3, quantum_instance=qins, sampler=Sampler() ) # raises an error because both quantum_instance and sampler are set. except ValueError as ex: print(ex) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the ResetAfterMeasureSimplification pass""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.circuit.classicalregister import Clbit from qiskit.transpiler.passes.optimization import ResetAfterMeasureSimplification from qiskit.test import QiskitTestCase class TestResetAfterMeasureSimplificationt(QiskitTestCase): """Test ResetAfterMeasureSimplification transpiler pass.""" def test_simple(self): """Test simple""" qc = QuantumCircuit(1, 1) qc.measure(0, 0) qc.reset(0) new_qc = ResetAfterMeasureSimplification()(qc) ans_qc = QuantumCircuit(1, 1) ans_qc.measure(0, 0) ans_qc.x(0).c_if(ans_qc.clbits[0], 1) self.assertEqual(new_qc, ans_qc) def test_simple_null(self): """Test simple no change in circuit""" qc = QuantumCircuit(1, 1) qc.measure(0, 0) qc.x(0) qc.reset(0) new_qc = ResetAfterMeasureSimplification()(qc) self.assertEqual(new_qc, qc) def test_simple_multi_reg(self): """Test simple, multiple registers""" cr1 = ClassicalRegister(1, "c1") cr2 = ClassicalRegister(1, "c2") qr = QuantumRegister(1, "q") qc = QuantumCircuit(qr, cr1, cr2) qc.measure(0, 1) qc.reset(0) new_qc = ResetAfterMeasureSimplification()(qc) ans_qc = QuantumCircuit(qr, cr1, cr2) ans_qc.measure(0, 1) ans_qc.x(0).c_if(cr2[0], 1) self.assertEqual(new_qc, ans_qc) def test_simple_multi_reg_null(self): """Test simple, multiple registers, null change""" cr1 = ClassicalRegister(1, "c1") cr2 = ClassicalRegister(1, "c2") qr = QuantumRegister(2, "q") qc = QuantumCircuit(qr, cr1, cr2) qc.measure(0, 1) qc.reset(1) # reset not on same qubit as meas new_qc = ResetAfterMeasureSimplification()(qc) self.assertEqual(new_qc, qc) def test_simple_multi_resets(self): """Only first reset is collapsed""" qc = QuantumCircuit(1, 2) qc.measure(0, 0) qc.reset(0) qc.reset(0) new_qc = ResetAfterMeasureSimplification()(qc) ans_qc = QuantumCircuit(1, 2) ans_qc.measure(0, 0) ans_qc.x(0).c_if(ans_qc.clbits[0], 1) ans_qc.reset(0) self.assertEqual(new_qc, ans_qc) def test_simple_multi_resets_with_resets_before_measure(self): """Reset BEFORE measurement not collapsed""" qc = QuantumCircuit(2, 2) qc.measure(0, 0) qc.reset(0) qc.reset(1) qc.measure(1, 1) new_qc = ResetAfterMeasureSimplification()(qc) ans_qc = QuantumCircuit(2, 2) ans_qc.measure(0, 0) ans_qc.x(0).c_if(Clbit(ClassicalRegister(2, "c"), 0), 1) ans_qc.reset(1) ans_qc.measure(1, 1) self.assertEqual(new_qc, ans_qc) def test_barriers_work(self): """Test that barriers block consolidation""" qc = QuantumCircuit(1, 1) qc.measure(0, 0) qc.barrier(0) qc.reset(0) new_qc = ResetAfterMeasureSimplification()(qc) self.assertEqual(new_qc, qc) def test_bv_circuit(self): """Test Bernstein Vazirani circuit with midcircuit measurement.""" bitstring = "11111" qc = QuantumCircuit(2, len(bitstring)) qc.x(1) qc.h(1) for idx, bit in enumerate(bitstring[::-1]): qc.h(0) if int(bit): qc.cx(0, 1) qc.h(0) qc.measure(0, idx) if idx != len(bitstring) - 1: qc.reset(0) # reset control qc.reset(1) qc.x(1) qc.h(1) new_qc = ResetAfterMeasureSimplification()(qc) for op in new_qc.data: if op.operation.name == "reset": self.assertEqual(op.qubits[0], new_qc.qubits[1]) def test_simple_if_else(self): """Test that the pass recurses into an if-else.""" pass_ = ResetAfterMeasureSimplification() base_test = QuantumCircuit(1, 1) base_test.measure(0, 0) base_test.reset(0) base_expected = QuantumCircuit(1, 1) base_expected.measure(0, 0) base_expected.x(0).c_if(0, True) test = QuantumCircuit(1, 1) test.if_else( (test.clbits[0], True), base_test.copy(), base_test.copy(), test.qubits, test.clbits ) expected = QuantumCircuit(1, 1) expected.if_else( (expected.clbits[0], True), base_expected.copy(), base_expected.copy(), expected.qubits, expected.clbits, ) self.assertEqual(pass_(test), expected) def test_nested_control_flow(self): """Test that the pass recurses into nested control flow.""" pass_ = ResetAfterMeasureSimplification() base_test = QuantumCircuit(1, 1) base_test.measure(0, 0) base_test.reset(0) base_expected = QuantumCircuit(1, 1) base_expected.measure(0, 0) base_expected.x(0).c_if(0, True) body_test = QuantumCircuit(1, 1) body_test.for_loop((0,), None, base_expected.copy(), body_test.qubits, body_test.clbits) body_expected = QuantumCircuit(1, 1) body_expected.for_loop( (0,), None, base_expected.copy(), body_expected.qubits, body_expected.clbits ) test = QuantumCircuit(1, 1) test.while_loop((test.clbits[0], True), body_test, test.qubits, test.clbits) expected = QuantumCircuit(1, 1) expected.while_loop( (expected.clbits[0], True), body_expected, expected.qubits, expected.clbits ) self.assertEqual(pass_(test), expected)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.providers.fake_provider import FakeHanoi backend = FakeHanoi() config = backend.configuration() # Basic Features print("This backend is called {0}, and is on version {1}. It has {2} qubit{3}. It " "{4} OpenPulse programs. The basis gates supported on this device are {5}." "".format(config.backend_name, config.backend_version, config.n_qubits, '' if config.n_qubits == 1 else 's', 'supports' if config.open_pulse else 'does not support', config.basis_gates)) config.dt # units of seconds config.meas_levels config.dtm config.meas_map config.drive(0) config.measure(0) config.acquire(0) props = backend.properties() def describe_qubit(qubit, properties): """Print a string describing some of reported properties of the given qubit.""" # Conversion factors from standard SI units us = 1e6 ns = 1e9 GHz = 1e-9 print("Qubit {0} has a \n" " - T1 time of {1} microseconds\n" " - T2 time of {2} microseconds\n" " - U2 gate error of {3}\n" " - U2 gate duration of {4} nanoseconds\n" " - resonant frequency of {5} GHz".format( qubit, properties.t1(qubit) * us, properties.t2(qubit) * us, properties.gate_error('sx', qubit), properties.gate_length('sx', qubit) * ns, properties.frequency(qubit) * GHz)) describe_qubit(0, props) defaults = backend.defaults() q0_freq = defaults.qubit_freq_est[0] # Hz q0_meas_freq = defaults.meas_freq_est[0] # Hz GHz = 1e-9 print("DriveChannel(0) defaults to a modulation frequency of {} GHz.".format(q0_freq * GHz)) print("MeasureChannel(0) defaults to a modulation frequency of {} GHz.".format(q0_meas_freq * GHz)) calibrations = defaults.instruction_schedule_map print(calibrations) measure_schedule = calibrations.get('measure', range(config.n_qubits)) measure_schedule.draw(backend=backend) # You can use `has` to see if an operation is defined. Ex: Does qubit 3 have an x gate defined? calibrations.has('x', 3) # Some circuit operations take parameters. U1 takes a rotation angle: calibrations.get('u1', 0, P0=3.1415) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/crabster/qiskit-learning
crabster
''' This program implements the quantum Fourier transform (QFT) ''' from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, IBMQ from qiskit.visualization import circuit_drawer as drawer from qiskit.tools.visualization import plot_histogram from qiskit import execute from qiskit import Aer import numpy as np import time, os, shutil from matplotlib.pyplot import plot, draw, show def QFT(q, c, n): qc = QuantumCircuit(q,c) # First get the most significant bit for k in range(n): j = n - k # now add the Hadamard transform to qubit j-1 qc.h(q[j-1]) # now each qubit from the lowest significance # takes one conditional phase shift for i in reversed(range(j-1)): qc.cp(2*np.pi/2**(j-i), q[i], q[j-1]) # Finally swap the qubits for i in range(n//2): qc.swap(q[i], q[n-i-1]) return qc # QFT is represented in a matrix form with 2^n rows and columns # where n represents the number of qubits def QFTmatrix(n): qft = np.zeros([2**n,2**n], dtype=complex) for i in range(2**n): for k in range(2**n): qft[i,k] = np.exp(i*k*2*2j*np.pi/(2**n)) return(1/np.sqrt(2**n)*qft) def QFTcircuit(n): q = QuantumRegister(n, "q") c = ClassicalRegister(n, "c") qc = QFT(q, c, n) backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) actual = job.result().get_unitary() np.around(actual, 2) expected = QFTmatrix(n) delta = actual - expected print("Deviation: ", round(np.linalg.norm(delta), 10)) return qc LaTex_folder_QFT = str(os.getcwd())+'/Latex_quantum_gates/Quantum_Fourier_transform/' if not os.path.exists(LaTex_folder_QFT): os.makedirs(LaTex_folder_QFT) else: shutil.rmtree(LaTex_folder_QFT) os.makedirs(LaTex_folder_QFT) n=4 qc = QFTcircuit(n) # create a LaTex file for the algorithm LaTex_code = qc.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit f_name = 'Quantum_Four_transform_'+str(n)+'qubits.tex' with open(LaTex_folder_QFT+f_name, 'w') as f: f.write(LaTex_code) n = 4 q = QuantumRegister(n, "x") c = ClassicalRegister(n, "c") qftCircuit = QFT(q, c, n) initCircuit = QuantumCircuit(q, c) for qubit in q: initCircuit.h(qubit) initCircuit.barrier(q) qc = QuantumCircuit.compose(initCircuit, qftCircuit) qc.barrier(q) qc.measure(q, c) # on simulator backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend) k = job.result().get_counts() print(k) # on a real quantum computer provider = IBMQ.load_account() backend = provider.backend.ibmq_lima print("Status of backened: ", backend.status()) job = execute(qc, backend=backend, shots = 1024) lapse = 0 print("This step might take some time.") time.sleep(3) interval = 60 while((job.status().name != 'DONE') and (job.status().name != 'Cancelled') and (job.status().name != 'ERROR')): print('Status @ {} seconds'.format(interval * lapse)) print(job.status()) print(job.queue_position()) time.sleep(interval) lapse +=1 print(job.status()) plt = plot_histogram(job.result().get_counts())
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import * # Create a Quantum Circuit acting on a quantum register of three qubits circ = QuantumCircuit(3) # Add a H gate on qubit $q_{0}$, putting this qubit in superposition. circ.h(0) # Add a CX (CNOT) gate on control qubit $q_{0}$ and target qubit $q_{1}$, putting # the qubits in a Bell state. circ.cx(0, 1) # Add a CX (CNOT) gate on control qubit $q_{0}$ and target qubit $q_{2}$, putting # the qubits in a GHZ state. circ.cx(0, 2) circ.draw('mpl') # Import Aer from qiskit import Aer # Run the quantum circuit on a statevector simulator backend backend = Aer.get_backend('statevector_simulator') # Create a Quantum Program for execution job = backend.run(circ) result = job.result() outputstate = result.get_statevector(circ, decimals=3) print(outputstate) from qiskit.visualization import plot_state_city plot_state_city(outputstate) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = backend.run(circ) result = job.result() # Show the results print(result.get_unitary(circ, decimals=3)) # Create a Quantum Circuit meas = QuantumCircuit(3, 3) meas.barrier(range(3)) # map the quantum measurement to the classical bits meas.measure(range(3), range(3)) # The Qiskit circuit object supports composition using # the compose method. circ.add_register(meas.cregs[0]) qc = circ.compose(meas) #drawing the circuit qc.draw() # Use Aer's qasm_simulator backend_sim = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator. # We've set the number of repeats of the circuit # to be 1024, which is the default. job_sim = backend_sim.run(transpile(qc, backend_sim), shots=1024) # Grab the results from the job. result_sim = job_sim.result() counts = result_sim.get_counts(qc) print(counts) from qiskit.visualization import plot_histogram plot_histogram(counts) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/jcylim/QiskitProject
jcylim
# useful additional packages import matplotlib.pyplot as plt #%matplotlib inline import numpy as np from pprint import pprint # importing QISKit from qiskit import QuantumProgram, QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import available_backends, execute, register, least_busy # import basic plot tools from qiskit.tools.visualization import plot_histogram, circuit_drawer qx_config = { "APItoken": 'dcdb2d9414a625c1f57373c544add3711c78c3d7faf39397fe2c41887110e8b59caf81bcb2bc32714d936da41a261fea510f96df379afcbdfa9df6cc6bfe3829', "url": 'https://quantumexperience.ng.bluemix.net/api' } backend = 'local_qasm_simulator' # run on local simulator by default '''register(qx_config['APItoken'], qx_config['url']) backend = least_busy(available_backends({'simulator': False, 'local': False})) print("the best backend is " + backend) ''' # Creating registers q2 = QuantumRegister(2) c2 = ClassicalRegister(2) # quantum circuit to make an entangled bell state bell = QuantumCircuit(q2, c2) bell.h(q2[0]) bell.cx(q2[0], q2[1]) # quantum circuit to measure q0 in the standard basis measureIZ = QuantumCircuit(q2, c2) measureIZ.measure(q2[0], c2[0]) bellIZ = bell+measureIZ # quantum circuit to measure q0 in the superposition basis measureIX = QuantumCircuit(q2, c2) measureIX.h(q2[0]) measureIX.measure(q2[0], c2[0]) bellIX = bell+measureIX # quantum circuit to measure q1 in the standard basis measureZI = QuantumCircuit(q2, c2) measureZI.measure(q2[1], c2[1]) bellZI = bell+measureZI # quantum circuit to measure q1 in the superposition basis measureXI = QuantumCircuit(q2, c2) measureXI.h(q2[1]) measureXI.measure(q2[1], c2[1]) bellXI = bell+measureXI # quantum circuit to measure q in the standard basis measureZZ = QuantumCircuit(q2, c2) measureZZ.measure(q2[0], c2[0]) measureZZ.measure(q2[1], c2[1]) bellZZ = bell+measureZZ # quantum circuit to measure q in the superposition basis measureXX = QuantumCircuit(q2, c2) measureXX.h(q2[0]) measureXX.h(q2[1]) measureXX.measure(q2[0], c2[0]) measureXX.measure(q2[1], c2[1]) bellXX = bell+measureXX # quantum circuit to make a mixed state mixed1 = QuantumCircuit(q2, c2) mixed2 = QuantumCircuit(q2, c2) mixed2.x(q2) mixed1.h(q2[0]) mixed1.h(q2[1]) mixed1.measure(q2[0], c2[0]) mixed1.measure(q2[1], c2[1]) mixed2.h(q2[0]) mixed2.h(q2[1]) mixed2.measure(q2[0], c2[0]) mixed2.measure(q2[1], c2[1]) '''circuits = [bellIZ,bellIX,bellZI,bellXI,bellZZ,bellXX] job = execute(circuits, backend) result = job.result() print(result.get_counts(bellXX)) plot_histogram(result.get_counts(bellXX))''' mixed_state = [mixed1,mixed2] job = execute(mixed_state, backend) result = job.result() counts1 = result.get_counts(mixed_state[0]) counts2 = result.get_counts(mixed_state[1]) from collections import Counter ground = Counter(counts1) excited = Counter(counts2) plot_histogram(ground+excited)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.visualization.timeline import draw as timeline_draw from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeBoeblingen backend = FakeBoeblingen() ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) circ = transpile(ghz, backend, scheduling_method="asap") timeline_draw(circ)
https://github.com/jdellaverson19/qiskit2020
jdellaverson19
from dj import DeutschJozsa import dj import time import sys from random import seed from random import randint import numpy as np import matplotlib.pyplot as plt import numpy as np from qiskit import * def main(): djObject = DeutschJozsa() # constants QUBIT_RANGE = 65 ITERATIONS = 10 worked = np.zeros(shape=(QUBIT_RANGE, ITERATIONS)) timing = np.zeros(shape=(QUBIT_RANGE, ITERATIONS)) print('Testing out Deutsch-Jozsa alorithm...') seed(3) for n in range(0,QUBIT_RANGE): print(f'Trying {n+2}-qubit machine...') for j in range(ITERATIONS): print(f'Iteration {j+1}...') # randomly decide f const_val = randint(0,1) def f_constant(_): return const_val def f_balanced(x): return x%2 constant = randint(0,1) f = f_constant if constant else f_balanced print(constant) oracle = dj.dj_oracle(constant, n+2) start = time.perf_counter() result = djObject.run(f,oracle, n+2) end = time.perf_counter() # print('worked' if result == constant else 'failed') timing[n][j] = (end - start) qubit_values = [] for i in range(QUBIT_RANGE): qubit_values += [i+2] average_runtimes = [] for i in range(QUBIT_RANGE): average_runtimes += [np.mean(timing[i])] plt.plot(qubit_values, average_runtimes) plt.ylabel('Runtime (s)') plt.xlabel('Number of Qubits') plt.xticks(qubit_values) plt.title('Quantum Simulation Scaling for Deutsch-Jozsa Algorithm') plt.show() if __name__ == "__main__": main()
https://github.com/ericardomuten/qiskit-advocate-mentorship
ericardomuten
# Mount Google Drive from google.colab import drive # import drive from google colab ROOT = "/content/drive" # default location for the drive print(ROOT) # print content of ROOT (Optional) drive.mount(ROOT) # we mount the google drive at /content/drive !pip install pennylane from IPython.display import clear_output clear_output() import os def restart_runtime(): os.kill(os.getpid(), 9) restart_runtime() # %matplotlib inline import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import numpy as np import tensorflow as tf from tensorflow.keras.utils import to_categorical (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() x_train_flatten = x_train.reshape(x_train.shape[0], x_train.shape[1]*x_train.shape[2])/255.0 x_test_flatten = x_test.reshape(x_test.shape[0], x_test.shape[1]*x_test.shape[2])/255.0 print(x_train_flatten.shape, y_train.shape) print(x_test_flatten.shape, y_test.shape) x_train_0 = x_train_flatten[y_train == 0] x_train_1 = x_train_flatten[y_train == 1] x_train_2 = x_train_flatten[y_train == 2] x_train_3 = x_train_flatten[y_train == 3] x_train_4 = x_train_flatten[y_train == 4] x_train_5 = x_train_flatten[y_train == 5] x_train_6 = x_train_flatten[y_train == 6] x_train_7 = x_train_flatten[y_train == 7] x_train_8 = x_train_flatten[y_train == 8] x_train_9 = x_train_flatten[y_train == 9] x_train_list = [x_train_0, x_train_1, x_train_2, x_train_3, x_train_4, x_train_5, x_train_6, x_train_7, x_train_8, x_train_9] print(x_train_0.shape) print(x_train_1.shape) print(x_train_2.shape) print(x_train_3.shape) print(x_train_4.shape) print(x_train_5.shape) print(x_train_6.shape) print(x_train_7.shape) print(x_train_8.shape) print(x_train_9.shape) x_test_0 = x_test_flatten[y_test == 0] x_test_1 = x_test_flatten[y_test == 1] x_test_2 = x_test_flatten[y_test == 2] x_test_3 = x_test_flatten[y_test == 3] x_test_4 = x_test_flatten[y_test == 4] x_test_5 = x_test_flatten[y_test == 5] x_test_6 = x_test_flatten[y_test == 6] x_test_7 = x_test_flatten[y_test == 7] x_test_8 = x_test_flatten[y_test == 8] x_test_9 = x_test_flatten[y_test == 9] x_test_list = [x_test_0, x_test_1, x_test_2, x_test_3, x_test_4, x_test_5, x_test_6, x_test_7, x_test_8, x_test_9] print(x_test_0.shape) print(x_test_1.shape) print(x_test_2.shape) print(x_test_3.shape) print(x_test_4.shape) print(x_test_5.shape) print(x_test_6.shape) print(x_test_7.shape) print(x_test_8.shape) print(x_test_9.shape) num_sample = 200 n_class = 2 mult_test = 2.5 X_train = x_train_list[0][:num_sample, :] X_test = x_test_list[0][:int(mult_test*num_sample), :] Y_train = np.zeros((n_class*X_train.shape[0],), dtype=int) Y_test = np.zeros((n_class*X_test.shape[0],), dtype=int) for i in range(n_class-1): X_train = np.concatenate((X_train, x_train_list[i+1][:num_sample, :]), axis=0) Y_train[num_sample*(i+1):num_sample*(i+2)] = int(i+1) X_test = np.concatenate((X_test, x_test_list[i+1][:int(mult_test*num_sample), :]), axis=0) Y_test[int(mult_test*num_sample*(i+1)):int(mult_test*num_sample*(i+2))] = int(i+1) print(X_train.shape, Y_train.shape) print(X_test.shape, Y_test.shape) def normalize(X, use_params=False, params=None): """Normalize the given dataset X Args: X: ndarray, dataset Returns: (Xbar, mean, std): tuple of ndarray, Xbar is the normalized dataset with mean 0 and standard deviation 1; mean and std are the mean and standard deviation respectively. Note: You will encounter dimensions where the standard deviation is zero, for those when you do normalization the normalized data will be NaN. Handle this by setting using `std = 1` for those dimensions when doing normalization. """ if use_params: mu = params[0] std_filled = [1] else: mu = np.mean(X, axis=0) std = np.std(X, axis=0) #std_filled = std.copy() #std_filled[std==0] = 1. Xbar = (X - mu)/(std + 1e-8) return Xbar, mu, std X_train, mu_train, std_train = normalize(X_train) X_train.shape, Y_train.shape X_test = (X_test - mu_train)/(std_train + 1e-8) X_test.shape, Y_test.shape from sklearn.decomposition import PCA from matplotlib import pyplot as plt num_component = 6 pca = PCA(n_components=num_component, svd_solver='full') pca.fit(X_train) np.cumsum(pca.explained_variance_ratio_) X_train = pca.transform(X_train) X_test = pca.transform(X_test) print(X_train.shape, Y_train.shape) print(X_test.shape, Y_test.shape) X_train = (X_train.T / np.sqrt(np.sum(X_train ** 2, -1))).T X_test = (X_test.T / np.sqrt(np.sum(X_test ** 2, -1))).T plt.scatter(X_train[:100, 0], X_train[:100, 1]) plt.scatter(X_train[100:200, 0], X_train[100:200, 1]) plt.scatter(X_train[200:300, 0], X_train[200:300, 1]) import pennylane as qml from pennylane import numpy as np from pennylane.optimize import AdamOptimizer, GradientDescentOptimizer qml.enable_tape() # Set a random seed np.random.seed(42) # Define output labels as quantum state vectors # def density_matrix(state): # """Calculates the density matrix representation of a state. # Args: # state (array[complex]): array representing a quantum state vector # Returns: # dm: (array[complex]): array representing the density matrix # """ # return state * np.conj(state).T label_0 = [[1], [0]] label_1 = [[0], [1]] def density_matrix(state): """Calculates the density matrix representation of a state. Args: state (array[complex]): array representing a quantum state vector Returns: dm: (array[complex]): array representing the density matrix """ return np.outer(state, np.conj(state)) state_labels = [label_0, label_1] #state_labels = np.loadtxt('./tetra_states.txt', dtype=np.complex_) dm_labels = [density_matrix(state_labels[i]) for i in range(2)] len(dm_labels) dm_labels n_qubits = 2 # number of class dev_fc = qml.device("default.qubit", wires=n_qubits) @qml.qnode(dev_fc) def q_fc(params, inputs): """A variational quantum circuit representing the DRC. Args: params (array[float]): array of parameters inputs = [x, y] x (array[float]): 1-d input vector y (array[float]): single output state density matrix Returns: float: fidelity between output state and input """ # layer iteration for l in range(len(params[0])): # qubit iteration for q in range(n_qubits): # gate iteration for g in range(int(len(inputs)/3)): qml.Rot(*(params[0][l][3*g:3*(g+1)] * inputs[3*g:3*(g+1)] + params[1][l][3*g:3*(g+1)]), wires=q) return [qml.expval(qml.Hermitian(dm_labels[i], wires=[i])) for i in range(n_qubits)] X_train[0].shape a = np.random.uniform(size=(2, 1, 6)) q_fc(a, X_train[0]) tetra_class = np.loadtxt('./tetra_class_label.txt') binary_class = np.array([[1, 0], [0, 1]]) class_labels = binary_class n_class = 2 temp = np.zeros((len(Y_train), n_class)) for i in range(len(Y_train)): temp[i, :] = class_labels[Y_train[i]] Y_train = temp temp = np.zeros((len(Y_test), n_class)) for i in range(len(Y_test)): temp[i, :] = class_labels[Y_test[i]] Y_test = temp Y_train.shape, Y_test.shape from keras import backend as K # Alpha Custom Layer class class_weights(tf.keras.layers.Layer): def __init__(self): super(class_weights, self).__init__() w_init = tf.random_normal_initializer() self.w = tf.Variable( initial_value=w_init(shape=(1, 2), dtype="float32"), trainable=True, ) def call(self, inputs): return (inputs * self.w) n_component = 6 X = tf.keras.Input(shape=(n_component,), name='Input_Layer') # Quantum FC Layer, trainable params = 18*L*n_class + 2, output size = 2 num_fc_layer = 3 q_fc_layer_0 = qml.qnn.KerasLayer(q_fc, {"params": (2, num_fc_layer, n_component)}, output_dim=2)(X) # Alpha Layer alpha_layer_0 = class_weights()(q_fc_layer_0) model = tf.keras.Model(inputs=X, outputs=alpha_layer_0) model(X_train[0:32]) opt = tf.keras.optimizers.Adam(learning_rate=0.1) model.compile(opt, loss='mse', metrics=["accuracy"]) filepath = "./Model_2/2_PCA_QFC_saved-model-{epoch:02d}.hdf5" checkpoint = tf.keras.callbacks.ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_weights_only=True, save_best_only=False, mode='auto') H = model.fit(X_train, Y_train, epochs=10, batch_size=32, initial_epoch=0, validation_data=(X_test, Y_test), verbose=1, callbacks=[checkpoint]) # another run to get 10 different set of weights # 3 layer, 6 components model.weights # another run to get 10 different set of weights # 3 layer, 6 components H.history # 3 layer, 3 components H.history # 2 layer, 3 components H.history # 1 layer, 3 components H.history # 3 layer, 6 components H.history # 2 layer, 6 components H.history # 1 layer, 6 components H.history model.summary() # 3 layer, 6 components model.weights # random weights model.weights QFC_weights = np.array([[[-0.23825717, -0.6927138 , 1.9275627 , -0.6338903 , -1.5635191 , -0.54419893], [-1.7943736 , 0.6555091 , 0.7756721 , -0.52433693, 0.33494785, 0.5896128 ], [-1.93925 , 0.26347128, -1.0761861 , 0.1370001 , 0.7956914 , 0.43674225]], [[ 0.04991536, 0.4438185 , 0.28958392, 0.17212974, -0.5826888 , 0.1689779 ], [-0.05101966, -0.45951375, -0.7024131 , -0.51385176, -1.2483467 , -0.46147949], [-0.37164477, -0.980824 , -0.43812418, -0.7645581 , -0.8557718 , -0.01652514]]]) alpha_weights = np.array([[1.0457449, 1.0058646]]) random_weights = np.array([[[-0.01116788, -0.24572456, -0.34748596, 0.12041545, -0.26595542, -0.18240207], [ 0.3004377 , 0.5260234 , 0.35336393, 0.19536716, 0.01010054, -0.40111852], [ 0.5502764 , -0.18851322, -0.25431797, -0.24531147, 0.07113147, -0.37417513]], [[-0.44977266, 0.34296083, 0.51045287, -0.2749984 , 0.41424918, -0.4837346 ], [ 0.10718679, 0.507282 , 0.07516974, -0.4324274 , 0.36671913, 0.3184935 ], [ 0.49623525, 0.49480498, 0.4315616 , 0.46681094, -0.12224993, -0.14642656]]]) QFC_weights.shape, alpha_weights.shape, random_weights.shape # sanity check pred = [] random_pred = [] for i in range(len(X_test)): pred += [np.argmax(q_fc(QFC_weights, X_test[i]).numpy())] random_pred += [np.argmax(q_fc(random_weights, X_test[i]).numpy())] n_qubits = 1 dev_state = qml.device("default.qubit", wires=n_qubits) @qml.qnode(dev_state) def q_fc_state(params, inputs): """A variational quantum circuit representing the DRC. Args: params (array[float]): array of parameters inputs = [x, y] x (array[float]): 1-d input vector y (array[float]): single output state density matrix Returns: float: fidelity between output state and input """ # layer iteration for l in range(len(params[0])): # qubit iteration for q in range(n_qubits): # gate iteration for g in range(int(len(inputs)/3)): qml.Rot(*(params[0][l][3*g:3*(g+1)] * inputs[3*g:3*(g+1)] + params[1][l][3*g:3*(g+1)]), wires=q) return qml.expval(qml.Hermitian(dm_labels[0], wires=[0])) q_fc_state(QFC_weights, X_test[0]) dev_state._state train_state = np.zeros((len(X_train), 2), dtype=np.complex_) test_state = np.zeros((len(X_test), 2), dtype=np.complex_) for i in range(len(train_state)): q_fc_state(QFC_weights, X_train[i]) temp = np.flip(dev_state._state) train_state[i, :] = temp for i in range(len(test_state)): q_fc_state(QFC_weights, X_test[i]) temp = np.flip(dev_state._state) test_state[i, :] = temp np.conj(train_state[150]) @ dm_labels[0] @ train_state[150] train_state[0] @ np.conj(train_state[0]) np.conj(test_state[0]) @ dm_labels[0] @ test_state[0] np.savetxt('./2_PCA_QFC-State_Train.txt', train_state) np.savetxt('./2_PCA_QFC-State_Test.txt', test_state) train_state = np.zeros((len(X_train), 2), dtype=np.complex_) test_state = np.zeros((len(X_test), 2), dtype=np.complex_) for i in range(len(train_state)): q_fc_state(random_weights, X_train[i]) temp = np.flip(dev_state._state) train_state[i, :] = temp for i in range(len(test_state)): q_fc_state(random_weights, X_test[i]) temp = np.flip(dev_state._state) test_state[i, :] = temp np.conj(train_state[0]) @ dm_labels[0] @ train_state[0] train_state[0] @ np.conj(train_state[0]) np.savetxt('./2_PCA_QFC-RandomState_Train.txt', train_state) np.savetxt('./2_PCA_QFC-RandomState_Test.txt', test_state) random_weights = np.array(model.get_weights()[0], dtype=float) QFC_weights_list = [random_weights] for i in range(10): if i == 9: model.load_weights('./Model_2/2_PCA_QFC_saved-model-' + str(i+1) + '.hdf5') else: model.load_weights('./Model_2/2_PCA_QFC_saved-model-0' + str(i+1) + '.hdf5') QFC_weights_list += [np.array(model.get_weights()[0], dtype=float)] len(QFC_weights_list) n_qubits = 1 dev_state = qml.device("default.qubit", wires=n_qubits) @qml.qnode(dev_state) def q_fc_state(params, inputs): """A variational quantum circuit representing the DRC. Args: params (array[float]): array of parameters inputs = [x, y] x (array[float]): 1-d input vector y (array[float]): single output state density matrix Returns: float: fidelity between output state and input """ # layer iteration for l in range(len(params[0])): # qubit iteration for q in range(n_qubits): # gate iteration for g in range(int(len(inputs)/3)): qml.Rot(*(params[0][l][3*g:3*(g+1)] * inputs[3*g:3*(g+1)] + params[1][l][3*g:3*(g+1)]), wires=q) return qml.expval(qml.Hermitian(dm_labels[0], wires=[0])) q_fc_state(QFC_weights_list[0], X_test[0]) for k in range(10+1): train_state = np.zeros((len(X_train), 2), dtype=np.complex_) test_state = np.zeros((len(X_test), 2), dtype=np.complex_) for i in range(len(train_state)): q_fc_state(QFC_weights_list[k], X_train[i]) temp = np.flip(dev_state._state) train_state[i, :] = temp for i in range(len(test_state)): q_fc_state(QFC_weights_list[k], X_test[i]) temp = np.flip(dev_state._state) test_state[i, :] = temp print(train_state.shape, test_state.shape) np.savetxt('./Model_2/2_PCA_QFC-State_Train_Epoch=' + str(k) + '.txt', train_state) np.savetxt('./Model_2/2_PCA_QFC-State_Test_Epoch=' + str(k) + '.txt', test_state)
https://github.com/Qiskit/feedback
Qiskit
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap from sklearn.svm import SVC, LinearSVC from sklearn.datasets import make_blobs # blue color_0 = '#1f77b4' color_0_light = '#8fbbd9' # orange color_1 = '#ff7f0e' color_1_light = '#ffbf86' cmap = LinearSegmentedColormap.from_list('blue_orange', [color_0_light, '#FFFFFF', color_1_light], N=100) X, y = make_blobs(n_samples=50, n_features=2, centers=np.array([[0,0], [4,4]]), random_state=9) X[:, 0] = 2* X[:, 0] svc = SVC(kernel='linear') svc.fit(X, y) fig, ax = plt.subplots(figsize=(12, 8)) s = 100 # decision boundary x = np.linspace(-2, 10, 50) ax.plot(x, - 1/svc.coef_[0][1] * (svc.coef_[0][0]*x + svc.intercept_), color='k') # margin b_0 = np.dot(svc.support_vectors_[0], svc.coef_[0]) ax.plot(x, - 1/svc.coef_[0][1] * (svc.coef_[0][0]*x - b_0), color='k', linestyle=':', zorder=0) b_1 = np.dot(svc.support_vectors_[1], svc.coef_[0]) ax.plot(x, - 1/svc.coef_[0][1] * (svc.coef_[0][0]*x - b_1), color='k', linestyle=':', zorder=0) # data ax.scatter(X[:,0][y==0], X[:,1][y==0], color=color_0, s=s) ax.scatter(X[:,0][y==1], X[:,1][y==1], color=color_1, s=s) # highlight support vectors ax.scatter(X[:,0][svc.support_][y[svc.support_]==0], X[:,1][svc.support_][y[svc.support_]==0], color=color_0, edgecolors='k', s=s, linewidth=3) ax.scatter(X[:,0][svc.support_][y[svc.support_]==1], X[:,1][svc.support_][y[svc.support_]==1], color=color_1, edgecolors='k', s=s, linewidth=3) # cosmetics ax.set(ylim=(-2, 6), xlim=(-2, 10)) ax.text(7.1, -0.1, r'$\frac{2}{||w||}$', fontdict={'size': 20}, color='g') x_margin = np.linspace(7.75, 8.57, 2) ax.plot(x_margin, 1/svc.coef_[0][0] * (svc.coef_[0][1]*x_margin - 7) , color='g', linestyle='--', marker='o') ax.set_aspect(1) import sys import os from sklearn.preprocessing import MinMaxScaler from qiskit import BasicAer from qiskit.utils import QuantumInstance, algorithm_globals from qiskit.circuit.library import ZFeatureMap, ZZFeatureMap from qiskit_machine_learning.kernels import QuantumKernel # import the implementation of Pegasos sys.path.insert(1, os.path.join(sys.path[0], 'C:/Users/4rnet/git/qiskit-machine-learning/qiskit_machine_learning/algorithms/classifiers/')) from pegasos_qsvc import PegasosQSVC def make_meshgrid(X, h=.02): """ :param X: ndarray of shape (x_samples, 2) :param h: float, stepsize for meshgrid :return: ndarray """ assert X.shape[1] == 2 x_min, x_max = X[:,0].min() - 0.1*X[:,0].max(), X[:,0].max() + 0.1*X[:,0].max() y_min, y_max = X[:,1].min() - 0.1*X[:,1].max(), X[:,1].max() + 0.1*X[:,1].max() xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) return xx, yy # example dataset sample, label = make_blobs( n_samples=20, n_features=2, centers=2, random_state=3, shuffle=True ) # preprocessing to ensure compatibility with the rotation encoding sample = MinMaxScaler(feature_range=(0, np.pi)).fit_transform(sample) # split into train and test set sample_train = sample[:15] label_train = label[:15] sample_test = sample[15:] label_test = label[15:] # number of qubits is equal to the number of features q = 2 # number of steps performed during the training procedure tau = 100 # regularization parameter C = 1000 feature_map = ZFeatureMap(feature_dimension=q, reps=1) statevector_simulator = QuantumInstance( BasicAer.get_backend("statevector_simulator"), shots=1, seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, ) qkernel = QuantumKernel( feature_map=feature_map, quantum_instance=statevector_simulator ) pegasos_qsvc = PegasosQSVC(quantum_kernel=qkernel, C=C, num_steps=tau) # training pegasos_qsvc.fit(sample_train, label_train) # testing score = pegasos_qsvc.score(sample_test, label_test) print(f'test score = {score}') # plot fig, ax = plt.subplots(figsize=(12,12)) xx, yy = make_meshgrid(sample_train[:, :2], h=0.1) # prediction Z = pegasos_qsvc.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) ax.pcolormesh(xx, yy, Z, cmap=cmap, shading='auto') # data ax.scatter(sample_train[:,0][label_train==0], sample_train[:,1][label_train==0], color=color_0) ax.scatter(sample_train[:,0][label_train==1], sample_train[:,1][label_train==1], color=color_1) pegasos_qsvc = PegasosQSVC(C=C, num_steps=tau, precomputed=True) # training kernel_matrix_train = qkernel.evaluate(sample_train, sample_train) pegasos_qsvc.fit(kernel_matrix_train, label_train) # testing kernel_matrix_test = qkernel.evaluate(sample_test, sample_train) score = pegasos_qsvc.score(kernel_matrix_test, label_test) print(f'test score = {score}')
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
from qiskit_chemistry import FermionicOperator, QMolecule from qiskit_chemistry.aqua_extensions.components.initial_states import HartreeFock from qiskit_chemistry.aqua_extensions.components.variational_forms import UCCSD from qiskit_chemistry import QMolecule as qm from qiskit_aqua.components.optimizers import COBYLA from qiskit_aqua import Operator from qiskit_aqua.algorithms import VQE, ExactEigensolver from qiskit import Aer from scipy import linalg as la import numpy as np import yaml as yml from yaml import SafeLoader as Loader import os import Load_Hamiltonians as lh ##Carefully upgrade terra to see if qasm/state-vector simulator perform quicker.## #################### WALK ROOT DIR ############################ root_dir = 'IntegralData/vqe-data-master/Li2_cc-pVTZ/4_ORBITALS' data_file_list = [] data_file_list_oe = [] for dirName, subdirList, fileList in os.walk(root_dir): print('Found directory: %s' % dirName) for fname in sorted(fileList): if fname.endswith('.yaml'): data_file_list.append(fname) if fname.endswith('.FOCK'): data_file_list_oe.append(fname) #This 'del' is four the 4-orbital case since the OEs are missing for the distance 13... #This should be resolved for the future del data_file_list[-1] #I added an x in front of the 10s for distance to force the sorting, else it sees 13 as 1 #If any distance is in the 100s (unlikely) then add a 'y' in front of dist in file name ############################################################### ############# Output Files to Plot stuff ############### print(data_file_list) Fout = open('Li2_ExactEnergies_wMP2_4-orbitals_061219.dat',"w") Fout_op = open('Li2_OptimalParams_wMP2_4-orbitals_061219.dat',"w") #Fout = open('Li2_ExactEnergiesG&FE_wMP2_4-orbitals_052919.dat',"w") ########################################################### #Variables that can be assigned outside of Loop map_type = str('jordan_wigner') truncation_threshold = 0.01 ################# IBM BACKEND ##################### backend1 = Aer.get_backend('statevector_simulator') backend2 = Aer.get_backend('qasm_simulator') ################################################### output_data = [] #Looping over all of the yaml files in a particular directory and saving the energies from VQE and Exact ind = 0 for file1, file2 in zip(data_file_list, data_file_list_oe): NW_data_file = str(os.path.join(root_dir,file1)) OE_data_file = str(os.path.join(root_dir+'/DOWNFOLDED_ORBITAL_ENERGIES',file2)) try: doc = open(NW_data_file, 'r') doc_oe = open(OE_data_file,'r') data = yml.load(doc, Loader) content_oe = doc_oe.readlines() finally: doc.close() doc_oe.close() #Import all the data from a yaml file print('Getting data') n_spatial_orbitals = data['integral_sets'][0]['n_orbitals'] nuclear_repulsion_energy = data['integral_sets'][0]['coulomb_repulsion']['value'] n_orbitals = 2 * n_spatial_orbitals n_particles = data['integral_sets'][0]['n_electrons'] dist = 2 * data['integral_sets'][0]['geometry']['atoms'][1]['coords'][2] print('Bond distance is {}'.format(dist)) if map_type == 'parity': # For two-qubit reduction n_qubits = n_orbitals - 2 else: n_qubits = n_orbitals # Populating the QMolecule class with the data to make calculations easier qm.num_orbitals = n_spatial_orbitals qm.num_alpha = n_particles // 2 qm.num_beta = n_particles // 2 qm.core_orbitals = 0 qm.nuclear_repulsion_energy = nuclear_repulsion_energy qm.hf_energy = data['integral_sets'][0]['scf_energy']['value'] ###################Get Orbital Energies from FOCK file######################## orbital_energies = [] found = False count = 0 for line in content_oe: if 'Eigenvalues:' in line.split()[0]: found = True if found and len(line.split()) > 1: orbital_energies.append(float(line.split()[1])) count += 1 if count >= n_spatial_orbitals: break qm.orbital_energies = orbital_energies print('OEs:\n',orbital_energies) ############################################################################## #Importing the integrals one_electron_import = data['integral_sets'][0]['hamiltonian']['one_electron_integrals']['values'] two_electron_import = data['integral_sets'][0]['hamiltonian']['two_electron_integrals']['values'] #Getting spatial integrals and spin integrals to construct Hamiltonian one_electron_spatial_integrals, two_electron_spatial_integrals = lh.get_spatial_integrals(one_electron_import, two_electron_import, n_spatial_orbitals) one_electron_spatial_integrals, two_electron_spatial_integrals = lh.trunctate_spatial_integrals( one_electron_spatial_integrals, two_electron_spatial_integrals, .001) h1, h2 = lh.convert_to_spin_index(one_electron_spatial_integrals, two_electron_spatial_integrals, n_spatial_orbitals, truncation_threshold) #For the MP2 Calculation qm.mo_eri_ints = two_electron_spatial_integrals #Constructing the fermion operator and qubit operator from integrals data fop = FermionicOperator(h1, h2) qop_paulis = fop.mapping(map_type) qop = Operator(paulis=qop_paulis.paulis) #Get Variational form and intial state init_state = HartreeFock(n_qubits, n_orbitals, n_particles, map_type, two_qubit_reduction=False) var_op = UCCSD(n_qubits, 1, n_orbitals, n_particles, active_occupied=None, active_unoccupied=None, initial_state=init_state, qubit_mapping=map_type, mp2_reduction=True) ######################## VQE RESULT ############################### # setup a classical optimizer for VQE max_eval = 200 optimizer = COBYLA(maxiter=max_eval, disp=True, tol=1e-3) #Choosing initial params based on previous iteration if ind == 0: # initial_params = var_op._mp2_coeff initial_params = None ind += 1 elif len(vqe_params) == var_op.num_parameters: initial_params = vqe_params else: initial_params = None print('Doing VQE') algorithm = VQE(qop_paulis,var_op,optimizer,'paulis', initial_point=initial_params, ) #VQE_Circ = algorithm.construct_circuit(dumpy_params, backend1) #print('The VQE circuit:\n',VQE_Circ) result = algorithm.run(backend1) vqe_energy = result['energy'] + nuclear_repulsion_energy vqe_params = result['opt_params'] # print('The VQE energy is: ',vqe_energy) # print('The optimized params are {}.'.format(vqe_params)) ################################################################### ################### EXACT RESULT ################################## exact_eigensolver = ExactEigensolver(qop, k=2) ret = exact_eigensolver.run() print('The electronic energy is: {:.12f}'.format(ret['eigvals'][0].real)) print('The total FCI energy is: {:.12f}'.format(ret['eigvals'][0].real + nuclear_repulsion_energy)) exact_energy = ret['eigvals'][0].real + nuclear_repulsion_energy exact_energy_fe = ret['eigvals'][1].real + nuclear_repulsion_energy qop.to_matrix() #print(qop) # eigval, eigvec = np.linalg.eigh(qop.matrix.toarray()) # exact_energy = eigval[0].real + nuclear_repulsion_energy # exact_energy_fe = eigval[1].real + nuclear_repulsion_energy # print('{} is the groundstate energy and {} is the first excited state'.format(eigval[0].real,eigval[1].real)) # print('Groundstate: \n', eigv[:,0]) # print('First excited state: \n', eigv[:, 0]) ################################################################### # The outputs to plot my_info = [dist,exact_energy,vqe_energy] param_info = [dist,vqe_params] # my_info = [dist, exact_energy,eigval[1].real + nuclear_repulsion_energy, eigval[2].real + nuclear_repulsion_energy, eigval[3].real\ # + nuclear_repulsion_energy, eigval[4].real + nuclear_repulsion_energy, eigval[5].real + nuclear_repulsion_energy, \ # eigval[6].real + nuclear_repulsion_energy, eigval[7].real + nuclear_repulsion_energy, eigval[8].real + nuclear_repulsion_energy, eigval[9].real + nuclear_repulsion_energy, \ # eigval[10].real + nuclear_repulsion_energy, eigval[11].real + nuclear_repulsion_energy] output_data.append(my_info) my_info_to_str = " ".join(str(e) for e in my_info) params_to_str = " ".join(str(e) for e in param_info) Fout.write(my_info_to_str + "\n") Fout_op.write(params_to_str + "\n") print(output_data) Fout.close() Fout_op.close() # output_data[:,0] = np.sort(output_data[:,0],axis=0) # print(output_data)
https://github.com/usamisaori/qLipschitz
usamisaori
from sklearn import datasets import pennylane as qml import numpy as np from pennylane.optimize import AdamOptimizer import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') X_train, Y_train = datasets.make_circles(n_samples=200, noise=0.09, factor=0.4) X_test, Y_test = datasets.make_circles(n_samples=50, noise=0.09, factor=0.4) print('Training Data:') print(X_train[:10]) print('\nTraining Label:') print(Y_train[:10]) plt.scatter(X_train[:, 0], X_train[:, 1], c=Y_train) plt.show() print(f'Total datas: {len(X_train)}') print(f'labels: {list(set(Y_train))}') print(f'label 0 datas: {len(list(filter(lambda x: x==0, Y_train)))}') print(f'label 1 datas: {len(list(filter(lambda x: x==1, Y_train)))}') Z_train = (X_train[:, 0] ** 2 + X_train[:, 1] ** 2) ** 0.5 temp = np.zeros((X_train.shape[0], len(X_train[0]) + 1)) temp[:, :-1] = X_train temp[:, -1] = Z_train X_train2 = temp Z_test = (X_test[:, 0] ** 2 + X_test[:, 1] ** 2) ** 0.5 temp = np.zeros((X_test.shape[0], len(X_test[0]) + 1)) temp[:, :-1] = X_test temp[:, -1] = Z_test X_test2 = temp print('Solved Training Data:') print(X_train2[:10]) def plot3D(X, Y): fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111, projection='3d') ax.scatter( X[:, 0], X[:, 1], X[:, 2], zdir='z', s=30, c=Y, depthshade=True ) plt.show() plot3D(X_train2, Y_train) print(f'Total datas: {len(X_train2)}') print(f'labels: {list(set(Y_train))}') print(f'label 0 datas: {len(list(filter(lambda x: x==0, Y_train)))}') print(f'label 1 datas: {len(list(filter(lambda x: x==1, Y_train)))}') qubits_num = 3 layers_num = 2 dev = qml.device("default.qubit", wires=qubits_num) class VQC: def __init__(self): # 3 => U3(theta, phi, lambda) self.params = (0.05 * np.random.randn(layers_num, qubits_num, 3)) self.bestparams = self.params self.bestcost = 10 self.opt = AdamOptimizer(0.08) self.weights = [] self.costs = [] self.accuracies = [] def fit(self, X_train, Y_train, epoch=300): batch_size = 20 for turn in range(epoch): # Update the weights by one optimizer step batch_index = np.random.randint(0, len(X_train), (batch_size,)) X_train_batch = X_train[batch_index] Y_train_batch = Y_train[batch_index] self.params = self.opt.step(lambda v: cost(v, X_train_batch, Y_train_batch), self.params) cost_now = cost(self.params, X_train, Y_train) acc_now = accuracy(self.params, X_train, Y_train) if cost_now < self.bestcost: self.bestcost = cost_now self.bestparams = self.params self.weights.append(self.params) self.costs.append(cost_now) self.accuracies.append(acc_now) print( "Turn: {:5d} | Cost: {:0.7f} | Accuracy: {:0.2f}% ".format( turn + 1, cost_now, acc_now * 100 )) def score(self, X_test, Y_test): predictions = [ predict(self.bestparams, data) for data in X_test ] acc = accuracy(self.bestparams, X_test, Y_test) print("FINAL ACCURACY: {:0.2f}%".format(acc * 100)) @qml.qnode(dev) def circuit(params, data): angles = [ i * np.pi for i in data ] for i in range(qubits_num): qml.RX(angles[i], wires=i) qml.Rot( *params[0, i], wires=i ) qml.CZ(wires=[1, 0]) qml.CZ(wires=[1, 2]) qml.CZ(wires=[0, 2]) for i in range(qubits_num): qml.Rot( *params[1, i], wires=i ) # PauliZ measure => 1 -> |0> while -1 -> |1> return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliZ(2)) import qiskit import numpy as np from qiskit import QuantumCircuit from qiskit import Aer, execute unitary_backend = Aer.get_backend('unitary_simulator') qasm_backend = Aer.get_backend('qasm_simulator') def predict(params, data): qcircuit = QuantumCircuit(3, 3) qubits = qcircuit.qubits for i, d in enumerate(data): qcircuit.rx(d * np.pi, qubits[i]) for i in range(qubits_num): qcircuit.u3(*params[0][i], qubits[i]) qcircuit.cz(qubits[0], qubits[1]) qcircuit.cz(qubits[1], qubits[2]) qcircuit.cz(qubits[0], qubits[2]) for i in range(qubits_num): qcircuit.u3(*params[1][i], qubits[i]) # the measurement qcircuit.measure([0, 1, 2], [0, 1, 2]) # job execution shots = 1000 job_sim = execute(qcircuit, qasm_backend, shots=shots) result_sim = job_sim.result() counts = result_sim.get_counts(qcircuit) p1 = (counts.get('100', 0) + counts.get('111', 0) + counts.get('101', 0) + counts.get('110', 0)) / shots if p1 > 0.5: return 1 else: return 0 def cost(weights, datas, labels): loss = 0 for i, data in enumerate(datas): # like [-1, 1, 1] measured = circuit(weights, data) p = measured[0] if labels[i] == 0: loss += (1 - p) ** 2 else: loss += (-1 - p) ** 2 return loss / len(datas) def accuracy(weights, datas, labels): predictions = [ predict(weights, data) for data in datas ] acc = 0 for i, p in enumerate(predictions): if p == labels[i]: acc += 1 return acc / len(predictions) vqc = VQC() # vqc.params = np.array([[[-1.18991246e-01, -8.69694713e-01, 1.43722811e-03], # [ 3.47641545e+00, -4.73632073e-02, 1.97135609e+00], # [ 1.95775707e+00, -1.12139160e-02, -6.21796144e-03]], # [[ 2.02460380e-02, -2.25797547e+00, 5.14234265e-03], # [-1.71552299e-02, 2.46283604e-03, -1.03805722e-02], # [-2.37244982e-03, -3.35799404e-03, 6.10191152e-03]]]) vqc.fit(X_train2, Y_train, epoch=10) print(cost(vqc.bestparams, X_train2, Y_train)) print(cost(vqc.bestparams, X_test2, Y_test)) vqc.score(X_test2, Y_test) def createCircuit(params, data): qcircuit = QuantumCircuit(3, 3) qubits = qcircuit.qubits for i, d in enumerate(data): qcircuit.rx(d * np.pi, qubits[i]) for i in range(qubits_num): qcircuit.u3(*params[0][i], qubits[i]) qcircuit.cz(qubits[0], qubits[1]) qcircuit.cz(qubits[1], qubits[2]) qcircuit.cz(qubits[0], qubits[2]) for i in range(qubits_num): qcircuit.u3(*params[1][i], qubits[i]) return qcircuit qcircuit = createCircuit(vqc.bestparams, X_train2[0]) qcircuit.draw(output='mpl') def measure(qcircuit, label): # the measurement qcircuit.measure([0, 1, 2], [0, 1, 2]) # job execution shots = 1000 job_sim = execute(qcircuit, qasm_backend, shots=shots) result_sim = job_sim.result() counts = result_sim.get_counts(qcircuit) print(f'simulation results: \n{counts}') p1 = (counts.get('100', 0) + counts.get('111', 0) + counts.get('101', 0) + counts.get('110',0)) / shots print(f'p1: {p1}') print(f'Expected label: {label}') example = [3, 30, 35, 70] for index in example: qcircuit = createCircuit(vqc.bestparams, X_train2[index]) measure(qcircuit, Y_train[index]) print() # origin data plt.scatter(X_train2[:, 0], X_train2[:, 1], c=Y_train) plt.show() predictions = [ predict(vqc.bestparams, data) for data in X_test2 ] Y_ = [ Y_test[i] if Y_test[i] == predictions[i] else 2 for i in range(len(Y_test)) ] plt.scatter(X_test2[:, 0], X_test2[:, 1], c=Y_) plt.show() train_params(X_train2[10:50], Y_train[10:50])
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Width pass testing""" import unittest from qiskit import QuantumCircuit, QuantumRegister from qiskit.converters import circuit_to_dag from qiskit.transpiler.passes import Width from qiskit.test import QiskitTestCase class TestWidthPass(QiskitTestCase): """Tests for Depth analysis methods.""" def test_empty_dag(self): """Empty DAG has 0 depth""" circuit = QuantumCircuit() dag = circuit_to_dag(circuit) pass_ = Width() _ = pass_.run(dag) self.assertEqual(pass_.property_set["width"], 0) def test_just_qubits(self): """A dag with 8 operations and no classic bits""" qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[1], qr[0]) dag = circuit_to_dag(circuit) pass_ = Width() _ = pass_.run(dag) self.assertEqual(pass_.property_set["width"], 2) if __name__ == "__main__": unittest.main()
https://github.com/scaleway/qiskit-scaleway
scaleway
# Copyright 2024 Scaleway # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json from typing import Union, List from qiskit.providers import JobError from qiskit.result import Result from qiskit import qasm3 from ..utils import QaaSClient from ..versions import USER_AGENT from .scaleway_job import ScalewayJob from .scaleway_models import ( JobPayload, ClientPayload, BackendPayload, RunPayload, SerializationType, CircuitPayload, ) class AerJob(ScalewayJob): def __init__( self, name: str, backend, client: QaaSClient, circuits, config, ) -> None: super().__init__(name, backend, client) self._circuits = circuits self._config = config def submit(self, session_id: str) -> None: if self._job_id: raise RuntimeError(f"Job already submitted (ID: {self._job_id})") options = self._config.copy() run_opts = RunPayload( options={ "shots": options.pop("shots"), "memory": options.pop("memory"), "seed_simulator": options.pop("seed_simulator"), }, circuits=list( map( lambda c: CircuitPayload( serialization_type=SerializationType.QASM_V3, circuit_serialization=qasm3.dumps(c), ), self._circuits, ) ), ) backend_opts = BackendPayload( name=self.backend().name, version=self.backend().version, options=options, ) client_opts = ClientPayload( user_agent=USER_AGENT, ) job_payload = JobPayload.schema().dumps( JobPayload( backend=backend_opts, run=run_opts, client=client_opts, ) ) self._job_id = self._client.create_job( name=self._name, session_id=session_id, circuits=job_payload, ) def result( self, timeout=None, fetch_interval: int = 3 ) -> Union[Result, List[Result]]: if self._job_id == None: raise JobError("Job ID error") job_results = self._wait_for_result(timeout, fetch_interval) def __make_result_from_payload(payload: str) -> Result: payload_dict = json.loads(payload) return Result.from_dict( { "results": payload_dict["results"], "backend_name": payload_dict["backend_name"], "backend_version": payload_dict["backend_version"], "job_id": self._job_id, "qobj_id": ", ".join(x.name for x in self._circuits), "success": payload_dict["success"], "header": payload_dict.get("header"), "metadata": payload_dict.get("metadata"), } ) qiskit_results = list( map( lambda r: __make_result_from_payload( self._extract_payload_from_response(r) ), job_results, ) ) if len(qiskit_results) == 1: return qiskit_results[0] return qiskit_results
https://github.com/jvscursulim/qamp_fall22_project
jvscursulim
import numpy as np import matplotlib.pyplot as plt from qiskit import Aer from qiskit.circuit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.providers.aer.backends import AerSimulator from qiskit.visualization import plot_histogram from qpie import QPIE from skimage import data from skimage.color import rgb2gray from skimage.transform import resize statevec_sim = Aer.get_backend("statevector_simulator") backend = AerSimulator() shots = 8192 image = np.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]]) plt.style.use("bmh") plt.xticks(range(image.shape[0])) plt.yticks(range(image.shape[1])) plt.imshow(image, extent=[0, image.shape[0], image.shape[1], 0]) qpie_class = QPIE() qc = qpie_class.image_quantum_circuit(image=image) qc.draw(output="mpl") statevec = statevec_sim.run(qc).result().get_statevector() np_statevec = np.real(statevec) np_statevec.reshape(8,8) plt.imshow(np_statevec.reshape(8,8), extent=[0, image.shape[0], image.shape[1], 0]) qc = qpie_class.image_quantum_circuit(image=image, measurements=True) qc.draw(output="mpl") counts = backend.run(qc, shots=2**20).result().get_counts() plot_histogram(counts, bar_labels=False) astro_pic = data.astronaut() plt.style.use("default") plt.imshow(astro_pic) gray_resized_astro_pic = resize(rgb2gray(astro_pic), (8,8)) plt.imshow(gray_resized_astro_pic, cmap="gray") qc = qpie_class.image_quantum_circuit(image=gray_resized_astro_pic) statevec = statevec_sim.run(qc).result().get_statevector() img = np.real(statevec).reshape(8,8) plt.imshow(img, cmap="gray") plt.style.use("bmh") threshold = lambda amp: (amp > 1e-15 or amp < -1e-15) D2n_1 = np.roll(np.identity(2**7), 1, axis=1) D2n_1 qc_h = QuantumCircuit(7) qc_h.initialize(qpie_class._amplitude_encode(image=image), range(1,7)) qc_h.h(0) qc_h.unitary(D2n_1, range(7)) qc_h.h(0) qc_h.draw("mpl") statevec_h = statevec_sim.run(qc_h).result().get_statevector() edge_scan_h = np.abs(np.array([1 if threshold(statevec_h[2*i+1].real) else 0 for i in range(2**6)])).reshape(8,8) plt.imshow(edge_scan_h, extent=[0, image.shape[0], image.shape[1], 0]) qc_v = QuantumCircuit(7) qc_v.initialize(qpie_class._amplitude_encode(image=image.T), range(1,7)) qc_v.h(0) qc_v.unitary(D2n_1, range(7)) qc_v.h(0) qc_v.draw("mpl") statevec_v = statevec_sim.run(qc_v).result().get_statevector() edge_scan_v = np.abs(np.array([1 if threshold(statevec_v[2*i+1].real) else 0 for i in range(2**6)])).reshape(8,8).T plt.imshow(edge_scan_v, extent=[0, image.shape[0], image.shape[1], 0]) edge_scan_sim = edge_scan_h | edge_scan_v plt.imshow(edge_scan_sim, extent=[0, image.shape[0], image.shape[1], 0])
https://github.com/jfraxanet/BasQ_industry_workshop_Qiskit
jfraxanet
from qiskit import QuantumCircuit #define quantum circuit qc = QuantumCircuit(4) #add gates qc.h(0) qc.cx(0,1) qc.h(2) qc.x(3) qc.cx(2,3) qc.measure_all() #draw qc.draw('mpl', style='clifford') #draw result = sampler.run(qc) print(result) from qiskit.primitives import Sampler from qiskit.visualization import plot_distribution sampler = Sampler() samp_dist = sampler.run(qc).result().quasi_dists[0] plot_distribution(samp_dist.binary_probabilities(), figsize=(15, 5)) from qiskit.circuit.library import NLocal, CZGate, RZGate, RXGate from qiskit.circuit import Parameter from qiskit import QuantumCircuit qc = QuantumCircuit(5) qc.x(0) qc.barrier() theta = Parameter("θ") ansatz = NLocal( initial_state = qc, num_qubits=5, rotation_blocks=[RXGate(theta), RZGate(theta)], entanglement_blocks = [CZGate()], entanglement=[[0, 1], [0, 2], [2, 1], [2, 4]], reps=2, insert_barriers=True, ) ansatz.decompose().draw("mpl") from qiskit.primitives import Estimator from qiskit import QuantumCircuit from qiskit.quantum_info import SparsePauliOp O = SparsePauliOp(["X", "Z"], [2, -1]) estimator = Estimator() qc1 = QuantumCircuit(1) job = estimator.run(qc1, O) expvals1 = job.result().values print("Exp. val qs1: ", expvals1) qc2 = QuantumCircuit(1) qc2.h(0) job = estimator.run(qc2, O) expvals2 = job.result().values print("Exp. val qs2: ", expvals2) from qiskit.circuit.library import NLocal, CXGate, RZGate, RXGate from qiskit.circuit import Parameter from qiskit import QuantumCircuit # Define an initial state with two qubits qc = QuantumCircuit(2) qc.x(0) qc.barrier() # Define an general ansatz theta = Parameter("θ") ansatz = NLocal( initial_state = qc, num_qubits=2, rotation_blocks=[RXGate(theta), RZGate(theta)], entanglement_blocks = [CXGate()], entanglement=[[0, 1]], reps=1, insert_barriers=True, ) ansatz.decompose().draw("mpl", style='Clifford') from scipy.optimize import minimize from qiskit.quantum_info import SparsePauliOp from qiskit.primitives import Estimator import numpy as np # Define observable and estimator observable = SparsePauliOp(["IZ", "ZI"], [-1,-1]) estimator = Estimator() # Define cost function def cost_func(params, ansatz, observable, estimator): cost = estimator.run(ansatz, observable, parameter_values=params).result().values[0] return cost # Define initial state of parameters randomly x0 = 2 * np.pi * np.random.rand(ansatz.num_parameters) # Minimize using an optimization method like COBYLA, SLSQP... res = minimize(cost_func, x0, args=(ansatz, observable, estimator), method="COBYLA") print(res) qc = ansatz.assign_parameters(res.x) qc.measure_all() qc.draw("mpl", style="clifford") from qiskit.visualization import plot_distribution samp_dist = sampler.run(qc).result().quasi_dists[0] plot_distribution(samp_dist.binary_probabilities(), figsize=(15, 5))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
number = 5 # integer real = -3.4 # float name = 'Asja' # string surname = "Sarkana" # string boolean1 = True # Boolean boolean1 = False # Boolean a = 13 b = 5 print("a =",a) print("b =",b) print() # basics operators print("a + b =",a+b) print("a - b =",a-b) print("a * b =",a*b) print("a / b =",a/b) a = 13 b = 5 print("a =",a) print("b =",b) print() # integer division print("a//b =",a//b) # modulus operator print("a mod b =",a % b) b = 5 print("b =",b) print() print("b*b =",b**2) print("b*b*b =",b**3) print("sqrt(b)=",b**0.5) # list mylist = [10,8,6,4,2] print(mylist) # tuple mytuple=(1,4,5,'Asja') print(mytuple) # dictionary mydictionary = { 'name' : "Asja", 'surname':'Sarkane', 'age': 23 } print(mydictionary) print(mydictionary['surname']) # list of the other objects or variables list_of_other_objects =[ mylist, mytuple, 3, "Asja", mydictionary ] print(list_of_other_objects) # length of a string print(len("Asja Sarkane")) # size of a list print(len([1,2,3,4])) # size of a dictionary mydictionary = { 'name' : "Asja", 'surname':'Sarkane', 'age': 23} print(len(mydictionary)) i = 10 while i>0: # while condition(s): print(i) i = i - 1 for i in range(10): # i is in [0,1,...,9] print(i) for i in range(-5,6): # i is in [-5,-4,...,0,...,4,5] print(i) for i in range(0,23,4): # i is in [0,4,8,12,16,20] print(i) for i in [3,8,-5,11]: print(i) for i in "Sarkane": print(i) # dictionary mydictionary = { 'name' : "Asja", 'surname':'Sarkane', 'age': 23, } for key in mydictionary: print("key is",key,"and its value is",mydictionary[key]) for a in range(4,7): # if condition(s) if a<5: print(a,"is less than 5") # elif conditions(s) elif a==5: print(a,"is equal to 5") # else else: print(a,"is greater than 5") # Logical operator "and" i = -3 j = 4 if i<0 and j > 0: print(i,"is negative AND",j,"is positive") # Logical operator "or" i = -2 j = 2 if i==2 or j == 2: print("i OR j is 2: (",i,",",j,")") # Logical operator "not" i = 3 if not (i==2): print(i,"is NOT equal to 2") # Operator "equal to" i = -1 if i == -1: print(i,"is EQUAL TO -1") # Operator "not equal to" i = 4 if i != 3: print(i,"is NOT EQUAL TO 3") # Operator "not equal to" i = 2 if i <= 5: print(i,"is LESS THAN OR EQUAL TO 5") # Operator "not equal to" i = 5 if i >= 1: print(i,"is GREATER THAN OR EQUAL TO 3") A =[ [1,2,3], [-2,-4,-6], [3,6,9] ] # print all print(A) print() # print list by list for list in A: print(list) list1 = [1,2,3] list2 = [4,5,6] #concatenation of two lists list3 = list1 + list2 print(list3) list4 = list2 + list1 print(list4) list = [0,1,2] list.append(3) print(list) list = list + [4] print(list) def summation_of_integers(n): summation = 0 for integer in range(n+1): summation = summation + integer return summation print(summation_of_integers(10)) print(summation_of_integers(20)) from random import randrange print(randrange(10),"is picked randomly between 0 and 9") print(randrange(-9,10),"is picked randomly between -9 and 9") print(randrange(0,20,3),"is picked randomly from the list [0,3,6,9,12,15,18]")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import * from qiskit.circuit import Gate my_gate = Gate(name='my_gate', num_qubits=2, params=[]) qr = QuantumRegister(3, 'q') circ = QuantumCircuit(qr) circ.append(my_gate, [qr[0], qr[1]]) circ.append(my_gate, [qr[1], qr[2]]) circ.draw() # Build a sub-circuit sub_q = QuantumRegister(2) sub_circ = QuantumCircuit(sub_q, name='sub_circ') sub_circ.h(sub_q[0]) sub_circ.crz(1, sub_q[0], sub_q[1]) sub_circ.barrier() sub_circ.id(sub_q[1]) sub_circ.u(1, 2, -2, sub_q[0]) # Convert to a gate and stick it into an arbitrary place in the bigger circuit sub_inst = sub_circ.to_instruction() qr = QuantumRegister(3, 'q') circ = QuantumCircuit(qr) circ.h(qr[0]) circ.cx(qr[0], qr[1]) circ.cx(qr[1], qr[2]) circ.append(sub_inst, [qr[1], qr[2]]) circ.draw() decomposed_circ = circ.decompose() # Does not modify original circuit decomposed_circ.draw() from qiskit.circuit import Parameter theta = Parameter('θ') n = 5 qc = QuantumCircuit(5, 1) qc.h(0) for i in range(n-1): qc.cx(i, i+1) qc.barrier() qc.rz(theta, range(5)) qc.barrier() for i in reversed(range(n-1)): qc.cx(i, i+1) qc.h(0) qc.measure(0, 0) qc.draw('mpl') print(qc.parameters) import numpy as np theta_range = np.linspace(0, 2 * np.pi, 128) circuits = [qc.bind_parameters({theta: theta_val}) for theta_val in theta_range] circuits[-1].draw() backend = BasicAer.get_backend('qasm_simulator') job = backend.run(transpile(circuits, backend)) counts = job.result().get_counts() import matplotlib.pyplot as plt fig = plt.figure(figsize=(8,6)) ax = fig.add_subplot(111) ax.plot(theta_range, list(map(lambda c: c.get('0', 0), counts)), '.-', label='0') ax.plot(theta_range, list(map(lambda c: c.get('1', 0), counts)), '.-', label='1') ax.set_xticks([i * np.pi / 2 for i in range(5)]) ax.set_xticklabels(['0', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$'], fontsize=14) ax.set_xlabel('θ', fontsize=14) ax.set_ylabel('Counts', fontsize=14) ax.legend(fontsize=14) import time from itertools import combinations from qiskit.compiler import assemble from qiskit.test.mock import FakeVigo start = time.time() qcs = [] theta_range = np.linspace(0, 2*np.pi, 32) for n in theta_range: qc = QuantumCircuit(5) for k in range(8): for i,j in combinations(range(5), 2): qc.cx(i,j) qc.rz(n, range(5)) for i,j in combinations(range(5), 2): qc.cx(i,j) qcs.append(qc) compiled_circuits = transpile(qcs, backend=FakeVigo()) qobj = assemble(compiled_circuits, backend=FakeVigo()) end = time.time() print('Time compiling over set of bound circuits: ', end-start) start = time.time() qc = QuantumCircuit(5) theta = Parameter('theta') for k in range(8): for i,j in combinations(range(5), 2): qc.cx(i,j) qc.rz(theta, range(5)) for i,j in combinations(range(5), 2): qc.cx(i,j) transpiled_qc = transpile(qc, backend=FakeVigo()) qobj = assemble([transpiled_qc.bind_parameters({theta: n}) for n in theta_range], backend=FakeVigo()) end = time.time() print('Time compiling over parameterized circuit, then binding: ', end-start) phi = Parameter('phi') sub_circ1 = QuantumCircuit(2, name='sc_1') sub_circ1.rz(phi, 0) sub_circ1.rx(phi, 1) sub_circ2 = QuantumCircuit(2, name='sc_2') sub_circ2.rx(phi, 0) sub_circ2.rz(phi, 1) qc = QuantumCircuit(4) qr = qc.qregs[0] qc.append(sub_circ1.to_instruction(), [qr[0], qr[1]]) qc.append(sub_circ2.to_instruction(), [qr[0], qr[1]]) qc.append(sub_circ2.to_instruction(), [qr[2], qr[3]]) print(qc.draw()) # The following raises an error: "QiskitError: 'Name conflict on adding parameter: phi'" # phi2 = Parameter('phi') # qc.u3(0.1, phi2, 0.3, 0) p = Parameter('p') qc = QuantumCircuit(3, name='oracle') qc.rz(p, 0) qc.cx(0, 1) qc.rz(p, 1) qc.cx(1, 2) qc.rz(p, 2) theta = Parameter('theta') phi = Parameter('phi') gamma = Parameter('gamma') qr = QuantumRegister(9) larger_qc = QuantumCircuit(qr) larger_qc.append(qc.to_instruction({p: theta}), qr[0:3]) larger_qc.append(qc.to_instruction({p: phi}), qr[3:6]) larger_qc.append(qc.to_instruction({p: gamma}), qr[6:9]) print(larger_qc.draw()) print(larger_qc.decompose().draw()) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/BOBO1997/osp_solutions
BOBO1997
import re import numpy as np import matplotlib.pyplot as plt import itertools import random import pickle plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.providers.aer import QasmSimulator from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity # Suppress warnings import warnings warnings.filterwarnings('ignore') def trotter_gate(dt, to_instruction = True): qc = QuantumCircuit(2) qc.rx(2*dt,0) qc.rz(2*dt,1) qc.h(1) qc.cx(1,0) qc.rz(-2*dt, 0) qc.rx(-2*dt, 1) qc.rz(2*dt, 1) qc.cx(1,0) qc.h(1) qc.rz(2*dt, 0) return qc.to_instruction() if to_instruction else qc trotter_gate(np.pi / 6, to_instruction=False).draw("mpl") # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate Trot_gate = trotter_gate(dt) # Number of trotter steps trotter_steps = 100 ### CAN BE >= 4 # Initialize quantum circuit for 3 qubits # qr = QuantumRegister(7) qc = QuantumCircuit(3) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) qc.x([1,0]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) qc.x([1]) # encoding # Simulate time evolution under H_heis3 Hamiltonian for _ in range(trotter_steps): qc.append(Trot_gate, [1, 0]) qc.cx(1, 2) qc.cx(0, 1) # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time/trotter_steps}) # circuit optimization t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_qc = transpile(t3_qc, optimization_level=3, basis_gates=["sx", "cx", "rz"]) # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(t3_qc, [2, 1, 0]) # Display circuit for confirmation # st_qcs[-1].decompose().draw() # view decomposition of trotter gates st_qcs[-1].draw("mpl") # only view trotter gates # Pauli Twirling def pauli_twirling(circ: str) -> QuantumCircuit: """ そのまま使う: 修正は後回し """ #! qasm ベタ書き def apply_pauli(num: int, qb: int) -> str: if (num == 0): return f'id q[{qb}];\n' elif (num == 1): return f'x q[{qb}];\n' elif (num == 2): return f'y q[{qb}];\n' else: return f'z q[{qb}];\n' paulis = [(i,j) for i in range(0,4) for j in range(0,4)] paulis.remove((0,0)) paulis_map = [(0, 1), (3, 2), (3, 3), (1, 1), (1, 0), (2, 3), (2, 2), (2, 1), (2, 0), (1, 3), (1, 2), (3, 0), (3, 1), (0, 2), (0, 3)] new_circ = '' ops = circ.qasm().splitlines(True) #! 生のqasmコードを持ってきてる: オペレータに分解 for op in ops: if (op[:2] == 'cx'): # can add for cz, etc. num = random.randrange(len(paulis)) #! permute paulis qbs = re.findall('q\[(.)\]', op) new_circ += apply_pauli(paulis[num][0], qbs[0]) new_circ += apply_pauli(paulis[num][1], qbs[1]) new_circ += op new_circ += apply_pauli(paulis_map[num][0], qbs[0]) new_circ += apply_pauli(paulis_map[num][1], qbs[1]) else: new_circ += op return QuantumCircuit.from_qasm_str(new_circ) def zne_wrapper(qcs, scale_factors = [1.0, 2.0, 3.0]): """ """ folded_qcs = [] #! ZNE用の回路 for qc in qcs: folded_qcs.append([mitiq.zne.scaling.fold_gates_at_random(qc, scale) for scale in scale_factors]) #! ここでmitiqを使用 folded_qcs = list(itertools.chain(*folded_qcs)) #! folded_qcsを平坦化 folded_qcs = [pauli_twirling(circ) for circ in folded_qcs] #! 後からPauli Twirlingを施す! return folded_qcs zne_qcs = zne_wrapper(st_qcs) print("number of circuits: ", len(zne_qcs)) zne_qcs[-3].draw("mpl") zne_qcs_jakarta = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"], initial_layout=[5,3,1]) zne_qcs_jakarta = transpile(zne_qcs_jakarta, optimization_level=3, basis_gates=["sx", "cx", "rz"]) from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 8192 reps = 8 jobs = [] for _ in range(reps): # execute job = execute(st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3) print('Job ID', cal_job.job_id()) with open("jakarta_100step.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = [] for job in jobs: mit_results.append( meas_fitter.filter.apply(job.result()) ) # Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits def state_tomo(result, st_qcs): # The expected final state; necessary to determine state tomography fidelity target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Fit state tomography results tomo_fitter = StateTomographyFitter(result, st_qcs) rho_fit = tomo_fitter.fit(method='lstsq') # Compute fidelity fid = state_fidelity(rho_fit, target_state) return fid # Compute tomography fidelities for each repetition fids = [] for result in mit_results: fid = state_tomo(result, st_qcs) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/TheGupta2012/QickStart-Challenges
TheGupta2012
## Enter Team ID import os os.environ["TEAMID"] = "Excalibur" from qiskit import QuantumCircuit from qiskit.visualization import visualize_transition import numpy as np # build the quantum circuit q = QuantumCircuit(1) # init the state q.h(0) q.rz(np.pi/2,0) # already |0> # apply transformation q.rz(0, 0) q.rx(np.pi/2, 0) q.ry(0, 0) visualize_transition(q) def generate_bloch_operation(state): rotation = [0,0,0] ### Your code goes here if(state=='1'): rotation=[0,0,-2] elif(state=='+'): rotation=[0,0,-1] elif(state=='-'): rotation=[0,0,1] elif(state=='r'): rotation=[0,1,0] elif(state=='l'): rotation=[0,-1,0] ### Your code goes here return rotation def test_function_1(): state = '+' rotation = generate_bloch_operation(state) return rotation test_function_1() from grader.graders.problem_3.grader import grader1 grader1.evaluate(generate_bloch_operation) def get_total_bloch_ops(state, arz, arx, ary): total = 0 qc=QuantumCircuit(1) ### Your code goes here for i in arz: for j in arx: for k in ary: qc.reset(0) if(state=='1'): qc.x(0) elif(state=='+'): qc.h(0) elif(state=='-'): qc.x(0) qc.h(0) elif(state=='r'): qc.h(0) qc.rz(np.pi/2,0) elif(state=='l'): qc.h(0) qc.rz(-np.pi/2,0) qc.rz(i*np.pi/2,0) qc.rx(j*np.pi/2,0) qc.ry(k*np.pi/2,0) ### Your code goes here return total def test_function_2(): # say we have these arrays arz = [2] arx = [-2] ary = [0, 2] # initial state is |0> state = '0' # your function would return these two things total = get_total_bloch_ops(state, arz, arx, ary) return total test_function_2() from grader.graders.problem_3.grader import grader2 grader2.evaluate(get_total_bloch_ops) def get_larger_total_bloch_ops(state, arz, arx, ary): total = 0 ### Your code goes here ### Your code goes here return total def test_function_3(): # say we have these arrays arz = [2] arx = [-2] ary = [0, 2] # initial state is |0> state = '0' # your function would return these two things total = get_larger_total_bloch_ops(state, arz, arx, ary) return total test_function_3() from grader.graders.problem_3.grader import grader3 grader3.evaluate(get_larger_total_bloch_ops)
https://github.com/Pitt-JonesLab/clonk_transpilation
Pitt-JonesLab
from backend_suite import backends, large_backends from circuit_suite import circuits qc = circuits["QAOA_Vanilla"].circuit_lambda(4) qc.remove_final_measurements() qc.draw(output="mpl") from qiskit.converters import circuit_to_dag from qiskit.visualization import dag_drawer new_qc = backends["Hatlab-Large-Riswap-Shuffle"].pass_manager.run(qc) dag = circuit_to_dag(new_qc) dag_drawer(dag)
https://github.com/meherafrozantar/QiskitClass
meherafrozantar
!pip install qiskit qiskit-aer !pip install qiskit !pip install pylatexenc from qiskit import * from qiskit.tools.monitor import job_monitor from qiskit.tools.visualization import plot_state_qsphere from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex # create a circuit circuit = QuantumCircuit (1) # Apply hadamard gate circuit.h(0) circuit.h(0) #draw circuit circuit.draw(output = 'mpl', initial_state = True) # select a simulator simulator = Aer.get_backend('aer_simulator') # save statevector circuit.save_statevector() # assemble our circuit qobj = assemble(circuit) # run on simulator job = simulator.run(qobj) # monitoring the process job_monitor(job) # get results from job result = job.result() # get statevector from result final_state = result.get_statevector() print(final_state) array_to_latex(final_state) # this vector is in which state of quantum? plot_bloch_multivector(final_state) # create a circuit circuit = QuantumCircuit(1) # Apply a gate circuit.h(0) circuit.h(0) # draw circuit circuit.draw(output = 'mpl', initial_state=True) # select a simulator simulator = Aer.get_backend('aer_simulator') # save unitary circuit.save_unitary() # assemble our circuit qobj = assemble(circuit) # run on simulator job = simulator.run(qobj) # monitoring the process job_monitor(job) # get results from job result = job.result() # get the unitary unitary = result.get_unitary() print (unitary) array_to_latex(unitary)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit, transpile from qiskit.quantum_info import Kraus, SuperOp from qiskit_aer import AerSimulator from qiskit.tools.visualization import plot_histogram # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError, pauli_error, depolarizing_error, thermal_relaxation_error) # Construct a 1-qubit bit-flip and phase-flip errors p_error = 0.05 bit_flip = pauli_error([('X', p_error), ('I', 1 - p_error)]) phase_flip = pauli_error([('Z', p_error), ('I', 1 - p_error)]) print(bit_flip) print(phase_flip) # Compose two bit-flip and phase-flip errors bitphase_flip = bit_flip.compose(phase_flip) print(bitphase_flip) # Tensor product two bit-flip and phase-flip errors with # bit-flip on qubit-0, phase-flip on qubit-1 error2 = phase_flip.tensor(bit_flip) print(error2) # Convert to Kraus operator bit_flip_kraus = Kraus(bit_flip) print(bit_flip_kraus) # Convert to Superoperator phase_flip_sop = SuperOp(phase_flip) print(phase_flip_sop) # Convert back to a quantum error print(QuantumError(bit_flip_kraus)) # Check conversion is equivalent to original error QuantumError(bit_flip_kraus) == bit_flip # Measurement miss-assignement probabilities p0given1 = 0.1 p1given0 = 0.05 ReadoutError([[1 - p1given0, p1given0], [p0given1, 1 - p0given1]]) # Create an empty noise model noise_model = NoiseModel() # Add depolarizing error to all single qubit u1, u2, u3 gates error = depolarizing_error(0.05, 1) noise_model.add_all_qubit_quantum_error(error, ['u1', 'u2', 'u3']) # Print noise model info print(noise_model) # Create an empty noise model noise_model = NoiseModel() # Add depolarizing error to all single qubit u1, u2, u3 gates on qubit 0 only error = depolarizing_error(0.05, 1) noise_model.add_quantum_error(error, ['u1', 'u2', 'u3'], [0]) # Print noise model info print(noise_model) # System Specification n_qubits = 4 circ = QuantumCircuit(n_qubits) # Test Circuit circ.h(0) for qubit in range(n_qubits - 1): circ.cx(qubit, qubit + 1) circ.measure_all() print(circ) # Ideal simulator and execution sim_ideal = AerSimulator() result_ideal = sim_ideal.run(circ).result() plot_histogram(result_ideal.get_counts(0)) # Example error probabilities p_reset = 0.03 p_meas = 0.1 p_gate1 = 0.05 # QuantumError objects error_reset = pauli_error([('X', p_reset), ('I', 1 - p_reset)]) error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)]) error_gate1 = pauli_error([('X',p_gate1), ('I', 1 - p_gate1)]) error_gate2 = error_gate1.tensor(error_gate1) # Add errors to noise model noise_bit_flip = NoiseModel() noise_bit_flip.add_all_qubit_quantum_error(error_reset, "reset") noise_bit_flip.add_all_qubit_quantum_error(error_meas, "measure") noise_bit_flip.add_all_qubit_quantum_error(error_gate1, ["u1", "u2", "u3"]) noise_bit_flip.add_all_qubit_quantum_error(error_gate2, ["cx"]) print(noise_bit_flip) # Create noisy simulator backend sim_noise = AerSimulator(noise_model=noise_bit_flip) # Transpile circuit for noisy basis gates circ_tnoise = transpile(circ, sim_noise) # Run and get counts result_bit_flip = sim_noise.run(circ_tnoise).result() counts_bit_flip = result_bit_flip.get_counts(0) # Plot noisy output plot_histogram(counts_bit_flip) # T1 and T2 values for qubits 0-3 T1s = np.random.normal(50e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec T2s = np.random.normal(70e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec # Truncate random T2s <= T1s T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(4)]) # Instruction times (in nanoseconds) time_u1 = 0 # virtual gate time_u2 = 50 # (single X90 pulse) time_u3 = 100 # (two X90 pulses) time_cx = 300 time_reset = 1000 # 1 microsecond time_measure = 1000 # 1 microsecond # QuantumError objects errors_reset = [thermal_relaxation_error(t1, t2, time_reset) for t1, t2 in zip(T1s, T2s)] errors_measure = [thermal_relaxation_error(t1, t2, time_measure) for t1, t2 in zip(T1s, T2s)] errors_u1 = [thermal_relaxation_error(t1, t2, time_u1) for t1, t2 in zip(T1s, T2s)] errors_u2 = [thermal_relaxation_error(t1, t2, time_u2) for t1, t2 in zip(T1s, T2s)] errors_u3 = [thermal_relaxation_error(t1, t2, time_u3) for t1, t2 in zip(T1s, T2s)] errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand( thermal_relaxation_error(t1b, t2b, time_cx)) for t1a, t2a in zip(T1s, T2s)] for t1b, t2b in zip(T1s, T2s)] # Add errors to noise model noise_thermal = NoiseModel() for j in range(4): noise_thermal.add_quantum_error(errors_reset[j], "reset", [j]) noise_thermal.add_quantum_error(errors_measure[j], "measure", [j]) noise_thermal.add_quantum_error(errors_u1[j], "u1", [j]) noise_thermal.add_quantum_error(errors_u2[j], "u2", [j]) noise_thermal.add_quantum_error(errors_u3[j], "u3", [j]) for k in range(4): noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k]) print(noise_thermal) # Run the noisy simulation sim_thermal = AerSimulator(noise_model=noise_thermal) # Transpile circuit for noisy basis gates circ_tthermal = transpile(circ, sim_thermal) # Run and get counts result_thermal = sim_thermal.run(circ_tthermal).result() counts_thermal = result_thermal.get_counts(0) # Plot noisy output plot_histogram(counts_thermal) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# useful additional packages import matplotlib.pyplot as plt %matplotlib inline # importing Qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer, IBMQ, execute # import basic plot tools from qiskit.tools.visualization import plot_histogram backend = BasicAer.get_backend('qasm_simulator') # run on local simulator by default # Uncomment the following lines to run on a real device # IBMQ.load_accounts() # from qiskit.backends.ibmq import least_busy # backend = least_busy(IBMQ.backends(operational=True, simulator=False)) # print("the best backend is " + backend.name()) # Creating registers q2 = QuantumRegister(2) c1 = ClassicalRegister(1) c2 = ClassicalRegister(2) # quantum circuit to make an entangled bell state bell = QuantumCircuit(q2) bell.h(q2[0]) bell.cx(q2[0], q2[1]) # quantum circuit to measure q0 in the standard basis measureIZ = QuantumCircuit(q2, c1) measureIZ.measure(q2[0], c1[0]) bellIZ = bell+measureIZ # quantum circuit to measure q0 in the superposition basis measureIX = QuantumCircuit(q2, c1) measureIX.h(q2[0]) measureIX.measure(q2[0], c1[0]) bellIX = bell+measureIX # quantum circuit to measure q1 in the standard basis measureZI = QuantumCircuit(q2, c1) measureZI.measure(q2[1], c1[0]) bellZI = bell+measureZI # quantum circuit to measure q1 in the superposition basis measureXI = QuantumCircuit(q2, c1) measureXI.h(q2[1]) measureXI.measure(q2[1], c1[0]) bellXI = bell+measureXI # quantum circuit to measure q in the standard basis measureZZ = QuantumCircuit(q2, c2) measureZZ.measure(q2[0], c2[0]) measureZZ.measure(q2[1], c2[1]) bellZZ = bell+measureZZ # quantum circuit to measure q in the superposition basis measureXX = QuantumCircuit(q2, c2) measureXX.h(q2[0]) measureXX.h(q2[1]) measureXX.measure(q2[0], c2[0]) measureXX.measure(q2[1], c2[1]) bellXX = bell+measureXX bellIZ.draw(output='mpl') bellIX.draw(output='mpl') bellZI.draw(output='mpl') bellXI.draw(output='mpl') bellZZ.draw(output='mpl') bellXX.draw(output='mpl') circuits = [bellIZ,bellIX,bellZI,bellXI,bellZZ,bellXX] job = execute(circuits, backend) result = job.result() plot_histogram(result.get_counts(bellIZ)) result.get_counts(bellIZ) plot_histogram(result.get_counts(bellIX)) plot_histogram(result.get_counts(bellZI)) plot_histogram(result.get_counts(bellXI)) plot_histogram(result.get_counts(bellZZ)) plot_histogram(result.get_counts(bellXX)) # quantum circuit to make a mixed state mixed1 = QuantumCircuit(q2, c2) mixed2 = QuantumCircuit(q2, c2) mixed2.x(q2) mixed1.measure(q2[0], c2[0]) mixed1.measure(q2[1], c2[1]) mixed2.measure(q2[0], c2[0]) mixed2.measure(q2[1], c2[1]) mixed1.draw(output='mpl') mixed2.draw(output='mpl') mixed_state = [mixed1,mixed2] job = execute(mixed_state, backend) result = job.result() counts1 = result.get_counts(mixed_state[0]) counts2 = result.get_counts(mixed_state[1]) from collections import Counter ground = Counter(counts1) excited = Counter(counts2) plot_histogram(ground+excited)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import FakeVigo backend = FakeVigo() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0) plot_circuit_layout(new_circ_lv0, backend)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) depths = [] gate_counts = [] non_local_gate_counts = [] levels = [str(x) for x in range(4)] for level in range(4): circ = transpile(ghz, backend, optimization_level=level) depths.append(circ.depth()) gate_counts.append(sum(circ.count_ops().values())) non_local_gate_counts.append(circ.num_nonlocal_gates()) fig, (ax1, ax2) = plt.subplots(2, 1) ax1.bar(levels, depths, label='Depth') ax1.set_xlabel("Optimization Level") ax1.set_ylabel("Depth") ax1.set_title("Output Circuit Depth") ax2.bar(levels, gate_counts, label='Number of Circuit Operations') ax2.bar(levels, non_local_gate_counts, label='Number of non-local gates') ax2.set_xlabel("Optimization Level") ax2.set_ylabel("Number of gates") ax2.legend() ax2.set_title("Number of output circuit gates") fig.tight_layout() plt.show()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # This file is part of QuTiP: Quantum Toolbox in Python. # # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names # of its contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ############################################################################### """ Routines for running Python functions in parallel using process pools from the multiprocessing library. """ import os from concurrent.futures import ProcessPoolExecutor import sys from qiskit.exceptions import QiskitError from qiskit.utils.multiprocessing import local_hardware_info from qiskit.tools.events.pubsub import Publisher from qiskit import user_config def get_platform_parallel_default(): """ Returns the default parallelism flag value for the current platform. Returns: parallel_default: The default parallelism flag value for the current platform. """ # Default False on Windows if sys.platform == "win32": parallel_default = False # On macOS default false on Python >=3.8 elif sys.platform == "darwin": parallel_default = False # On linux (and other OSes) default to True else: parallel_default = True return parallel_default CONFIG = user_config.get_config() if os.getenv("QISKIT_PARALLEL", None) is not None: PARALLEL_DEFAULT = os.getenv("QISKIT_PARALLEL", None).lower() == "true" else: PARALLEL_DEFAULT = get_platform_parallel_default() # Set parallel flag if os.getenv("QISKIT_IN_PARALLEL") is None: os.environ["QISKIT_IN_PARALLEL"] = "FALSE" if os.getenv("QISKIT_NUM_PROCS") is not None: CPU_COUNT = int(os.getenv("QISKIT_NUM_PROCS")) else: CPU_COUNT = CONFIG.get("num_process", local_hardware_info()["cpus"]) def _task_wrapper(param): (task, value, task_args, task_kwargs) = param return task(value, *task_args, **task_kwargs) def parallel_map( # pylint: disable=dangerous-default-value task, values, task_args=(), task_kwargs={}, num_processes=CPU_COUNT ): """ Parallel execution of a mapping of `values` to the function `task`. This is functionally equivalent to:: result = [task(value, *task_args, **task_kwargs) for value in values] On Windows this function defaults to a serial implementation to avoid the overhead from spawning processes in Windows. Args: task (func): Function that is to be called for each value in ``values``. values (array_like): List or array of values for which the ``task`` function is to be evaluated. task_args (list): Optional additional arguments to the ``task`` function. task_kwargs (dict): Optional additional keyword argument to the ``task`` function. num_processes (int): Number of processes to spawn. Returns: result: The result list contains the value of ``task(value, *task_args, **task_kwargs)`` for each value in ``values``. Raises: QiskitError: If user interrupts via keyboard. Events: terra.parallel.start: The collection of parallel tasks are about to start. terra.parallel.update: One of the parallel task has finished. terra.parallel.finish: All the parallel tasks have finished. Examples: .. code-block:: python import time from qiskit.tools.parallel import parallel_map def func(_): time.sleep(0.1) return 0 parallel_map(func, list(range(10))); """ if len(values) == 0: return [] if len(values) == 1: return [task(values[0], *task_args, **task_kwargs)] Publisher().publish("terra.parallel.start", len(values)) nfinished = [0] def _callback(_): nfinished[0] += 1 Publisher().publish("terra.parallel.done", nfinished[0]) # Run in parallel if not Win and not in parallel already if ( num_processes > 1 and os.getenv("QISKIT_IN_PARALLEL") == "FALSE" and CONFIG.get("parallel_enabled", PARALLEL_DEFAULT) ): os.environ["QISKIT_IN_PARALLEL"] = "TRUE" try: results = [] with ProcessPoolExecutor(max_workers=num_processes) as executor: param = ((task, value, task_args, task_kwargs) for value in values) future = executor.map(_task_wrapper, param) results = list(future) Publisher().publish("terra.parallel.done", len(results)) except (KeyboardInterrupt, Exception) as error: if isinstance(error, KeyboardInterrupt): Publisher().publish("terra.parallel.finish") os.environ["QISKIT_IN_PARALLEL"] = "FALSE" raise QiskitError("Keyboard interrupt in parallel_map.") from error # Otherwise just reset parallel flag and error os.environ["QISKIT_IN_PARALLEL"] = "FALSE" raise error Publisher().publish("terra.parallel.finish") os.environ["QISKIT_IN_PARALLEL"] = "FALSE" return results # Cannot do parallel on Windows , if another parallel_map is running in parallel, # or len(values) == 1. results = [] for _, value in enumerate(values): result = task(value, *task_args, **task_kwargs) results.append(result) _callback(0) Publisher().publish("terra.parallel.finish") return results
https://github.com/yatharth0610/Quantum-Algorithms-qiskit-
yatharth0610
from qiskit import * from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * import matplotlib.pyplot as plotter import numpy as np from IPython.display import display, Math, Latex %matplotlib inline # Loading your IBM Q account(s) provider = IBMQ.load_account() qc1 = QuantumCircuit(3,3) # All initialized to '0' by default. qc1.x(0) #This is for the purpose of setting the control qubit to '1' qc1.x(2) #As a result, the second target qubit becomes '1' while the first remains '0'. Now, lets's try swapping them. #Fredkin gate: def fredkin(qc): qc.toffoli(0,1,2) qc.toffoli(0,2,1) qc.toffoli(0,1,2) fredkin(qc1) qc1.draw('mpl') #First let's measure all three qubits. #We're using the classical bits to store the result obtained on measuring each corresponding qubit. qc1.measure(0,0) qc1.measure(1,1) qc1.measure(2,2) #Now we use the same function we defined yesterday to run a quantum circuit def run_circuit(qc2): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc2, backend, shots = 2000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts1=run_circuit(qc1) print(counts1) plot_histogram(counts1) qc2 = QuantumCircuit(3,3) # All initialized to '0' by default. qc2.x(2) #The second target qubit is initialised to '1' fredkin(qc2) qc2.measure(0,0) qc2.measure(1,1) qc2.measure(2,2) qc2.draw(output='mpl') counts2=run_circuit(qc2) print(counts2) plot_histogram(counts2) qc = QuantumCircuit(1) #This is how we apply the rotation operators in Qiskit, mentioning the angle of rotation and qubit no. as parameters qc.rx(np.pi/2, 0) qc.draw('mpl') def final_vector(qc): backend = Aer.get_backend('statevector_simulator') job = execute(qc, backend) result = job.result() outputstate = result.get_statevector(qc, decimals=3) return outputstate print(final_vector(qc)) # This prints the vector obtained on applying the above gate to the qubit state '0' # The Pauli-X gate serves this purpose, as demonstrated below: qc3 = QuantumCircuit(1) theta = np.pi/7 qc3.x(0) qc3.ry(theta, 0) qc3.x(0) print(final_vector(qc3)) qc3 = QuantumCircuit(1) qc3.ry(-theta, 0) print(final_vector(qc3)) #Run this code for different values of theta and see if the two vectors printed are equal in each case qc4 = QuantumCircuit(1) alpha = np.pi/2 beta = 0 gamma = np.pi/2 delta = np.pi def A(qc, qbits, beta, gamma): qc.ry(gamma/2, qbits) qc.rz(beta, qbits) def B(qc, qbits, beta, gamma, delta): qc.rz(-(beta+delta)/2, qbits) qc.ry(-gamma/2, qbits) def C(qc, qbits, beta, delta): qc.rz((delta-beta)/2, qbits) C(qc4, 0, beta, delta) qc4.x(0) B(qc4, 0, beta, gamma, delta) qc4.x(0) A(qc4, 0, beta, gamma) qc4.unitary([[1.j, 0.], [0., 1.j]], [0]) print(final_vector(qc4)) qc4 = QuantumCircuit(1) qc4.h(0) print(final_vector(qc4)) qc5 = QuantumCircuit(3, 3) # Target qubit q1 is initially |1> and target qubit q2 is initially |0>. qc5.x(0) # Control qubit initialized to |1> to see effects of controlled Hadamard. qc5.x(1) # One target qubit initialized to |1>. alpha = np.pi/2 beta = 0 gamma = np.pi/2 delta = np.pi def A(qc, qbits, beta, gamma): qc.ry(gamma/2, qbits) qc.rz(beta, qbits) def B(qc, qbits, beta, gamma, delta): qc.rz(-(beta+delta)/2, qbits) qc.ry(-gamma/2, qbits) def C(qc, qbits, beta, delta): qc.rz((delta-beta)/2, qbits) C(qc5, [1, 2], beta, delta) qc5.cx(0, [1, 2]) B(qc5, [1, 2], beta, gamma, delta) qc5.cx(0, [1, 2]) A(qc5, [1, 2], beta, gamma) qc5.s(0) # Using S gate because alpha = pi/2 qc5.measure(0, 0) qc5.measure(1, 1) qc5.measure(2, 2) qc5.draw('mpl') def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') result = execute(qc, backend, shots = 10000).result() counts = result.get_counts() return counts counts = run_circuit(qc5) print(counts) plot_histogram(counts) qc_u3=QuantumCircuit(1) qc_u3.u3(np.pi/6,-np.pi/2,np.pi/2,0) print(final_vector(qc_u3)) qc_rx=QuantumCircuit(1) qc_rx.rx(np.pi/6,0) print(final_vector(qc_rx)) #Getting the same results will verify our observation stated above ######### Defining some constants and functions ########## # Constants for the decomposition of Hadamard gate. H_alpha = np.pi/2 H_beta = 0 H_gamma = np.pi/2 H_delta = np.pi # V^2 = X V = [[0.5+0.5j, 0.5-0.5j], [0.5-0.5j, 0.5+0.5j]] # Constants for the decomposition of V (where V^2 = X). V_alpha = np.pi/4 V_beta = np.pi/2 V_gamma = -np.pi/2 V_delta = -np.pi/2 # Functions to implement A, B, C (generalized). def A_gate(qc, qbits, beta, gamma): qc.ry(gamma/2, qbits) qc.rz(beta, qbits) def B_gate(qc, qbits, beta, gamma, delta): qc.rz(-(beta+delta)/2, qbits) qc.ry(-gamma/2, qbits) def C_gate(qc, qbits, beta, delta): qc.rz((delta-beta)/2, qbits) # Higher abstraction functions. def controlled_V(qc, control, target): C_gate(qc, target, V_beta, V_delta) qc.cx(control, target) B_gate(qc, target, V_beta, V_gamma, V_delta) qc.cx(control, target) A_gate(qc, target, V_beta, V_gamma) qc.t(control) # Using T gate because V_alpha = pi/4. def controlled_Vdg(qc, control, target): C_gate(qc, target, V_beta, V_delta) qc.cx(control, target) B_gate(qc, target, V_beta, -V_gamma, V_delta) qc.cx(control, target) A_gate(qc, target, V_beta, -V_gamma) qc.tdg(control) # Using Tdg gate because V_alpha = pi/4, so Vdg_alpha would be -pi/4. def double_controlled_X(qc, control1, control2, target): controlled_V(qc, control2, target) qc.cx(control1, control2) controlled_Vdg(qc, control2, target) qc.cx(control1, control2) controlled_V(qc, control1, target) ############ Constructing the circuit ############## qc6 = QuantumCircuit(7, 5) # No need to measure ancillary qubits :P # q0, q1, q2, q3 are control qubits # q4, q5 are ancillary qubits # q6 is the target qubit # Change the following line to try different combinations of control qubits: qc6.x([0,1,2,3]) C_gate(qc6, 6, H_beta, H_delta) double_controlled_X(qc6, 0, 1, 4) double_controlled_X(qc6, 2, 3, 5) double_controlled_X(qc6, 4, 5, 6) double_controlled_X(qc6, 2, 3, 5) double_controlled_X(qc6, 0, 1, 4) B_gate(qc6, 6, H_beta, H_gamma, H_delta) double_controlled_X(qc6, 0, 1, 4) double_controlled_X(qc6, 2, 3, 5) double_controlled_X(qc6, 4, 5, 6) double_controlled_X(qc6, 2, 3, 5) double_controlled_X(qc6, 0, 1, 4) A_gate(qc6, 6, H_beta, H_gamma) qc6.s([0,1,2,3]) # Using S gate because H_alpha = pi/2. qc6.measure(0, 0) qc6.measure(1, 1) qc6.measure(2, 2) qc6.measure(3, 3) qc6.measure(6, 4) qc6.draw('mpl') def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') result = execute(qc, backend, shots = 2000).result() counts = result.get_counts() return counts counts = run_circuit(qc6) print(counts) plot_histogram(counts)
https://github.com/madmen2/QASM
madmen2
import numpy as np from qiskit import * import matplotlib qr = QuantumRegister(2) #measurements from quantum bits = use classical register cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.draw() # adding quantum gates to create entanglement (Hadamart gate) circuit.h(qr[0]) %matplotlib inline circuit.draw(output='mpl') #two qubit operation control X (logical if) circuit.cx(qr[0], qr[1]) circuit.draw(output='mpl') #entanglement achieved #measurement, storing measurements into computational register circuit.measure(qr,cr) circuit.draw(output='mpl') #performance simulations simulator = Aer.get_backend('qasm_simulator') execute(circuit, backend = simulator) result = execute(circuit, backend = simulator).result() #plotting results from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) #running circuit on quantum computer IBMQ.load_account() provider= IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmq_manila') job= execute(circuit, backend=qcomp) from qiskit.tools import job_monitor job_monitor(job) result = job.result() from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit), title='Performance metric on Quantum Computer')
https://github.com/renatawong/classical-shadow-vqe
renatawong
# Installation of the requirements #!python -m pip install -r requirements.txt ''' (C) Renata Wong 2023 Qiskit code for testing fidelity of randomised classical shadow on the ground state energy of molecules. Procedure: 1. Choose a variational ansatz with initial parameters selected at random. 2. Generate a set of random basis change operators. 3. Apply the random operators to change bases in the ansatz. 4. Measure the ansatz in the Pauli Z basis and store the results as a shadow. 5. Obtain the expectation value of the molecular Hamiltonian from the shadow. 6. Optimize for minimum Hamiltonian expectation value. 7. Feed the calculated angles/parameters back to the ansatz. 8. Repeat steps 3-7 till the optimization is completed. 9. Output the minimized expectation value of the molecular Hamiltonian and the mean-square-root-error. Note: Below we perform calculations on the molecular Hamiltonian of H_2. To perform calculations on other molecules, you will need to specify their geometry, charge and spin to replace the values in the driver. Note: predicting_quantum_properties module comes from https://github.com/hsinyuan-huang/predicting-quantum-properties ''' from qiskit import QuantumCircuit, execute from qiskit_aer import QasmSimulator from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.mappers import BravyiKitaevMapper from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms import GroundStateEigensolver from qiskit.circuit.library import EfficientSU2 from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA import time import numpy as np from functools import partial import matplotlib.pyplot as plt from collections import Counter from predicting_quantum_properties.data_acquisition_shadow import randomized_classical_shadow from predicting_quantum_properties.prediction_shadow import estimate_exp # handle deprecation issues import qiskit_nature qiskit_nature.settings.use_pauli_sum_op = False import h5py H5PY_DEFAULT_READONLY=1 # classically obtained ground state energy EXPECTED_EIGENVALUE = -1.86 # specifying the geometry of the molecule in question driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.735", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) problem = driver.run() hamiltonian = problem.hamiltonian # electronic Hamiltonian of the system second_q_op = hamiltonian.second_q_op() # The Bravyi-Kitaev repserentation of the Fermionic Hamiltonian mapper = BravyiKitaevMapper() bkencoded_hamiltonian = mapper.map(second_q_op) print(bkencoded_hamiltonian) def process_hamiltonian(hamiltonian, derandomize = False): hamiltonian_observables = [] hamiltonian_coefficients = [] for observable in hamiltonian.paulis: op_list = [] for op_index, pauli_op in enumerate(observable): pauli_op = str(pauli_op) if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z': op_list.append((pauli_op, op_index)) hamiltonian_observables.append(op_list) hamiltonian_coefficients = hamiltonian.coeffs.real system_size = len(hamiltonian_observables[0]) # removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left # these observables are needed for estimate_exp() observables_xyze = [] for observable in hamiltonian_observables: XYZE = [] for pauli in observable: if pauli[0] != 'I': XYZE.append(pauli) observables_xyze.append(XYZE) # derandomisation procedure requires that coefficients are non-negative if derandomize == True: absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients] # removing the empty list as well # these observables are needed for derandomisation procedure observables_xyz = [] for idx, observable in enumerate(observables_xyze): if observable: observables_xyz.append(observable) else: absolute_coefficients.pop(idx) return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients return system_size, observables_xyze, hamiltonian_coefficients # process the Hamiltonian to obtain properly formatted data hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = False) system_size, observables_xyze, hamiltonian_coefficients = hamiltonian_data #print('HAMILTONIAN\n', observables_xyze) ''' VARIATIONAL ANSATZ Note that for molecules other than H_2 you may need to specify a different number of reps. ''' reps = 1 ansatz = EfficientSU2(system_size, su2_gates=['rx', 'ry'], entanglement='circular', reps=reps, skip_final_rotation_layer=False) ansatz.decompose().draw('mpl') ''' COST FUNCTION ''' def basis_change_circuit(pauli_op): # Generating circuit with just the basis change operators # # pauli_op: n-qubit Pauli operator basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits) for idx, op in enumerate(pauli_op): if op == 'X': basis_change.h(idx) elif op == 'Y': basis_change.h(idx) basis_change.p(-np.pi/2, idx) return basis_change def min_cost(): return min(cost_history) def log_cost(cost): global cost_history cost_history.append(cost) def objective_function(operators, params): backend = QasmSimulator(method='statevector', shots=1) pauli_op_dict = Counter(tuple(x) for x in operators) shadow = [] for pauli_op in pauli_op_dict: qc = ansatz.bind_parameters(params) qc = qc.compose(basis_change_circuit(pauli_op)) qc.measure(reversed(range(system_size)), range(system_size)) result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result() counts = result.get_counts() for count in counts: for _ in range(counts[count]): # number of repeated measurement values output_str = list(count) output = [int(i) for i in output_str] eigenvals = [x+1 if x == 0 else x-2 for x in output] snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)] shadow.append(snapshot) cost = 0.0 for term, weight in zip(observables_xyze, hamiltonian_coefficients): sum_product, match_count = estimate_exp(shadow, term) if match_count != 0: exp_val = sum_product / match_count cost += weight * exp_val log_cost(cost) return cost ''' RUNNING EXPERIMENTS ''' start_time = time.time() rmse_errors = [] print('NUMBER OF OPERATORS | RANDOMISED OPERATORS | AVERAGE RMSE ERROR\n') measurement_range = [50, 100, 200, 600, 1000, 1600] for num_operators in measurement_range: basis_change = randomized_classical_shadow(num_operators, system_size) tuples = (tuple(pauli) for pauli in basis_change) counts = Counter(tuples) optimizer = SPSA(maxiter=2000) cost_function = partial(objective_function, basis_change) expectation_values = [] num_experiments = 5 for iteration in range(num_experiments): cost_history = [] params = np.random.rand(ansatz.num_parameters) result = optimizer.minimize(fun=cost_function, x0=params) minimal_cost = min_cost() expectation_values.append(minimal_cost) print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, minimal_cost)) rmse_randomised_cs = np.sqrt(np.sum([(expectation_values[i] - EXPECTED_EIGENVALUE)**2 for i in range(num_experiments)])/num_experiments) rmse_errors.append(rmse_randomised_cs) print('{} | {} | {}'.format(num_operators, counts, rmse_randomised_cs)) elapsed_time = time.time() - start_time print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time))) points = measurement_range num_points = len(measurement_range) plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label='SPSA(maxiter=2000)') plt.xlabel('Number of measurements') plt.ylabel('Average RMSE error') plt.legend(loc=1)
https://github.com/lvillasen/Quantum-Teleportation-with-Qiskit-on-a-Real-Computer
lvillasen
!pip install qiskit !pip install pylatexenc import numpy as np from qiskit.visualization import array_to_latex from qiskit.quantum_info import random_statevector psi = random_statevector(2) display(array_to_latex(psi, prefix="|\\psi\\rangle =")) from qiskit import QuantumCircuit, assemble, Aer import qiskit.quantum_info as qi import numpy as np import qiskit.quantum_info as qi qc = QuantumCircuit(3,2) qc.initialize(psi, 0) stv0 = qi.Statevector.from_instruction(qc) qc.barrier() qc.h(1) # Hadamard qc.cx(1,2) # CNOT qc.barrier() qc.cx(0,1) qc.h(0) qc.barrier() stv = qi.Statevector.from_instruction(qc) qc.measure(0,0) qc.measure(1,1) qc.draw("mpl") from qiskit.visualization import plot_bloch_multivector plot_bloch_multivector(stv0) from qiskit import QuantumCircuit, Aer,execute from qiskit.visualization import plot_histogram backend = Aer.get_backend("qasm_simulator") shots = 1000 #backend = Aer.get_backend('qasm_simulator') job = backend.run(qc, shots=1) print(job.result().get_counts(qc)) plot_histogram(job.result().get_counts()) import qiskit.quantum_info as qi import numpy as np qc1 = QuantumCircuit(3,2) print(job.result().get_counts()) for key in job.result().data()["counts"]: if int(key,0) == 0 : print("Result: 00") q2_state = [np.round(stv[0],3),np.round(stv[4],3)] qc1.initialize(0, 0) qc1.initialize(0, 1) elif int(key,0) == 1 : print("Result: 01") q2_state = [np.round(stv[1],3),np.round(stv[5],3)] qc1.initialize(1, 0) qc1.initialize(0, 1) elif int(key,0) == 2 : print("Result: 10") q2_state = [np.round(stv[2],3),np.round(stv[6],3)] qc1.initialize(0, 0) qc1.initialize(1, 1) elif int(key,0) == 3 : print("Result: 11") q2_state = [np.round(stv[3],3),np.round(stv[7],3)] qc1.initialize(1, 0) qc1.initialize(1, 1) q2_normalizado = q2_state/np.linalg.norm(q2_state) qc1.barrier() qc1.initialize(q2_normalizado, 2) for key in job.result().data()["counts"]: if int(key,0) == 1 : qc1.z(2) if int(key,0) == 2 : qc1.x(2) if int(key,0) == 3 : qc1.x(2) qc1.z(2) stv1 = qi.Statevector.from_instruction(qc1) stv1.draw('latex', prefix='Estado \quad del \quad qubit \quad 2 = ') import qiskit.quantum_info as qi import numpy as np qc2 = QuantumCircuit(3,2) for key in job.result().data(qc)["counts"]: if int(key,0) != 0 : qc2.initialize(psi, 2) qcc = qc.compose(qc1) qc3 = qcc.compose(qc2) qc3.draw("mpl") from qiskit.visualization import plot_bloch_multivector plot_bloch_multivector(stv1) from qiskit import IBMQ from qiskit import QuantumCircuit from qiskit_aer import AerSimulator from qiskit.tools.visualization import plot_histogram from qiskit.providers.ibmq import least_busy IBMQ.save_account('CLAVE',overwrite=True) # See https://quantum-computing.ibm.com/ IBMQ.load_account() # Load account from disk print(IBMQ.providers()) # List all available providers provider = IBMQ.get_provider(hub='ibm-q') provider.backends() from qiskit_aer.noise import NoiseModel provider = IBMQ.load_account() backend = provider.get_backend('ibmq_manila') noise_model = NoiseModel.from_backend(backend) print("----------Noise Model for",backend,"--------------\n",noise_model) provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) print("----------Noise Model for",backend,"--------------\n",noise_model) from qiskit import QuantumCircuit, assemble, Aer from qiskit import IBMQ, transpile from qiskit.providers.ibmq import least_busy from qiskit.tools.visualization import plot_histogram import qiskit.quantum_info as qi import numpy as np import qiskit.quantum_info as qi theta=np.pi*np.random.rand() phi = 2*np.pi*np.random.rand() print("theta =",np.round(theta,2),"rad, theta =",np.round(180*theta/np.pi,2),"degrees") print("phi=",np.round(phi,2),"rad, phi =",np.round(180*phi/np.pi,2),"degrees") qc = QuantumCircuit(3,3) qc.ry(theta,0) qc.rz(phi,0) stv0 = qi.Statevector.from_instruction(qc) qc.barrier() qc.h(1) # Hadamard qc.cx(1,2) # CNOT qc.barrier() qc.cx(0,1) qc.h(0) qc.barrier() qc.rz(-phi,2) qc.ry(-theta,2) qc.measure(0,0) qc.measure(1,1) qc.measure(2,2) qc.draw("mpl") from qiskit.visualization import plot_bloch_multivector plot_bloch_multivector(stv0) from qiskit import IBMQ, transpile sim_backend = AerSimulator.from_backend(backend) print("least busy backend: ", sim_backend) # Transpile the circuit for the noisy basis gates tqc = transpile(qc, sim_backend,optimization_level=3) # Execute noisy simulation and get counts job = sim_backend.run(tqc,shots=1000) print("Counts for teleportation with simulated noise model for", backend,"\n\n") try : n_error = job.result().get_counts(qc)['100'] except: n_error = 0 import matplotlib.pyplot as plt try : n_error = job.result().get_counts(qc)['100'] except: n_error = 0 import matplotlib.pyplot as plt fig = plt.figure(figsize=(10,6)) states = ['000', '100'] counts = [job.result().get_counts(qc)['000'],n_error] plt.rcParams.update({'font.size': 20}) plt.bar(states,counts,width=0.4, bottom=None,align='center', data=None) for index, value in enumerate(counts): plt.text(index, value, str(value),fontsize=20) plt.xlabel('States',fontsize=20) plt.ylabel('Counts',fontsize=20) plt.show() tqc.draw("mpl") from qiskit import IBMQ from qiskit import QuantumCircuit from qiskit_aer import AerSimulator from qiskit.tools.visualization import plot_histogram from qiskit.providers.ibmq import least_busy IBMQ.load_account() # Load account from disk provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) print("----------Noise Model for",backend,"--------------\n",noise_model) from qiskit import QuantumCircuit, assemble, Aer from qiskit.providers.ibmq import least_busy from qiskit.tools.visualization import plot_histogram import qiskit.quantum_info as qi import numpy as np import qiskit.quantum_info as qi theta=np.pi*np.random.rand() phi = 2*np.pi*np.random.rand() print("theta =",np.round(theta,2),"rad, theta =",np.round(180*theta/np.pi,2),"degrees") print("phi=",np.round(phi,2),"rad, phi =",np.round(180*phi/np.pi,2),"degrees") qc = QuantumCircuit(3,3) qc.ry(theta,0) qc.rz(phi,0) stv0 = qi.Statevector.from_instruction(qc) qc.barrier() qc.h(1) # Hadamard qc.cx(1,2) # CNOT qc.barrier() qc.cx(0,1) qc.h(0) qc.barrier() qc.rz(-phi,2) qc.ry(-theta,2) qc.measure(0,0) qc.measure(1,1) qc.measure(2,2) qc.draw("mpl") from qiskit.visualization import plot_bloch_multivector plot_bloch_multivector(stv0) from qiskit import IBMQ, transpile tqc = transpile(qc, backend, optimization_level=3) job_teleportation = backend.run(tqc,shots = 1000) print(job_teleportation.status(),job_teleportation.queue_position()) print("Counts for teleportation on", backend,"\n\n") try : n_error = job.result().get_counts(qc)['100'] except: n_error = 0 import matplotlib.pyplot as plt try : n_error = job.result().get_counts(qc)['100'] except: n_error = 0 import matplotlib.pyplot as plt fig = plt.figure(figsize=(10,6)) states = ['000', '100'] counts = [job_teleportation.result().get_counts(qc)['000'],n_error] plt.rcParams.update({'font.size': 20}) plt.bar(states,counts,width=0.4, bottom=None,align='center', data=None) for index, value in enumerate(counts): plt.text(index, value, str(value),fontsize=20) plt.xlabel('States',fontsize=20) plt.ylabel('Counts',fontsize=20) plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import execute, pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(100, 1.0), d0) pulse_prog.draw()
https://github.com/unif2/Quantum-Computing-Mentorship-Task-4-Code
unif2
import numpy as np from numpy import kron import qiskit as qk def decomposition(H): """Decompose any 4x4 Hermitian matrix into a sum of tensor products of two Pauli matrices """ identity = np.array([[1, 0],[ 0, 1]], dtype=np.complex128) x = np.array([[0, 1], [ 1, 0]], dtype=np.complex128) y = np.array([[0, -1j],[1j, 0]], dtype=np.complex128) z = np.array([[1, 0], [0, -1]], dtype=np.complex128) S = [identity, x, y, z] labels = ['I', 'sigma_x', 'sigma_y', 'sigma_z'] d = {'00': 'I product I', '01': 'I product sigma_x', '02': 'I product sigma_y', '03': 'I product sigma_z', '10': 'sigma_x product I', '11': 'sigma_x product sigma_x', '12': 'sigma_x product sigma_y', '13': 'sigma_x product sigma_z', '20': 'sigma_y product I', '21': 'sigma_y product sigma_x', '22': 'sigma_y product sigma_y', '23': 'sigma_y product sigma_z', '30': 'sigma_z product I', '31': 'sigma_z product sigma_x', '32': 'sigma_z product sigma_y', '33': 'sigma_z product sigma_z'} for i in range(4): for j in range(4): a_ij = 0.25 * np.dot(kron(S[i], S[j]), H).trace() if a_ij != 0.0: print(str(a_ij) + ' * ' + d[str(i)+str(j)]) H = np.array([[0,0,0,0],[0,-1,1,0],[0,1,-1,0],[0,0,0,0]]) decomposition(H) def prepare_state(theta, n=3): """ Prepare three 2-qubit states with 3 associated quantum registers, 3 associated classical registers, and 3 quantum circuits. We will prepare the state with the ansatz mentioned in the notes in which we act on the first qubit with the Hadamard operator, then with the R_z operator, then we act on the 2-qubit state with the CNOT gate, and then on the second qubit in each terms of the superposition with the sigma_x operator. After that, we will take the first circuit and act on each qubit with the R_y(pi/2) operator, and take the second circuit and act on each qubit with the R_x(-pi/2) operator as explained in the notes. We do this so that those qubits will be in the basis of eigenvectors of sigma_x and sigma_y as explained in the notes. We can measure the qubits in the other circuit as-is because we need the expectation value of sigma_z and the qubits are already in the computational basis. """ qr0 = qk.QuantumRegister(2) cr0 = qk.ClassicalRegister(2) qc0 = qk.QuantumCircuit(qr0,cr0) qr1 = qk.QuantumRegister(2) cr1 = qk.ClassicalRegister(2) qc1 = qk.QuantumCircuit(qr1,cr1) qr2 = qk.QuantumRegister(2) cr2 = qk.ClassicalRegister(2) qc2 = qk.QuantumCircuit(qr2,cr2) qregisters = [qr0,qr1,qr2] cregisters = [cr0,cr1,cr2] qcircuits = [qc0,qc1,qc2] for i in range(n): qcircuits[i].h(qregisters[i][0]) for i in range(n): qcircuits[i].rz(theta, qregisters[i][0]) for i in range(n): qcircuits[i].cx(qregisters[i][0], qregisters[i][1]) for i in range(n): qcircuits[i].x(qregisters[i][1]) qcircuits[0].ry((np.pi)/2, qregisters[0][0]) qcircuits[0].ry((np.pi)/2, qregisters[0][1]) qcircuits[1].rx(-(np.pi)/2, qregisters[1][0]) qcircuits[1].rx(-(np.pi)/2, qregisters[1][1]) return qregisters, cregisters, qcircuits qregisters, cregisters, qcircuits = prepare_state(np.pi, n=3) qcircuits[0].draw(output='mpl') qcircuits[1].draw(output='mpl') qcircuits[2].draw(output='mpl') def expectation(qcircuits, cregisters, qregisters, n_shots, n=3): """ For each circuit, execute and measure it using the classical simulator 5000 times as explained above. Multiply each of the three expectation values by 0.5, add them up, and subtract -0.5. Return the result. """ expect = -0.5 for i in range(n): qcircuits[i].measure(qregisters[i],cregisters[i]) qk.Aer.backends() sim = qk.Aer.get_backend('qasm_simulator') res = qk.execute(qcircuits[i], sim, shots=n_shots).result() counts = res.get_counts() sum = 0 for k,v in counts.items(): if k=='01' or k=='10': sum += (-1)*v/n_shots elif k=='00' or k=='11': sum += v/n_shots sum = 0.5*sum expect += sum return expect # Consider 100 values of theta, between 0 and Pi. This theta is the one used in state preparation. thetas = np.linspace(0, np.pi, 100) # For each theta, store the resulting expectation value in results results = [] # For each theta, find the expectation value for theta in thetas: qregisters, cregisters, qcircuits = prepare_state(theta, n=3) expect = expectation(qcircuits, cregisters, qregisters, 5000, n=3) results.append(expect) # Sort the results in ascending order. The first one is your minimum eigenvalue. results.sort() print("The minimum eigenvalue is: {}.".format(results[0])) from qiskit import IBMQ #IBMQ.delete_account() IBMQ.save_account('my IBM token', overwrite=True) IBMQ.load_account() provider = IBMQ.get_provider() procs=provider.backends(operational=True, simulator=False) from qiskit.tools.jupyter import * %qiskit_backend_overview from qiskit.tools import monitor backend = qk.providers.ibmq.least_busy([p for p in procs if len(p.properties().qubits) >= 2]) from qiskit.tools.monitor import backend_overview, backend_monitor backend_monitor(backend) def q_expectation(qcircuits, cregisters, qregisters, n_shots, n=3): """ For each circuit, execute and measure it using the classical simulator 5000 times as explained above. Multiply each of the three expectation values by 0.5, add them up, and subtract -0.5. Return the result. """ expect = -0.5 for i in range(n): qcircuits[i].measure(qregisters[i],cregisters[i]) qk.Aer.backends() sim = qk.Aer.get_backend('qasm_simulator') res = qk.execute(qcircuits[i], backend=backend, shots=n_shots).result() #mon = monitor.job_monitor(res) counts = res.get_counts() sum = 0 for k,v in counts.items(): if k=='01' or k=='10': sum += (-1)*v/n_shots elif k=='00' or k=='11': sum += v/n_shots sum = 0.5*sum expect += sum return expect # Consider 10 values of theta, between 0 and Pi. This theta is the one used in state preparation. thetas = np.linspace(0, np.pi, 10) # Use n_shots = 100 results = [] # For each theta, find the expectation value for theta in thetas: qregisters, cregisters, qcircuits = prepare_state(theta, n=3) expect = q_expectation(qcircuits, cregisters, qregisters, 100, n=3) results.append(expect) # Sort the results in ascending order. The first one is your minimum eigenvalue. results.sort() print("The minimum eigenvalue is: {}.".format(results[0])) # Use n_shots = 1000 results = [] # For each theta, find the expectation value for theta in thetas: qregisters, cregisters, qcircuits = prepare_state(theta, n=3) expect = q_expectation(qcircuits, cregisters, qregisters, 1000, n=3) results.append(expect) # Sort the results in ascending order. The first one is your minimum eigenvalue. results.sort() print("The minimum eigenvalue is: {}.".format(results[0])) # Use n_shots = 5000 results = [] # For each theta, find the expectation value for theta in thetas: qregisters, cregisters, qcircuits = prepare_state(theta, n=3) expect = q_expectation(qcircuits, cregisters, qregisters, 5000, n=3) results.append(expect) # Sort the results in ascending order. The first one is your minimum eigenvalue. results.sort() print("The minimum eigenvalue is: {}.".format(results[0])) # Use n_shots = 8192 = max allowed results = [] thetas = [np.pi] # For each theta, find the expectation value for theta in thetas: qregisters, cregisters, qcircuits = prepare_state(theta, n=3) expect = q_expectation(qcircuits, cregisters, qregisters, 8192, n=3) results.append(expect) # Sort the results in ascending order. The first one is your minimum eigenvalue. results.sort() print("The minimum eigenvalue is: {}.".format(results[0])) def decomposition(H): """Decompose any 4x4 Hermitian matrix into a sum of tensor products of two Pauli matrices """ A_ij = [] identity = np.array([[1, 0],[ 0, 1]], dtype=np.complex128) x = np.array([[0, 1], [ 1, 0]], dtype=np.complex128) y = np.array([[0, -1j],[1j, 0]], dtype=np.complex128) z = np.array([[1, 0], [0, -1]], dtype=np.complex128) S = [identity, x, y, z] labels = ['I', 'sigma_x', 'sigma_y', 'sigma_z'] d = {'00': 'I product I', '01': 'I product sigma_x', '02': 'I product sigma_y', '03': 'I product sigma_z', '10': 'sigma_x product I', '11': 'sigma_x product sigma_x', '12': 'sigma_x product sigma_y', '13': 'sigma_x product sigma_z', '20': 'sigma_y product I', '21': 'sigma_y product sigma_x', '22': 'sigma_y product sigma_y', '23': 'sigma_y product sigma_z', '30': 'sigma_z product I', '31': 'sigma_z product sigma_x', '32': 'sigma_z product sigma_y', '33': 'sigma_z product sigma_z'} for i in range(4): for j in range(4): a_ij = 0.25 * np.dot(kron(S[i], S[j]), H).trace() A_ij.append(a_ij) if a_ij != 0.0: print(str(a_ij) + ' * ' + d[str(i)+str(j)]) return np.asarray(A_ij).reshape(4,4) def prepare_state2(A, theta): qregisters = [] cregisters = [] qcircuits = [] identity = np.array([[1, 0],[ 0, 1]], dtype=np.complex128) x = np.array([[0, 1], [ 1, 0]], dtype=np.complex128) y = np.array([[0, -1j],[1j, 0]], dtype=np.complex128) z = np.array([[1, 0], [0, -1]], dtype=np.complex128) d = {} for i in range(4): for j in range(4): if A[i,j] != 0: if i !=0 and j!=0: qr = qk.QuantumRegister(2) cr = qk.ClassicalRegister(2) qc = qk.QuantumCircuit(qr,cr) qc.h(qr[0]) qc.rz(theta, qr[0]) qc.cx(qr[0], qr[1]) qc.x(qr[1]) if i==1: qc.ry((np.pi)/2, qr[0]) if i==2: qc.rx(-(np.pi)/2, qr[0]) if j==1: qc.ry((np.pi)/2, qr[1]) if j==2: qc.rx(-(np.pi)/2, qr[1]) qregisters.append(qr) cregisters.append(cr) qcircuits.append(qc) d[(i,j)] = [qregisters, cregisters, qcircuits] if i == 0 and j != 0: qr = qk.QuantumRegister(2) cr = qk.ClassicalRegister(2) qc = qk.QuantumCircuit(qr,cr) qc.h(qr[0]) qc.rz(theta, qr[0]) qc.cx(qr[0], qr[1]) qc.x(qr[1]) if j==1: qc.ry((np.pi)/2, qr[1]) if j==2: qc.rx(-(np.pi)/2, qr[1]) qregisters.append(qr) cregisters.append(cr) qcircuits.append(qc) d[(i,j)] = [qregisters, cregisters, qcircuits] if i != 0 and j == 0: qr = qk.QuantumRegister(2) cr = qk.ClassicalRegister(2) qc = qk.QuantumCircuit(qr,cr) qc.h(qr[0]) qc.rz(theta, qr[0]) qc.cx(qr[0], qr[1]) qc.x(qr[1]) if i==1: qc.ry((np.pi)/2, qr[0]) if i==2: qc.rx(-(np.pi)/2, qr[0]) qregisters.append(qr) cregisters.append(cr) qcircuits.append(qc) d[(i,j)] = [qregisters, cregisters, qcircuits] return d, A def expectation2(d, A, n_shots): """ For each circuit, execute and measure it using the classical simulator 5000 times as explained above. Return the result. """ expect = A[0,0] qk.Aer.backends() sim = qk.Aer.get_backend('qasm_simulator') for k,v in d.items(): for i in range(len(v[2])): v[2][i].measure(v[0][i],v[1][i]) res = qk.execute(v[2][i], sim, shots=n_shots).result() counts = res.get_counts() sum = 0 for m,n in counts.items(): if m=='01' or m=='10': sum += (-1)*n/n_shots elif m=='00' or m=='11': sum += n/n_shots sum = A[k[0],k[1]]*sum expect += sum return expect thetas = np.linspace(0, np.pi, 100) H = np.array([[0,0,0,0],[0,-1,1,0],[0,1,-1,0],[0,0,0,0]]) A = decomposition(H) # For each theta, store the resulting expectation value in results results = [] # For each theta, find the expectation value for theta in thetas: d, A = prepare_state2(A, theta) expect = expectation2(d, A, 5000) results.append(expect) # Sort the results in ascending order. The first one is your minimum eigenvalue. results.sort() print("The minimum eigenvalue is: {}.".format(results[0])) # -5??!! Maybe I missed something in my logic. Will continue to look into this. :-)
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
nahumsa
%matplotlib inline import qiskit as qsk import numpy as np import matplotlib.pyplot as plt qreg = qsk.QuantumRegister(2, name='q') circ = qsk.QuantumCircuit(qreg) circ.draw('mpl') circ.x(qreg[0]); #Add x on 0 circ.draw('mpl') circ.h(qreg[0]); #Add x on 0 circ.draw('mpl') circ.cx(qreg[0], qreg[1]); #Add CNOT on 0 and 1 circ.draw(output='mpl') backend = qsk.Aer.get_backend('statevector_simulator') job = qsk.execute(circ, backend) result = job.result() outputstate = result.get_statevector(circ, decimals=3) print(outputstate) from qiskit.visualization import plot_state_city plot_state_city(outputstate) creg = qsk.ClassicalRegister(2, name='c') circ.add_register(creg) circ.draw('mpl') circ.measure(qreg,creg) circ.draw('mpl') backend_sim = qsk.Aer.get_backend('qasm_simulator') job_sim = qsk.execute(circ, backend_sim, shots=1024) result_sim = job_sim.result() counts = result_sim.get_counts(circ) print(counts) from qiskit.visualization import plot_histogram plot_histogram(counts) from qiskit import IBMQ token = np.loadtxt("Token.txt", unpack=True, dtype=str) IBMQ.save_account(token, overwrite=True) provider = IBMQ.load_account(); backend_list = provider.backends() for i in backend_list: print(f'{i} \n') from qiskit.providers.ibmq import least_busy num_qubits = 2 backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= num_qubits and not x.configuration().simulator and x.status().operational==True)) backend from qiskit.tools.monitor import job_monitor job_exp = qsk.execute(circ, backend=backend) job_monitor(job_exp) result_exp = job_exp.result() from qiskit.visualization import plot_histogram counts_exp = result_exp.get_counts(circ) plot_histogram([counts_exp,counts], legend=['Device', 'Simulator']) job_id = job_exp.job_id() print('JOB ID: {}'.format(job_id)) retrieved_job = backend.retrieve_job(job_id) retrieved_job.result().get_counts(circ) qsk.__qiskit_version__ from qiskit.tools.jupyter import * %qiskit_version_table
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/Qiskit/feedback
Qiskit
from qiskit_aer.primitives import Estimator from qiskit.quantum_info import SparsePauliOp from qiskit.circuit.library import RealAmplitudes ansatz = RealAmplitudes(num_qubits=2, reps=2) observable = SparsePauliOp.from_list([("XX", 1), ("YY", 2), ("ZZ", 3)]) estimator = Estimator() result = estimator.run(ansatz, observable, parameter_values=[0, 1, 1, 2, 3, 5]).result() print("Expectation value:", result.values) estimator = Estimator(approximation=True) result = estimator.run(ansatz, observable, parameter_values=[0, 1, 1, 2, 3, 5]).result() print("Expectation value:", result.values) from itertools import product import numpy as np num_qubits = 8 abelian_grouping = True ansatz = RealAmplitudes(num_qubits=num_qubits, reps=1) observables = [ SparsePauliOp("".join(pauli_str)) for pauli_str in product("IZ", repeat=num_qubits) ] parameter_values = list(np.random.rand(1, ansatz.num_parameters)) estimator = Estimator(abelian_grouping=abelian_grouping) %%time result = estimator.run( circuits=[ansatz] * len(observables), observables=observables, parameter_values=parameter_values * len(observables), ).result() # opflow and estimator can group SparsePauliOp(["XX", "XI"]) # Estimator can group [SparsePauliOp("XX"), SparsePauliOp("XI")]
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the TrivialLayout pass""" import unittest from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit.transpiler import CouplingMap from qiskit.transpiler.passes import TrivialLayout from qiskit.transpiler.target import Target from qiskit.circuit.library import CXGate from qiskit.transpiler import TranspilerError from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeTenerife, FakeRueschlikon class TestTrivialLayout(QiskitTestCase): """Tests the TrivialLayout pass""" def setUp(self): super().setUp() self.cmap5 = FakeTenerife().configuration().coupling_map self.cmap16 = FakeRueschlikon().configuration().coupling_map def test_3q_circuit_5q_coupling(self): """Test finds trivial layout for 3q circuit on 5q device.""" qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) circuit.cx(qr[0], qr[2]) circuit.cx(qr[1], qr[2]) dag = circuit_to_dag(circuit) pass_ = TrivialLayout(CouplingMap(self.cmap5)) pass_.run(dag) layout = pass_.property_set["layout"] for i in range(3): self.assertEqual(layout[qr[i]], i) def test_3q_circuit_5q_coupling_with_target(self): """Test finds trivial layout for 3q circuit on 5q device.""" qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) circuit.cx(qr[0], qr[2]) circuit.cx(qr[1], qr[2]) dag = circuit_to_dag(circuit) target = Target() target.add_instruction(CXGate(), {tuple(edge): None for edge in self.cmap5}) pass_ = TrivialLayout(target) pass_.run(dag) layout = pass_.property_set["layout"] for i in range(3): self.assertEqual(layout[qr[i]], i) def test_9q_circuit_16q_coupling(self): """Test finds trivial layout for 9q circuit with 2 registers on 16q device.""" qr0 = QuantumRegister(4, "q0") qr1 = QuantumRegister(5, "q1") cr = ClassicalRegister(2, "c") circuit = QuantumCircuit(qr0, qr1, cr) circuit.cx(qr0[1], qr0[2]) circuit.cx(qr0[0], qr1[3]) circuit.cx(qr1[4], qr0[2]) circuit.measure(qr1[1], cr[0]) circuit.measure(qr0[2], cr[1]) dag = circuit_to_dag(circuit) pass_ = TrivialLayout(CouplingMap(self.cmap16)) pass_.run(dag) layout = pass_.property_set["layout"] for i in range(4): self.assertEqual(layout[qr0[i]], i) for i in range(5): self.assertEqual(layout[qr1[i]], i + 4) def test_raises_wider_circuit(self): """Test error is raised if the circuit is wider than coupling map.""" qr0 = QuantumRegister(3, "q0") qr1 = QuantumRegister(3, "q1") circuit = QuantumCircuit(qr0, qr1) circuit.cx(qr0, qr1) dag = circuit_to_dag(circuit) with self.assertRaises(TranspilerError): pass_ = TrivialLayout(CouplingMap(self.cmap5)) pass_.run(dag) if __name__ == "__main__": unittest.main()
https://github.com/victor-onofre/Quantum_Algorithms
victor-onofre
import numpy as np from qiskit import QuantumCircuit as QC from qiskit import execute from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit.tools.jupyter import * provider = IBMQ.load_account() from qiskit.visualization import plot_histogram def oracle(case, n): ##creating an oracle oracle_qc = QC(n+1) if case=="balanced": for i in range(n): oracle_qc.cx(i,n) if case=="constant": pass ##converting circuit to a indivsual gate oracle_gate = oracle_qc.to_gate() oracle_gate.name = "Oracle" return oracle_gate def dj_algo(n, case="random"): dj_crc = QC(n+1,n) for i in range(n): dj_crc.h(i) dj_crc.x(n) dj_crc.h(n) if case=="random": rnd = np.random.randint(2) if rnd == 0: case = "constant" else: case = "balanced" dj_oracle = oracle(case, n) dj_crc.append(dj_oracle, range(n+1)) for i in range(n): dj_crc.h(i) dj_crc.measure(i,i) return dj_crc n = 3 dj_crc = dj_algo(n) dj_crc.draw('mpl') #simulating backend=BasicAer.get_backend('qasm_simulator') shots = 1024 dj_circuit = dj_algo(n, "balanced") results = execute(dj_circuit, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer) #running on real quantum computer backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and not x.configuration().simulator and x.status().operational == True)) print("Using least busy backend: ", backend) %qiskit_job_watcher dj_circuit = dj_algo(n, "balanced") job = execute(dj_circuit, backend=backend, shots=shots, optimization_level=3) result = job.result() answer = result.get_counts() plot_histogram(answer)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from math import acos # acos is the inverse of function cosine from math import pi def angle_between_two_quantum_states(quantum_state1,quantum_state2): inner_product = quantum_state1[0] * quantum_state2[0] + quantum_state1[1] * quantum_state2[1] return acos(inner_product) print("function 'angle_between_two_quantum_states' is defined now, and so it can be used in the following part") print("the angle between |0> and |1> is pi/2 (90 degree)") print(angle_between_two_quantum_states([1,0],[0,1]),"is the angle between |0> and |1>") print(pi/2,"is the value of pi/2") print() print("the angle between |0> and the quantum state [3/5,4/5] is around 0.295*pi") print(angle_between_two_quantum_states([3/5,4/5],[1,0]),"is the angle between |0> and the quantum state [3/5,4/5]") print(0.295*pi,"is the value of 0.295*pi") print() print("the angle between |0> and quantum state [-1/(2**0.5),-1/(2**0.5)] is 3pi/4 (135 degree)") print(angle_between_two_quantum_states([-1/(2**0.5),-1/(2**0.5)],[1,0]),"is the angle between |0> and quantum state [-1/(2**0.5),-1/(2**0.5)]") print(3*pi/4,"is the value of 3*pi/4",) print() # # OPTIONAL # # you may also test the function angle_between_two_quantum_states # from random import randrange # randomly create a quantum state of a qubit def random_quantum_state(): first_entry = randrange(100) first_entry = first_entry/100 first_entry = first_entry**0.5 if randrange(2) == 0: # determine the sign of the first entry first_entry = -1 * first_entry second_entry = 1 - (first_entry**2) second_entry = second_entry**0.5 # the second entry cannot be nonnegative if randrange(2) == 0: # determine the sign second_entry = -1 * second_entry return [first_entry,second_entry] print("function 'random_quantum_state' is defined now, and so it can be used in the following part") from math import pi def find_angle_of_a_quantum_state(quantum_state): # find the angle between quantum_state and [1,0] angle = angle_between_two_quantum_states(quantum_state,[1,0]) if quantum_state[1] < 0: # the angle is greater than pi angle = 2 * pi - angle return angle print("function 'find_angle_of_a_quantum_state' is defined now, and so it can be used in the following part") # find the angles of |0>, |1>, -|0>, and -|1> print(find_angle_of_a_quantum_state([1,0]),"is the angle of |0>, which should be 0*pi=",0*pi) print(find_angle_of_a_quantum_state([0,1]),"is the angle of |1>, which should be pi/2=",pi/2) print(find_angle_of_a_quantum_state([-1,0]),"is the angle of -|0>, which should be pi=",pi) print(find_angle_of_a_quantum_state([0,-1]),"is the angle of -|1>, which should be 3*pi/2=",3*pi/2) print() # find the angle of H|0> = [1/2**0.5,1/2**0.5] print(find_angle_of_a_quantum_state([1/2**0.5,1/2**0.5]),"is the angle of H|0>, which should be pi/4=",pi/4) # find the angle of [-1/2**0.5,1/2**0.5], which is pi/2 more than the previous angle print(find_angle_of_a_quantum_state([-1/2**0.5,1/2**0.5]),"is pi/2 more than the previous angle, which should be 3*pi/4=",3*pi/4) # find the angle of [-1/2**0.5,-1/2**0.5], which is pi/2 more than the previous angle print(find_angle_of_a_quantum_state([-1/2**0.5,-1/2**0.5]),"is pi/2 more than the previous angle, which should be 5*pi/4=",5*pi/4) # find the angle of [-1/2**0.5,1/2**0.5], which is pi/2 more than the previous angle print(find_angle_of_a_quantum_state([1/2**0.5,-1/2**0.5]),"is pi/2 more than the previous angle, which should be 7*pi/4=",7*pi/4) def visualize_quantum_states(quantum_states): # import the useful tool for drawing figures in pythpn from matplotlib.pyplot import plot, show, figure, Circle, axis, gca, annotate, arrow, text # import the constant pi from math import pi figure(figsize=(6,6), dpi=80) # size of the figure gca().add_patch( Circle((0,0),1,color='black',fill=False) ) # draw the circle # auxiliary points plot(-1.3,0) plot(1.3,0) plot(0,1.3) plot(0,-1.3) # axes arrow(0,0,1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,-1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,0,-1.1,head_width=0.04, head_length=0.08) arrow(0,0,0,1.1,head_width=0.04, head_length=0.08) # draw all quantum states for quantum_state in quantum_states: # show the quantum state as an arrow on the diagram state_name = quantum_state[0] # label of the quantum state x_value = quantum_state[1] # amplitude of |0> y_value = quantum_state[2] # amplitude of |1> # draw the arrow arrow(0,0,x_value,y_value,head_width=0.04, head_length=0.04,color='blue') # the following code is used to write the name of quantum states if x_value<0: text_x_value=x_value-0.1 else: text_x_value=x_value+0.05 if y_value<0: text_y_value=y_value-0.1 else: text_y_value=y_value+0.05 text(text_x_value,text_y_value,state_name) show() # show the diagram # end of function print("function 'visualize_quantum_states' is defined now, and so it can be used in the following part") # define a list of three quantum states with their labels all_quantum_states =[ ['u',-1/2**0.5,-1/2**0.5], ['v',3/5,4/5], ['|1>',0,1] ] # visualize all quantum states visualize_quantum_states(all_quantum_states) def amplitudes_of_a_quantum_state(quantum_circuit): # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # the following code is used to get the quantum state of a quantum circuit job = execute(quantum_circuit,Aer.get_backend('statevector_simulator')) current_quantum_state=job.result().get_statevector(quantum_circuit) # now we read the real parts of the amplitudes the_first_amplitude = current_quantum_state[0].real # amplitude of |0> the_second_amplitude = current_quantum_state[1].real # amplitude of |1> return[the_first_amplitude,the_second_amplitude] # end of function def reflection_game(): # randomly construct u u = random_quantum_state() print("u is",u) # randomly construct v v = random_quantum_state() print("v is",v) print() # the angle representing u uniquely angle_of_u = find_angle_of_a_quantum_state(u) print("the angle uniquely representing u is",angle_of_u,"=",angle_of_u/pi*180,"degrees") # the angle representing v uniquely angle_of_v = find_angle_of_a_quantum_state(v) print("the angle uniquely representing v is",angle_of_v,"=",angle_of_v/pi*180,"degrees") # the angle between u and v angle_between_u_and_v = angle_of_u-angle_of_v print("the angle between u and v is",angle_between_u_and_v,"=",angle_between_u_and_v/pi*180,"degrees") # # # we find |u>, |v>, and |uv> by writing a quantum program # # # start in |0> # rotate with u_angle to find |u> # rotate with -angle_between_u_and_v to find |v> # rotate with -angle_between_u_and_v once more to find the reflection of |u> over the axis |v> # we use ry-gatefor the rotations # COPY-PASTE from the previous programs # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # we define a quantum circuit with one qubit and one bit qreg1 = QuantumRegister(1) # quantum register with a single qubit creg1 = ClassicalRegister(1) # classical register with a single bit mycircuit1 = QuantumCircuit(qreg1,creg1) # quantum circuits with quantum and classical registers # store all quantum states with their labels all_quantum_states = [ ['0',1,0] # start with |0> ] print()# print an empty line # 1) # already started in |0> # rotate with angle_of_u to find |u> mycircuit1.ry(2*angle_of_u,qreg1[0]) # get the amplitudes of the current quantum state [x_value,y_value] = amplitudes_of_a_quantum_state(mycircuit1) all_quantum_states.append(['u',x_value,y_value]) # add the quantum state u # 2) # rotate with -angle_between_u_and_v to find |v> mycircuit1.ry(-2*angle_between_u_and_v,qreg1[0]) # get the amplitudes of the current quantum state [x_value,y_value] = amplitudes_of_a_quantum_state(mycircuit1) all_quantum_states.append(['v',x_value,y_value]) # add the quantum state v # 3) # rotate with -angle_between_u_and_v once more to find the reflection of |u> over the axis |v> mycircuit1.ry(-2*angle_between_u_and_v,qreg1[0]) # get the amplitudes of the current quantum state [x_value,y_value] = amplitudes_of_a_quantum_state(mycircuit1) all_quantum_states.append(['uv',x_value,y_value]) # add the quantum state uv print("all quantum states:") print(all_quantum_states) # visualize all quantum states visualize_quantum_states(all_quantum_states) # end of function print("function 'reflection game' is defined now, and so it can be used in the following part") # game 1 reflection_game() # game 2 reflection_game() # game 3 reflection_game() # game 4 reflection_game() # game 5 reflection_game() # games 6 - 20 for i in range(6,21): reflection_game()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2024. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test ObservablesArray""" import itertools as it import ddt import numpy as np import qiskit.quantum_info as qi from qiskit.primitives.containers.observables_array import ObservablesArray from test import QiskitTestCase # pylint: disable=wrong-import-order @ddt.ddt class ObservablesArrayTestCase(QiskitTestCase): """Test the ObservablesArray class""" @ddt.data(0, 1, 2) def test_coerce_observable_str(self, num_qubits): """Test coerce_observable for allowed basis str input""" for chars in it.permutations(ObservablesArray.ALLOWED_BASIS, num_qubits): label = "".join(chars) obs = ObservablesArray.coerce_observable(label) self.assertEqual(obs, {label: 1}) def test_coerce_observable_custom_basis(self): """Test coerce_observable for custom al flowed basis""" class PauliArray(ObservablesArray): """Custom array allowing only Paulis, not projectors""" ALLOWED_BASIS = "IXYZ" with self.assertRaises(ValueError): PauliArray.coerce_observable("0101") for p in qi.pauli_basis(1): obs = PauliArray.coerce_observable(p) self.assertEqual(obs, {p.to_label(): 1}) @ddt.data("iXX", "012", "+/-") def test_coerce_observable_invalid_str(self, basis): """Test coerce_observable for Pauli input""" with self.assertRaises(ValueError): ObservablesArray.coerce_observable(basis) @ddt.data(1, 2, 3) def test_coerce_observable_pauli(self, num_qubits): """Test coerce_observable for Pauli input""" for p in qi.pauli_basis(num_qubits): obs = ObservablesArray.coerce_observable(p) self.assertEqual(obs, {p.to_label(): 1}) @ddt.data(0, 1, 2, 3) def test_coerce_observable_phased_pauli(self, phase): """Test coerce_observable for phased Pauli input""" pauli = qi.Pauli("IXYZ") pauli.phase = phase coeff = (-1j) ** phase if phase % 2: with self.assertRaises(ValueError): ObservablesArray.coerce_observable(pauli) else: obs = ObservablesArray.coerce_observable(pauli) self.assertIsInstance(obs, dict) self.assertEqual(list(obs.keys()), ["IXYZ"]) np.testing.assert_allclose( list(obs.values()), [coeff], err_msg=f"Wrong value for Pauli {pauli}" ) @ddt.data("+IXYZ", "-IXYZ", "iIXYZ", "+iIXYZ", "-IXYZ") def test_coerce_observable_phased_pauli_str(self, pauli): """Test coerce_observable for phased Pauli input""" pauli = qi.Pauli(pauli) coeff = (-1j) ** pauli.phase if pauli.phase % 2: with self.assertRaises(ValueError): ObservablesArray.coerce_observable(pauli) else: obs = ObservablesArray.coerce_observable(pauli) self.assertIsInstance(obs, dict) self.assertEqual(list(obs.keys()), ["IXYZ"]) np.testing.assert_allclose( list(obs.values()), [coeff], err_msg=f"Wrong value for Pauli {pauli}" ) def test_coerce_observable_signed_sparse_pauli_op(self): """Test coerce_observable for SparsePauliOp input with phase paulis""" op = qi.SparsePauliOp(["+I", "-X", "Y", "-Z"], [1, 2, 3, 4]) obs = ObservablesArray.coerce_observable(op) self.assertIsInstance(obs, dict) self.assertEqual(len(obs), 4) self.assertEqual(sorted(obs.keys()), sorted(["I", "X", "Y", "Z"])) np.testing.assert_allclose([obs[i] for i in ["I", "X", "Y", "Z"]], [1, -2, 3, -4]) def test_coerce_observable_zero_sparse_pauli_op(self): """Test coerce_observable for SparsePauliOp input with zero val coeffs""" op = qi.SparsePauliOp(["I", "X", "Y", "Z"], [0, 0, 0, 1]) obs = ObservablesArray.coerce_observable(op) self.assertIsInstance(obs, dict) self.assertEqual(len(obs), 1) self.assertEqual(sorted(obs.keys()), ["Z"]) self.assertEqual(obs["Z"], 1) def test_coerce_observable_duplicate_sparse_pauli_op(self): """Test coerce_observable for SparsePauliOp wiht duplicate paulis""" op = qi.SparsePauliOp(["XX", "-XX", "XX", "-XX"], [2, 1, 3, 2]) obs = ObservablesArray.coerce_observable(op) self.assertIsInstance(obs, dict) self.assertEqual(len(obs), 1) self.assertEqual(list(obs.keys()), ["XX"]) self.assertEqual(obs["XX"], 2) def test_coerce_observable_pauli_mapping(self): """Test coerce_observable for pauli-keyed Mapping input""" mapping = dict(zip(qi.pauli_basis(1), range(1, 5))) obs = ObservablesArray.coerce_observable(mapping) target = {key.to_label(): val for key, val in mapping.items()} self.assertEqual(obs, target) def test_coerce_0d(self): """Test the coerce() method with 0-d input.""" obs = ObservablesArray.coerce("X") self.assertEqual(obs.shape, ()) self.assertDictAlmostEqual(obs[()], {"X": 1}) obs = ObservablesArray.coerce({"I": 2}) self.assertEqual(obs.shape, ()) self.assertDictAlmostEqual(obs[()], {"I": 2}) obs = ObservablesArray.coerce(qi.SparsePauliOp(["X", "Y"], [1, 3])) self.assertEqual(obs.shape, ()) self.assertDictAlmostEqual(obs[()], {"X": 1, "Y": 3}) def test_format_invalid_mapping_qubits(self): """Test an error is raised when different qubits in mapping keys""" mapping = {"IX": 1, "XXX": 2} with self.assertRaises(ValueError): ObservablesArray.coerce_observable(mapping) def test_format_invalid_mapping_basis(self): """Test an error is raised when keys contain invalid characters""" mapping = {"XX": 1, "0Z": 2, "02": 3} with self.assertRaises(ValueError): ObservablesArray.coerce_observable(mapping) def test_init_nested_list_str(self): """Test init with nested lists of str""" obj = [["X", "Y", "Z"], ["0", "1", "+"]] obs = ObservablesArray(obj) self.assertEqual(obs.size, 6) self.assertEqual(obs.shape, (2, 3)) def test_init_nested_list_sparse_pauli_op(self): """Test init with nested lists of SparsePauliOp""" obj = [ [qi.SparsePauliOp(qi.random_pauli_list(2, 3, phase=False)) for _ in range(3)] for _ in range(5) ] obs = ObservablesArray(obj) self.assertEqual(obs.size, 15) self.assertEqual(obs.shape, (5, 3)) def test_init_single_sparse_pauli_op(self): """Test init with single SparsePauliOps""" obj = qi.SparsePauliOp(qi.random_pauli_list(2, 3, phase=False)) obs = ObservablesArray(obj) self.assertEqual(obs.size, 1) self.assertEqual(obs.shape, ()) def test_init_pauli_list(self): """Test init with PauliList""" obs = ObservablesArray(qi.pauli_basis(2)) self.assertEqual(obs.size, 16) self.assertEqual(obs.shape, (16,)) def test_init_nested_pauli_list(self): """Test init with nested PauliList""" obj = [qi.random_pauli_list(2, 3, phase=False) for _ in range(5)] obs = ObservablesArray(obj) self.assertEqual(obs.size, 15) self.assertEqual(obs.shape, (5, 3)) def test_init_ragged_array(self): """Test init with ragged input""" obj = [["X", "Y"], ["X", "Y", "Z"]] with self.assertRaises(ValueError): ObservablesArray(obj) def test_init_validate_false(self): """Test init validate kwarg""" obj = [["A", "B", "C"], ["D", "E", "F"]] obs = ObservablesArray(obj, validate=False) self.assertEqual(obs.shape, (2, 3)) self.assertEqual(obs.size, 6) for i in range(2): for j in range(3): self.assertEqual(obs[i, j], obj[i][j]) def test_init_validate_true(self): """Test init validate kwarg""" obj = [["A", "B", "C"], ["D", "E", "F"]] with self.assertRaises(ValueError): ObservablesArray(obj, validate=True) @ddt.data(0, 1, 2, 3) def test_size_and_shape_single(self, ndim): """Test size and shape method for size=1 array""" obs = {"XX": 1} for _ in range(ndim): obs = [obs] arr = ObservablesArray(obs, validate=False) self.assertEqual(arr.size, 1, msg="Incorrect ObservablesArray.size") self.assertEqual(arr.shape, (1,) * ndim, msg="Incorrect ObservablesArray.shape") @ddt.data(0, 1, 2, 3) def test_tolist_single(self, ndim): """Test tolist method for size=1 array""" obs = {"XX": 1} for _ in range(ndim): obs = [obs] arr = ObservablesArray(obs, validate=False) ls = arr.tolist() self.assertEqual(ls, obs) @ddt.data(0, 1, 2, 3) def test_array_single(self, ndim): """Test __array__ method for size=1 array""" obs = {"XX": 1} for _ in range(ndim): obs = [obs] arr = ObservablesArray(obs, validate=False) nparr = np.array(arr) self.assertEqual(nparr.dtype, object) self.assertEqual(nparr.shape, arr.shape) self.assertEqual(nparr.size, arr.size) self.assertTrue(np.all(nparr == np.array(obs))) @ddt.data(0, 1, 2, 3) def test_getitem_single(self, ndim): """Test __getitem__ method for size=1 array""" base_obs = {"XX": 1} obs = base_obs for _ in range(ndim): obs = [obs] arr = ObservablesArray(obs, validate=False) idx = ndim * (0,) item = arr[idx] self.assertEqual(item, base_obs) def test_tolist_1d(self): """Test tolist method""" obj = ["A", "B", "C", "D"] obs = ObservablesArray(obj, validate=False) self.assertEqual(obs.tolist(), obj) def test_tolist_2d(self): """Test tolist method""" obj = [["A", "B", "C"], ["D", "E", "F"]] obs = ObservablesArray(obj, validate=False) self.assertEqual(obs.tolist(), obj) def test_array_1d(self): """Test __array__ dunder method""" obj = np.array(["A", "B", "C", "D"], dtype=object) obs = ObservablesArray(obj, validate=False) self.assertTrue(np.all(np.array(obs) == obj)) def test_array_2d(self): """Test __array__ dunder method""" obj = np.array([["A", "B", "C"], ["D", "E", "F"]], dtype=object) obs = ObservablesArray(obj, validate=False) self.assertTrue(np.all(np.array(obs) == obj)) def test_getitem_1d(self): """Test __getitem__ for 1D array""" obj = np.array(["A", "B", "C", "D"], dtype=object) obs = ObservablesArray(obj, validate=False) for i in range(obj.size): self.assertEqual(obs[i], obj[i]) def test_getitem_2d(self): """Test __getitem__ for 2D array""" obj = np.array([["A", "B", "C"], ["D", "E", "F"]], dtype=object) obs = ObservablesArray(obj, validate=False) for i in range(obj.shape[0]): row = obs[i] self.assertIsInstance(row, ObservablesArray) self.assertEqual(row.shape, (3,)) self.assertTrue(np.all(np.array(row) == obj[i])) def test_ravel(self): """Test ravel method""" bases_flat = qi.pauli_basis(2).to_labels() bases = [bases_flat[4 * i : 4 * (i + 1)] for i in range(4)] obs = ObservablesArray(bases) flat = obs.ravel() self.assertEqual(flat.ndim, 1) self.assertEqual(flat.shape, (16,)) self.assertEqual(flat.size, 16) for ( i, label, ) in enumerate(bases_flat): self.assertEqual(flat[i], {label: 1}) def test_reshape(self): """Test reshape method""" bases = qi.pauli_basis(2) labels = np.array(bases.to_labels(), dtype=object) obs = ObservablesArray(qi.pauli_basis(2)) def various_formats(shape): # call reshape with a single argument yield [shape] yield [(-1,) + shape[1:]] yield [np.array(shape)] yield [list(shape)] yield [list(map(np.int64, shape))] yield [tuple(map(np.int64, shape))] # call reshape with multiple arguments yield shape yield np.array(shape) yield list(shape) yield list(map(np.int64, shape)) yield tuple(map(np.int64, shape)) for shape in [(16,), (4, 4), (2, 4, 2), (2, 2, 2, 2), (1, 8, 1, 2)]: with self.subTest(shape): for input_shape in various_formats(shape): obs_rs = obs.reshape(*input_shape) self.assertEqual(obs_rs.shape, shape) labels_rs = labels.reshape(shape) for idx in np.ndindex(shape): self.assertEqual( obs_rs[idx], {labels_rs[idx]: 1}, msg=f"failed for shape {shape} with input format {input_shape}", ) def test_validate(self): """Test the validate method""" ObservablesArray({"XX": 1}).validate() ObservablesArray([{"XX": 1}] * 5).validate() ObservablesArray([{"XX": 1}] * 15).reshape((3, 5)).validate() obs = ObservablesArray([{"XX": 1}, {"XYZ": 1}], validate=False) with self.assertRaisesRegex(ValueError, "number of qubits must be the same"): obs.validate()