repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/Antonio297/Qiskit_Algoritmo_Cuantico
Antonio297
### Quantum indexed Bidirectional Associative Memory by A. Sarkar, Z. Al-Ars, C. G. Almudever, K. Bertels ### Repository reference: https://gitlab.com/prince-ph0en1x/QaGs (by A. Sarkar) ## Importing libraries %matplotlib inline import qiskit from qiskit import IBMQ from qiskit import Aer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QiskitError from qiskit.quantum_info.operators import Operator from qiskit.tools.visualization import circuit_drawer from qiskit.tools.visualization import plot_histogram from qiskit.providers.aer import noise from qiskit.providers.aer.noise import NoiseModel, errors import random from math import * import os import re import sys import math import matplotlib.pyplot as plt import numpy as np ## Defining some auxiliary functions def hamming_distance(str1, str2): count = sum(c1 != c2 for c1, c2 in zip(str1, str2)) return count def convertToNumEncoding(genome_str): bin_str = "" for i in range(0, len(genome_str)): if genome_str[i] == 'A': bin_str = bin_str + "0" elif genome_str[i] == 'C': bin_str = bin_str + "1" elif genome_str[i] == 'G': bin_str = bin_str + "2" elif genome_str[i] == 'T': bin_str = bin_str + "3" return bin_str def convertReadToBin(read): bin_read = "" for i in range(0, len(read)): if read[i] == '0': bin_read = bin_read + "00" elif read[i] == '1': bin_read = bin_read + "01" elif read[i] == '2': bin_read = bin_read + "10" elif read[i] == '3': bin_read = bin_read + "11" return bin_read ## Initializing global variables # Alphabet set {0, 1, 2, 3} := {A, C, G, T} for DNA Nucleotide bases AS = {'00', '01', '10', '11'} A = len(AS) ################# Default Test ################# # Reference Genome: "AATTGTCTAGGCGACC" #w = "0033231302212011" #N = len(w) # Short Read: "CA" #p = "10" # Distributed query around zero Hamming distance #pb = "0000" ################################################ ############## Test on HIV genome ############## genome_file = open("HIVgenome.txt", "r") #select the data source w = genome_file.read() genome_file.close() w = convertToNumEncoding(w) w = w[0:128] #changes the number of characters you want to read from the file N = len(w) # Short read: "TCT" #Try with chains of three p = "313" # Distributed query around zero Hamming distance pb = "000000" ################################################ # Short Read size M = len(p) # Number of qubits to encode one character Q_A = ceil(log2(A)) # Number of data qubits Q_D = Q_A * M # Tag Qubits Q_T = ceil(log2(N-M)) #print('valor Q_T:',Q_T) # Ancilla Qubits Q_anc = 8 # Ancilla qubits ids anc = [] for qi in range(0, Q_anc): anc.append(Q_D + Q_T + qi) total_qubits = Q_D + Q_T + Q_anc ## Inizializing Oracle O Matrix gamma = 0.25 SS = 2**Q_D bp = np.empty([1, SS]) for i in range(0, SS): i_binary = format(i, '0'+str(Q_D)+'b') hd = hamming_distance(i_binary, pb) bp[0][i] = sqrt((gamma**hd)*((1 - gamma)**(Q_D - hd))) BO = np.identity(SS) - 2*np.dot(np.conjugate(np.transpose(bp)), bp) orc = Operator(BO) qbsp = [] for qi in range (0, Q_D): qbsp.append(Q_T+qi) qbsp.reverse() ## Initialization of IBM QX IBMQ.enable_account('My Token') provider = IBMQ.get_provider() # Pick an available backend # If this isn't available pick a backend whose name containes '_qasm_simulator' from the output above backend = provider.get_backend('ibmq_qasm_simulator') # Uncomment if you want to use local simulator #backend= Aer.get_backend('qasm_simulator') ## Defining functions def QIBAM(): print('Reference genome:', w) print('Chosen pattern for testing:', p) print('Total number of qubits:', total_qubits) print('Number of ancilla qubits:', Q_anc) qr = qiskit.QuantumRegister(total_qubits) cr = qiskit.ClassicalRegister(Q_T) qc = qiskit.QuantumCircuit(qr, cr) # Initialise generateInitialState(qc, qr) # Transform to Hamming distance evolveToHammingDistances(qc, qr) # Oracle call oracle(qc) # Inversion about mean inversionAboutMean(qc, qr) it = 0 for r in range(0, 2): # Oracle call oracle(qc) # Inversion about mean inversionAboutMean(qc, qr) it = it + 1 print("Grover's algorithm had {} iterations.".format(int(it))) # Measurement finalGroverMeasurement(qc, qr, cr) return qc # Initialization as suggested by L. C. L. Hollenberg def generateInitialState(qc, qr): for qi in range(0, Q_T): qc.h(qr[qi]) control_qubits = [] for ci in range(0,Q_T): control_qubits.append(qr[ci]) ancilla_qubits = [] for qi in anc: ancilla_qubits.append(qr[qi]) for qi in range(0, N - M + 1): qis = format(qi, '0' + str(Q_T) + 'b') for qisi in range(0, Q_T): if qis[qisi] == '0': qc.x(qr[qisi]) wMi = w[qi:qi + M] print("Tag: {} - Data: {} - Hamming distance: {}".format(qis, wMi, hamming_distance(convertReadToBin(wMi), convertReadToBin(p)))) for wisi in range(0, M): wisia = format(int(wMi[wisi]), '0' + str(Q_A) + 'b') for wisiai in range(0, Q_A): if wisia[wisiai] == '1': qc.mct(control_qubits, qr[Q_T + wisi * Q_A + wisiai], ancilla_qubits) for qisi in range(0, Q_T): if qis[qisi] == '0': qc.x(qr[qisi]) wMi = p for qi in range(N - M + 1, 2**Q_T): qis = format(qi, '0' + str(Q_T) + 'b') for qisi in range(0, Q_T): if qis[qisi] == '0': qc.x(qr[qisi]) for wisi in range(0, M): wisia = format(int(wMi[wisi]), '0' + str(Q_A) + 'b') for wisiai in range(0, Q_A): if wisia[wisiai] == '0': qc.mct(control_qubits, qr[Q_T + wisi * Q_A + wisiai], ancilla_qubits) for qisi in range(0, Q_T): if qis[qisi] == '0': qc.x(qr[qisi]) return # Calculate Hamming Distance def evolveToHammingDistances(qc, qr): for pi in range(0, M): ppi = format(int(p[pi]), '0' + str(Q_A) + 'b') for ppii in range(0, Q_A): if ppi[ppii] == '1': qc.x(qr[Q_T + pi * Q_A + ppii]) return # Oracle to mark zero Hamming distance def oracle(qc): qc.unitary(orc, qbsp, label='orc') return # Inversion about mean def inversionAboutMean(qc, qr): for si in range(0, Q_D + Q_T): qc.h(qr[si]) qc.x(qr[si]) control_qubits = [] for sj in range(0, Q_D + Q_T - 1): control_qubits.append(qr[sj]) ancilla_qubits = [] for qi in anc: ancilla_qubits.append(qr[qi]) qc.h(qr[Q_D + Q_T - 1]) qc.mct(control_qubits, qr[Q_D + Q_T - 1], ancilla_qubits) qc.h(qr[Q_D + Q_T - 1]) for si in range(0,Q_D + Q_T): qc.x(qr[si]) qc.h(qr[si]) return # Oracle to mark Memory States def markStoredStates(qc, qr): control_qubits = [] for qsi in range(0, Q_T + Q_D - 1): control_qubits.append(qr[qsi]) ancilla_qubits = [] for qi in anc: ancilla_qubits.append(qr[qi]) for qi in range(0, N - M + 1): qis = format(qi, '0' + str(Q_T) + 'b') wMi = w[qi:qi + M] wt = qis for wisi in range(0, M): hd = int(format(int(wMi[wisi]), '0'+str(Q_A)+'b'), 2) ^ int(format(int(p[wisi]), '0'+str(Q_A)+'b'), 2) wisia = format(hd, '0' + str(Q_A) + 'b') wt = wt + wisia for qisi in range(0, Q_T + Q_D): if wt[qisi] == '0': qc.x(qr[qisi]) qc.h(qr[Q_D + Q_T - 1]) qc.mct(control_qubits, qr[Q_D + Q_T - 1], ancilla_qubits) qc.h(qr[Q_D + Q_T - 1]) if wt[qisi] == '0': qc.x(qr[qisi]) return # Final measurement def finalGroverMeasurement(qc, qr, cr): for qi in range(0, Q_T): qc.measure(qr[qi], cr[qi]) return ## Main function if __name__ == '__main__': # Printing some data for testing qc = QIBAM() print("Circuit depth: {}".format(qc.depth())) # Total number of gates print("Number of gates: {}".format(len(qc.data))) gate_num = 1 for item in qc.data: qb_list = '' for qb in item[1]: qb_list = qb_list + str(qb.index) + ', ' qb_list = qb_list[:len(qb_list)-2] print("#{}: {}, {}".format(gate_num, item[0].name, qb_list)) gate_num = gate_num + 1 # Drawing circuit # qc.draw() # Showing histogram # BE CAREFUL! # Qiskit uses a LSB ordering, meaning the first qubit is all the way to the right! # For example, a state of |01> would mean the first qubit is 1 and the second qubit is 0! sim = qiskit.execute(qc, backend=backend, shots=8192) result = sim.result() final=result.get_counts(qc) print(final) plot_histogram(final)
https://github.com/martian17/qiskit-graph-coloring-hamiltonian
martian17
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, BasicAer from qiskit.visualization import plot_histogram def multi_toffoli_q(qc, q_controls, q_target, q_ancillas=None): """ N = number of qubits controls = control qubits target = target qubit ancillas = ancilla qubits, len(ancillas) = len(controls) - 2 """ # q_controls = register_to_list(q_controls) # q_ancillas = register_to_list(q_ancillas) if len(q_controls) == 1: qc.cx(q_controls[0], q_target) elif len(q_controls) == 2: qc.ccx(q_controls[0], q_controls[1], q_target) elif len(q_controls) > 2 and (q_ancillas is None or len(q_ancillas) < len(q_controls) - 2): raise Exception('ERROR: need more ancillas for multi_toffoli!') else: multi_toffoli_q(qc, q_controls[:-1], q_ancillas[-1], q_ancillas[:-1]) qc.ccx(q_controls[-1], q_ancillas[-1], q_target) multi_toffoli_q(qc, q_controls[:-1], q_ancillas[-1], q_ancillas[:-1]) n = 7 q1 = QuantumRegister(n) q2 = QuantumRegister(n) q3 = QuantumRegister(1) q4 = QuantumRegister(n) cr = ClassicalRegister(n) def m_gate_for_special_case(q1,q2,q4, hamiltonian): circuit = QuantumCircuit(qr, cr) def gate_aza(q1,q2,q3,q4): #circuit = QuantumCircuit(q1,q2,q3,q4) matrix = [[1, 0, 0, 0], [0, 1/math.sqrt(2), 1/math.sqrt(2), 0], [0, 1/math.sqrt(2), -1/math.sqrt(2), 0], [0,0,0,1]] for i in range(n): circuit.unitary(matrix,[q1[i],q2[i]]) circuit.barrier() for i in range(n): circuit.x(q2[i]) circuit.ccx(q1[i],q2[i],q3) circuit.x(q2[i]) circuit.barrier() #hogehoge circuit.x(q3) for i in range(n): circuit.cu1(-2**i, q3, q4[i]) circuit.x(q3) for i in range(n): circuit.cu1(2**i, q3, q4[i]) circuit.barrier() for i in range(n): circuit.x(q2[i]) circuit.ccx(q1[i],q2[i],q3) circuit.x(q2[i]) circuit.barrier() for i in range(n): circuit.unitary(matrix,[q1[i],q2[i]])
https://github.com/JessicaJohnBritto/Quantum-Computing-and-Information
JessicaJohnBritto
import pennylane as qml from pennylane import numpy as np import matplotlib.pyplot as plt dev = qml.device("default.qubit", wires=1) @qml.qnode(dev) def prepare_state(): ################## # YOUR CODE HERE # ################## # APPLY OPERATIONS TO PREPARE THE TARGET STATE qml.Hadamard(wires=0) qml.PauliZ(wires=0) qml.T(wires=0) return qml.state() dev = qml.device("default.qubit", wires=1) @qml.qnode(dev) def prepare_state(): ################## # YOUR CODE HERE # ################## # APPLY OPERATIONS TO PREPARE THE TARGET STATE qml.RX((np.pi)/3, wires=0) return qml.state() v = np.array([0.52889389-0.14956775j, 0.67262317+0.49545818j]) ################## # YOUR CODE HERE # ################## # CREATE A DEVICE dev = qml.device("default.qubit", wires=1) # CONSTRUCT A QNODE THAT USES qml.MottonenStatePreparation # TO PREPARE A QUBIT IN STATE V, AND RETURN THE STATE @qml.qnode(dev) def prepare_state(state=v): qml.MottonenStatePreparation(state, wires=0) return qml.state() # This will draw the quantum circuit and allow you to inspect the output gates print(prepare_state(v)) print() print(qml.draw(prepare_state)(v)) dev = qml.device("default.qubit", wires=1) @qml.qnode(dev) def apply_h_and_measure(state): """Complete the function such that we apply the Hadamard gate and measure in the computational basis. Args: state (int): Either 0 or 1. If 1, prepare the qubit in state |1>, otherwise leave it in state 0. Returns: array[float]: The measurement outcome probabilities. """ if state == 1: qml.PauliX(wires=0) ################## # YOUR CODE HERE # ################## # APPLY HADAMARD AND MEASURE qml.Hadamard(wires=0) return qml.probs(wires=[0]) print(apply_h_and_measure(0)) print(apply_h_and_measure(1)) ################## # YOUR CODE HERE # ################## # WRITE A QUANTUM FUNCTION THAT PREPARES (1/2)|0> + i(sqrt(3)/2)|1> def prepare_psi(): qml.RX(4*(np.pi)/3, wires=0) # return qml.probs(wires=[0]) # pass # return qml.state() # WRITE A QUANTUM FUNCTION THAT SENDS BOTH |0> TO |y_+> and |1> TO |y_-> def y_basis_rotation(): # qml.RX(3*(np.pi)/2, wires=0) qml.Hadamard(wires=0) qml.S(wires=0) dev = qml.device("default.qubit", wires=1) @qml.qnode(dev) def measure_in_y_basis(): ################## # YOUR CODE HERE # ################## # PREPARE THE STATE prepare_psi() # PERFORM THE ROTATION BACK TO COMPUTATIONAL BASIS qml.adjoint(y_basis_rotation)() # RETURN THE MEASUREMENT OUTCOME PROBABILITIES return qml.probs(wires=[0]) print(measure_in_y_basis()) dev = qml.device('default.qubit', wires=1) @qml.qnode(dev) def circuit(): ################## # YOUR CODE HERE # ################## qml.RX(np.pi/4, wires=0) qml.Hadamard(wires=0) qml.PauliZ(wires=0) # IMPLEMENT THE CIRCUIT IN THE PICTURE AND MEASURE PAULI Y return qml.expval(qml.PauliY(0)) print(circuit()) # An array to store your results shot_results = [] # dev = qml.device('default.qubit', wires=1) # @qml.qnode(dev) def circuit(): ################## # YOUR CODE HERE # ################## qml.RX(np.pi/4, wires=0) qml.Hadamard(wires=0) qml.PauliZ(wires=0) # IMPLEMENT THE CIRCUIT IN THE PICTURE AND MEASURE PAULI Y return qml.expval(qml.PauliY(0)) # Different numbers of shots shot_values = [100, 1000, 10000, 100000, 1000000] for shots in shot_values: ################## # YOUR CODE HERE # ################## # CREATE A DEVICE, CREATE A QNODE, AND RUN IT dev = qml.device('default.qubit', wires=1, shots=shots) # @qml.qnode(dev) qnode = qml.QNode(circuit, dev) # def circu(): shot_results.append(qnode()) # STORE RESULT IN SHOT_RESULTS ARRAY print(qml.math.unwrap(shot_results)) dev = qml.device("default.qubit", wires=1, shots=100000) @qml.qnode(dev) def circuit(): qml.RX(np.pi/4, wires=0) qml.Hadamard(wires=0) qml.PauliZ(wires=0) ################## # YOUR CODE HERE # ################## # RETURN THE MEASUREMENT SAMPLES OF THE CORRECT OBSERVABLE return qml.sample(qml.PauliY(wires=0)) def compute_expval_from_samples(samples): """Compute the expectation value of an observable given a set of sample outputs. You can assume that there are two possible outcomes, 1 and -1. Args: samples (array[float]): 100000 samples representing the results of running the above circuit. Returns: float: the expectation value computed based on samples. """ estimated_expval = 0 ################## # YOUR CODE HERE # ################## k = np.array(samples) estimated_expval = np.average(k) # USE THE SAMPLES TO ESTIMATE THE EXPECTATION VALUE return estimated_expval samples = circuit() print(compute_expval_from_samples(samples)) def variance_experiment(n_shots): """Run an experiment to determine the variance in an expectation value computed with a given number of shots. Args: n_shots (int): The number of shots Returns: float: The variance in expectation value we obtain running the circuit 100 times with n_shots shots each. """ # To obtain a variance, we run the circuit multiple times at each shot value. n_trials = 100 ################## # YOUR CODE HERE # ################## samples = [] # CREATE A DEVICE WITH GIVEN NUMBER OF SHOTS dev = qml.device('default.qubit', wires=1, shots = n_shots) # qnode = qml.QNode(circuit, dev) # DECORATE THE CIRCUIT BELOW TO CREATE A QNODE @qml.qnode(dev) def circuit(): qml.Hadamard(wires=0) return qml.expval(qml.PauliZ(wires=0)) # qnode = qml.QNode(circuit, dev, shots = n_shots) # RUN THE QNODE N_TRIALS TIMES AND RETURN THE VARIANCE OF THE RESULTS for i in range(n_trials): sample = circuit() samples.append(sample) k = np.var(np.array(samples)) return k def variance_scaling(n_shots): """Once you have determined how the variance in expectation value scales with the number of shots, complete this function to programmatically represent the relationship. Args: n_shots (int): The number of shots Returns: float: The variance in expectation value we expect to see when we run an experiment with n_shots shots. """ estimated_variance = 0 sample=[] ################## # YOUR CODE HERE # ################## # ESTIMATE THE VARIANCE BASED ON SHOT NUMBER # for i in range(n_shots): # if i != 0: # sample.append(1/i) # estimated_variance = np.var(np.array(sample)) return 1/n_shots # Various numbers of shots; you can change this shot_vals = [10, 20, 40, 100, 200, 400, 1000, 2000, 4000] # Used to plot your results results_experiment = [variance_experiment(shots) for shots in shot_vals] results_scaling = [variance_scaling(shots) for shots in shot_vals] plot = plotter(shot_vals, results_experiment, results_scaling)
https://github.com/abbarreto/qiskit3
abbarreto
0.4*7.6
https://github.com/qclib/qclib
qclib
# Copyright 2021 qclib project. # 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. """ Implements the state preparation defined at https://arxiv.org/abs/1003.5760. """ import numpy as np from qiskit import QuantumCircuit from qclib.unitary import unitary as decompose_unitary, cnot_count as cnots_unitary from qclib.isometry import decompose as decompose_isometry, cnot_count as cnots_isometry from qclib.gates.initialize import Initialize from qclib.entanglement import schmidt_decomposition, _to_qubits from .topdown import TopDownInitialize # pylint: disable=maybe-no-member class LowRankInitialize(Initialize): """ Approximated quantum-state preparation with entanglement dependent complexity https://arxiv.org/abs/2111.03132 This class implements a state preparation gate. """ def __init__(self, params, label=None, opt_params=None): """ Parameters ---------- params: list of complex A unit vector representing a quantum state. Values are amplitudes. opt_params: {'lr': low_rank, 'iso_scheme': isometry_scheme, 'unitary_scheme': unitary_scheme, 'partition': partition} low_rank: int ``state`` low-rank approximation (1 <= ``low_rank`` < 2**(n_qubits//2)). If ``low_rank`` is not in the valid range, it will be ignored. This parameter limits the rank of the Schmidt decomposition. If the Schmidt rank of the state decomposition is greater than ``low_rank``, a low-rank approximation is applied. iso_scheme: string Scheme used to decompose isometries. Possible values are ``'knill'`` and ``'ccd'`` (column-by-column decomposition). Default is ``isometry_scheme='ccd'``. unitary_scheme: string Scheme used to decompose unitaries. Possible values are ``'csd'`` (cosine-sine decomposition) and ``'qsd'`` (quantum Shannon decomposition). Default is ``unitary_scheme='qsd'``. partition: list of int Set of qubit indices that represent a part of the bipartition. The other partition will be the relative complement of the full set of qubits with respect to the set ``partition``. The valid range for indexes is ``0 <= index < n_qubits``. The number of indexes in the partition must be greater than or equal to ``1`` and less than or equal to ``n_qubits//2`` (``n_qubits//2+1`` if ``n_qubits`` is odd). Default is ``partition=list(range(n_qubits//2 + odd))``. svd: string Function to compute the SVD, acceptable values are 'auto' (default), 'regular', and 'randomized'. 'auto' sets `svd='randomized'` for `n_qubits>=14 and rank==1`. """ self._name = "low_rank" self._get_num_qubits(params) if opt_params is None: self.isometry_scheme = "ccd" self.unitary_scheme = "qsd" self.low_rank = 0 self.partition = None self.svd = "auto" else: self.low_rank = 0 if opt_params.get("lr") is None else opt_params.get("lr") self.partition = opt_params.get("partition") if opt_params.get("iso_scheme") is None: self.isometry_scheme = "ccd" else: self.isometry_scheme = opt_params.get("iso_scheme") if opt_params.get("unitary_scheme") is None: self.unitary_scheme = "qsd" else: self.unitary_scheme = opt_params.get("unitary_scheme") if opt_params.get("svd") is None: self.svd = "auto" else: self.svd = opt_params.get("svd") if label is None: label = "LRSP" super().__init__(self._name, self.num_qubits, params, label=label) def _define(self): self.definition = self._define_initialize() def _define_initialize(self): if self.num_qubits < 2: return TopDownInitialize(self.params).definition circuit, reg_a, reg_b = self._create_quantum_circuit() # Schmidt decomposition rank, svd_u, singular_values, svd_v = schmidt_decomposition( self.params, reg_a, rank=self.low_rank, svd=self.svd ) # Schmidt measure of entanglement e_bits = _to_qubits(rank) # Phase 1. Encodes the singular values. if e_bits > 0: reg_sv = reg_b[:e_bits] singular_values = singular_values / np.linalg.norm(singular_values) self._encode(singular_values.reshape(rank, 1), circuit, reg_sv) # Phase 2. Entangles only the necessary qubits, according to rank. for j in range(e_bits): circuit.cx(reg_b[j], reg_a[j]) # Phase 3 and 4 encode gates U and V.T self._encode(svd_u, circuit, reg_b) self._encode(svd_v.T, circuit, reg_a) return circuit.reverse_bits() @staticmethod def initialize(q_circuit, state, qubits=None, opt_params=None): """ Appends a LowRankInitialize gate into the q_circuit """ if qubits is None: q_circuit.append( LowRankInitialize(state, opt_params=opt_params), q_circuit.qubits ) else: q_circuit.append(LowRankInitialize(state, opt_params=opt_params), qubits) def _encode(self, data, circuit, reg): """ Encodes data using the most appropriate method. """ if data.shape[1] == 1: # state preparation gate_u = LowRankInitialize(data[:, 0], opt_params={ "iso_scheme": self.isometry_scheme, "unitary_scheme": self.unitary_scheme, "svd": self.svd }) elif data.shape[0] // 2 == data.shape[1]: # isometry 2^(n-1) to 2^n. gate_u = decompose_isometry(data, scheme="csd") elif data.shape[0] > data.shape[1]: gate_u = decompose_isometry(data, scheme=self.isometry_scheme) else: gate_u = decompose_unitary(data, decomposition=self.unitary_scheme) # Apply gate U to the register reg circuit.compose(gate_u, reg, inplace=True) def _create_quantum_circuit(self): if self.partition is None: self.partition = _default_partition(self.num_qubits) complement = sorted(set(range(self.num_qubits)).difference(set(self.partition))) circuit = QuantumCircuit(self.num_qubits) return circuit, self.partition[::-1], complement[::-1] def _default_partition(n_qubits): odd = n_qubits % 2 return list(range(n_qubits // 2 + odd)) def cnot_count( state_vector, low_rank=0, isometry_scheme="ccd", unitary_scheme="qsd", partition=None, method = "estimate", svd="auto" ): """ Estimate the number of CNOTs to build the state preparation circuit. """ n_qubits = _to_qubits(len(state_vector)) if n_qubits < 2: return 0 if partition is None: partition = _default_partition(n_qubits) cnots = 0 rank, svd_u, singular_values, svd_v = schmidt_decomposition( state_vector, partition, rank=low_rank, svd=svd ) # Schmidt measure of entanglement ebits = _to_qubits(rank) # Phase 1. if ebits > 0: singular_values = singular_values / np.linalg.norm(singular_values) cnots += _cnots( singular_values.reshape(rank, 1), isometry_scheme, unitary_scheme, method, svd ) # Phase 2. cnots += ebits # Phases 3 and 4. cnots += _cnots(svd_u, isometry_scheme, unitary_scheme, method, svd) cnots += _cnots(svd_v.T, isometry_scheme, unitary_scheme, method, svd) return cnots def _cnots(data, iso_scheme="ccd", uni_scheme="qsd", method="estimate", svd="auto"): if data.shape[1] == 1: return cnot_count( data[:, 0], isometry_scheme=iso_scheme, unitary_scheme=uni_scheme, method=method, svd=svd ) if data.shape[0] // 2 == data.shape[1]: return cnots_isometry(data, scheme="csd", method=method) if data.shape[0] > data.shape[1]: return cnots_isometry(data, scheme=iso_scheme, method=method) return cnots_unitary(data, decomposition=uni_scheme, method=method)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl')
https://github.com/C2QA/bosonic-qiskit
C2QA
from math import sqrt, pi from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import oracle_simple import composed_gates def get_circuit(n, oracles): """ Build the circuit composed by the oracle black box and the other quantum gates. :param n: The number of qubits (not including the ancillas) :param oracles: A list of black box (quantum) oracles; each of them selects a specific state :returns: The proper quantum circuit :rtype: qiskit.QuantumCircuit """ cr = ClassicalRegister(n) ## Testing if n > 3: #anc = QuantumRegister(n - 1, 'anc') # n qubits for the real number # n - 1 qubits for the ancillas qr = QuantumRegister(n + n - 1) qc = QuantumCircuit(qr, cr) else: # We don't need ancillas qr = QuantumRegister(n) qc = QuantumCircuit(qr, cr) ## /Testing print("Number of qubits is {0}".format(len(qr))) print(qr) # Initial superposition for j in range(n): qc.h(qr[j]) # The length of the oracles list, or, in other words, how many roots of the function do we have m = len(oracles) # Grover's algorithm is a repetition of an oracle box and a diffusion box. # The number of repetitions is given by the following formula. print("n is ", n) r = int(round((pi / 2 * sqrt((2**n) / m) - 1) / 2)) print("Repetition of ORACLE+DIFFUSION boxes required: {0}".format(r)) oracle_t1 = oracle_simple.OracleSimple(n, 5) oracle_t2 = oracle_simple.OracleSimple(n, 0) for j in range(r): for i in range(len(oracles)): oracles[i].get_circuit(qr, qc) diffusion(n, qr, qc) for j in range(n): qc.measure(qr[j], cr[j]) return qc, len(qr) def diffusion(n, qr, qc): """ The Grover diffusion operator. Given the arry of qiskit QuantumRegister qr and the qiskit QuantumCircuit qc, it adds the diffusion operator to the appropriate qubits in the circuit. """ for j in range(n): qc.h(qr[j]) # D matrix, flips state |000> only (instead of flipping all the others) for j in range(n): qc.x(qr[j]) # 0..n-2 control bits, n-1 target, n.. if n > 3: composed_gates.n_controlled_Z_circuit( qc, [qr[j] for j in range(n - 1)], qr[n - 1], [qr[j] for j in range(n, n + n - 1)]) else: composed_gates.n_controlled_Z_circuit( qc, [qr[j] for j in range(n - 1)], qr[n - 1], None) for j in range(n): qc.x(qr[j]) for j in range(n): qc.h(qr[j])
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit qc = QuantumCircuit(1, 1) qc.h(0) qc.measure(0,0) qc.x(0).c_if(0, 0) qc.draw(output='mpl') from qiskit import QuantumRegister, ClassicalRegister q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') qc = QuantumCircuit(q, c) qc.h([0, 1, 2]) qc.barrier() qc.measure(q, c) qc.draw('mpl') print(bin(3)) print(bin(7)) qc.x(2).c_if(c, 3) # for the 011 case qc.x(2).c_if(c, 7) # for the 111 case qc.draw(output='mpl') nq = 2 m = 2 q = QuantumRegister(nq, 'q') c = ClassicalRegister(m, 'c') qc_S = QuantumCircuit(q,c) qc_S.h(0) qc_S.x(1) qc_S.draw('mpl') from math import pi cu_circ = QuantumCircuit(2) cu_circ.cp(pi/2, 0, 1) cu_circ.draw('mpl') for _ in range(2 ** (m - 1)): qc_S.cp(pi/2, 0, 1) qc_S.draw('mpl') def x_measurement(qc, qubit, cbit): """Measure 'qubit' in the X-basis, and store the result in 'cbit'""" qc.h(qubit) qc.measure(qubit, cbit) x_measurement(qc_S, q[0], c[0]) qc_S.draw('mpl') qc_S.reset(0) qc_S.h(0) qc_S.draw('mpl') qc_S.p(-pi/2, 0).c_if(c, 1) qc_S.draw('mpl') ## 2^t c-U operations (with t=m-2) for _ in range(2 ** (m - 2)): qc_S.cp(pi/2, 0, 1) x_measurement(qc_S, q[0], c[1]) qc_S.draw('mpl') import matplotlib.pyplot as plt from qiskit.tools.visualization import plot_histogram from qiskit_aer.primitives import Sampler sampler = Sampler() job = sampler.run(qc_S) result = job.result() dist0 = result.quasi_dists[0] key_new = [str(key/2**m) for key in list(dist0.keys())] dist1 = dict(zip(key_new, dist0.values())) fig, ax = plt.subplots(1,2) plot_histogram(dist0, ax=ax[0]) plot_histogram(dist1, ax=ax[1]) plt.tight_layout() nq = 3 # number of qubits m = 3 # number of classical bits q = QuantumRegister(nq,'q') c = ClassicalRegister(m,'c') qc = QuantumCircuit(q,c) qc.h(0) qc.x([1, 2]) qc.draw('mpl') cu_circ = QuantumCircuit(nq) cu_circ.mcp(pi/4, [0, 1], 2) cu_circ.draw('mpl') for _ in range(2 ** (m - 1)): qc.mcp(pi/4, [0, 1], 2) qc.draw('mpl') x_measurement(qc, q[0], c[0]) qc.draw('mpl') qc.reset(0) qc.h(0) qc.draw('mpl') qc.p(-pi/2, 0).c_if(c, 1) qc.draw('mpl') for _ in range(2 ** (m - 2)): qc.mcp(pi/4, [0, 1], 2) x_measurement(qc, q[0], c[1]) qc.draw('mpl') # initialization of qubit q0 qc.reset(0) qc.h(0) # phase correction qc.p(-pi/4, 0).c_if(c, 1) qc.p(-pi/2, 0).c_if(c, 2) qc.p(-3*pi/2, 0).c_if(c, 3) # c-U operations for _ in range(2 ** (m - 3)): qc.mcp(pi/4, [0, 1], 2) # X measurement qc.h(0) qc.measure(0, 2) qc.draw('mpl') result = sampler.run(qc).result() dist0 = result.quasi_dists[0] key_new = [str(key/2**m) for key in list(dist0.keys())] dist1 = dict(zip(key_new, dist0.values())) fig, ax = plt.subplots(1,2) plot_histogram(dist0, ax=ax[0]) plot_histogram(dist1, ax=ax[1]) plt.tight_layout() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import qiskit.qasm3 program = """ OPENQASM 3.0; include "stdgates.inc"; input float[64] a; qubit[3] q; bit[2] mid; bit[3] out; let aliased = q[0:1]; gate my_gate(a) c, t { gphase(a / 2); ry(a) c; cx c, t; } gate my_phase(a) c { ctrl @ inv @ gphase(a) c; } my_gate(a * 2) aliased[0], q[{1, 2}][0]; measure q[0] -> mid[0]; measure q[1] -> mid[1]; while (mid == "00") { reset q[0]; reset q[1]; my_gate(a) q[0], q[1]; my_phase(a - pi/2) q[1]; mid[0] = measure q[0]; mid[1] = measure q[1]; } if (mid[0]) { let inner_alias = q[{0, 1}]; reset inner_alias; } out = measure q; """ circuit = qiskit.qasm3.loads(program) circuit.draw("mpl")
https://github.com/Pitt-JonesLab/slam_decomposition
Pitt-JonesLab
import logging logger = logging.getLogger() import numpy as np from qiskit import QuantumCircuit from weylchamber import c1c2c3 from slam.basis import CircuitTemplate, MixedOrderBasisCircuitTemplate from slam.basisv2 import CircuitTemplateV2 from slam.cost_function import SquareCost from slam.optimizer import TemplateOptimizer from slam.utils.gates.custom_gates import ConversionGainGate from slam.utils.polytopes.polytope_wrap import monodromy_range_from_target def recursive_sibling_check( basis: CircuitTemplate, target_u, basis_factor=1, rec_iter_factor=1, cost_1q=0.1, use_smush=False, ): """Function used to instantiate a circuit using 1Q gate simplification rules basis_factor is duration of root basis gate.""" # get class of current recursion level gate child_gate = next(basis.gate_2q_base) # check if target_u is identity if np.allclose(target_u, np.eye(4)): qc = QuantumCircuit(2) return qc, 0 # if child gate is locally equivalent to target gate, then we want to see if they can be equal using phase and VZ gates # I'm not checking this for now because slow and only small benefit if False and np.all(np.isclose(c1c2c3(child_gate.to_matrix()), c1c2c3(target_u))): def phase_lambda(p1, p2): return ConversionGainGate( p1, p2, child_gate.params[2], child_gate.params[3], t_el=child_gate.params[-1], ) template = CircuitTemplateV2( base_gates=[phase_lambda], maximum_span_guess=1, vz_only=True ) template.spanning_range = range(1, 2) optimizer3 = TemplateOptimizer( basis=template, objective=SquareCost(), override_fail=True, success_threshold=1e-10, training_restarts=1, ) ret3 = optimizer3.approximate_target_U(target_U=target_u) if ret3.success_label: # basis.no_exterior_1q = True basis.vz_only = True basis.build(1) return basis, basis_factor # first get necessary range using basis ki = monodromy_range_from_target(basis, target_u)[0] # cost to beat child_cost = (ki + 1) * cost_1q + ki * basis_factor assert ( ki >= 1 ), "Monodromy range must be at least 1, taget is identity gate case not implemented" # if basis is locally equivalent to target, return k=1 if ki == 1: basis.no_exterior_1q = False basis.build(1) return basis, 1.2 # construct the older sibling, based on parity of ki if ki % 2 == 0: rec_iter_factor = 2 else: rec_iter_factor = 3 sib_basis_factor = rec_iter_factor * basis_factor older_sibling = ConversionGainGate( *child_gate.params[:-1], t_el=child_gate.params[-1] * rec_iter_factor ) # TODO need to set a duration attribute here older_sibling.normalize_duration(1) # stop condition, if sibling is bigger than iswap # TODO, what we can check is a mixed basis (e.g. rather than 3 sqiswaps becoming 1.5 iswap and fail, make it 1 iswap and 1 sqiswap) if older_sibling.params[2] + older_sibling.params[3] <= np.pi / 2: # new basis using older sibling sibling_basis = MixedOrderBasisCircuitTemplate( base_gates=[older_sibling], chatty_build=False, use_smush_polytope=use_smush ) sibling_decomp, sib_score = recursive_sibling_check( sibling_basis, target_u, use_smush=use_smush, basis_factor=sib_basis_factor, rec_iter_factor=rec_iter_factor, cost_1q=cost_1q, ) else: sib_score = np.inf # if length of qc is shorter using the siblings decomp template, else use self template if sib_score < child_cost: return sibling_decomp, sib_score else: basis.build(ki) return basis, child_cost if __name__ == "__main__": from qiskit.circuit.library import CXGate from slam.utils.gates.duraton_scaling import atomic_cost_scaling target = CXGate().to_matrix() params = [0, 0, 0, np.pi / 16, 1] basis = ConversionGainGate(*params) template = MixedOrderBasisCircuitTemplate( base_gates=[basis], chatty_build=False, use_smush_polytope=0 ) duration = atomic_cost_scaling(params, 1, speed_method="linear", duration_1q=0) ret = recursive_sibling_check( template, target, cost_1q=0.1, basis_factor=duration[1] ) decomp_cost = ret[1] print(decomp_cost)
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector excited = Statevector.from_int(1, 2) plot_bloch_multivector(excited.data) 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 us = 1.0e-6 # Microseconds ns = 1.0e-9 # Nanoseconds # We will find the qubit frequency for the following qubit. qubit = 0 # The Rabi sweep will be at the given 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.") from qiskit import pulse, assemble # This is where we access all of our Pulse features! from qiskit.pulse import Play from qiskit.pulse import pulse_lib # This Pulse module helps us build sampled pulses for common pulse shapes ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) inst_sched_map = backend_defaults.instruction_schedule_map measure = inst_sched_map.get('measure', qubits=[0]) # Rabi experiment parameters # Drive amplitude values to iterate over: 50 amplitudes evenly spaced from 0 to 0.75 num_rabi_points = 50 drive_amp_min = 0 drive_amp_max = 0.75 drive_amps = np.linspace(drive_amp_min, drive_amp_max, num_rabi_points) # drive waveforms mush be in units of 16 drive_sigma = 80 # in dt drive_samples = 8*drive_sigma # in dt # Build the Rabi experiments: # A drive pulse at the qubit frequency, followed by a measurement, # where we vary the drive amplitude each time. rabi_schedules = [] for drive_amp in drive_amps: rabi_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_amp, sigma=drive_sigma, name=f"Rabi drive amplitude = {drive_amp}") this_schedule = pulse.Schedule(name=f"Rabi drive amplitude = {drive_amp}") this_schedule += Play(rabi_pulse, drive_chan) # The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration this_schedule += measure << this_schedule.duration rabi_schedules.append(this_schedule) rabi_schedules[-1].draw(label=True, scaling=1.0) # assemble the schedules into a Qobj num_shots_per_point = 1024 rabi_experiment_program = assemble(rabi_schedules, backend=backend, meas_level=1, meas_return='avg', shots=num_shots_per_point, schedule_los=[{drive_chan: center_frequency_Hz}] * num_rabi_points) # 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("5ef3bf17dc3044001186c011") rabi_results = job.result() import matplotlib.pyplot as plt plt.style.use('dark_background') scale_factor = 1e-14 # center data around 0 def baseline_remove(values): return np.array(values) - np.mean(values) rabi_values = [] for i in range(num_rabi_points): # Get the results for `qubit` from the ith experiment rabi_values.append(rabi_results.get_memory(i)[qubit]*scale_factor) rabi_values = np.real(baseline_remove(rabi_values)) plt.xlabel("Drive amp [a.u.]") plt.ylabel("Measured signal [a.u.]") plt.scatter(drive_amps, rabi_values, color='white') # plot real part of Rabi values 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(drive_amps, rabi_values, lambda x, A, B, drive_period, phi: (A*np.cos(2*np.pi*x/drive_period - phi) + B), [10, 0.1, 0.6, 0]) plt.scatter(drive_amps, rabi_values, color='white') plt.plot(drive_amps, y_fit, color='red') drive_period = fit_params[2] # get period of rabi oscillation plt.axvline(drive_period/2, color='red', linestyle='--') plt.axvline(drive_period, color='red', linestyle='--') plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2,0), arrowprops=dict(arrowstyle="<->", color='red')) plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() pi_amp = abs(drive_period / 2) print(f"Pi Amplitude = {pi_amp}") # Drive parameters # The drive amplitude for pi/2 is simply half the amplitude of the pi pulse drive_amp = pi_amp / 2 # x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees x90_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_amp, sigma=drive_sigma, name='x90_pulse') # Ramsey experiment parameters time_max_us = 1.8 time_step_us = 0.025 times_us = np.arange(0.1, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt # create schedules for Ramsey experiment ramsey_schedules = [] for delay in delay_times_dt: this_schedule = pulse.Schedule(name=f"Ramsey delay = {delay * dt / us} us") this_schedule += Play(x90_pulse, drive_chan) this_schedule += Play(x90_pulse, drive_chan) << this_schedule.duration + int(delay) this_schedule += measure << this_schedule.duration ramsey_schedules.append(this_schedule) ramsey_schedules[-1].draw(label=True, scaling=1.0) # Execution settings num_shots = 256 detuning_MHz = 2 ramsey_frequency = round(center_frequency_Hz + detuning_MHz * MHz, 6) # need ramsey freq in Hz ramsey_program = assemble(ramsey_schedules, backend=backend, meas_level=1, meas_return='avg', shots=num_shots, schedule_los=[{drive_chan: ramsey_frequency}]*len(ramsey_schedules) ) # RUN the job on a real device #job = backend.run(ramsey_experiment_program) #print(job.job_id()) #from qiskit.tools.monitor import job_monitor #job_monitor(job) # OR retreive job from previous run job = backend.retrieve_job('5ef3ed3a84b1b70012374317') ramsey_results = job.result() ramsey_values = [] for i in range(len(times_us)): ramsey_values.append(ramsey_results.get_memory(i)[qubit]*scale_factor) fit_params, y_fit = fit_function(times_us, np.real(ramsey_values), lambda x, A, del_f_MHz, C, B: ( A * np.cos(2*np.pi*del_f_MHz*x - C) + B ), [5, 1./0.4, 0, 0.25] ) # Off-resonance component _, del_f_MHz, _, _, = fit_params # freq is MHz since times in us plt.scatter(times_us, np.real(ramsey_values), color='white') plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.2f} MHz") plt.xlim(0, np.max(times_us)) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.title('Ramsey Experiment', fontsize=15) plt.legend() plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can make the bars more transparent to better see the ones that are behind # if they overlap. import numpy as np from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_city from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) state = Statevector(qc) plot_state_city(state, alpha=0.6)
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
shell-raiser
import numpy as np import pylab import copy from qiskit import BasicAer from qiskit.aqua import aqua_globals, QuantumInstance from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE from qiskit.aqua.components.optimizers import SLSQP from qiskit.chemistry.components.initial_states import HartreeFock from qiskit.chemistry.components.variational_forms import UCCSD from qiskit.chemistry.drivers import PySCFDriver from qiskit.chemistry.core import Hamiltonian, QubitMappingType # modeling lithium hidride molecule = 'H .0 .0 -{0}; Li .0 .0 {0}' distances = np.arange(0.5,4.25,0.25) # 5 to 4 angstroms in 25 intervals vqe_energies = [] #array to store energy hf_energies = [] exact_energies = [] for i,d in enumerate(distances): print('step',i) #set up experiment driver = PySCFDriver(molecule.format(d/12), basis='sto3g') qmolecule = driver.run() operator = Hamiltonian(qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=True, orbital_reduction=[-3,-2]) qubit_op, aux_ops = operator.run(qmolecule) #exact classical result exact_result = NumPyMinimumEigensolver(qubit_op, aux_operators = aux_ops).run() exact_result = operator.process_algorithm_result(exact_result) #VQE optimizer = SLSQP(maxiter=1000) initial_state=HartreeFock(operator.molecule_info['num_orbitals'], operator.molecule_info['num_particles'], qubit_mapping=operator._qubit_mapping, two_qubit_reduction = operator._two_qubit_reduction) var_form = UCCSD(num_orbitals=operator.molecule_info['num_orbitals'], num_particles = operator.molecule_info['num_particles'], initial_state=initial_state, qubit_mapping=operator._qubit_mapping, two_qubit_reduction=operator._two_qubit_reduction) algo = VQE(qubit_op, var_form, optimizer, aux_operators=aux_ops) vqe_result = algo.run(QuantumInstance(BasicAer.get_backend('statevector_simulator'))) vqe_result = operator.process_algorithm_result(vqe_result) exact_energies.append(exact_result.energy) vqe_energies.append(vqe_result.energy) hf_energies.append(vqe_result.hartree_fock_energy) print(vqe_energies) print(exact_energies) print(hf_energies) pylab.plot(distances, hf_energies, label= 'Hartree-Fock') pylab.plot(distances, vqe_energies, 'o', label='VQE') pylab.plot(distances, exact_energies, 'x', label='Exact') pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title("LiH Ground State Energy") pylab.legend(loc='upper right')
https://github.com/quantumjim/pewpew_qiskit_workshops
quantumjim
%matplotlib notebook import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen qc = QuantumCircuit(2,2) # create an empty circuit with two qubits and two output bits # create a circuit with the required measurements, so we can add them in easily meas = QuantumCircuit(2,2) meas.measure(0,0) meas.measure(1,1) # loop over the squares centered on (1,2) and (6,2) and make all dim for (X,Y) in [(1,2),(6,2)]: for dX in [+1,0,-1]: for dY in [+1,0,-1]: screen.pixel(X+dX,Y+dY,2) for (X,Y) in [(1,2),(6,2)]: screen.pixel(X,Y,0) # turn off the center pixels of the squares old_keys = 0 while True: # loop which checks for user input and responds # look for and act upon key presses keys = pew.keys() # get current key presses if keys!=0 and keys!=old_keys: if keys&pew.K_UP: qc.x(0) # x for qubit 0 when UP is pressed if keys&pew.K_LEFT: qc.x(1) # x for qubit 1 when LEFT is pressed old_keys = keys # execute the circuit and get a single sample of memory m = simulate(qc+meas,shots=1,get='memory') # turn the pixel (1,2) on or off depending on whether the first bit value is 1 or 0 if m[0][0]=='1': screen.pixel(1,2,3) else: screen.pixel(1,2,0) # do the same for pixel (6,2) if m[0][1]=='1': screen.pixel(6,2,3) else: screen.pixel(6,2,0) pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen # create an empty circuit with two qubits and two output bits qc = QuantumCircuit(2,2) cnot = QuantumCircuit(2,2) cnot.cx(0,1) # create a circuit with the required measurements, so we can add them in easily meas = QuantumCircuit(2,2) meas.measure(0,0) meas.measure(1,1) # loop over the square centered on (1,2) and make all dim for (X,Y) in [(1,2),(6,2)]: for dX in [+1,0,-1]: for dY in [+1,0,-1]: screen.pixel(X+dX,Y+dY,2) for (X,Y) in [(1,2),(6,2)]: screen.pixel(X,Y,0) # turn off the center pixels of the squares old_keys = 0 while True: # loop which checks for user input and responds # look for and act upon key presses keys = pew.keys() # get current key presses if keys!=0 and keys!=old_keys: if keys&pew.K_UP: qc.x(0) # x for qubit 0 when UP is pressed if keys&pew.K_LEFT: qc.x(1) # x for qubit 1 when LEFT is pressed old_keys = keys # execute the circuit and get a single sample of memory m = simulate(qc+meas,shots=1,get='memory') # turn the pixel (1,2) on or off depending on whether the first bit value is 1 or 0 if m[0][0]=='1': screen.pixel(1,2,3) else: screen.pixel(1,2,0) # do the same for pixel (6,2) if m[0][1]=='1': screen.pixel(6,2,3) else: screen.pixel(6,2,0) m = simulate(qc+cnot+meas,shots=1,get='memory') xor = m[0][0] if xor=='0': for (X,Y) in [(3,2),(4,2)]: screen.pixel(X,Y,0) else: for (X,Y) in [(3,2),(4,2)]: screen.pixel(X,Y,3) pew.show(screen) # update screen to display any changes pew.tick(1/6) # pause for a sixth of a second
https://github.com/abbarreto/qiskit2
abbarreto
%run init.ipynb from qiskit import * nshots = 8192 IBMQ.load_account() provider = IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main') simulator = Aer.get_backend('qasm_simulator') device = provider.get_backend('ibmq_jakarta') from qiskit.tools.visualization import plot_histogram from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor def bernstein_vazirani(s): ls = len(s) qc = QuantumCircuit(ls+1,ls) qc.h(range(ls)) qc.x(ls) qc.h(ls) qc.barrier(); for ii, yesno in enumerate(reversed(s)): # the black box if yesno == '1': qc.cx(ii, ls); qc.barrier(); qc.h(range(ls)); qc.barrier(); qc.measure(range(ls),range(ls)) return qc s = '011' # secretnumber qc = bernstein_vazirani(s) qc.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend = simulator, shots = 1).result() counts = result.get_counts() print(counts) jobE = execute(qc, backend = device, shots = nshots) job_monitor(jobE) jobS = execute(qc, backend = simulator, shots = nshots) plot_histogram([jobS.result().get_counts(0), jobE.result().get_counts(0)], bar_labels = False, legend = ['sim', 'exp'])
https://github.com/Qubico-Hack/tutorials
Qubico-Hack
from sklearn.datasets import load_iris iris_data = load_iris() print(iris_data.DESCR) features = iris_data.data labels = iris_data.target from sklearn.preprocessing import MinMaxScaler features = MinMaxScaler().fit_transform(features) import pandas as pd import seaborn as sns df = pd.DataFrame(iris_data.data, columns=iris_data.feature_names) df["class"] = pd.Series(iris_data.target) sns.pairplot(df, hue="class", palette="tab10") # Entrenamiento de un modelo clásico de aprendizaje automático from sklearn.model_selection import train_test_split from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 123; train_features, test_features, train_labels, test_labels = train_test_split( features, labels, train_size=0.8, random_state=algorithm_globals.random_seed ) from sklearn.svm import SVC svc = SVC() _ = svc.fit(train_features, train_labels) train_score_c4 = svc.score(train_features, train_labels) test_score_c4 = svc.score(test_features, test_labels) print(f"Classical SVC on the training dataset: {train_score_c4:.2f}") print(f"Classical SVC on the test dataset: {test_score_c4:.2f}") # Entrenamiento de un modelo de aprendizaje automático !pip install qiskit[all] from qiskit.circuit.library import ZZFeatureMap num_features = features.shape[1] feature_map = ZZFeatureMap(feature_dimension=num_features, reps=1) feature_map.decompose().draw(output="mpl", fold=20) from qiskit.circuit.library import RealAmplitudes ansatz = RealAmplitudes(num_qubits=num_features, reps=3) ansatz.decompose().draw(output="mpl", fold=20) from qiskit_algorithms.optimizers import COBYLA optimizer = COBYLA(maxiter=100) from qiskit.primitives import Sampler sampler = Sampler() from matplotlib import pyplot as plt from IPython.display import clear_output objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) def callback_graph(weights, obj_func_eval): clear_output(wait=True) objective_func_vals.append(obj_func_eval) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() import time from qiskit_machine_learning.algorithms.classifiers import VQC vqc = VQC( sampler=sampler, feature_map=feature_map, ansatz=ansatz, optimizer=optimizer, callback=callback_graph, ) # clear objective value history objective_func_vals = [] start = time.time() vqc.fit(train_features, train_labels) elapsed = time.time() - start print(f"Training time: {round(elapsed)} seconds") train_score_q4 = vqc.score(train_features, train_labels) test_score_q4 = vqc.score(test_features, test_labels) print(f"Quantum VQC on the training dataset: {train_score_q4:.2f}") print(f"Quantum VQC on the test dataset: {test_score_q4:.2f}") # Reducir el número de funciones from sklearn.decomposition import PCA features = PCA(n_components=2).fit_transform(features) plt.rcParams["figure.figsize"] = (6, 6) sns.scatterplot(x=features[:, 0], y=features[:, 1], hue=labels, palette="tab10") train_features, test_features, train_labels, test_labels = train_test_split( features, labels, train_size=0.8, random_state=algorithm_globals.random_seed ) svc.fit(train_features, train_labels) train_score_c2 = svc.score(train_features, train_labels) test_score_c2 = svc.score(test_features, test_labels) print(f"Classical SVC on the training dataset: {train_score_c2:.2f}") print(f"Classical SVC on the test dataset: {test_score_c2:.2f}") num_features = features.shape[1] feature_map = ZZFeatureMap(feature_dimension=num_features, reps=1) ansatz = RealAmplitudes(num_qubits=num_features, reps=3) optimizer = COBYLA(maxiter=40) vqc = VQC( sampler=sampler, feature_map=feature_map, ansatz=ansatz, optimizer=optimizer, callback=callback_graph, ) # clear objective value history objective_func_vals = [] # make the objective function plot look nicer. plt.rcParams["figure.figsize"] = (12, 6) start = time.time() vqc.fit(train_features, train_labels) elapsed = time.time() - start print(f"Training time: {round(elapsed)} seconds") train_score_q2_ra = vqc.score(train_features, train_labels) test_score_q2_ra = vqc.score(test_features, test_labels) print(f"Quantum VQC on the training dataset using RealAmplitudes: {train_score_q2_ra:.2f}") print(f"Quantum VQC on the test dataset using RealAmplitudes: {test_score_q2_ra:.2f}") from qiskit.circuit.library import EfficientSU2 ansatz = EfficientSU2(num_qubits=num_features, reps=3) optimizer = COBYLA(maxiter=40) vqc = VQC( sampler=sampler, feature_map=feature_map, ansatz=ansatz, optimizer=optimizer, callback=callback_graph, ) # clear objective value history objective_func_vals = [] start = time.time() vqc.fit(train_features, train_labels) elapsed = time.time() - start print(f"Training time: {round(elapsed)} seconds") train_score_q2_eff = vqc.score(train_features, train_labels) test_score_q2_eff = vqc.score(test_features, test_labels) print(f"Quantum VQC on the training dataset using EfficientSU2: {train_score_q2_eff:.2f}") print(f"Quantum VQC on the test dataset using EfficientSU2: {test_score_q2_eff:.2f}") #Conclusión print(f"Model | Test Score | Train Score") print(f"SVC, 4 features | {train_score_c4:10.2f} | {test_score_c4:10.2f}") print(f"VQC, 4 features, RealAmplitudes | {train_score_q4:10.2f} | {test_score_q4:10.2f}") print(f"----------------------------------------------------------") print(f"SVC, 2 features | {train_score_c2:10.2f} | {test_score_c2:10.2f}") print(f"VQC, 2 features, RealAmplitudes | {train_score_q2_ra:10.2f} | {test_score_q2_ra:10.2f}") print(f"VQC, 2 features, EfficientSU2 | {train_score_q2_eff:10.2f} | {test_score_q2_eff:10.2f}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/mickahell/qiskit-ecosystem_template
mickahell
"""Docstring.""" from qiskit import QuantumCircuit, execute, QuantumRegister, ClassicalRegister from qiskit_aer import Aer class Random: """Demo random.""" def __init__(self): """Demo random.""" self.pow = 2 self.qasm = Aer.get_backend("aer_simulator") def run(self, number: int) -> int: """Run method.""" nb_qubits = number print("Generate random number") circ = QuantumRegister(nb_qubits, "the number") meas = ClassicalRegister(nb_qubits, "measurement") quant_circ = QuantumCircuit(circ, meas) for i in range(0, nb_qubits): quant_circ.x(i) quant_circ.measure(circ, meas) job = execute(quant_circ, self.qasm, shots=1, memory=True) result_sim = job.result() memory = result_sim.get_memory() result = int(memory[0], 2) + 1 return result def __repr__(self): return f"Random(circuit of: {self.pow})"
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, assemble, transpile import qiskit.tools.jupyter from qiskit.test.mock import FakeTokyo code = QuantumRegister(5,'code') syn = QuantumRegister(4,'syn') out = ClassicalRegister(4,'output') backend = FakeTokyo() error_qubits = [0,4] # qc_syn qc_syn = QuantumCircuit(code,syn,out) # left ZZZ qc_syn.cx(code[0],syn[1]) qc_syn.cx(code[2],syn[1]) qc_syn.cx(code[3],syn[1]) qc_syn.barrier() # right ZZZ qc_syn.cx(code[2],syn[2]) qc_syn.cx(code[4],syn[2]) qc_syn.cx(code[1],syn[0]) # qc_syn.cx(syn[0],syn[2]) # qc_syn.cx(code[1],syn[0]) # qc_syn.barrier() # top XXX qc_syn.h(syn[0]) qc_syn.cx(syn[0],code[0]) qc_syn.cx(syn[0],code[1]) qc_syn.cx(syn[0],code[2]) qc_syn.h(syn[0]) qc_syn.barrier() # bottom XXX qc_syn.h(syn[3]) qc_syn.cx(syn[3],code[2]) qc_syn.cx(syn[3],code[3]) qc_syn.cx(syn[3],code[4]) qc_syn.h(syn[3]) qc_syn.barrier() # measure the auxilliary qubits qc_syn.measure(syn,out) # qc_init qc_init = QuantumCircuit(code,syn,out) qc_init.h(syn[0]) qc_init.cx(syn[0],code[0]) qc_init.cx(syn[0],code[1]) qc_init.cx(syn[0],code[2]) qc_init.cx(code[2],syn[0]) qc_init.h(syn[3]) qc_init.cx(syn[3],code[2]) qc_init.cx(syn[3],code[3]) qc_init.cx(syn[3],code[4]) qc_init.cx(code[4],syn[3]) qc_init.barrier() # initial layout initial_layout = [0,2,6,10,12,1,5,7,11] # qc_syn qc_syn = QuantumCircuit(code,syn,out) # left ZZZ qc_syn.cx(code[0],syn[1]) qc_syn.cx(code[2],syn[1]) qc_syn.cx(code[3],syn[1]) qc_syn.barrier() # right ZZZ qc_syn.cx(code[2],syn[2]) qc_syn.cx(code[4],syn[2]) qc_syn.cx(code[1],syn[0]) qc_syn.cx(syn[0],syn[2]) qc_syn.cx(code[1],syn[0]) qc_syn.barrier() # top XXX qc_syn.h(syn[0]) qc_syn.cx(syn[0],code[0]) qc_syn.cx(syn[0],code[1]) qc_syn.cx(syn[0],code[2]) qc_syn.h(syn[0]) qc_syn.barrier() # bottom XXX qc_syn.h(syn[3]) qc_syn.cx(syn[3],code[2]) qc_syn.cx(syn[3],code[3]) qc_syn.cx(syn[3],code[4]) qc_syn.h(syn[3]) qc_syn.barrier() # measure the auxilliary qubits qc_syn.measure(syn,out) # qc_init qc_init = QuantumCircuit(code,syn,out) # initial layout initial_layout = [0,2,6,10,12,1,5,7,11] # qc_syn qc_syn = QuantumCircuit(code,syn,out) qc_syn.measure(syn,out) # qc_init qc_init = QuantumCircuit(code,syn,out) qc_init.h(syn[0]) qc_init.cx(syn[0],code[0]) qc_init.cx(syn[0],code[1]) qc_init.cx(syn[0],code[2]) qc_init.cx(code[2],syn[0]) qc_init.h(syn[3]) qc_init.cx(syn[3],code[2]) qc_init.cx(syn[3],code[3]) qc_init.cx(syn[3],code[4]) qc_init.cx(code[4],syn[3]) qc_init.barrier() # initial layout initial_layout = [0,2,6,10,12,1,5,7,11] # qc_syn qc_syn = QuantumCircuit(code,syn,out) # left ZZZ qc_syn.cx(code[0],syn[1]) qc_syn.cx(code[2],syn[1]) qc_syn.cx(code[3],syn[1]) qc_syn.barrier() # right ZZZ qc_syn.cx(code[2],syn[2]) qc_syn.cx(code[4],syn[2]) qc_syn.cx(code[1],syn[2]) qc_syn.barrier() # top XXX qc_syn.h(syn[0]) qc_syn.cx(syn[0],code[0]) qc_syn.cx(syn[0],code[1]) qc_syn.cx(syn[0],code[2]) qc_syn.h(syn[0]) qc_syn.barrier() # bottom XXX qc_syn.h(syn[3]) qc_syn.cx(syn[3],code[2]) qc_syn.cx(syn[3],code[3]) qc_syn.cx(syn[3],code[4]) qc_syn.h(syn[3]) qc_syn.barrier() # measure the auxilliary qubits qc_syn.measure(syn,out) # qc_init qc_init = QuantumCircuit(code,syn,out) qc_init.h(code[0]) qc_init.cx(code[0],code[1]) qc_init.cx(code[0],code[2]) qc_init.h(code[3]) qc_init.cx(code[3],code[2]) qc_init.cx(code[3],code[4]) qc_init.barrier() # initial layout initial_layout = list(range(9))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np # Import Qiskit from qiskit import QuantumCircuit from qiskit import Aer, transpile from qiskit.tools.visualization import plot_histogram, plot_state_city import qiskit.quantum_info as qi Aer.backends() simulator = Aer.get_backend('aer_simulator') # Create circuit circ = QuantumCircuit(2) circ.h(0) circ.cx(0, 1) circ.measure_all() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get counts result = simulator.run(circ).result() counts = result.get_counts(circ) plot_histogram(counts, title='Bell-State counts') # Run and get memory result = simulator.run(circ, shots=10, memory=True).result() memory = result.get_memory(circ) print(memory) # Increase shots to reduce sampling variance shots = 10000 # Stabilizer simulation method sim_stabilizer = Aer.get_backend('aer_simulator_stabilizer') job_stabilizer = sim_stabilizer.run(circ, shots=shots) counts_stabilizer = job_stabilizer.result().get_counts(0) # Statevector simulation method sim_statevector = Aer.get_backend('aer_simulator_statevector') job_statevector = sim_statevector.run(circ, shots=shots) counts_statevector = job_statevector.result().get_counts(0) # Density Matrix simulation method 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) # Matrix Product State simulation method 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 # Initialize a GPU backend # Note that the cloud instance for tutorials does not have a GPU # so this will raise an exception. try: simulator_gpu = Aer.get_backend('aer_simulator') simulator_gpu.set_options(device='GPU') except AerError as e: print(e) # Configure a single-precision statevector simulator backend simulator = Aer.get_backend('aer_simulator_statevector') simulator.set_options(precision='single') # Run and get counts result = simulator.run(circ).result() counts = result.get_counts(circ) print(counts) # Construct quantum circuit without measure circ = QuantumCircuit(2) circ.h(0) circ.cx(0, 1) circ.save_statevector() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get statevector result = simulator.run(circ).result() statevector = result.get_statevector(circ) plot_state_city(statevector, title='Bell state') # Construct quantum circuit without measure circ = QuantumCircuit(2) circ.h(0) circ.cx(0, 1) circ.save_unitary() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get unitary result = simulator.run(circ).result() unitary = result.get_unitary(circ) print("Circuit unitary:\n", np.asarray(unitary).round(5)) # Construct quantum circuit without measure 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}') # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get saved data result = simulator.run(circ).result() data = result.data(0) data # Generate a random statevector num_qubits = 2 psi = qi.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) # Use initilize instruction to set initial state circ = QuantumCircuit(num_qubits) circ.initialize(psi, range(num_qubits)) circ.save_state() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get result data result = simulator.run(circ).result() result.data(0) num_qubits = 2 rho = qi.random_density_matrix(2 ** num_qubits, seed=100) circ = QuantumCircuit(num_qubits) circ.set_density_matrix(rho) 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) # Generate a random Clifford C num_qubits = 2 stab = qi.random_clifford(num_qubits, seed=100) # Set initial state to stabilizer state C|0> circ = QuantumCircuit(num_qubits) circ.set_stabilizer(stab) 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) # Generate a random unitary num_qubits = 2 unitary = qi.random_unitary(2 ** num_qubits, seed=100) # Set initial state to unitary circ = QuantumCircuit(num_qubits) circ.set_unitary(unitary) 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/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt try: import cplex from cplex.exceptions import CplexError except: print("Warning: Cplex not found.") import math from qiskit.utils import algorithm_globals from qiskit.algorithms.minimum_eigensolvers import SamplingVQE from qiskit.algorithms.optimizers import SPSA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Sampler # Initialize the problem by defining the parameters n = 3 # number of nodes + depot (n+1) K = 2 # number of vehicles # Get the data class Initializer: def __init__(self, n): self.n = n def generate_instance(self): n = self.n # np.random.seed(33) np.random.seed(1543) xc = (np.random.rand(n) - 0.5) * 10 yc = (np.random.rand(n) - 0.5) * 10 instance = np.zeros([n, n]) for ii in range(0, n): for jj in range(ii + 1, n): instance[ii, jj] = (xc[ii] - xc[jj]) ** 2 + (yc[ii] - yc[jj]) ** 2 instance[jj, ii] = instance[ii, jj] return xc, yc, instance # Initialize the problem by randomly generating the instance initializer = Initializer(n) xc, yc, instance = initializer.generate_instance() class ClassicalOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n # number of nodes self.K = K # number of vehicles def compute_allowed_combinations(self): f = math.factorial return f(self.n) / f(self.K) / f(self.n - self.K) def cplex_solution(self): # refactoring instance = self.instance n = self.n K = self.K my_obj = list(instance.reshape(1, n**2)[0]) + [0.0 for x in range(0, n - 1)] my_ub = [1 for x in range(0, n**2 + n - 1)] my_lb = [0 for x in range(0, n**2)] + [0.1 for x in range(0, n - 1)] my_ctype = "".join(["I" for x in range(0, n**2)]) + "".join( ["C" for x in range(0, n - 1)] ) my_rhs = ( 2 * ([K] + [1 for x in range(0, n - 1)]) + [1 - 0.1 for x in range(0, (n - 1) ** 2 - (n - 1))] + [0 for x in range(0, n)] ) my_sense = ( "".join(["E" for x in range(0, 2 * n)]) + "".join(["L" for x in range(0, (n - 1) ** 2 - (n - 1))]) + "".join(["E" for x in range(0, n)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + ii, n**2, n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) # Sub-tour elimination constraints: for ii in range(0, n): for jj in range(0, n): if (ii != jj) and (ii * jj > 0): col = [ii + (jj * n), n**2 + ii - 1, n**2 + jj - 1] coef = [1, 1, -1] rows.append([col, coef]) for ii in range(0, n): col = [(ii) * (n + 1)] coef = [1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(instance, n, K) # Print number of feasible solutions print("Number of feasible solutions = " + str(classical_optimizer.compute_allowed_combinations())) # Solve the problem in a classical fashion via CPLEX x = None z = None try: x, classical_cost = classical_optimizer.cplex_solution() # Put the solution in the z variable z = [x[ii] for ii in range(n**2) if ii // n != ii % n] # Print the solution print(z) except: print("CPLEX may be missing.") # Visualize the solution def visualize_solution(xc, yc, x, C, n, K, title_str): plt.figure() plt.scatter(xc, yc, s=200) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.15, yc[i]), size=16, color="r") plt.plot(xc[0], yc[0], "r*", ms=20) plt.grid() for ii in range(0, n**2): if x[ii] > 0: ix = ii // n iy = ii % n plt.arrow( xc[ix], yc[ix], xc[iy] - xc[ix], yc[iy] - yc[ix], length_includes_head=True, head_width=0.25, ) plt.title(title_str + " cost = " + str(int(C * 100) / 100.0)) plt.show() if x is not None: visualize_solution(xc, yc, x, classical_cost, n, K, "Classical") from qiskit_optimization import QuadraticProgram from qiskit_optimization.algorithms import MinimumEigenOptimizer class QuantumOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n self.K = K def binary_representation(self, x_sol=0): instance = self.instance n = self.n K = self.K A = np.max(instance) * 100 # A parameter of cost function # Determine the weights w instance_vec = instance.reshape(n**2) w_list = [instance_vec[x] for x in range(n**2) if instance_vec[x] > 0] w = np.zeros(n * (n - 1)) for ii in range(len(w_list)): w[ii] = w_list[ii] # Some variables I will use Id_n = np.eye(n) Im_n_1 = np.ones([n - 1, n - 1]) Iv_n_1 = np.ones(n) Iv_n_1[0] = 0 Iv_n = np.ones(n - 1) neg_Iv_n_1 = np.ones(n) - Iv_n_1 v = np.zeros([n, n * (n - 1)]) for ii in range(n): count = ii - 1 for jj in range(n * (n - 1)): if jj // (n - 1) == ii: count = ii if jj // (n - 1) != ii and jj % (n - 1) == count: v[ii][jj] = 1.0 vn = np.sum(v[1:], axis=0) # Q defines the interactions between variables Q = A * (np.kron(Id_n, Im_n_1) + np.dot(v.T, v)) # g defines the contribution from the individual variables g = ( w - 2 * A * (np.kron(Iv_n_1, Iv_n) + vn.T) - 2 * A * K * (np.kron(neg_Iv_n_1, Iv_n) + v[0].T) ) # c is the constant offset c = 2 * A * (n - 1) + 2 * A * (K**2) try: max(x_sol) # Evaluates the cost distance from a binary representation of a path fun = ( lambda x: np.dot(np.around(x), np.dot(Q, np.around(x))) + np.dot(g, np.around(x)) + c ) cost = fun(x_sol) except: cost = 0 return Q, g, c, cost def construct_problem(self, Q, g, c) -> QuadraticProgram: qp = QuadraticProgram() for i in range(n * (n - 1)): qp.binary_var(str(i)) qp.objective.quadratic = Q qp.objective.linear = g qp.objective.constant = c return qp def solve_problem(self, qp): algorithm_globals.random_seed = 10598 vqe = SamplingVQE(sampler=Sampler(), optimizer=SPSA(), ansatz=RealAmplitudes()) optimizer = MinimumEigenOptimizer(min_eigen_solver=vqe) result = optimizer.solve(qp) # compute cost of the obtained result _, _, _, level = self.binary_representation(x_sol=result.x) return result.x, level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(instance, n, K) # Check if the binary representation is correct try: if z is not None: Q, g, c, binary_cost = quantum_optimizer.binary_representation(x_sol=z) print("Binary cost:", binary_cost, "classical cost:", classical_cost) if np.abs(binary_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the binary formulation") else: print("Could not verify the correctness, due to CPLEX solution being unavailable.") Q, g, c, binary_cost = quantum_optimizer.binary_representation() print("Binary cost:", binary_cost) except NameError as e: print("Warning: Please run the cells above first.") print(e) qp = quantum_optimizer.construct_problem(Q, g, c) quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp) print(quantum_solution, quantum_cost) # Put the solution in a way that is compatible with the classical variables x_quantum = np.zeros(n**2) kk = 0 for ii in range(n**2): if ii // n != ii % n: x_quantum[ii] = quantum_solution[kk] kk += 1 # visualize the solution visualize_solution(xc, yc, x_quantum, quantum_cost, n, K, "Quantum") # and visualize the classical for comparison if x is not None: visualize_solution(xc, yc, x, classical_cost, n, K, "Classical") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/jakelishman/qiskit-qasm2
jakelishman
# 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=missing-module-docstring,missing-class-docstring,missing-function-docstring import ddt import qiskit.qasm2 from qiskit.test import QiskitTestCase @ddt.ddt class TestLexer(QiskitTestCase): # Most of the lexer is fully exercised in the parser tests. These tests here are really mopping # up some error messages and whatnot that might otherwise be missed. def test_pathological_formatting(self): # This is deliberately _terribly_ formatted, included multiple blanks lines in quick # succession and comments in places you really wouldn't expect to see comments. program = """ OPENQASM // do we really need a comment here? 2.0//and another comment very squished up ; include // this line introduces a file import "qelib1.inc" // this is the file imported ; // this is a semicolon gate // we're making a gate bell( // void, with loose parenthesis in comment ) ) a,// b{h a;cx a //,,,, ,b;} qreg // a quantum register q [ // a square bracket 2];bell q[0],// q[1];creg c[2];measure q->c;""" parsed = qiskit.qasm2.loads(program) expected_unrolled = qiskit.QuantumCircuit( qiskit.QuantumRegister(2, "q"), qiskit.ClassicalRegister(2, "c") ) expected_unrolled.h(0) expected_unrolled.cx(0, 1) expected_unrolled.measure([0, 1], [0, 1]) self.assertEqual(parsed.decompose(), expected_unrolled) @ddt.data("0.25", "00.25", "2.5e-1", "2.5e-01", "0.025E+1", ".25", ".025e1", "25e-2") def test_float_lexes(self, number): program = f"qreg q[1]; U({number}, 0, 0) q[0];" parsed = qiskit.qasm2.loads(program) self.assertEqual(list(parsed.data[0].operation.params), [0.25, 0, 0]) def test_no_decimal_float_rejected_in_strict_mode(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"\[strict\] all floats must include a decimal point", ): qiskit.qasm2.loads("OPENQASM 2.0; qreg q[1]; U(25e-2, 0, 0) q[0];", strict=True) @ddt.data("", "qre", "cre", ".") def test_non_ascii_bytes_error(self, prefix): token = f"{prefix}\xff" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "encountered a non-ASCII byte"): qiskit.qasm2.loads(token) def test_integers_cannot_start_with_zero(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "integers cannot have leading zeroes" ): qiskit.qasm2.loads("0123") @ddt.data("", "+", "-") def test_float_exponents_must_have_a_digit(self, sign): token = f"12.34e{sign}" with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "needed to see an integer exponent" ): qiskit.qasm2.loads(token) def test_non_builtins_cannot_be_capitalised(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "identifiers cannot start with capital" ): qiskit.qasm2.loads("Qubit") def test_unterminated_filename_is_invalid(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "unexpected end-of-file while lexing string literal" ): qiskit.qasm2.loads('include "qelib1.inc') def test_filename_with_linebreak_is_invalid(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "unexpected line break while lexing string literal" ): qiskit.qasm2.loads('include "qe\nlib1.inc";') def test_strict_single_quoted_path_rejected(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"\[strict\] paths must be in double quotes" ): qiskit.qasm2.loads("OPENQASM 2.0; include 'qelib1.inc';", strict=True) def test_version_must_have_word_boundary_after(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a version" ): qiskit.qasm2.loads("OPENQASM 2a;") with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a version" ): qiskit.qasm2.loads("OPENQASM 2.0a;") def test_no_boundary_float_in_version_position(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float" ): qiskit.qasm2.loads("OPENQASM .5a;") with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float" ): qiskit.qasm2.loads("OPENQASM 0.2e1a;") def test_integers_must_have_word_boundaries_after(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after an integer" ): qiskit.qasm2.loads("OPENQASM 2.0; qreg q[2a];") def test_floats_must_have_word_boundaries_after(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float" ): qiskit.qasm2.loads("OPENQASM 2.0; qreg q[1]; U(2.0a, 0, 0) q[0];") def test_single_equals_is_rejected(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"single equals '=' is never valid" ): qiskit.qasm2.loads("if (a = 2) U(0, 0, 0) q[0];") def test_bare_dot_is_not_valid_float(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a numeric fractional part" ): qiskit.qasm2.loads("qreg q[0]; U(2 + ., 0, 0) q[0];") def test_invalid_token(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"encountered '!', which doesn't match" ): qiskit.qasm2.loads("!")
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# let's define both vectors u = [-3,-2,0,-1,4] v = [-1,-1,2,-3,5] uv = 0; # summation is initially zero for i in range(len(u)): # iteratively access every pair with the same indices print("pairwise multiplication of the entries with index",i,"is",u[i]*v[i]) uv = uv + u[i]*v[i] # i-th entries are multiplied and then added to summation print() # print an empty line print("The inner product of",u,'and',v,'is',uv) # # your solution is here # # # your solution is here # # let's find the inner product of v and u v = [-4,0] u = [0,-5] result = 0; for i in range(2): result = result + v[i]*u[i] print("the inner product of u and v is",result) # we can use the same code v = [-4,3] u = [-3,-4] result = 0; for i in range(2): result = result + v[i]*u[i] print("the inner product of u and v is",result) # you may consider to write a function in python for innner product # # your solution is here # # # your solution is here #
https://github.com/hugoecarl/TSP-Problem-Study
hugoecarl
with open('in-exemplo.txt', 'r') as f: print(f.read()) with open('out-exemplo.txt', 'r') as f: print(f.read()) import time import matplotlib.pyplot as plt import pandas as pd import os import subprocess %matplotlib inline #Roda entradas def roda_com_entrada(executavel, arquivo_in, envs = '1', deb = '0'): with open(arquivo_in) as f: start = time.perf_counter() a = f.read() proc = subprocess.run([executavel], input=a, text=True, capture_output=True, env=dict(OMP_NUM_THREADS=envs, DEBUG=deb, **os.environ)) end = time.perf_counter() f.close() ret = '' for i in a: if i == "\n": break ret += i return (proc.stdout, end - start, int(ret)) #retorna tamanho do tour apartir do stdout def tamanho_tour(out): buf = '' for i in out: if i == " ": return float(buf) buf += i #Cria resultados tamanho_entradas = [] tempos = [] tempos_1 = [] tempos_2 = [] resultados1 = [] resultados2 = [] resultados3 = [] #Usando as mesmas entradas for i in range(8): print("Rodando entrada: "+str(i)) a = roda_com_entrada('./busca_local_antigo','busca-exaustiva/in-'+str(i)+'.txt') b = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt') c = roda_com_entrada('./heuristico/heuristico','busca-exaustiva/in-'+str(i)+'.txt') tempos.append(a[1]) tempos_1.append(b[1]) tempos_2.append(c[1]) tamanho_entradas.append(a[2]) resultados1.append(tamanho_tour(a[0])) resultados2.append(tamanho_tour(b[0])) resultados3.append(tamanho_tour(c[0])) #Teste com entrada um pouco maior print("Rodando entrada: 8") tempos.append(roda_com_entrada('./busca_local_antigo','maior.txt')[1]) tempos_1.append(roda_com_entrada('./busca-exaustiva/busca-exaustiva','maior.txt')[1]) tempos_2.append(roda_com_entrada('./heuristico/heuristico','maior.txt')[1]) tamanho_entradas.append(roda_com_entrada('./busca-local/busca-local','maior.txt')[2]) resultados1.append(tamanho_tour(roda_com_entrada('./busca_local_antigo','maior.txt')[0])) resultados2.append(tamanho_tour(roda_com_entrada('./busca-exaustiva/busca-exaustiva','maior.txt')[0])) resultados3.append(tamanho_tour(roda_com_entrada('./heuristico/heuristico','maior.txt')[0])) plt.title("Comparacao Desempenho") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos_1) plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_2) plt.legend(["busca-exaustiva", "busca-local","heuristico"]) plt.show() plt.title("Comparacao Desempenho") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_2) plt.legend(["busca-local","heuristico"]) plt.show() df = pd.DataFrame() df["Tamanho Entrada"] = pd.Series(tamanho_entradas) df["busca-local-tempo"] = pd.Series(tempos) df["busca-exaustiva-tempo"] = pd.Series(tempos_1) df["heuristica-tempo"] = pd.Series(tempos_2) df["busca-local-resultado"] = pd.Series(resultados1) df["busca-exaustiva-resultado"] = pd.Series(resultados2) df["heuristica-resultado"] = pd.Series(resultados3) df df.describe() #Cria resultados tamanho_entradas = [] tempos = [] tempos_1 = [] tempos_2 = [] tempos_3 = [] tempos_4 = [] tempos_5 = [] #Usando as mesmas entradas for i in range(7): print("Rodando entrada: "+str(i)) a = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt') b = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt','2') c = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt','3') d = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt','4') e = roda_com_entrada('./busca_local_antigo','busca-local/in-'+str(i)+'.txt') f = roda_com_entrada('./busca-local/busca-local-gpu','busca-local/in-'+str(i)+'.txt') tempos.append(a[1]) tempos_1.append(b[1]) tempos_2.append(c[1]) tempos_3.append(d[1]) tempos_4.append(e[1]) tempos_5.append(f[1]) tamanho_entradas.append(a[2]) plt.title("Comparacao Desempenho Busca Local") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_1) plt.plot(tamanho_entradas, tempos_2) plt.plot(tamanho_entradas, tempos_3) plt.legend(["1 thread otimizado", "2 threads otimizado","3 threads otimizado", "4 threads otimizado", "Sem otimizações"]) plt.show() plt.title("Comparacao Desempenho Busca Local") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos_3) plt.plot(tamanho_entradas, tempos_5) plt.legend(["4 thread otimizado", "GPU"]) plt.show() plt.title("Comparacao Desempenho Busca Local") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_4) plt.legend(["1 thread otimizado", "Sem otimizações"]) plt.show() df = pd.DataFrame() df["Tamanho Entrada"] = pd.Series(tamanho_entradas) df["busca-local-1-thread"] = pd.Series(tempos) df["busca-local-2-threads"] = pd.Series(tempos_1) df["busca-local-3-threads"] = pd.Series(tempos_2) df["busca-local-4-threads"] = pd.Series(tempos_3) df["busca-local-gpu"] = pd.Series(tempos_5) df["busca-local-semopt"] = pd.Series(tempos_4) df #Cria resultados tamanho_entradas = [] tempos = [] tempos_1 = [] #Usando as mesmas entradas for i in range(7): print("Rodando entrada: "+str(i)) a = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt', '1', '1') b = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt', '1', '0') tempos.append(a[1]) tempos_1.append(b[1]) tamanho_entradas.append(a[2]) plt.title("Comparacao Desempenho Busca Exaustiva") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_1) plt.legend(["Exaustivo Simples", "Exaustivo Branch and Bound"]) plt.show() df = pd.DataFrame() df["Tamanho Entrada"] = pd.Series(tamanho_entradas) df["busca-exaustiva-simples"] = pd.Series(tempos) df["busca-exaustiva-branchnbound"] = pd.Series(tempos_1) df
https://github.com/quantum-tokyo/qiskit-handson
quantum-tokyo
# Qiskitライブラリーを導入 from qiskit import * # 数値計算モジュールを導入 import numpy as np # 描画のためのライブラリーを導入 import matplotlib.pyplot as plt %matplotlib inline # Qiskitバージョンの確認 qiskit.__qiskit_version__ q = QuantumCircuit(1,1) # 1量子ビット回路を用意 q.ry(np.pi/3,0) # y軸を中心にπ/3回転 q.draw(output="mpl") # 回路を描画 # 状態ベクトルシミュレーターの実行 vector_sim = Aer.get_backend('statevector_simulator') job = execute(q, vector_sim ) result = job.result().get_statevector(q, decimals=3) print(result) # ブロッホ球での表示 from qiskit.visualization import plot_bloch_multivector plot_bloch_multivector(result) q = QuantumCircuit(2,2) # 2量子ビット回路を用意 q.h(0) # Hゲートを0番目の量子ビットに操作します。 q.cx(0,1) # CNOTゲートを0番目を制御ビット、1番目を目標ビットとして操作します。 # 回路を測定 q.measure(0,0) q.measure(1,1) q.draw(output="mpl") # 回路を描画 # QASMシミュレーターで実験 simulator = Aer.get_backend('qasm_simulator') job = execute(q, backend=simulator, shots=1024) result = job.result() # 測定された回数を表示 counts = result.get_counts(q) print(counts) ## ヒストグラムで測定された確率をプロット from qiskit.visualization import * plot_histogram( counts )
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, 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. """BasicAer provider integration tests.""" import unittest from qiskit import BasicAer from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import execute from qiskit.result import Result from qiskit.providers.basicaer import BasicAerError from qiskit.test import QiskitTestCase class TestBasicAerIntegration(QiskitTestCase): """Qiskit BasicAer simulator integration tests.""" def setUp(self): super().setUp() qr = QuantumRegister(1) cr = ClassicalRegister(1) self._qc1 = QuantumCircuit(qr, cr, name="qc1") self._qc2 = QuantumCircuit(qr, cr, name="qc2") self._qc1.measure(qr[0], cr[0]) self.backend = BasicAer.get_backend("qasm_simulator") self._result1 = execute(self._qc1, self.backend).result() def test_builtin_simulator_result_fields(self): """Test components of a result from a local simulator.""" self.assertEqual("qasm_simulator", self._result1.backend_name) self.assertIsInstance(self._result1.job_id, str) self.assertEqual(self._result1.status, "COMPLETED") self.assertEqual(self._result1.results[0].status, "DONE") def test_basicaer_execute(self): """Test Compiler and run.""" qubit_reg = QuantumRegister(2, name="q") clbit_reg = ClassicalRegister(2, name="c") qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) job = execute(qc, self.backend) result = job.result() self.assertIsInstance(result, Result) def test_basicaer_execute_two(self): """Test Compiler and run.""" qubit_reg = QuantumRegister(2, name="q") clbit_reg = ClassicalRegister(2, name="c") qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) qc_extra = QuantumCircuit(qubit_reg, clbit_reg, name="extra") qc_extra.measure(qubit_reg, clbit_reg) job = execute([qc, qc_extra], self.backend) result = job.result() self.assertIsInstance(result, Result) def test_basicaer_num_qubits(self): """Test BasicAerError is raised if num_qubits too large to simulate.""" qc = QuantumCircuit(50, 1) qc.x(0) qc.measure(0, 0) with self.assertRaises(BasicAerError): execute(qc, self.backend) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/Pitt-JonesLab/slam_decomposition
Pitt-JonesLab
import logging logger = logging.getLogger() logger.setLevel(logging.INFO) import matplotlib.pyplot as plt import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.quantum_info import Operator from weylchamber import c1c2c3 from slam.basisv2 import CircuitTemplateV2 from slam.utils.gates.custom_gates import ConversionGainSmush1QPhaseGate from slam.utils.visualize import coordinate_2dlist_weyl, update_coordinate_2dlist_weyl class ParallelDrivenGateWidget: def __init__( self, N=10, gc=np.pi / 2, gg=0, gz1=0, gz2=0, phase_a=0, phase_b=0, phase_c=0, phase_g=0, ) -> None: self.N = N self.gc = gc self.gg = gg self.gz1 = gz1 self.gz2 = gz2 self.phase_a = phase_a self.phase_b = phase_b self.phase_c = phase_c self.phase_g = phase_g self.t = 0.1 self.timesteps = 1 self.duration_1q = self.t / self.timesteps self.construct_basis() self.prepare_parameters(0, 0) self.fig = None def __add__(self, other): if self.qc is None: self.construct_basis() if other.qc is None: other.construct_basis() # need to rename the parameters to avoid conflicts for p in self.qc.parameters: self.qc = self.qc.assign_parameters({p: Parameter(str(p) + "_")}) ret = ParallelDrivenGateWidget() ret.qc = self.qc.compose(other.qc) ret.N = self.N + other.N return ret def construct_basis(self): varg_offset = 0 # ConversionGainSmushGate def pp2(*vargs): return ConversionGainSmush1QPhaseGate( self.phase_a, self.phase_b, self.phase_c, self.phase_g, self.gc, self.gg, self.gz1, self.gz2, vargs[varg_offset : varg_offset + round(self.t / self.duration_1q)], vargs[varg_offset + round(self.t / self.duration_1q) :], t_el=self.t, ) self.basis = CircuitTemplateV2( n_qubits=2, base_gates=[pp2], edge_params=[[(0, 1)]], no_exterior_1q=True, param_vec_expand=[ varg_offset, round(self.t / self.duration_1q), round(self.t / self.duration_1q), ], ) self.basis.build(1) # basis.circuit.draw(output='mpl'); # repeat the atomic pd gate multiple times qc = QuantumCircuit(2) for _ in range(self.N): qc = qc.compose(self.basis.circuit) self.qc = qc def plot(self): self.fig = coordinate_2dlist_weyl(*self.coordinate_list) plt.show() def widget_wrap(self, q0, q1, pa, pb, pc, pg, gz1, gz2): self.gz1 = gz1 self.gz2 = gz2 self.phase_a = pa self.phase_b = pb self.phase_c = pc self.phase_g = pg self.construct_basis() self.prepare_parameters(q0, q1) self.iterate_time() if self.fig is not None: self.fig = update_coordinate_2dlist_weyl(self.fig, *self.coordinate_list) # self.fig.show() else: self.fig = coordinate_2dlist_weyl(*self.coordinate_list) plt.show() def widget_wrap_different_start(self, q0, q1): self.prepare_parameters(q0, q1) self.iterate_time_different_start(R=25) if self.fig is not None: self.fig = update_coordinate_2dlist_weyl(self.fig, *self.coordinate_list) # self.fig.show() else: self.fig = coordinate_2dlist_weyl(*self.coordinate_list) plt.show() def widget_wrap_nonuniform(self, g0_vector, g1_vector): self.prepare_parameters_nonuniform(g0_vector, g1_vector) self.iterate_time() if self.fig is not None: self.fig = update_coordinate_2dlist_weyl(self.fig, *self.coordinate_list) # self.fig.show() else: self.fig = coordinate_2dlist_weyl(*self.coordinate_list) plt.show() def prepare_parameters(self, q0, q1): i = 0 out = self.qc.copy() for instr, qargs, cargs in out: if instr.params and instr.name == "2QSmushGate": instr.params[4:6] = [q0, q1] instr.params[-1] = Parameter(f"t{i}") i += 1 elif instr.params and instr.name == "2QSmushGate1QPhase": instr.params[8:10] = [q0, q1] instr.params[-1] = Parameter(f"t{i}") i += 1 self.prep_qc = out def prepare_parameters_nonuniform(self, g0_vector, g1_vector): assert len(g0_vector) == len(g1_vector) == self.N i = 0 out = self.qc.copy() for instr, qargs, cargs in out: if instr.params and instr.name == "2QSmushGate": instr.params[4:6] = [g0_vector[i], g1_vector[i]] instr.params[-1] = Parameter(f"t{i}") i += 1 elif instr.params and instr.name == "2QSmushGate1QPhase": instr.params[8:10] = [g0_vector[i], g1_vector[i]] instr.params[-1] = Parameter(f"t{i}") i += 1 self.prep_qc = out def solve_end(self): # bind each time to full duration and evalute qc = QuantumCircuit(2) # copying the circuit manually this way moves t parameters into the parameterview object for gate in self.prep_qc: qc.append(gate[0], gate[1]) for i in range(self.N): qc = qc.bind_parameters({qc[i][0].params[-1]: self.duration_1q}) return Operator(qc).data def iterate_time(self, R=5): # R = 5 # resolution endpoints = range(1, self.N + 1) coordinate_list = [] end_segment_list = [] for end in endpoints: temp_coords = [] qc = QuantumCircuit(2) for gate in self.prep_qc[0:end]: qc.append(gate[0], gate[1]) qc2 = qc.copy() # for all prior 2Q gates, set time parameter to full length for i in [el for el in endpoints if el < end]: qc2 = qc2.bind_parameters({qc2[i - 1][0].params[-1]: self.duration_1q}) # for current 2Q gate, iterate over time and append coordinate for t in np.linspace(0, self.duration_1q, R): qc3 = qc2.bind_parameters({qc2[end - 1][0].params[-1]: t}) # eliminating x-axis symmetry c = list(c1c2c3(Operator(qc3).data)) if c[0] > 0.5: c[0] = -1 * c[0] + 1 temp_coords.append(c) coordinate_list.append(temp_coords) end_segment_list.append(c) self.coordinate_list = coordinate_list self.end_segment_list = end_segment_list self.final_unitary = Operator(qc3).data # qc2.draw(output='mpl'); def iterate_time_different_start(self, R=5): # R = 5 # resolution endpoints = range(1, self.N + 1) coordinate_list = [] end_segment_list = [] for end_iter, end in enumerate(endpoints): temp_coords = [] qc = QuantumCircuit(2) # for gate in self.prep_qc[0:end]: # qc.append(gate[0], gate[1]) qc.rzx(np.pi / 5 * end_iter, 0, 1) # append the self.prep_qc for gate in self.prep_qc[end_iter : end_iter + 1]: qc.append(gate[0], gate[1]) qc2 = qc.copy() # # for all prior 2Q gates, set time parameter to full length # for i in [el for el in endpoints if el < end]: # qc2 = qc2.bind_parameters({qc2[i-1][0].params[-1] : self.duration_1q}) # for current 2Q gate, iterate over time and append coordinate for t in np.linspace(0, self.duration_1q, R): qc3 = qc2.bind_parameters({qc2[1][0].params[-1]: t}) # eliminating x-axis symmetry c = list(c1c2c3(Operator(qc3).data)) if c[0] > 0.5: c[0] = -1 * c[0] + 1 temp_coords.append(c) coordinate_list.append(temp_coords) end_segment_list.append(c) self.coordinate_list = coordinate_list self.end_segment_list = end_segment_list self.final_unitary = Operator(qc3).data # qc2.draw(output='mpl'); class ImprovedCX(ParallelDrivenGateWidget): def __init__(self): super().__init__() self.prepare_parameters_nonuniform([3] * self.N, [0] * self.N) self.iterate_time() R = 5 # append 1Q at (0,0,0) and (0.5, 0 ,0) self.coordinate_list.append([[0, 0, 0]] * R) self.coordinate_list.append([(0.5, 0, 0)] * R) # want to plot comparing the nonoptimized version # spline between (0,0,0), (.25, .25, 0), (.5, 0, 0) baseline_coords = [] # interpolate endpoints inclusive i_steps = 25 # hardcoded but this is R * t/duration_1q baseline_coords.append( [ [0.25 / (i_steps - 1) * i, 0.25 / (i_steps - 1) * i, 0] for i in range(i_steps) ] ) # interpolate 5 points between (.25 .25 0) and (.5, 0, 0) baseline_coords.append( [ [0.25 + 0.25 / (i_steps - 1) * i, 0.25 - 0.25 / (i_steps - 1) * i, 0] for i in range(i_steps) ] ) baseline_coords.append([[0, 0, 0]] * R) baseline_coords.append([[0.25, 0.25, 0]] * R) baseline_coords.append([[0.5, 0, 0]] * R) self.baseline_coords = baseline_coords # self.fig = coordinate_2dlist_weyl(*baseline_coords, c='cyan', no_bar=1, fig=self.fig); # self.fig = coordinate_2dlist_weyl(*self.coordinate_list, c='red', no_bar=1); # plt.show() class ImprovedSWAP(ParallelDrivenGateWidget): def __init__(self): super().__init__() self.prepare_parameters_nonuniform([np.pi] * self.N, [np.pi] * self.N) self.iterate_time() R = 5 # tack on the final sqiswap, found from decomp_trajectory.ipynb # we tried to optimize this away but could not perfectly do so yet # start with the previous circuit all binded extended_qc = self.prep_qc.copy() # for gate in extended_qc: # gate[0].params[-1] = self.duration_1q # XXX ugly hardcoding because we are messing with parameters in an unsafe way # ie circuit parameter table is out of date for gate in range(self.N): extended_qc[gate][0].params[-1] = self.duration_1q # next build the remaining gates from qiskit.circuit.library import U3Gate extended_qc.append( U3Gate(7.84862563826406, 9.44285614361501, 2.30856826810552), [0] ) extended_qc.append( U3Gate(7.85928560541358, 9.44027709402712, -3.9923157086907), [0] ) for _ in np.linspace(0, R): c = list(c1c2c3(Operator(extended_qc).data)) if c[0] > 0.5: c[0] = -1 * c[0] + 1 self.coordinate_list.append(c) # for _ in range(self.N/2): # should be N=10, and N/2 # self.qc = self.qc.compose(self.basis.circuit) # now need to compute final part of trajectory # this is messy because in parent class, we assumed there were no interior 1Q gates # hardcode, lets just go back 6 timesteps from the end # finally # append 1Q at (0,0,0) and (0.5, 0.5 ,0.5) self.coordinate_list.append([[0, 0, 0]] * 5) self.coordinate_list.append([(0.5, 0.5, 0.5)] * 5) # self.coordinate_list = coordinate_list # self.end_segment_list = end_segment_list # self.final_unitary = Operator(qc3).data # self.fig = coordinate_2dlist_weyl(*self.coordinate_list); # plt.show()
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools import pickle # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # 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 = list(range(1,10)) + list(range(10, 101, 10)) st_qcs_list = [] for num_steps in trotter_steps: # Initialize quantum circuit for 3 qubits qr = QuantumRegister(7) qc = QuantumCircuit(qr) # 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([5]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Simulate time evolution under H_heis3 Hamiltonian for _ in range(num_steps): qc.append(Trot_gate, [qr[3], qr[5]]) qc.cx(qr[3], qr[1]) qc.cx(qr[5], qr[3]) # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time/num_steps}) 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, [qr[1], qr[3], qr[5]]) st_qcs_list.append(st_qcs) # Display circuit for confirmation # st_qcs[-1].decompose().draw() # view decomposition of trotter gates st_qcs_list[-1][-1].draw("mpl") # only view trotter gates from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # 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, initial_layout=[5,3,1]) print('Job ID', cal_job.job_id()) dt_now = datetime.datetime.now() print(dt_now) with open("jobs_jakarta_50step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_50step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) with open("jakarta_50step.pkl", "rb") as f: job_list = pickle.load(f) jobs = job_list["jobs"] cal_job = job_list["cal_job"] cal_results = cal_job.result() print("retrieved cal_results") meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = [] for i, job in enumerate(jobs): mit_results.append( meas_fitter.filter.apply(job.result()) ) print("retrieved", i, "th results") # 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/rodolfocarobene/SPVQE
rodolfocarobene
import logging import math from datetime import datetime import numpy as np from qiskit import IBMQ, Aer, QuantumCircuit from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B from qiskit.circuit import Parameter, QuantumRegister from qiskit.circuit.library import EfficientSU2, TwoLocal from qiskit.opflow.primitive_ops import PauliOp from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Pauli from qiskit.utils import QuantumInstance from qiskit_nature.algorithms import GroundStateEigensolver, VQEUCCFactory from qiskit_nature.circuit.library import UCCSD, HartreeFock from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.drivers import Molecule, UnitsType from qiskit_nature.drivers.second_quantization import PySCFDriver from qiskit_nature.drivers.second_quantization.electronic_structure_driver import ( MethodType, ) from qiskit_nature.mappers.second_quantization import BravyiKitaevMapper, ParityMapper from qiskit_nature.problems.second_quantization.electronic import ( ElectronicStructureProblem, ) from qiskit_nature.results import EigenstateResult, ElectronicStructureResult from qiskit_nature.runtime import VQEProgram from qiskit_nature.transformers.second_quantization.electronic import ( ActiveSpaceTransformer, FreezeCoreTransformer, ) def order_of_magnitude(number): if number == 0: return -100 return math.floor(math.log(number, 10)) def get_date_time_string(): now = datetime.now() return now.strftime("%d_%m_%H_%M") myLogger = logging.getLogger("myLogger") myLogger.setLevel(logging.DEBUG) ch = logging.FileHandler("./logs/" + get_date_time_string() + ".log") ch.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") ch.setFormatter(formatter) myLogger.addHandler(ch) def add_single_so4_gate(circuit, qubit1, qubit2, params, par0): myLogger.info("Inizio di add_single_so4_gate") circuit.s(qubit1) circuit.s(qubit2) circuit.h(qubit2) circuit.cx(qubit2, qubit1) circuit.u(params[par0], params[par0 + 1], params[par0 + 2], qubit1) par0 += 3 circuit.u(params[par0], params[par0 + 1], params[par0 + 2], qubit2) par0 += 3 circuit.cx(qubit2, qubit1) circuit.h(qubit2) circuit.sdg(qubit1) circuit.sdg(qubit2) myLogger.info("Fine di add_single_so4_gate") def construct_so4_ansatz(numqubits, init=None): myLogger.info("Inizio di construct_so4_ansatz") num_parameters = 6 * (numqubits - 1) so4_parameters = [] for i in range(num_parameters): name = "par" + str(i) new = Parameter(name) so4_parameters.append(new) quantum_reg = QuantumRegister(numqubits, name="q") if init is not None: circ = init else: circ = QuantumCircuit(quantum_reg) i = 0 j = 0 while i + 1 < numqubits: add_single_so4_gate(circ, i, i + 1, so4_parameters, 6 * j) j = j + 1 i = i + 2 i = 1 while i + 1 < numqubits: add_single_so4_gate(circ, i, i + 1, so4_parameters, 6 * j) j = j + 1 i = i + 2 myLogger.info("Fine di construct_so4_ansatz") return circ def create_lagrange_operator_ps(hamiltonian, auxiliary, multiplier, operator, value): myLogger.info("Inizio di create_lagrange_operator_ps") if operator == "number": idx = 0 elif operator == "spin-squared": idx = 1 elif operator == "spin-z": idx = 2 list_x_zeros = np.zeros(hamiltonian.num_qubits) list_z_zeros = np.zeros(hamiltonian.num_qubits) equality = auxiliary[idx].add(PauliOp(Pauli((list_z_zeros, list_x_zeros)), -value)) penalty_squared = (equality**2).mul(multiplier) lagrangian = hamiltonian.add(penalty_squared) myLogger.info("Fine di create_lagrange_operator_ps") return lagrangian def create_lagrange_operator_aug(hamiltonian, auxiliary, multiplier_simple, multiplier_square, operator, value): myLogger.info("Inizio di create_lagrange_operator_aug") if operator == "number": idx = 0 elif operator == "spin-squared": idx = 1 elif operator == "spin-z": idx = 2 list_x_zeros = np.zeros(hamiltonian.num_qubits) list_z_zeros = np.zeros(hamiltonian.num_qubits) equality = auxiliary[idx].add(PauliOp(Pauli((list_z_zeros, list_x_zeros)), -value)) penalty_squared = (equality**2).mul(multiplier_square) penalty_simple = equality.mul(-multiplier_simple) lagrangian = hamiltonian.add(penalty_squared).add(penalty_simple) myLogger.info("Fine di create_lagrange_operator_aug") return lagrangian def get_transformers_from_mol_type(mol_type): transf_list = [] if mol_type == "LiH": # transf_list.append(FreezeCoreTransformer(True)) #, [2, 3, 4])) transf_list.append(ActiveSpaceTransformer(num_electrons=2, num_molecular_orbitals=3)) if mol_type == "H2O": transf_list.append(ActiveSpaceTransformer(num_electrons=4, num_molecular_orbitals=3)) if mol_type == "C2H4": transf_list.append(ActiveSpaceTransformer(num_electrons=2, num_molecular_orbitals=2)) if mol_type == "N2": transf_list.append(ActiveSpaceTransformer(num_electrons=6, num_molecular_orbitals=3)) if mol_type == "Li3+": transf_list.append(ActiveSpaceTransformer(num_electrons=2, num_molecular_orbitals=3)) if mol_type == "Na-": transf_list.append(FreezeCoreTransformer(True)) return transf_list def from_geometry_to_atoms(geometry): tot_atoms = [] atoms_geom = geometry.split(";") for single_atom_geom in atoms_geom: atom = single_atom_geom.split()[0] tot_atoms.append(atom) return tot_atoms def get_num_particles(mol_type, particle_number): alpha, beta = particle_number.num_alpha, particle_number.num_beta num_spin_orbitals = particle_number.num_spin_orbitals if mol_type == "LiH": a_b_spinorbs = 1, 1, 6 # 10#4 if mol_type == "Li3+": a_b_spinorbs = 1, 1, 6 # 10#4 elif mol_type == "H2O": a_b_spinorbs = 2, 2, 6 elif mol_type == "C2H4": a_b_spinorbs = 1, 1, 4 elif mol_type == "N2": a_b_spinorbs = 3, 3, 6 else: a_b_spinorbs = alpha, beta, num_spin_orbitals return a_b_spinorbs def prepare_base_vqe(options): myLogger.info("Inizio di prepare_base_vqe") spin = options["molecule"]["spin"] charge = options["molecule"]["charge"] basis = options["molecule"]["basis"] geometry = options["molecule"]["geometry"] var_form_type = options["var_form_type"] quantum_instance = options["quantum_instance"] optimizer = options["optimizer"] converter = options["converter"] init_point = options["init_point"] driver = PySCFDriver( atom=geometry, unit=UnitsType.ANGSTROM, basis=basis, spin=spin, charge=charge, method=MethodType.RHF ) transformers = get_transformers_from_mol_type(options["molecule"]["molecule"]) problem = ElectronicStructureProblem(driver, transformers) main_op = problem.second_q_ops()[0] driver_result = driver.run() particle_number = driver_result.get_property("ParticleNumber") alpha, beta, num_spin_orbitals = get_num_particles(options["molecule"]["molecule"], particle_number) num_particles = (alpha, beta) myLogger.info("alpha %d", alpha) myLogger.info("beta %d", beta) myLogger.info("spin-orb %d", num_spin_orbitals) qubit_op = converter.convert(main_op, num_particles=num_particles) init_state = HartreeFock(num_spin_orbitals, num_particles, converter) num_qubits = qubit_op.num_qubits myLogger.info("num qubit qubitop : %d", qubit_op.num_qubits) if init_state.num_qubits != num_qubits: myLogger.info("num qubit initsta: %d", init_state.num_qubits) init_state = None vqe_solver = create_vqe_from_ansatz_type( var_form_type, num_qubits, init_state, quantum_instance, optimizer, converter, num_particles, num_spin_orbitals, init_point, ) myLogger.info("Fine di prepare_base_vqe") return converter, vqe_solver, problem, qubit_op def store_intermediate_result(count, par, energy, std): global PARAMETERS PARAMETERS.append(par) log_string = str(count) + " " + str(energy) + " " + str(std) myLogger.info(log_string) def from_energy_pars_to_log_msg(pars, energy): message = "" for par in pars: message += str(par).strip() message += "," message = message[:-1] message += " ; " message += str(energy) message += "\n" return message def get_ansatz(var_form_type, num_qubits, init_state=None): if var_form_type == "TwoLocal": ansatz = TwoLocal( num_qubits=num_qubits, rotation_blocks="ry", entanglement_blocks="cx", initial_state=init_state, entanglement="linear", ) elif var_form_type == "EfficientSU(2)": ansatz = EfficientSU2( num_qubits=num_qubits, entanglement="linear", reps=1, skip_final_rotation_layer=True, initial_state=init_state, ) else: print("Ansatz non ancora implementato in get_ansatz()") return ansatz def create_vqe_from_ansatz_type( var_form_type, num_qubits, init_state, quantum_instance, optimizer, converter, num_particles, num_spin_orbitals, initial_point, ): myLogger.info("Inizio create_vqe_from_ansatz_type") if var_form_type in ("TwoLocal", "EfficientSU(2)"): ansatz = get_ansatz(var_form_type, num_qubits, init_state) if None in initial_point: initial_point = np.random.rand(ansatz.num_parameters) vqe_solver = VQE( ansatz=ansatz, optimizer=optimizer, initial_point=initial_point, callback=store_intermediate_result, quantum_instance=quantum_instance, ) elif var_form_type == "UCCSD": ansatz = UCCSD( qubit_converter=converter, initial_state=init_state, num_particles=num_particles, num_spin_orbitals=num_spin_orbitals, ) if None in initial_point: initial_point = np.random.rand(8) # MUST BE SET HERE vqe_solver = VQE( quantum_instance=quantum_instance, ansatz=ansatz._build(), optimizer=optimizer, callback=store_intermediate_result, initial_point=initial_point, ) elif var_form_type == "SO(4)": ansatz = construct_so4_ansatz(num_qubits, init=init_state) if None in initial_point: initial_point = np.random.rand(6 * (num_qubits - 1)) vqe_solver = VQE( ansatz=ansatz, optimizer=optimizer, initial_point=initial_point, callback=store_intermediate_result, quantum_instance=quantum_instance, ) else: raise Exception("VAR_FORM_TYPE NOT EXISTS") myLogger.info("Fine create_vqe_from_ansatz_type") return vqe_solver def solve_hamiltonian_vqe(options): myLogger.info("Inizio solve_hamiltonian_vqe") myLogger.info("OPTIONS") myLogger.info(options) converter, vqe_solver, problem, qubit_op = prepare_base_vqe(options) calc = GroundStateEigensolver(converter, vqe_solver) result = calc.solve(problem) myLogger.info("Fine solve_hamiltonian_vqe") myLogger.info(PARAMETERS[len(PARAMETERS) - 1]) myLogger.info("RESULT") myLogger.info(result) return result def get_runtime_vqe_program(options, num_qubits): # IBMQ.load_account() provider = IBMQ.get_provider(hub="ibm-q-research-2", group="uni-milano-bicoc-1", project="main") backend_list = [] backend_list.append(provider.get_backend("ibm_perth")) backend_list.append(provider.get_backend("ibm_lagos")) backend_list.append(provider.get_backend("ibmq_casablanca")) backend_list.append(provider.get_backend("ibmq_bogota")) backend_list.append(provider.get_backend("ibmq_manila")) quantum_instance = least_busy(backend_list) print("Run su backend: ", quantum_instance.backend_name) ansatz = get_ansatz(options["var_form_type"], num_qubits) init_point = options["init_point"] if None in init_point: init_point = np.random.rand(ansatz.num_parameters) global LAST_OPTIMIZER_OPT if LAST_OPTIMIZER_OPT is not None: options["optimizer"].set_options(LAST_OPTIMIZER_OPT) vqe_program = VQEProgram( ansatz=ansatz, optimizer=options["optimizer"], initial_point=init_point, provider=provider, backend=quantum_instance, shots=options["shots"], callback=store_intermediate_result, store_intermediate=True, ) return vqe_program def solve_lagrangian_vqe(options): myLogger.info("Inizio solve_lagrangian_vqe") myLogger.info("OPTIONS") myLogger.info(options) converter, vqe_solver, problem, qubit_op = prepare_base_vqe(options) if options["hardware"] is True: vqe_solver = get_runtime_vqe_program(options, qubit_op.num_qubits) aux_ops_not_converted = problem.second_q_ops()[1:4] aux_ops = convert_list_op_ferm_to_qubit(aux_ops_not_converted, converter, problem.num_particles) lagrange_op = qubit_op for operatore in options["lagrange"]["operators"]: operator = operatore[0] value = operatore[1] multiplier = operatore[2] lagrange_op = create_lagrange_operator_ps( lagrange_op, aux_ops, multiplier=multiplier, operator=operator, value=value ) old_result = vqe_solver.compute_minimum_eigenvalue(operator=lagrange_op, aux_operators=aux_ops) global PARAMETERS if options["hardware"] is True: for elem in old_result.optimizer_history["params"]: PARAMETERS.append(list(elem)) myLogger.info("OLDRESULT:") myLogger.info(old_result) new_result = problem.interpret(old_result) myLogger.info("Fine solve_lagrangian_vqe") myLogger.info("RESULT") myLogger.info(new_result) if options["hardware"] is True: LAST_OPTIMIZER_OPT = options["optimizer"].setting myLogger.info("OPTIMIZER SETTINGS:") myLogger.info(options["optimizer"].setting) return new_result def solve_aug_lagrangian_vqe(options, lamb): myLogger.info("Inizio solve_aug_lagrangian_vqe") myLogger.info("OPTIONS") myLogger.info(options) converter, vqe_solver, problem, qubit_op = prepare_base_vqe(options) if options["var_form_type"] == "UCCSD": vqe_solver = vqe_solver.get_solver(problem, converter) aux_ops_not_converted = problem.second_q_ops()[1:4] aux_ops = convert_list_op_ferm_to_qubit(aux_ops_not_converted, converter, problem.num_particles) lagrange_op = qubit_op for operatore in options["lagrange"]["operators"]: operator = operatore[0] value = operatore[1] multiplier = operatore[2] lagrange_op = create_lagrange_operator_aug( lagrange_op, aux_ops, multiplier_square=multiplier, multiplier_simple=lamb, operator=operator, value=value ) old_result = vqe_solver.compute_minimum_eigenvalue(operator=lagrange_op, aux_operators=aux_ops) myLogger.info("OLDRESULT:") myLogger.info(old_result) new_result = problem.interpret(old_result) myLogger.info("Fine solve_aug_lagrangian_vqe") myLogger.info("RESULT") myLogger.info(new_result) return new_result def convert_list_op_ferm_to_qubit(old_aux_ops, converter, num_particles): myLogger.info("Inizio convert_list_op_ferm_to_qubit") new_aux_ops = [] for old_aux_op in old_aux_ops: op_new = converter.convert(old_aux_op, num_particles) new_aux_ops.append(op_new) myLogger.info("Fine convert_list_op_ferm_to_qubit") return new_aux_ops def find_best_result(partial_results): penal_min = 100 optimal_par = [] tmp_result = ElectronicStructureResult() tmp_result.nuclear_repulsion_energy = 50 tmp_result.computed_energies = np.array([0]) tmp_result.extracted_transformer_energies = {"dummy": 0} for result, penalty, par in partial_results: myLogger.info("currE: %s", str(tmp_result.total_energies[0])) myLogger.info("GUARDO: %s", str(penalty)) myLogger.info("CONFRONTO: %s", str(penal_min)) if abs(order_of_magnitude(penalty) - order_of_magnitude(penal_min)) == 0: if tmp_result.total_energies[0] > result.total_energies[0]: tmp_result = result penal_min = penalty optimal_par = par elif penalty < penal_min: tmp_result = result penal_min = penalty optimal_par = par myLogger.info("newE: %s", str(tmp_result.total_energies[0])) return tmp_result, optimal_par def calc_penalty(lag_op_list, result, threshold, tmp_mult): penalty = 0 accectable_result = True for operatore in lag_op_list: if operatore[0] == "number": penalty += tmp_mult * ((result.num_particles[0] - operatore[1]) ** 2) myLogger.info("penalty at number: %s", str(penalty)) if abs(result.num_particles[0] - operatore[1]) > threshold: accectable_result = False if operatore[0] == "spin-squared": penalty += tmp_mult * ((result.total_angular_momentum[0] - operatore[1]) ** 2) myLogger.info("penalty at spin2: %s", str(penalty)) if abs(result.total_angular_momentum[0] - operatore[1]) > threshold: accectable_result = False if operatore[0] == "spin-z": penalty += tmp_mult * ((result.magnetization[0] - operatore[1]) ** 2) myLogger.info("penalty at spinz: %s", str(penalty)) if abs(result.magnetization[0] - operatore[1]) > threshold: accectable_result = False return penalty, accectable_result def solve_lag_series_vqe(options): iter_max = options["series"]["itermax"] step = options["series"]["step"] if "init_point" not in options: par = np.random.rand(get_num_par(options["var_form_type"], options["molecule"]["molecule"])) else: par = options["init_point"] mult = 0.01 threshold = 0.6 global PARAMETERS PARAMETERS = [par] partial_results = [] for i in range(iter_max): tmp_mult = mult + step * i lag_op_list = [] for single_op in options["lagrange"]["operators"]: operatore = (single_op[0], single_op[1], float(tmp_mult)) lag_op_list.append(operatore) options["lagrange"]["operators"] = lag_op_list options["init_point"] = par result = solve_lagrangian_vqe(options) if options["hardware"] is not True: par = PARAMETERS[len(PARAMETERS) - 1] penalty, accectable_result = calc_penalty(lag_op_list, result, threshold, tmp_mult) log_str = "Iter " + str(i) log_str += " mult " + str(np.round(tmp_mult, 2)) log_str += "\tE = " + str(np.round(result.total_energies[0], 7)) log_str += "\tP = " + str(penalty) log_str += "\tE-P = " + str(np.round(result.total_energies[0] - penalty, 7)) myLogger.info(log_str) if accectable_result: partial_results.append((result, penalty / tmp_mult, par)) if accectable_result and penalty / tmp_mult < 1e-8 and i > 4: break if not accectable_result and i == iter_max - 1: partial_results.append((result, penalty / tmp_mult, par)) result, optimal_par = find_best_result(partial_results) result = dummy_vqe(options, optimal_par) return result def dummy_vqe(options, optimal_par): myLogger.info("inizio dummy_vqe") options["optimizer"] = COBYLA(maxiter=0) options["init_point"] = optimal_par new_result = solve_hamiltonian_vqe(options) myLogger.info("fine dummy_vqe") return new_result def get_num_par(varform, mol_type): num_pars = 0 if mol_type == "H3+": if varform == "TwoLocal": num_pars = 16 elif varform == "SO(4)": num_pars = 18 elif varform == "UCCSD": num_pars = 16 elif varform == "EfficientSU(2)": num_pars = 8 elif mol_type == "Na-": if varform == "TwoLocal": num_pars = 24 else: raise Exception("varform not yet implemented for this mol") elif "H2O" in mol_type: if varform == "TwoLocal": num_pars = 16 elif varform == "EfficientSU(2)": num_pars = 8 elif varform == "SO(4)": num_pars = 30 elif varform == "UCCSD": num_pars = 24 else: raise Exception("varform not yet implemented for this mol") elif mol_type == "C2H4": if varform == "TwoLocal": num_pars = 8 else: raise Exception("varform not yet implemented for this mol") elif "H2" in mol_type: if varform == "TwoLocal": num_pars = 8 elif varform == "SO(4)": num_pars = 6 elif varform == "UCCSD": num_pars = 8 elif varform == "EfficientSU(2)": num_pars = 4 elif "H4" in mol_type: if varform == "TwoLocal": num_pars = 24 elif varform == "SO(4)": num_pars = 30 elif varform == "UCCSD": num_pars = 24 elif varform == "EfficientSU(2)": num_pars = 48 elif "Li2" in mol_type: if varform == "TwoLocal": num_pars = 72 else: raise Exception("varform not yet implemented for this mol") elif "LiH" == mol_type: if varform == "TwoLocal": num_pars = 16 elif varform == "EfficientSU(2)": num_pars = 8 else: raise Exception("varform not yet implemented for this mol") else: raise Exception("mol_type not totally implemented") return num_pars def solve_lag_aug_series_vqe(options): iter_max = options["series"]["itermax"] if "init_point" not in options: par = np.random.rand(get_num_par(options["var_form_type"], options["molecule"]["molecule"])) else: par = options["init_point"] mult = 0.01 step = options["series"]["step"] lamb = options["series"]["lamb"] global PARAMETERS PARAMETERS = [par] for i in range(iter_max): tmp_mult = mult + step * i lag_op_list = [] for single_op in options["lagrange"]["operators"]: operatore = (single_op[0], single_op[1], float(tmp_mult)) lag_op_list.append(operatore) options["lagrange"]["operators"] = lag_op_list options["init_point"] = par result = solve_aug_lagrangian_vqe(options, lamb) penalty = tmp_mult * ((result.num_particles[0] - operatore[1]) ** 2) penalty -= lamb * (result.num_particles[0] - operatore[1]) log_str = "Iter " + str(i) log_str += " mult " + str(np.round(tmp_mult, 2)) log_str += " lamb " + str(lamb) log_str += "\tE = " + str(np.round(result.total_energies[0], 7)) log_str += "\tE-P = " + str(np.round(result.total_energies[0] - penalty, 7)) myLogger.info(log_str) par = PARAMETERS[len(PARAMETERS) - 1] for operatore in lag_op_list: if operatore[0] == "number": lamb = lamb - tmp_mult * 2 * (result.num_particles[0] - operatore[1]) if operatore[0] == "spin-squared": lamb = lamb - tmp_mult * 2 * (result.total_angular_momentum[0] - operatore[1]) if operatore[0] == "spin-z": lamb = lamb - tmp_mult * 2 * (result.magnetization[0] - operatore[1]) # print(result.total_energies[0] - penalty, " ", penalty) return result def solve_VQE(options): global PARAMETERS PARAMETERS = [] global LAST_OPTIMIZER_OPT LAST_OPTIMIZER_OPT = None if not options["lagrange"]["active"]: vqe_result = solve_hamiltonian_vqe(options) elif not options["lagrange"]["series"]: lag_result = solve_lagrangian_vqe(options) optimal_par = PARAMETERS[len(PARAMETERS) - 1] vqe_result = dummy_vqe(options, optimal_par) else: if options["lagrange"]["augmented"]: vqe_result = solve_lag_aug_series_vqe(options) else: vqe_result = solve_lag_series_vqe(options) return vqe_result, PARAMETERS[len(PARAMETERS) - 1]
https://github.com/Anastasia-Sim/PoW-QCSA-fa22
Anastasia-Sim
!pip install qiskit matplotlib import qiskit import matplotlib from qiskit import QuantumCircuit, assemble, Aer, circuit, QuantumRegister, ClassicalRegister, transpile from qiskit.visualization import plot_histogram from qiskit.quantum_info.operators import Operator def hash_operator(): hash_gate = Operator([ [0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0], [0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0], [0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0], [0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] ]) hash_gate.name = "Hash Gate" return hash_gate def dehash_operator(): hash_dagger = hash_operator().conjugate().transpose() hash_dagger.name = "Hash Dagger" return hash_dagger def oracle(): qreg_q = QuantumRegister(4, 'q') oracle = QuantumCircuit(qreg_q, name='oracle') oracle.x(qreg_q[2:4]) oracle.cz(qreg_q[2], qreg_q[3]) oracle.x(qreg_q[2:4]) oracle_op = oracle.to_gate() oracle_op.name = 'oracle' return oracle oracle().draw() # diffuser from https://qiskit.org/textbook/ch-algorithms/grover.html def diffuser(nqubits): qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> (H-gates) for qubit in range(nqubits): qc.h(qubit) # Apply transformation |00..0> -> |11..1> (X-gates) for qubit in range(nqubits): qc.x(qubit) # Do multi-controlled-Z gate qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) # Apply transformation |11..1> -> |00..0> for qubit in range(nqubits): qc.x(qubit) # Apply transformation |00..0> -> |s> for qubit in range(nqubits): qc.h(qubit) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "diffusor" return U_s n_qubits = 4 controls = QuantumRegister(n_qubits) circuit = QuantumCircuit(controls) circuit.append(hash_operator(), [0, 1, 2, 3]) circuit.append(oracle(), [0, 1, 2, 3]) circuit.append(dehash_operator(), [0, 1, 2, 3]) circuit.append(diffuser(n_qubits), [0, 1, 2, 3]) #circuit.measure_all() circuit.draw() n_qubits = 4 controls = QuantumRegister(n_qubits) circuit = QuantumCircuit(controls) #Create uniform superposition of possible inputs circuit.h([0,1,2,3]) #Run Grover's 2^(4/2) times circuit.append(hash_operator(), [0, 1, 2, 3]) circuit.append(oracle(), [0, 1, 2, 3]) circuit.append(dehash_operator(), [0, 1, 2, 3]) circuit.append(diffuser(n_qubits), [0, 1, 2, 3]) circuit.append(hash_operator(), [0, 1, 2, 3]) circuit.append(oracle(), [0, 1, 2, 3]) circuit.append(dehash_operator(), [0, 1, 2, 3]) circuit.append(diffuser(n_qubits), [0, 1, 2, 3]) circuit.append(hash_operator(), [0, 1, 2, 3]) circuit.append(oracle(), [0, 1, 2, 3]) circuit.append(dehash_operator(), [0, 1, 2, 3]) circuit.append(diffuser(n_qubits), [0, 1, 2, 3]) circuit.append(hash_operator(), [0, 1, 2, 3]) circuit.append(oracle(), [0, 1, 2, 3]) circuit.append(dehash_operator(), [0, 1, 2, 3]) circuit.append(diffuser(n_qubits), [0, 1, 2, 3]) circuit.measure_all() circuit.draw() sim = Aer.get_backend('aer_simulator') # We run the simulator with sim.run(QUANTUM CIRCUIT), # And we get the resulting values with .result() transpiled_grover_circuit = transpile(circuit, sim) qobj = assemble(transpiled_grover_circuit) result = sim.run(qobj).result() # We then collect the results using .get_counts() counts = result.get_counts() # Visualization plot_histogram(counts)
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/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)) ghz.draw(output='mpl')
https://github.com/qiskit-community/qiskit-pocket-guide
qiskit-community
from qiskit.opflow import Zero, One state = One ^ Zero ^ One ^ Zero ^ Zero print(state) from qiskit.opflow import X, Z pauli_piXZ = -(X ^ Z) print(pauli_piXZ) print(pauli_piXZ.to_matrix()) from qiskit.opflow import I, X, H, CX op = (CX ^ I) @ (I ^ CX) @ (I ^ I ^ H) print(op) from qiskit.quantum_info import Statevector qc = op.to_circuit() sv = Statevector(qc) print(sv.sample_counts(1000))
https://github.com/matheusmtta/Quantum-Computing
matheusmtta
#initialization import matplotlib.pyplot as plt import numpy as np import math # importing Qiskit from qiskit import IBMQ, Aer, transpile, assemble from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister # import basic plot tools from qiskit.visualization import plot_histogram qpe = QuantumCircuit(4, 3) qpe.x(3) #Apply Hadamard gate for qubit in range(3): qpe.h(qubit) qpe.draw() repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): qpe.cp(math.pi/4, counting_qubit, 3); # This is CU # we use 2*pi*(1/theta) repetitions *= 2 qpe.draw() def qft_dagger(qc, n): """n-qubit QFTdagger the first n qubits in circ""" # Don't forget the Swaps! for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-math.pi/float(2**(j-m)), m, j) qc.h(j) qpe.barrier() # Apply inverse QFT qft_dagger(qpe, 3) # Measure qpe.barrier() for n in range(3): qpe.measure(n,n) qpe.draw() aer_sim = Aer.get_backend('aer_simulator') shots = 2048 t_qpe = transpile(qpe, aer_sim) qobj = assemble(t_qpe, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) # Create and set up circuit qpe2 = QuantumCircuit(4, 3) # Apply H-Gates to counting qubits: for qubit in range(3): qpe2.h(qubit) # Prepare our eigenstate |psi>: qpe2.x(3) # Do the controlled-U operations: angle = 2*math.pi/3 repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): qpe2.cp(angle, counting_qubit, 3); repetitions *= 2 # Do the inverse QFT: qft_dagger(qpe2, 3) # Measure of course! for n in range(3): qpe2.measure(n,n) qpe2.draw() # Let's see the results! aer_sim = Aer.get_backend('aer_simulator') shots = 4096 t_qpe2 = transpile(qpe2, aer_sim) qobj = assemble(t_qpe2, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) # Create and set up circuit qpe3 = QuantumCircuit(6, 5) # Apply H-Gates to counting qubits: for qubit in range(5): qpe3.h(qubit) # Prepare our eigenstate |psi>: qpe3.x(5) # Do the controlled-U operations: angle = 2*math.pi/3 repetitions = 1 for counting_qubit in range(5): for i in range(repetitions): qpe3.cp(angle, counting_qubit, 5); repetitions *= 2 # Do the inverse QFT: qft_dagger(qpe3, 5) # Measure of course! qpe3.barrier() for n in range(5): qpe3.measure(n,n) qpe3.draw() # Let's see the results! aer_sim = Aer.get_backend('aer_simulator') shots = 4096 t_qpe3 = transpile(qpe3, aer_sim) qobj = assemble(t_qpe3, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
mcoggins96
# 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. """Multiple-Control, Multiple-Target Gate.""" from __future__ import annotations from collections.abc import Callable from qiskit import circuit from qiskit.circuit import ControlledGate, Gate, Qubit, QuantumRegister, QuantumCircuit from qiskit.exceptions import QiskitError from ..standard_gates import XGate, YGate, ZGate, HGate, TGate, TdgGate, SGate, SdgGate class MCMT(QuantumCircuit): """The multi-controlled multi-target gate, for an arbitrary singly controlled target gate. For example, the H gate controlled on 3 qubits and acting on 2 target qubit is represented as: .. parsed-literal:: ───■──── │ ───■──── │ ───■──── ┌──┴───┐ ┤0 ├ │ 2-H │ ┤1 ├ └──────┘ This default implementations requires no ancilla qubits, by broadcasting the target gate to the number of target qubits and using Qiskit's generic control routine to control the broadcasted target on the control qubits. If ancilla qubits are available, a more efficient variant using the so-called V-chain decomposition can be used. This is implemented in :class:`~qiskit.circuit.library.MCMTVChain`. """ def __init__( self, gate: Gate | Callable[[QuantumCircuit, Qubit, Qubit], circuit.Instruction], num_ctrl_qubits: int, num_target_qubits: int, ) -> None: """Create a new multi-control multi-target gate. Args: gate: The gate to be applied controlled on the control qubits and applied to the target qubits. Can be either a Gate or a circuit method. If it is a callable, it will be casted to a Gate. num_ctrl_qubits: The number of control qubits. num_target_qubits: The number of target qubits. Raises: AttributeError: If the gate cannot be casted to a controlled gate. AttributeError: If the number of controls or targets is 0. """ if num_ctrl_qubits == 0 or num_target_qubits == 0: raise AttributeError("Need at least one control and one target qubit.") # set the internal properties and determine the number of qubits self.gate = self._identify_gate(gate) self.num_ctrl_qubits = num_ctrl_qubits self.num_target_qubits = num_target_qubits num_qubits = num_ctrl_qubits + num_target_qubits + self.num_ancilla_qubits # initialize the circuit object super().__init__(num_qubits, name="mcmt") self._label = f"{num_target_qubits}-{self.gate.name.capitalize()}" # build the circuit self._build() def _build(self): """Define the MCMT gate without ancillas.""" if self.num_target_qubits == 1: # no broadcasting needed (makes for better circuit diagrams) broadcasted_gate = self.gate else: broadcasted = QuantumCircuit(self.num_target_qubits, name=self._label) for target in list(range(self.num_target_qubits)): broadcasted.append(self.gate, [target], []) broadcasted_gate = broadcasted.to_gate() mcmt_gate = broadcasted_gate.control(self.num_ctrl_qubits) self.append(mcmt_gate, self.qubits, []) @property def num_ancilla_qubits(self): """Return the number of ancillas.""" return 0 def _identify_gate(self, gate): """Case the gate input to a gate.""" valid_gates = { "ch": HGate(), "cx": XGate(), "cy": YGate(), "cz": ZGate(), "h": HGate(), "s": SGate(), "sdg": SdgGate(), "x": XGate(), "y": YGate(), "z": ZGate(), "t": TGate(), "tdg": TdgGate(), } if isinstance(gate, ControlledGate): base_gate = gate.base_gate elif isinstance(gate, Gate): if gate.num_qubits != 1: raise AttributeError("Base gate must act on one qubit only.") base_gate = gate elif isinstance(gate, QuantumCircuit): if gate.num_qubits != 1: raise AttributeError( "The circuit you specified as control gate can only have one qubit!" ) base_gate = gate.to_gate() # raises error if circuit contains non-unitary instructions else: if callable(gate): # identify via name of the passed function name = gate.__name__ elif isinstance(gate, str): name = gate else: raise AttributeError(f"Invalid gate specified: {gate}") base_gate = valid_gates[name] return base_gate def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return the controlled version of the MCMT circuit.""" if ctrl_state is None: # TODO add ctrl state implementation by adding X gates return MCMT(self.gate, self.num_ctrl_qubits + num_ctrl_qubits, self.num_target_qubits) return super().control(num_ctrl_qubits, label, ctrl_state) def inverse(self): """Return the inverse MCMT circuit, which is itself.""" return MCMT(self.gate, self.num_ctrl_qubits, self.num_target_qubits) class MCMTVChain(MCMT): """The MCMT implementation using the CCX V-chain. This implementation requires ancillas but is decomposed into a much shallower circuit than the default implementation in :class:`~qiskit.circuit.library.MCMT`. **Expanded Circuit:** .. plot:: from qiskit.circuit.library import MCMTVChain, ZGate from qiskit.tools.jupyter.library import _generate_circuit_library_visualization circuit = MCMTVChain(ZGate(), 2, 2) _generate_circuit_library_visualization(circuit.decompose()) **Examples:** >>> from qiskit.circuit.library import HGate >>> MCMTVChain(HGate(), 3, 2).draw() q_0: ──■────────────────────────■── │ │ q_1: ──■────────────────────────■── │ │ q_2: ──┼────■──────────────■────┼── │ │ ┌───┐ │ │ q_3: ──┼────┼──┤ H ├───────┼────┼── │ │ └─┬─┘┌───┐ │ │ q_4: ──┼────┼────┼──┤ H ├──┼────┼── ┌─┴─┐ │ │ └─┬─┘ │ ┌─┴─┐ q_5: ┤ X ├──■────┼────┼────■──┤ X ├ └───┘┌─┴─┐ │ │ ┌─┴─┐└───┘ q_6: ─────┤ X ├──■────■──┤ X ├───── └───┘ └───┘ """ def _build(self): """Define the MCMT gate.""" control_qubits = self.qubits[: self.num_ctrl_qubits] target_qubits = self.qubits[ self.num_ctrl_qubits : self.num_ctrl_qubits + self.num_target_qubits ] ancilla_qubits = self.qubits[self.num_ctrl_qubits + self.num_target_qubits :] if len(ancilla_qubits) > 0: master_control = ancilla_qubits[-1] else: master_control = control_qubits[0] self._ccx_v_chain_rule(control_qubits, ancilla_qubits, reverse=False) for qubit in target_qubits: self.append(self.gate.control(), [master_control, qubit], []) self._ccx_v_chain_rule(control_qubits, ancilla_qubits, reverse=True) @property def num_ancilla_qubits(self): """Return the number of ancilla qubits required.""" return max(0, self.num_ctrl_qubits - 1) def _ccx_v_chain_rule( self, control_qubits: QuantumRegister | list[Qubit], ancilla_qubits: QuantumRegister | list[Qubit], reverse: bool = False, ) -> None: """Get the rule for the CCX V-chain. The CCX V-chain progressively computes the CCX of the control qubits and puts the final result in the last ancillary qubit. Args: control_qubits: The control qubits. ancilla_qubits: The ancilla qubits. reverse: If True, compute the chain down to the qubit. If False, compute upwards. Returns: The rule for the (reversed) CCX V-chain. Raises: QiskitError: If an insufficient number of ancilla qubits was provided. """ if len(ancilla_qubits) == 0: return if len(ancilla_qubits) < len(control_qubits) - 1: raise QiskitError("Insufficient number of ancilla qubits.") iterations = list(enumerate(range(2, len(control_qubits)))) if not reverse: self.ccx(control_qubits[0], control_qubits[1], ancilla_qubits[0]) for i, j in iterations: self.ccx(control_qubits[j], ancilla_qubits[i], ancilla_qubits[i + 1]) else: for i, j in reversed(iterations): self.ccx(control_qubits[j], ancilla_qubits[i], ancilla_qubits[i + 1]) self.ccx(control_qubits[0], control_qubits[1], ancilla_qubits[0]) def inverse(self): return MCMTVChain(self.gate, self.num_ctrl_qubits, self.num_target_qubits)
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
%run init.ipynb X = Matrix([[0,1],[1,0]]); Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]]); I = Matrix([[1,0],[0,1]]) x,y,z=symbols('x y z'); rho = (1/2)*(x*X+y*Y+z*Z+I); rho rho.eigenvals() from qiskit.visualization import plot_bloch_vector plot_bloch_vector([[0.5,0.5,0.3]]) # Exemplo de representacao de vários estados na esfera de Bloch points = [] r = 0.1; M = 3; dr = 1/M for k in range(0, M): r += dr th = math.pi/2; ph = 0+k*0.01; N = 10; dph = 2*math.pi/N for j in range(0, N): ph += dph x = r*math.sin(th)*math.cos(ph); y = r*math.sin(th)*math.sin(ph); z = r*math.cos(th) points.append([x,y,z]) plot_bloch_vector(points) #bb.savefig('blochb.pdf', format = 'png', dpi = 100) trace(rho**2)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Necessary imports import matplotlib.pyplot as plt import numpy as np from IPython.display import clear_output from qiskit import QuantumCircuit from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import ZFeatureMap, RealAmplitudes from qiskit.utils import algorithm_globals from sklearn.datasets import make_classification from sklearn.preprocessing import MinMaxScaler from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier from qiskit_machine_learning.neural_networks import EffectiveDimension, LocalEffectiveDimension from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN # set random seed algorithm_globals.random_seed = 42 num_qubits = 3 # create a feature map feature_map = ZFeatureMap(feature_dimension=num_qubits, reps=1) # create a variational circuit ansatz = RealAmplitudes(num_qubits, reps=1) # combine feature map and ansatz into a single circuit qc = QuantumCircuit(num_qubits) qc.append(feature_map, range(num_qubits)) qc.append(ansatz, range(num_qubits)) qc.decompose().draw("mpl") # parity maps bitstrings to 0 or 1 def parity(x): return "{:b}".format(x).count("1") % 2 output_shape = 2 # corresponds to the number of classes, possible outcomes of the (parity) mapping. # construct QNN qnn = SamplerQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=output_shape, sparse=False, ) # we can set the total number of input samples and weight samples for random selection num_input_samples = 10 num_weight_samples = 10 global_ed = EffectiveDimension( qnn=qnn, weight_samples=num_weight_samples, input_samples=num_input_samples ) # we can also provide user-defined samples and parameters input_samples = algorithm_globals.random.normal(0, 1, size=(10, qnn.num_inputs)) weight_samples = algorithm_globals.random.uniform(0, 1, size=(10, qnn.num_weights)) global_ed = EffectiveDimension(qnn=qnn, weight_samples=weight_samples, input_samples=input_samples) # finally, we will define ranges to test different numbers of data, n n = [5000, 8000, 10000, 40000, 60000, 100000, 150000, 200000, 500000, 1000000] global_eff_dim_0 = global_ed.get_effective_dimension(dataset_size=n[0]) d = qnn.num_weights print("Data size: {}, global effective dimension: {:.4f}".format(n[0], global_eff_dim_0)) print( "Number of weights: {}, normalized effective dimension: {:.4f}".format(d, global_eff_dim_0 / d) ) global_eff_dim_1 = global_ed.get_effective_dimension(dataset_size=n) print("Effective dimension: {}".format(global_eff_dim_1)) print("Number of weights: {}".format(d)) # plot the normalized effective dimension for the model plt.plot(n, np.array(global_eff_dim_1) / d) plt.xlabel("Number of data") plt.ylabel("Normalized GLOBAL effective dimension") plt.show() num_inputs = 3 num_samples = 50 X, y = make_classification( n_samples=num_samples, n_features=num_inputs, n_informative=3, n_redundant=0, n_clusters_per_class=1, class_sep=2.0, ) X = MinMaxScaler().fit_transform(X) y = 2 * y - 1 # labels in {-1, 1} estimator_qnn = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters ) # callback function that draws a live plot when the .fit() method is called def callback_graph(weights, obj_func_eval): clear_output(wait=True) objective_func_vals.append(obj_func_eval) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() # construct classifier initial_point = algorithm_globals.random.random(estimator_qnn.num_weights) estimator_classifier = NeuralNetworkClassifier( neural_network=estimator_qnn, optimizer=COBYLA(maxiter=80), initial_point=initial_point, callback=callback_graph, ) # create empty array for callback to store evaluations of the objective function (callback) objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data estimator_classifier.fit(X, y) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier estimator_classifier.score(X, y) trained_weights = estimator_classifier.weights # get Local Effective Dimension for set of trained weights local_ed_trained = LocalEffectiveDimension( qnn=estimator_qnn, weight_samples=trained_weights, input_samples=X ) local_eff_dim_trained = local_ed_trained.get_effective_dimension(dataset_size=n) print( "normalized local effective dimensions for trained QNN: ", local_eff_dim_trained / estimator_qnn.num_weights, ) # get Local Effective Dimension for set of untrained weights local_ed_untrained = LocalEffectiveDimension( qnn=estimator_qnn, weight_samples=initial_point, input_samples=X ) local_eff_dim_untrained = local_ed_untrained.get_effective_dimension(dataset_size=n) print( "normalized local effective dimensions for untrained QNN: ", local_eff_dim_untrained / estimator_qnn.num_weights, ) # plot the normalized effective dimension for the model plt.plot(n, np.array(local_eff_dim_trained) / estimator_qnn.num_weights, label="trained weights") plt.plot( n, np.array(local_eff_dim_untrained) / estimator_qnn.num_weights, label="untrained weights" ) plt.xlabel("Number of data") plt.ylabel("Normalized LOCAL effective dimension") plt.legend() plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/usamisaori/quantum-expressibility-entangling-capability
usamisaori
import numpy as np from qiskit.quantum_info import state_fidelity, Statevector def getStatevector(circuit): return Statevector(circuit).data import warnings warnings.filterwarnings('ignore') def P_haar(N, F): if F == 1: return 0 else: return (N - 1) * ((1 - F) ** (N - 2)) def KL(P, Q): epsilon = 1e-8 kl_divergence = 0.0 for p, q in zip(P, Q): kl_divergence += p * np.log( (p + epsilon) / (q + epsilon) ) return abs(kl_divergence) def expressibility(qubits, sampler, *, bins=100, epoch=3000, layer=1, encode=False, return_detail=False): unit = 1 / bins limits = [] probabilities = np.array([0] * bins) for i in range(1, bins + 1): limits.append(unit * i) for i in range(epoch): circuit_1 = sampler(layer=layer, qubits=qubits) circuit_2 = sampler(layer=layer, qubits=qubits) f = state_fidelity( getStatevector(circuit_1), getStatevector(circuit_2) ) for j in range(bins): if f <= limits[j]: probabilities[j] += 1 break pHaar_vqc = [ P_haar(2 ** qubits, f - (unit/2)) / bins for f in limits] probabilities = [ p / epoch for p in probabilities ] if return_detail: return pHaar_vqc, probabilities else: return KL(probabilities, pHaar_vqc)
https://github.com/abbarreto/qiskit3
abbarreto
from qiskit_ibm_runtime import QiskitRuntimeService # Save an IBM Quantum account. QiskitRuntimeService.save_account(channel='ibm_quantum', #channel='ibm_cloud', token='17efde49764005e8eeb00dd065d44bc208778be72d44b475e508d20504818786f842988b0e506515c78debdd1b0c4b570717863db5e4f85569fb43c4c8626b8a', overwrite=True) service = QiskitRuntimeService( channel='ibm_quantum', instance='ibm-q/open/main' #instance='ibm-q-research-2/federal-uni-sant-1/main' ) program_inputs = {'iterations': 1} options = {"backend_name": "ibmq_qasm_simulator"} job = service.run(program_id="hello-world", options=options, inputs=program_inputs ) #print(f"job id: {job.job_id()}") result = job.result() print(result) backend = service.get_backend("ibmq_qasm_simulator") from qiskit.circuit.random import random_circuit from qiskit.quantum_info import SparsePauliOp from qiskit.primitives import Estimator from qiskit import QuantumCircuit #circuit = random_circuit(2, 2, seed=1).decompose(reps=1) circuit = QuantumCircuit(2) circuit.x(0) circuit.draw(output='mpl') observable = SparsePauliOp("IZ") # ordem ...210 #options = {"backend_name": "ibmq_qasm_simulator"} estimator = Estimator()#options=options) job = estimator.run(circuit, observable) result = job.result() display(circuit.draw("mpl")) print(f" > Observable: {observable.paulis}") print(f" > Expectation value: {result.values[0]}") print(f" > Metadata: {result.metadata[0]}") import math qc1 = QuantumCircuit(2); qc2 = QuantumCircuit(2) qc1.h(1) qc2.h(0); qc2.p(-math.pi/2, 0) circuits = ( #random_circuit(2, 2, seed=0).decompose(reps=1), #random_circuit(2, 2, seed=1).decompose(reps=1), qc1, qc2 ) observables = ( SparsePauliOp("XZ"), SparsePauliOp("IY"), ) estimator = Estimator() job = estimator.run(circuits, observables) result = job.result() [display(cir.draw("mpl")) for cir in circuits] print(f" > Observables: {[obs.paulis for obs in observables]}") print(f" > Expectation values: {result.values.tolist()}") print(f" > Metadata: {result.metadata}") circuits = ( random_circuit(2, 2, seed=0).decompose(reps=1), random_circuit(2, 2, seed=1).decompose(reps=1), ) observables = ( SparsePauliOp("XZ"), SparsePauliOp("IY"), ) estimator = Estimator() job_0 = estimator.run(circuits[0], observables[0]) job_1 = estimator.run(circuits[1], observables[1]) result_0 = job_0.result() result_1 = job_1.result() [display(cir.draw("mpl")) for cir in circuits] print(f" > Observables: {[obs.paulis for obs in observables]}") print(f" > Expectation values [0]: {result_0.values.tolist()[0]}") print(f" > Metadata [0]: {result_0.metadata[0]}") print(f" > Expectation values [1]: {result_1.values.tolist()[0]}") print(f" > Metadata [1]: {result_1.metadata[0]}") from qiskit.circuit.library import RealAmplitudes circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1) observable = SparsePauliOp("ZI") parameter_values = [0, 1, 2, 3, 4, 5] estimator = Estimator() job = estimator.run(circuit, observable, parameter_values) result = job.result() display(circuit.draw("mpl")) print(f" > Observable: {observable.paulis}") print(f" > Parameter values: {parameter_values}") print(f" > Expectation value: {result.values}") print(f" > Metadata: {result.metadata[0]}") circuit = RealAmplitudes(num_qubits=2, reps=1).decompose(reps=1) display(circuit.draw("mpl")) from qiskit.circuit.random import random_circuit from qiskit.quantum_info import SparsePauliOp from qiskit_ibm_runtime import QiskitRuntimeService, Session, Estimator, Options circuit = random_circuit(2, 2, seed=1).decompose(reps=1) observable = SparsePauliOp("IY") options = Options() options.optimization_level = 2 options.resilience_level = 2 service = QiskitRuntimeService() with Session(service=service, backend="ibmq_qasm_simulator") as session: estimator = Estimator(session=session, options=options) job = estimator.run(circuit, observable) result = job.result() display(circuit.draw("mpl")) print(f" > Observable: {observable.paulis}") print(f" > Expectation value: {result.values[0]}") print(f" > Metadata: {result.metadata[0]}") from qiskit.circuit.random import random_circuit from qiskit.quantum_info import SparsePauliOp from qiskit_ibm_runtime import QiskitRuntimeService, Session, Estimator, Options circuit = random_circuit(2, 2, seed=1).decompose(reps=1) observable = SparsePauliOp("IY") options = Options() options.optimization_level = 2 options.resilience_level = 2 service = QiskitRuntimeService() with Session(service=service, backend="ibmq_belem") as session: estimator = Estimator(session=session, options=options) job = estimator.run(circuit, observable) result = job.result() display(circuit.draw("mpl")) print(f" > Observable: {observable.paulis}") print(f" > Expectation value: {result.values[0]}") print(f" > Metadata: {result.metadata[0]}") from qiskit_ibm_runtime import Session, Options circuit = random_circuit(2, 2, seed=1).decompose(reps=1) observable = SparsePauliOp("IY") options = Options() options.optimization_level = 2 options.resilience_level = 2 service = QiskitRuntimeService() backend = service.get_backend("ibmq_belem") with Session(service=service, backend=backend): estimator = Estimator() job = estimator.run(circuit, observable) result = job.result() display(circuit.draw("mpl")) print(f" > Observable: {observable.paulis}") print(f" > Expectation value: {result.values[0]}") print(f" > Metadata: {result.metadata[0]}") from qiskit.circuit.random import random_circuit from qiskit.primitives import Sampler circuit = random_circuit(2, 2, seed=1).decompose(reps=1) circuit.measure_all() sampler = Sampler() job = sampler.run(circuit) result = job.result() display(circuit.draw("mpl")) print(f" > Quasi probability distribution: {result.quasi_dists[0]}") #print(f" > Metadata: {result.metadata[0]}") #print(result.quasi_dists,result.quasi_dists[0][1]) print(result.quasi_dists[0][0]+result.quasi_dists[0][1]+result.quasi_dists[0][2]+result.quasi_dists[0][3]) from qiskit.circuit.random import random_circuit from qiskit.primitives import Sampler circuits = ( random_circuit(2, 2, seed=0).decompose(reps=1), random_circuit(2, 2, seed=1).decompose(reps=1), ) [c.measure_all() for c in circuits] sampler = Sampler() job = sampler.run(circuits) result = job.result() [display(cir.draw("mpl")) for cir in circuits] print(f" > Quasi probability distributions: {result.quasi_dists}") #print(f" > Metadata: {result.metadata}") from qiskit.circuit.library import RealAmplitudes # RealAmplitudes is one way to generate a parametrized circuit from qiskit.primitives import Sampler circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1) circuit.measure_all() parameter_values = [0, 1, 2, 3, 4, 5] sampler = Sampler() job = sampler.run(circuit, parameter_values) result = job.result() display(circuit.draw("mpl")) print(f" > Parameter values: {parameter_values}") print(f" > Quasi probability distribution: {result.quasi_dists[0]}") print(f" > Metadata: {result.metadata[0]}") from qiskit.circuit.random import random_circuit from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Options backend = service.get_backend("ibmq_qasm_simulator") circuit = random_circuit(2, 2, seed=2).decompose(reps=1) circuit.measure_all() options = Options() options.optimization_level = 2 options.resilience_level = 0 service = QiskitRuntimeService() with Session(service=service, backend=backend): sampler = Sampler() job = sampler.run(circuit) result = job.result() display(circuit.draw("mpl")) print(f" > Quasi probability distribution: {result.quasi_dists[0]}") print(f" > Metadata: {result.metadata[0]}") from qiskit.circuit.random import random_circuit from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Options backend = service.get_backend("ibmq_quito") circuit = random_circuit(2, 2, seed=2).decompose(reps=1) circuit.measure_all() options = Options() options.optimization_level = 2 options.resilience_level = 0 service = QiskitRuntimeService() with Session(service=service, backend=backend): sampler = Sampler() job = sampler.run(circuit) print(job.job_id()) result = job.result() display(circuit.draw("mpl")) print(f" > Quasi probability distribution: {result.quasi_dists[0]}") print(f" > Metadata: {result.metadata[0]}")
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. # # 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 cases for the circuit qasm_file and qasm_string method.""" from qiskit import QiskitError from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit import Gate from qiskit.test import QiskitTestCase, Path class LoadFromQasmTest(QiskitTestCase): """Test circuit.from_qasm_* set of methods.""" def setUp(self): self.qasm_file_name = 'entangled_registers.qasm' self.qasm_file_path = self._get_resource_path( 'qasm/' + self.qasm_file_name, Path.EXAMPLES) def test_qasm_file(self): """Test qasm_file and get_circuit. If all is correct we should get the qasm file loaded in _qasm_file_path """ q_circuit = QuantumCircuit.from_qasm_file(self.qasm_file_path) qr_a = QuantumRegister(4, 'a') qr_b = QuantumRegister(4, 'b') cr_c = ClassicalRegister(4, 'c') cr_d = ClassicalRegister(4, 'd') q_circuit_2 = QuantumCircuit(qr_a, qr_b, cr_c, cr_d) q_circuit_2.h(qr_a) q_circuit_2.cx(qr_a, qr_b) q_circuit_2.barrier(qr_a) q_circuit_2.barrier(qr_b) q_circuit_2.measure(qr_a, cr_c) q_circuit_2.measure(qr_b, cr_d) self.assertEqual(q_circuit, q_circuit_2) def test_fail_qasm_file(self): """Test fail_qasm_file. If all is correct we should get a QiskitError """ self.assertRaises(QiskitError, QuantumCircuit.from_qasm_file, "") def test_fail_qasm_string(self): """Test fail_qasm_string. If all is correct we should get a QiskitError """ self.assertRaises(QiskitError, QuantumCircuit.from_qasm_str, "") def test_qasm_text(self): """Test qasm_text and get_circuit. If all is correct we should get the qasm file loaded from the string """ qasm_string = "// A simple 8 qubit example\nOPENQASM 2.0;\n" qasm_string += "include \"qelib1.inc\";\nqreg a[4];\n" qasm_string += "qreg b[4];\ncreg c[4];\ncreg d[4];\nh a;\ncx a, b;\n" qasm_string += "barrier a;\nbarrier b;\nmeasure a[0]->c[0];\n" qasm_string += "measure a[1]->c[1];\nmeasure a[2]->c[2];\n" qasm_string += "measure a[3]->c[3];\nmeasure b[0]->d[0];\n" qasm_string += "measure b[1]->d[1];\nmeasure b[2]->d[2];\n" qasm_string += "measure b[3]->d[3];" q_circuit = QuantumCircuit.from_qasm_str(qasm_string) qr_a = QuantumRegister(4, 'a') qr_b = QuantumRegister(4, 'b') cr_c = ClassicalRegister(4, 'c') cr_d = ClassicalRegister(4, 'd') ref = QuantumCircuit(qr_a, qr_b, cr_c, cr_d) ref.h(qr_a[3]) ref.cx(qr_a[3], qr_b[3]) ref.h(qr_a[2]) ref.cx(qr_a[2], qr_b[2]) ref.h(qr_a[1]) ref.cx(qr_a[1], qr_b[1]) ref.h(qr_a[0]) ref.cx(qr_a[0], qr_b[0]) ref.barrier(qr_b) ref.measure(qr_b, cr_d) ref.barrier(qr_a) ref.measure(qr_a, cr_c) self.assertEqual(len(q_circuit.cregs), 2) self.assertEqual(len(q_circuit.qregs), 2) self.assertEqual(q_circuit, ref) def test_qasm_text_conditional(self): """Test qasm_text and get_circuit when conditionals are present. """ qasm_string = '\n'.join(["OPENQASM 2.0;", "include \"qelib1.inc\";", "qreg q[1];", "creg c0[4];", "creg c1[4];", "x q[0];", "if(c1==4) x q[0];"]) + '\n' q_circuit = QuantumCircuit.from_qasm_str(qasm_string) qr = QuantumRegister(1, 'q') cr0 = ClassicalRegister(4, 'c0') cr1 = ClassicalRegister(4, 'c1') ref = QuantumCircuit(qr, cr0, cr1) ref.x(qr[0]) ref.x(qr[0]).c_if(cr1, 4) self.assertEqual(len(q_circuit.cregs), 2) self.assertEqual(len(q_circuit.qregs), 1) self.assertEqual(q_circuit, ref) def test_opaque_gate(self): """Test parse an opaque gate See https://github.com/Qiskit/qiskit-terra/issues/1566""" qasm_string = '\n'.join(["OPENQASM 2.0;", "include \"qelib1.inc\";", "opaque my_gate(theta,phi,lambda) a,b;", "qreg q[3];", "my_gate(1,2,3) q[1],q[2];"]) + '\n' circuit = QuantumCircuit.from_qasm_str(qasm_string) qr = QuantumRegister(3, 'q') expected = QuantumCircuit(qr) expected.append(Gate(name='my_gate', num_qubits=2, params=[1, 2, 3]), [qr[1], qr[2]]) self.assertEqual(circuit, expected) def test_qasm_example_file(self): """Loads qasm/example.qasm. """ qasm_filename = self._get_resource_path('example.qasm', Path.QASMS) expected_circuit = QuantumCircuit.from_qasm_str('\n'.join(["OPENQASM 2.0;", "include \"qelib1.inc\";", "qreg q[3];", "qreg r[3];", "creg c[3];", "creg d[3];", "h q[2];", "cx q[2],r[2];", "measure r[2] -> d[2];", "h q[1];", "cx q[1],r[1];", "measure r[1] -> d[1];", "h q[0];", "cx q[0],r[0];", "measure r[0] -> d[0];", "barrier q[0],q[1],q[2];", "measure q[2] -> c[2];", "measure q[1] -> c[1];", "measure q[0] -> c[0];"]) + '\n') q_circuit = QuantumCircuit.from_qasm_file(qasm_filename) self.assertEqual(q_circuit, expected_circuit) self.assertEqual(len(q_circuit.cregs), 2) self.assertEqual(len(q_circuit.qregs), 2) def test_qasm_qas_string_order(self): """ Test that gates are returned in qasm in ascending order""" expected_qasm = '\n'.join(["OPENQASM 2.0;", "include \"qelib1.inc\";", "qreg q[3];", "h q[0];", "h q[1];", "h q[2];"]) + '\n' qasm_string = """OPENQASM 2.0; include "qelib1.inc"; qreg q[3]; h q;""" q_circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual(q_circuit.qasm(), expected_qasm)
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. """Tests for qiskit.quantum_info.analysis""" import unittest import qiskit from qiskit import BasicAer from qiskit.quantum_info.analysis.average import average_data from qiskit.quantum_info.analysis.make_observable import make_dict_observable from qiskit.quantum_info.analysis import hellinger_fidelity from qiskit.test import QiskitTestCase class TestAnalyzation(QiskitTestCase): """Test qiskit.Result API""" def test_average_data_dict_observable(self): """Test average_data for dictionary observable input""" qr = qiskit.QuantumRegister(2) cr = qiskit.ClassicalRegister(2) qc = qiskit.QuantumCircuit(qr, cr, name="qc") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) shots = 10000 backend = BasicAer.get_backend("qasm_simulator") result = qiskit.execute(qc, backend, shots=shots).result() counts = result.get_counts(qc) observable = {"00": 1, "11": 1, "01": -1, "10": -1} mean_zz = average_data(counts=counts, observable=observable) observable = {"00": 1, "11": -1, "01": 1, "10": -1} mean_zi = average_data(counts, observable) observable = {"00": 1, "11": -1, "01": -1, "10": 1} mean_iz = average_data(counts, observable) self.assertAlmostEqual(mean_zz, 1, places=1) self.assertAlmostEqual(mean_zi, 0, places=1) self.assertAlmostEqual(mean_iz, 0, places=1) def test_average_data_list_observable(self): """Test average_data for list observable input.""" qr = qiskit.QuantumRegister(3) cr = qiskit.ClassicalRegister(3) qc = qiskit.QuantumCircuit(qr, cr, name="qc") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.cx(qr[0], qr[2]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qc.measure(qr[2], cr[2]) shots = 10000 backend = BasicAer.get_backend("qasm_simulator") result = qiskit.execute(qc, backend, shots=shots).result() counts = result.get_counts(qc) observable = [1, -1, -1, 1, -1, 1, 1, -1] mean_zzz = average_data(counts=counts, observable=observable) observable = [1, 1, 1, 1, -1, -1, -1, -1] mean_zii = average_data(counts, observable) observable = [1, 1, -1, -1, 1, 1, -1, -1] mean_izi = average_data(counts, observable) observable = [1, 1, -1, -1, -1, -1, 1, 1] mean_zzi = average_data(counts, observable) self.assertAlmostEqual(mean_zzz, 0, places=1) self.assertAlmostEqual(mean_zii, 0, places=1) self.assertAlmostEqual(mean_izi, 0, places=1) self.assertAlmostEqual(mean_zzi, 1, places=1) def test_average_data_matrix_observable(self): """Test average_data for matrix observable input.""" qr = qiskit.QuantumRegister(2) cr = qiskit.ClassicalRegister(2) qc = qiskit.QuantumCircuit(qr, cr, name="qc") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) shots = 10000 backend = BasicAer.get_backend("qasm_simulator") result = qiskit.execute(qc, backend, shots=shots).result() counts = result.get_counts(qc) observable = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]] mean_zz = average_data(counts=counts, observable=observable) observable = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]] mean_zi = average_data(counts, observable) observable = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]] mean_iz = average_data(counts, observable) self.assertAlmostEqual(mean_zz, 1, places=1) self.assertAlmostEqual(mean_zi, 0, places=1) self.assertAlmostEqual(mean_iz, 0, places=1) def test_make_dict_observable(self): """Test make_dict_observable.""" list_in = [1, 1, -1, -1] list_out = make_dict_observable(list_in) list_expected = {"00": 1, "01": 1, "10": -1, "11": -1} matrix_in = [[4, 0, 0, 0], [0, -3, 0, 0], [0, 0, 2, 0], [0, 0, 0, -1]] matrix_out = make_dict_observable(matrix_in) matrix_expected = {"00": 4, "01": -3, "10": 2, "11": -1} long_list_in = [1, 1, -1, -1, -1, -1, 1, 1] long_list_out = make_dict_observable(long_list_in) long_list_expected = { "000": 1, "001": 1, "010": -1, "011": -1, "100": -1, "101": -1, "110": 1, "111": 1, } self.assertEqual(list_out, list_expected) self.assertEqual(matrix_out, matrix_expected) self.assertEqual(long_list_out, long_list_expected) def test_hellinger_fidelity_same(self): """Test hellinger fidelity is one for same dist.""" qc = qiskit.QuantumCircuit(5, 5) qc.h(2) qc.cx(2, 1) qc.cx(2, 3) qc.cx(3, 4) qc.cx(1, 0) qc.measure(range(5), range(5)) sim = BasicAer.get_backend("qasm_simulator") res = qiskit.execute(qc, sim).result() ans = hellinger_fidelity(res.get_counts(), res.get_counts()) self.assertEqual(ans, 1.0) def test_hellinger_fidelity_no_overlap(self): """Test hellinger fidelity is zero for no overlap.""" # ┌───┐ ┌─┐ # q_0: ──────────┤ X ├─────┤M├──────────── # ┌───┐└─┬─┘ └╥┘┌─┐ # q_1: ─────┤ X ├──■────────╫─┤M├───────── # ┌───┐└─┬─┘ ║ └╥┘┌─┐ # q_2: ┤ H ├──■────■────────╫──╫─┤M├────── # └───┘ ┌─┴─┐ ║ ║ └╥┘┌─┐ # q_3: ──────────┤ X ├──■───╫──╫──╫─┤M├─── # └───┘┌─┴─┐ ║ ║ ║ └╥┘┌─┐ # q_4: ───────────────┤ X ├─╫──╫──╫──╫─┤M├ # └───┘ ║ ║ ║ ║ └╥┘ # c: 5/═════════════════════╩══╩══╩══╩══╩═ # 0 1 2 3 4 qc = qiskit.QuantumCircuit(5, 5) qc.h(2) qc.cx(2, 1) qc.cx(2, 3) qc.cx(3, 4) qc.cx(1, 0) qc.measure(range(5), range(5)) # ┌───┐ ┌─┐ # q_0: ──────────┤ X ├─────┤M├───────── # ┌───┐└─┬─┘ └╥┘┌─┐ # q_1: ─────┤ X ├──■────────╫─┤M├────── # ┌───┐└─┬─┘┌───┐ ║ └╥┘┌─┐ # q_2: ┤ H ├──■──┤ Y ├──■───╫──╫─┤M├─── # └───┘ └───┘┌─┴─┐ ║ ║ └╥┘┌─┐ # q_3: ───────────────┤ X ├─╫──╫──╫─┤M├ # ┌─┐ └───┘ ║ ║ ║ └╥┘ # q_4: ─┤M├─────────────────╫──╫──╫──╫─ # └╥┘ ║ ║ ║ ║ # c: 5/══╩══════════════════╩══╩══╩══╩═ # 4 0 1 2 3 qc2 = qiskit.QuantumCircuit(5, 5) qc2.h(2) qc2.cx(2, 1) qc2.y(2) qc2.cx(2, 3) qc2.cx(1, 0) qc2.measure(range(5), range(5)) sim = BasicAer.get_backend("qasm_simulator") res1 = qiskit.execute(qc, sim).result() res2 = qiskit.execute(qc2, sim).result() ans = hellinger_fidelity(res1.get_counts(), res2.get_counts()) self.assertEqual(ans, 0.0) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/rickapocalypse/final_paper_qiskit_sat
rickapocalypse
from qiskit import* from qiskit import circuit import matplotlib.pyplot as plt from qiskit.tools.visualization import plot_histogram from qiskit.tools.visualization import plot_histogram from qiskit.tools.visualization import plot_bloch_multivector qr = QuantumRegister(2) #Registrador quântico de 2bits cr = ClassicalRegister(2) #vai ser utilizado para fazer medições circuit = QuantumCircuit(qr,cr) circuit.h(qr[0]) circuit.cx(qr[0],qr[1]) circuit.measure(qr,cr) simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend = simulator).result() plot_histogram(result.get_counts(circuit)) plt.show() simulator = Aer.get_backend('statevector_simulator') result = execute(circuit, backend = simulator).result() statevector = result.get_statevector() plot_bloch_multivector(statevector) plt.show()
https://github.com/rochisha0/quantum-ugly-duckling
rochisha0
import numpy as np from qiskit import execute, QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.providers.aer import QasmSimulator # Import from Qiskit Aer noise module from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise import QuantumError, ReadoutError from qiskit.providers.aer.noise import pauli_error ## Applying bit flip error def get_noise(): 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"]) return noise_bit_flip def random_number(): circ = QuantumCircuit(4) simulator = QasmSimulator() #NQRNS Circuit for i in range(200): circ.u3(0,0,0,0) circ.u3(0,0,0,1) circ.u3(0,0,0,2) circ.u3(0,0,0,3) circ.cx(0,1) circ.cx(1,2) circ.cx(0,2) circ.cx(0,3) circ.cx(1,3) circ.cx(2,3) circ.barrier() circ.measure_all() noise_bit_flip = get_noise() #get output job = execute(circ, simulator, basis_gates=noise_bit_flip.basis_gates, noise_model=noise_bit_flip, shots= 1) result_bit_flip = job.result() counts_bit_flip = result_bit_flip.get_counts(0) num=list(counts_bit_flip.keys())[0] num = int(num, 2) return num
https://github.com/madmen2/QASM
madmen2
#quantum SVM import qiskit from matplotlib import pyplot as plt import numpy as np from qiskit.ml.datasets import ad_hoc_data from qiskit import BasicAer from qiskit.aqua import QuantumInstance from qiskit.circuit.library import ZZFeatureMap from qiskit.aqua.algorithms import QSVM from qiskit.aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name feature_dim =2 training_dataset=20 testing_dataset_size = 10 random_seed = 10598 shots=10000 #data sample_Total, training_input, test_input, class_labels= ad_hoc_data(training_size=training_dataset, test_size=testing_dataset_size, gap= 0.5, #gap in higher dim space, n=feature_dim, plot_data=True) datapoints , class_to_label = split_dataset_to_data_and_labels(test_input) print(class_to_label) #run on simulator backend = BasicAer.get_backend('qasm_simulator') feature_map =ZZFeatureMap(feature_dim,reps=2) svm= QSVM(feature_map,training_input,test_input,None) svm.random_seed = random_seed quantim_instance = QuantumInstance(backend,shots=shots, seed_simulator=random_seed,seed_transpiler=random_seed) result=svm.run(quantim_instance) #distance between points in higher dimensional space print('kernal Matrix during training:') kernel_matrix= result['kernel_matrix_training'] img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest', origin='upper',cmap='bone_r') plt.show() #validating accuracy predicted_labels = svm.predict(datapoints[0]) predicted_classes= map_label_to_class_name(predicted_labels, svm.label_to_class) print("ground truth: {}".format(datapoints[0])) print("prediction : {}".format(predicted_labels)) print("testing success ratio: ", result['testing_accuracy'])
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
#General imports import numpy as np #Operator Imports from qiskit.opflow import Z, X, I, StateFn, CircuitStateFn, SummedOp from qiskit.opflow.gradients import Gradient, NaturalGradient, QFI, Hessian #Circuit imports from qiskit.circuit import QuantumCircuit, QuantumRegister, Parameter, ParameterVector, ParameterExpression from qiskit.circuit.library import EfficientSU2 # Instantiate the quantum state a = Parameter('a') b = Parameter('b') q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.rz(a, q[0]) qc.rx(b, q[0]) # Instantiate the Hamiltonian observable H = (2 * X) + Z # Combine the Hamiltonian observable and the state op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.) # Print the operator corresponding to the expectation value print(op) params = [a, b] # Define the values to be assigned to the parameters value_dict = {a: np.pi / 4, b: np.pi} # Convert the operator and the gradient target params into the respective operator grad = Gradient().convert(operator = op, params = params) # Print the operator corresponding to the Gradient print(grad) # Assign the parameters and evaluate the gradient grad_result = grad.assign_parameters(value_dict).eval() print('Gradient', grad_result) # Define the Hamiltonian with fixed coefficients H = 0.5 * X - 1 * Z # Define the parameters w.r.t. we want to compute the gradients params = [a, b] # Define the values to be assigned to the parameters value_dict = { a: np.pi / 4, b: np.pi} # Combine the Hamiltonian observable and the state into an expectation value operator op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.) print(op) # Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameters using # the parameter shift method. state_grad = Gradient(grad_method='param_shift').convert(operator=op, params=params) # Print the operator corresponding to the gradient print(state_grad) # Assign the parameters and evaluate the gradient state_grad_result = state_grad.assign_parameters(value_dict).eval() print('State gradient computed with parameter shift', state_grad_result) # Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameter using # the linear combination of unitaries method. state_grad = Gradient(grad_method='lin_comb').convert(operator=op, params=params) # Print the operator corresponding to the gradient print(state_grad) # Assign the parameters and evaluate the gradient state_grad_result = state_grad.assign_parameters(value_dict).eval() print('State gradient computed with the linear combination method', state_grad_result) # Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameter using # the finite difference method. state_grad = Gradient(grad_method='fin_diff').convert(operator=op, params=params) # Print the operator corresponding to the gradient print(state_grad) # Assign the parameters and evaluate the gradient state_grad_result = state_grad.assign_parameters(value_dict).eval() print('State gradient computed with finite difference', state_grad_result) # Besides the method to compute the circuit gradients resp. QFI, a regularization method can be chosen: # `ridge` or `lasso` with automatic parameter search or `perturb_diag_elements` or `perturb_diag` # which perturb the diagonal elements of the QFI. nat_grad = NaturalGradient(grad_method='lin_comb', qfi_method='lin_comb_full', regularization='ridge').convert( operator=op, params=params) # Assign the parameters and evaluate the gradient nat_grad_result = nat_grad.assign_parameters(value_dict).eval() print('Natural gradient computed with linear combination of unitaries', nat_grad_result) # Instantiate the Hamiltonian observable H = X # Instantiate the quantum state with two parameters a = Parameter('a') b = Parameter('b') q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.rz(a, q[0]) qc.rx(b, q[0]) # Combine the Hamiltonian observable and the state op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.) # Convert the operator and the hessian target coefficients into the respective operator hessian = Hessian().convert(operator = op, params = [a, b]) # Define the values to be assigned to the parameters value_dict = {a: np.pi / 4, b: np.pi/4} # Assign the parameters and evaluate the Hessian w.r.t. the Hamiltonian coefficients hessian_result = hessian.assign_parameters(value_dict).eval() print('Hessian \n', np.real(np.array(hessian_result))) # Define parameters params = [a, b] # Get the operator object representing the Hessian state_hess = Hessian(hess_method='param_shift').convert(operator=op, params=params) # Assign the parameters and evaluate the Hessian hessian_result = state_hess.assign_parameters(value_dict).eval() print('Hessian computed using the parameter shift method\n', (np.array(hessian_result))) # Get the operator object representing the Hessian state_hess = Hessian(hess_method='lin_comb').convert(operator=op, params=params) # Assign the parameters and evaluate the Hessian hessian_result = state_hess.assign_parameters(value_dict).eval() print('Hessian computed using the linear combination of unitaries method\n', (np.array(hessian_result))) # Get the operator object representing the Hessian using finite difference state_hess = Hessian(hess_method='fin_diff').convert(operator=op, params=params) # Assign the parameters and evaluate the Hessian hessian_result = state_hess.assign_parameters(value_dict).eval() print('Hessian computed with finite difference\n', (np.array(hessian_result))) # Wrap the quantum circuit into a CircuitStateFn state = CircuitStateFn(primitive=qc, coeff=1.) # Convert the state and the parameters into the operator object that represents the QFI qfi = QFI(qfi_method='lin_comb_full').convert(operator=state, params=params) # Define the values for which the QFI is to be computed values_dict = {a: np.pi / 4, b: 0.1} # Assign the parameters and evaluate the QFI qfi_result = qfi.assign_parameters(values_dict).eval() print('full QFI \n', np.real(np.array(qfi_result))) # Convert the state and the parameters into the operator object that represents the QFI # and set the approximation to 'block_diagonal' qfi = QFI('overlap_block_diag').convert(operator=state, params=params) # Assign the parameters and evaluate the QFI qfi_result = qfi.assign_parameters(values_dict).eval() print('Block-diagonal QFI \n', np.real(np.array(qfi_result))) # Convert the state and the parameters into the operator object that represents the QFI # and set the approximation to 'diagonal' qfi = QFI('overlap_diag').convert(operator=state, params=params) # Assign the parameters and evaluate the QFI qfi_result = qfi.assign_parameters(values_dict).eval() print('Diagonal QFI \n', np.real(np.array(qfi_result))) # Execution Imports from qiskit import Aer from qiskit.utils import QuantumInstance # Algorithm Imports from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import CG from qiskit.opflow import I, X, Z from qiskit.circuit import QuantumCircuit, ParameterVector from scipy.optimize import minimize # Instantiate the system Hamiltonian h2_hamiltonian = -1.05 * (I ^ I) + 0.39 * (I ^ Z) - 0.39 * (Z ^ I) - 0.01 * (Z ^ Z) + 0.18 * (X ^ X) # This is the target energy h2_energy = -1.85727503 # Define the Ansatz wavefunction = QuantumCircuit(2) params = ParameterVector('theta', length=8) it = iter(params) wavefunction.ry(next(it), 0) wavefunction.ry(next(it), 1) wavefunction.rz(next(it), 0) wavefunction.rz(next(it), 1) wavefunction.cx(0, 1) wavefunction.ry(next(it), 0) wavefunction.ry(next(it), 1) wavefunction.rz(next(it), 0) wavefunction.rz(next(it), 1) # Define the expectation value corresponding to the energy op = ~StateFn(h2_hamiltonian) @ StateFn(wavefunction) grad = Gradient(grad_method='lin_comb') qi_sv = QuantumInstance(Aer.get_backend('aer_simulator_statevector'), shots=1, seed_simulator=2, seed_transpiler=2) #Conjugate Gradient algorithm optimizer = CG(maxiter=50) # Gradient callable vqe = VQE(wavefunction, optimizer=optimizer, gradient=grad, quantum_instance=qi_sv) result = vqe.compute_minimum_eigenvalue(h2_hamiltonian) print('Result:', result.optimal_value, 'Reference:', h2_energy) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) ### added h gate ### qc.h(1) qc.cx(1, 0) 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) qc.h(1) return qc
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """Assembler Test.""" import unittest import numpy as np from numpy.testing import assert_allclose from qiskit import pulse from qiskit.compiler.assembler import assemble from qiskit.assembler.disassemble import disassemble from qiskit.assembler.run_config import RunConfig from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Gate, Instruction, Parameter from qiskit.circuit.library import RXGate from qiskit.pulse.transforms import target_qobj_transform from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeOpenPulse2Q import qiskit.quantum_info as qi def _parametric_to_waveforms(schedule): instructions = list(schedule.instructions) for i, time_instruction_tuple in enumerate(schedule.instructions): time, instruction = time_instruction_tuple if not isinstance(instruction.pulse, pulse.library.Waveform): new_inst = pulse.Play(instruction.pulse.get_waveform(), instruction.channel) instructions[i] = (time, new_inst) return tuple(instructions) class TestQuantumCircuitDisassembler(QiskitTestCase): """Tests for disassembling circuits to qobj.""" def test_disassemble_single_circuit(self): """Test disassembling a single circuit.""" qr = QuantumRegister(2, name="q") cr = ClassicalRegister(2, name="c") circ = QuantumCircuit(qr, cr, name="circ") circ.h(qr[0]) circ.cx(qr[0], qr[1]) circ.measure(qr, cr) qubit_lo_freq = [5e9, 5e9] meas_lo_freq = [6.7e9, 6.7e9] qobj = assemble( circ, shots=2000, memory=True, qubit_lo_freq=qubit_lo_freq, meas_lo_freq=meas_lo_freq, ) circuits, run_config_out, headers = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 2) self.assertEqual(run_config_out.memory_slots, 2) self.assertEqual(run_config_out.shots, 2000) self.assertEqual(run_config_out.memory, True) self.assertEqual(run_config_out.qubit_lo_freq, qubit_lo_freq) self.assertEqual(run_config_out.meas_lo_freq, meas_lo_freq) self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0], circ) self.assertEqual({}, headers) def test_disassemble_multiple_circuits(self): """Test disassembling multiple circuits, all should have the same config.""" qr0 = QuantumRegister(2, name="q0") qc0 = ClassicalRegister(2, name="c0") circ0 = QuantumCircuit(qr0, qc0, name="circ0") circ0.h(qr0[0]) circ0.cx(qr0[0], qr0[1]) circ0.measure(qr0, qc0) qr1 = QuantumRegister(3, name="q1") qc1 = ClassicalRegister(3, name="c1") circ1 = QuantumCircuit(qr1, qc1, name="circ0") circ1.h(qr1[0]) circ1.cx(qr1[0], qr1[1]) circ1.cx(qr1[0], qr1[2]) circ1.measure(qr1, qc1) qobj = assemble([circ0, circ1], shots=100, memory=False, seed=6) circuits, run_config_out, headers = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 3) self.assertEqual(run_config_out.memory_slots, 3) self.assertEqual(run_config_out.shots, 100) self.assertEqual(run_config_out.memory, False) self.assertEqual(run_config_out.seed, 6) self.assertEqual(len(circuits), 2) for circuit in circuits: self.assertIn(circuit, [circ0, circ1]) self.assertEqual({}, headers) def test_disassemble_no_run_config(self): """Test disassembling with no run_config, relying on default.""" qr = QuantumRegister(2, name="q") qc = ClassicalRegister(2, name="c") circ = QuantumCircuit(qr, qc, name="circ") circ.h(qr[0]) circ.cx(qr[0], qr[1]) circ.measure(qr, qc) qobj = assemble(circ) circuits, run_config_out, headers = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 2) self.assertEqual(run_config_out.memory_slots, 2) self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0], circ) self.assertEqual({}, headers) def test_disassemble_initialize(self): """Test disassembling a circuit with an initialize.""" q = QuantumRegister(2, name="q") circ = QuantumCircuit(q, name="circ") circ.initialize([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)], q[:]) qobj = assemble(circ) circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 2) self.assertEqual(run_config_out.memory_slots, 0) self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0], circ) self.assertEqual({}, header) def test_disassemble_isometry(self): """Test disassembling a circuit with an isometry.""" q = QuantumRegister(2, name="q") circ = QuantumCircuit(q, name="circ") circ.iso(qi.random_unitary(4).data, circ.qubits, []) qobj = assemble(circ) circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 2) self.assertEqual(run_config_out.memory_slots, 0) self.assertEqual(len(circuits), 1) # params array assert_allclose(circuits[0]._data[0].operation.params[0], circ._data[0].operation.params[0]) # all other data self.assertEqual( circuits[0]._data[0].operation.params[1:], circ._data[0].operation.params[1:] ) self.assertEqual(circuits[0]._data[0].qubits, circ._data[0].qubits) self.assertEqual(circuits[0]._data[0].clbits, circ._data[0].clbits) self.assertEqual(circuits[0]._data[1:], circ._data[1:]) self.assertEqual({}, header) def test_opaque_instruction(self): """Test the disassembler handles opaque instructions correctly.""" opaque_inst = Instruction(name="my_inst", num_qubits=4, num_clbits=2, params=[0.5, 0.4]) q = QuantumRegister(6, name="q") c = ClassicalRegister(4, name="c") circ = QuantumCircuit(q, c, name="circ") circ.append(opaque_inst, [q[0], q[2], q[5], q[3]], [c[3], c[0]]) qobj = assemble(circ) circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 6) self.assertEqual(run_config_out.memory_slots, 4) self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0], circ) self.assertEqual({}, header) def test_circuit_with_conditionals(self): """Verify disassemble sets conditionals correctly.""" qr = QuantumRegister(2) cr1 = ClassicalRegister(1) cr2 = ClassicalRegister(2) qc = QuantumCircuit(qr, cr1, cr2) qc.measure(qr[0], cr1) # Measure not required for a later conditional qc.measure(qr[1], cr2[1]) # Measure required for a later conditional qc.h(qr[1]).c_if(cr2, 3) qobj = assemble(qc) circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 2) self.assertEqual(run_config_out.memory_slots, 3) self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0], qc) self.assertEqual({}, header) def test_circuit_with_simple_conditional(self): """Verify disassemble handles a simple conditional on the only bits.""" qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(qr[0]).c_if(cr, 1) qobj = assemble(qc) circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 1) self.assertEqual(run_config_out.memory_slots, 1) self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0], qc) self.assertEqual({}, header) def test_circuit_with_single_bit_conditions(self): """Verify disassemble handles a simple conditional on a single bit of a register.""" # This circuit would fail to perfectly round-trip if 'cr' below had only one bit in it. # This is because the format of QasmQobj is insufficient to disambiguate single-bit # conditions from conditions on registers with only one bit. Since single-bit conditions are # mostly a hack for the QasmQobj format at all, `disassemble` always prefers to return the # register if it can. It would also fail if registers overlap. qr = QuantumRegister(1) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]).c_if(cr[0], 1) qobj = assemble(qc) circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, len(qr)) self.assertEqual(run_config_out.memory_slots, len(cr)) self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0], qc) self.assertEqual({}, header) def test_circuit_with_mcx(self): """Verify disassemble handles mcx gate - #6271.""" qr = QuantumRegister(5) cr = ClassicalRegister(5) qc = QuantumCircuit(qr, cr) qc.mcx([0, 1, 2], 4) qobj = assemble(qc) circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 5) self.assertEqual(run_config_out.memory_slots, 5) self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0], qc) self.assertEqual({}, header) def test_multiple_conditionals_multiple_registers(self): """Verify disassemble handles multiple conditionals and registers.""" qr = QuantumRegister(3) cr1 = ClassicalRegister(3) cr2 = ClassicalRegister(5) cr3 = ClassicalRegister(6) cr4 = ClassicalRegister(1) qc = QuantumCircuit(qr, cr1, cr2, cr3, cr4) qc.x(qr[1]) qc.h(qr) qc.cx(qr[1], qr[0]).c_if(cr3, 14) qc.ccx(qr[0], qr[2], qr[1]).c_if(cr4, 1) qc.h(qr).c_if(cr1, 3) qobj = assemble(qc) circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 3) self.assertEqual(run_config_out.memory_slots, 15) self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0], qc) self.assertEqual({}, header) def test_circuit_with_bit_conditional_1(self): """Verify disassemble handles conditional on a single bit.""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]).c_if(cr[1], True) qobj = assemble(qc) circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 2) self.assertEqual(run_config_out.memory_slots, 2) self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0], qc) self.assertEqual({}, header) def test_circuit_with_bit_conditional_2(self): """Verify disassemble handles multiple single bit conditionals.""" qr = QuantumRegister(2) cr = ClassicalRegister(2) cr1 = ClassicalRegister(2) qc = QuantumCircuit(qr, cr, cr1) qc.h(qr[0]).c_if(cr1[1], False) qc.h(qr[1]).c_if(cr[0], True) qc.cx(qr[0], qr[1]).c_if(cr1[0], False) qobj = assemble(qc) circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 2) self.assertEqual(run_config_out.memory_slots, 4) self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0], qc) self.assertEqual({}, header) def assertCircuitCalibrationsEqual(self, in_circuits, out_circuits): """Verify circuit calibrations are equivalent pre-assembly and post-disassembly""" self.assertEqual(len(in_circuits), len(out_circuits)) for in_qc, out_qc in zip(in_circuits, out_circuits): in_cals = in_qc.calibrations out_cals = out_qc.calibrations self.assertEqual(in_cals.keys(), out_cals.keys()) for gate_name in in_cals: self.assertEqual(in_cals[gate_name].keys(), out_cals[gate_name].keys()) for gate_params, in_sched in in_cals[gate_name].items(): out_sched = out_cals[gate_name][gate_params] self.assertEqual(*map(_parametric_to_waveforms, (in_sched, out_sched))) def test_single_circuit_calibrations(self): """Test that disassembler parses single circuit QOBJ calibrations (from QOBJ-level).""" theta = Parameter("theta") qc = QuantumCircuit(2) qc.h(0) qc.rx(np.pi, 0) qc.rx(theta, 1) qc = qc.assign_parameters({theta: np.pi}) with pulse.build() as h_sched: pulse.play(pulse.library.Drag(1, 0.15, 4, 2), pulse.DriveChannel(0)) with pulse.build() as x180: pulse.play(pulse.library.Gaussian(1, 0.2, 5), pulse.DriveChannel(0)) qc.add_calibration("h", [0], h_sched) qc.add_calibration(RXGate(np.pi), [0], x180) qobj = assemble(qc, FakeOpenPulse2Q()) output_circuits, _, _ = disassemble(qobj) self.assertCircuitCalibrationsEqual([qc], output_circuits) def test_parametric_pulse_circuit_calibrations(self): """Test that disassembler parses parametric pulses back to pulse gates.""" with pulse.build() as h_sched: pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0)) qc = QuantumCircuit(2) qc.h(0) qc.add_calibration("h", [0], h_sched) backend = FakeOpenPulse2Q() backend.configuration().parametric_pulses = ["drag"] qobj = assemble(qc, backend) output_circuits, _, _ = disassemble(qobj) out_qc = output_circuits[0] self.assertCircuitCalibrationsEqual([qc], output_circuits) self.assertTrue( all( qc_sched.instructions == out_qc_sched.instructions for (_, qc_gate), (_, out_qc_gate) in zip( qc.calibrations.items(), out_qc.calibrations.items() ) for qc_sched, out_qc_sched in zip(qc_gate.values(), out_qc_gate.values()) ), ) def test_multi_circuit_uncommon_calibrations(self): """Test that disassembler parses uncommon calibrations (stored at QOBJ experiment-level).""" with pulse.build() as sched: pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0)) qc_0 = QuantumCircuit(2) qc_0.h(0) qc_0.append(RXGate(np.pi), [1]) qc_0.add_calibration("h", [0], sched) qc_0.add_calibration(RXGate(np.pi), [1], sched) qc_1 = QuantumCircuit(2) qc_1.h(0) circuits = [qc_0, qc_1] qobj = assemble(circuits, FakeOpenPulse2Q()) output_circuits, _, _ = disassemble(qobj) self.assertCircuitCalibrationsEqual(circuits, output_circuits) def test_multi_circuit_common_calibrations(self): """Test that disassembler parses common calibrations (stored at QOBJ-level).""" with pulse.build() as sched: pulse.play(pulse.library.Drag(1, 0.15, 4, 2), pulse.DriveChannel(0)) qc_0 = QuantumCircuit(2) qc_0.h(0) qc_0.append(RXGate(np.pi), [1]) qc_0.add_calibration("h", [0], sched) qc_0.add_calibration(RXGate(np.pi), [1], sched) qc_1 = QuantumCircuit(2) qc_1.h(0) qc_1.add_calibration(RXGate(np.pi), [1], sched) circuits = [qc_0, qc_1] qobj = assemble(circuits, FakeOpenPulse2Q()) output_circuits, _, _ = disassemble(qobj) self.assertCircuitCalibrationsEqual(circuits, output_circuits) def test_single_circuit_delay_calibrations(self): """Test that disassembler parses delay instruction back to delay gate.""" qc = QuantumCircuit(2) qc.append(Gate("test", 1, []), [0]) test_sched = pulse.Delay(64, pulse.DriveChannel(0)) + pulse.Delay( 160, pulse.DriveChannel(0) ) qc.add_calibration("test", [0], test_sched) qobj = assemble(qc, FakeOpenPulse2Q()) output_circuits, _, _ = disassemble(qobj) self.assertEqual(len(qc.calibrations), len(output_circuits[0].calibrations)) self.assertEqual(qc.calibrations.keys(), output_circuits[0].calibrations.keys()) self.assertTrue( all( qc_cal.keys() == out_qc_cal.keys() for qc_cal, out_qc_cal in zip( qc.calibrations.values(), output_circuits[0].calibrations.values() ) ) ) self.assertEqual( qc.calibrations["test"][((0,), ())], output_circuits[0].calibrations["test"][((0,), ())] ) class TestPulseScheduleDisassembler(QiskitTestCase): """Tests for disassembling pulse schedules to qobj.""" def setUp(self): super().setUp() self.backend = FakeOpenPulse2Q() self.backend_config = self.backend.configuration() self.backend_config.parametric_pulses = ["constant", "gaussian", "gaussian_square", "drag"] def test_disassemble_single_schedule(self): """Test disassembling a single schedule.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build(self.backend) as sched: with pulse.align_right(): pulse.play(pulse.library.Constant(10, 1.0), d0) pulse.set_phase(1.0, d0) pulse.shift_phase(3.11, d0) pulse.set_frequency(1e9, d0) pulse.shift_frequency(1e7, d0) pulse.delay(20, d0) pulse.delay(10, d1) pulse.play(pulse.library.Constant(8, 0.1), d1) pulse.measure_all() qobj = assemble(sched, backend=self.backend, shots=2000) scheds, run_config_out, _ = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.memory_slots, 2) self.assertEqual(run_config_out.shots, 2000) self.assertEqual(run_config_out.memory, False) self.assertEqual(run_config_out.meas_level, 2) self.assertEqual(run_config_out.meas_lo_freq, self.backend.defaults().meas_freq_est) self.assertEqual(run_config_out.qubit_lo_freq, self.backend.defaults().qubit_freq_est) self.assertEqual(run_config_out.rep_time, 99) self.assertEqual(len(scheds), 1) self.assertEqual(scheds[0], target_qobj_transform(sched)) def test_disassemble_multiple_schedules(self): """Test disassembling multiple schedules, all should have the same config.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build(self.backend) as sched0: with pulse.align_right(): pulse.play(pulse.library.Constant(10, 1.0), d0) pulse.set_phase(1.0, d0) pulse.shift_phase(3.11, d0) pulse.set_frequency(1e9, d0) pulse.shift_frequency(1e7, d0) pulse.delay(20, d0) pulse.delay(10, d1) pulse.play(pulse.library.Constant(8, 0.1), d1) pulse.measure_all() with pulse.build(self.backend) as sched1: with pulse.align_right(): pulse.play(pulse.library.Constant(8, 0.1), d0) pulse.play(pulse.library.Waveform([0.0, 1.0]), d1) pulse.set_phase(1.1, d0) pulse.shift_phase(3.5, d0) pulse.set_frequency(2e9, d0) pulse.shift_frequency(3e7, d1) pulse.delay(20, d1) pulse.delay(10, d0) pulse.play(pulse.library.Constant(8, 0.4), d1) pulse.measure_all() qobj = assemble([sched0, sched1], backend=self.backend, shots=2000) scheds, run_config_out, _ = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.memory_slots, 2) self.assertEqual(run_config_out.shots, 2000) self.assertEqual(run_config_out.memory, False) self.assertEqual(len(scheds), 2) self.assertEqual(scheds[0], target_qobj_transform(sched0)) self.assertEqual(scheds[1], target_qobj_transform(sched1)) def test_disassemble_parametric_pulses(self): """Test disassembling multiple schedules all should have the same config.""" d0 = pulse.DriveChannel(0) with pulse.build(self.backend) as sched: with pulse.align_right(): pulse.play(pulse.library.Constant(10, 1.0), d0) pulse.play(pulse.library.Gaussian(10, 1.0, 2.0), d0) pulse.play(pulse.library.GaussianSquare(10, 1.0, 2.0, 3), d0) pulse.play(pulse.library.Drag(10, 1.0, 2.0, 0.1), d0) qobj = assemble(sched, backend=self.backend, shots=2000) scheds, _, _ = disassemble(qobj) self.assertEqual(scheds[0], target_qobj_transform(sched)) def test_disassemble_schedule_los(self): """Test disassembling schedule los.""" d0 = pulse.DriveChannel(0) m0 = pulse.MeasureChannel(0) d1 = pulse.DriveChannel(1) m1 = pulse.MeasureChannel(1) sched0 = pulse.Schedule() sched1 = pulse.Schedule() schedule_los = [ {d0: 4.5e9, d1: 5e9, m0: 6e9, m1: 7e9}, {d0: 5e9, d1: 4.5e9, m0: 7e9, m1: 6e9}, ] qobj = assemble([sched0, sched1], backend=self.backend, schedule_los=schedule_los) _, run_config_out, _ = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.schedule_los, schedule_los) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/KMU-quantum-classroom/qiskit-classroom-converter
KMU-quantum-classroom
""" QuantumCircuit to Matrix Converter """ # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. from typing import List import numpy as np from qiskit import QuantumCircuit from qiskit.visualization import array_to_latex from qiskit_class_converter.converters.base import BaseConverter class QuantumCircuitToMatrixConverter(BaseConverter): """ Converter class """ def __init__(self, option=None): super().__init__(option) self.__programmable_variable_per_qubit = None def insert_i_gate(self): """ Trace empty space in the layer to enter the Identity gate. """ arr = [f"I_{{q{i}}}" for i in range(self.__programmable_variable_per_qubit["total_qubits"])] for i in self.__programmable_variable_per_qubit["gate_qubits"]: for j in i["qubit"]: arr[j] = i["name"] arr = list(dict.fromkeys(arr)) arr.reverse() return arr def actual_convert_action(self): self.logger.debug("quantum circuit to matrix") matrix_list = {"gate": [], "name": []} # type validate if isinstance(self.input_value, (List, QuantumCircuit)): self.input_value = self.input_value.remove_final_measurements(inplace=False) dag = self.qiskit.converters.circuit_to_dag(self.input_value) else: raise TypeError("QuantumCircuit is required.") layer_index = 0 for layer in dag.layers(): circuit = self.qiskit.converters.dag_to_circuit(layer['graph']) matrix_list["gate"].append(self.qiskit.quantum_info.Operator(circuit).to_matrix()) self.__programmable_variable_per_qubit = {"total_qubits": circuit.num_qubits, "gate_qubits": []} for _inst in circuit.data: _inst_upper_name = _inst[0].name.upper() qubit_indices = [circuit.find_bit(qubit)[0] for qubit in _inst[1]] gate_name = (_inst_upper_name + "_{" + ", ".join(f"q{i}" for i in qubit_indices) + "}") self.__programmable_variable_per_qubit["gate_qubits"].append( {"name": gate_name, "qubit": qubit_indices} ) matrix_list["name"].append((layer_index, self.insert_i_gate())) layer_index += 1 matrix_list["result"] = self.qiskit.quantum_info.Operator(self.input_value).to_matrix() if self.option.get("print", False) == "raw": latex_source_list = {"gate": [], "name": matrix_list["name"]} for each_matrix in matrix_list["gate"]: latex_source_list["gate"].append( array_to_latex(array=np.array(each_matrix), source=True)) latex_source_list["result"] = array_to_latex( array=np.array(matrix_list["result"]), source=True) return latex_source_list return matrix_list
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import * import matplotlib.pyplot as plt import random from scipy.stats import unitary_group import os import sys sys.path.append("../..") import seaborn as sns import numpy as np from Modules.normal_SPEA import SPEA from Modules.changed_SPEA import global_max_SPEA unit = unitary_group.rvs(4) unit # get the eigenvalues and eigenstates eig_v, eig_vect = np.linalg.eig(unit) eig_v = np.angle(eig_v) eig = [] for k in eig_v: if k < 0: e = (k+2*np.pi)/(2*np.pi) else: e = (k)/(2*np.pi) eig.append(e) eig_v = np.array(eig) print("Eigenvalues :", eig_v) print("Eigenstates :", eig_vect) sample = unitary_group.rvs(4) basis = [] for k in sample: basis.append(k) basis_ind = np.random.choice(range(4)) print("Basis :", basis) print("Basis index :", basis_ind) def generate_plot1(actual_E, returned_E, iters): colors = ['blue', 'orange', 'red', 'green', 'brown', 'magenta', 'pink'] plt.figure(figsize=(9, 7)) plt.scatter(range(iters), returned_E, marker='o', edgecolors='grey', color=np.random.choice(colors), alpha=0.8,) for i, k in enumerate(actual_E): if i == 0: plt.plot([0, iters], [k, k], color='black', linewidth=2, label='Actual Values') else: plt.plot([0, iters], [k, k], color='black', linewidth=2) plt.xlabel("Number of iterations", fontsize=14) plt.ylabel("Eigenvalues", fontsize=14) plt.title("Scatter plot for returned eigenvalues", fontsize=17) plt.legend() plt.grid() def generate_plot2(actual_E, returned_E, size, experiments): colors = ['blue', 'orange', 'red', 'green', 'brown', 'magenta', 'pink'] fig = plt.figure(figsize=(16, 13)) for i in range(size): ax = fig.add_subplot(size/2, 2, i+1) ax.scatter(range(experiments), returned_E[i], marker='o', edgecolors='grey', color=np.random.choice(colors), alpha=0.8,) for i, k in enumerate(actual_E): if i == 0: ax.plot([0, experiments], [k, k], color='black', linewidth=2, label='Actual Values') else: ax.plot([0, experiments], [k, k], color='black', linewidth=2) ax.set_xlabel("Experiment Number", fontsize=14) ax.set_ylabel("Eigenvalues", fontsize=14) ax.set_title("Scatter plot for returned eigenvalues", fontsize=17) ax.legend(loc='best') ax.grid() simulator = Aer.get_backend('qasm_simulator') spea1 = SPEA(unit,resolution=40,error = 2, max_iters=15) eigen_vals_ret1 = [] while len(eigen_vals_ret1) != 100: res = spea1.get_eigen_pair( backend=simulator, algo='alternate', basis=basis, basis_ind=basis_ind) if res['cost'] < 0.75: continue print(res) eigen_vals_ret1.append(res['theta']) generate_plot1(eig_v, eigen_vals_ret1, 100) spea2 = global_max_SPEA(unit, resolution=40, error=2, max_iters=15) simulator = Aer.get_backend('qasm_simulator') eigen_vals_ret2 = [] while len(eigen_vals_ret2) != 100: res = spea2.get_eigen_pair( backend=simulator, algo='alternate', basis=basis, basis_ind=basis_ind) if res['cost'] < 0.75: continue print(res) eigen_vals_ret2.append(res['theta']) generate_plot1(eig_v, eigen_vals_ret2, 100) unit = unitary_group.rvs(4) # get the eigenvalues and eigenstates eig_v, eig_vect = np.linalg.eig(unit) eig_v = np.angle(eig_v) eig = [] for k in eig_v: if k < 0: e = (k+2*np.pi)/(2*np.pi) else: e = (k)/(2*np.pi) eig.append(e) eig_v = np.array(eig) print(eig_v) y = np.array([[0,-1j], [1j,0]]) yy= np.kron(y,y) basis = [] for k in yy: basis.append(k) basis eig_ret = [] spea1 = SPEA(unit, resolution=30, error=2, max_iters=10) simulator = Aer.get_backend('qasm_simulator') for i in range(4): basis_index = i eigen_vals_ret1 = [] while len(eigen_vals_ret1) != 15: res = spea1.get_eigen_pair( backend=simulator, algo='alternate', basis=basis, basis_ind=basis_index) if res['cost'] < 0.75: continue print((len(eigen_vals_ret1)/15)*100, "% done...") eigen_vals_ret1.append(res['theta']) eig_ret.append(eigen_vals_ret1) generate_plot2(eig_v, eig_ret, 4, 15) eig_ret2 = [] spea2 = global_max_SPEA(unit, resolution=30, error=2, max_iters=10) simulator = Aer.get_backend('qasm_simulator') for i in range(4): basis_index = i eigen_vals_ret2 = [] while len(eigen_vals_ret2) != 40: res = spea2.get_eigen_pair( backend=simulator, algo='alternate', basis=basis, basis_ind=basis_index) if res['cost'] < 0.75: continue print((len(eigen_vals_ret2)/40)*100, "% done...") eigen_vals_ret2.append(res['theta']) eig_ret2.append(eigen_vals_ret2) generate_plot2(eig_v, eig_ret2, 4, 40) plt.title("Original Algorithm ") for i in range(4): sns.kdeplot(eig_ret[i], shade=True, label='Basis '+str(i)) plt.xlabel("Eigenvalues Returned") plt.legend() plt.title("Modified Algorithm ") for i in range(4): sns.kdeplot(eig_ret2[i], shade=True, label='Basis '+str(i), palette='red') plt.xlabel("Eigenvalues Returned") plt.legend() def min_eigensolver(unitary, algo, experiments=20, min_threshold=0.9): dims = unitary.shape[0] simulator = Aer.get_backend('qasm_simulator') step_size = (1/dims) # generate the steps steps = np.arange(0, 1 + 1e-12, step_size) if steps[-1] != 1: steps = np.append(steps, 1) print("Steps :", steps) if algo == 0: spe = SPEA(unitary, resolution=40, error=2, max_iters=12) else: spe = global_max_SPEA(unitary, resolution=40, error=2, max_iters=12) # start the experiments max_cost = -1 for i in range(len(steps) - 1): # define left and right bounds left = steps[i] right = steps[i+1] costs, eigs = [], [] # lists to store costs for _ in range(experiments): res = spe.get_eigen_pair( backend=simulator, theta_left=left, theta_right=right, randomize=True) costs.append(res['cost']) eigs.append(res['theta']) # if the cost is above threshold, return them if np.average(costs) > min_threshold: return (np.average(costs), eigs) if np.average(costs) > max_cost: max_cost = np.average(costs) best_eigs = eigs # return the cost with the max average cost return (max_cost, best_eigs) unit = unitary_group.rvs(4) unit # get the eigenvalues and eigenstates eig_v, eig_vect = np.linalg.eig(unit) eig_v = np.angle(eig_v) eig = [] for k in eig_v: if k < 0: e = (k+2*np.pi)/(2*np.pi) else: e = (k)/(2*np.pi) eig.append(e) eig_v = np.array(eig) print("Eigenvalues :", eig_v) print("Eigenstates :", eig_vect) res1 = min_eigensolver(unit, algo=0, experiments=40, min_threshold=0.85) res2 = min_eigensolver(unit, algo=1, experiments=40, min_threshold=0.85) res1[1], res2[1] generate_plot1(eig_v,res1[1],40) generate_plot1(eig_v,res2[1],40)
https://github.com/magn5452/QiskitQaoa
magn5452
from abc import ABC, abstractmethod from qiskit import QuantumCircuit class InitialStrategy(ABC): @abstractmethod def set_up_initial_state_circuit(self, quantum_circuit: QuantumCircuit): pass class PhaseStrategy(ABC): @abstractmethod def set_up_phase_circuit(self, gamma, quantum_circuit: QuantumCircuit): pass class MixerStrategy(ABC): @abstractmethod def set_up_mixer_circuit(self, beta, quantum_circuit: QuantumCircuit): pass class MeasurementStrategy(ABC): @abstractmethod def set_up_measurement_circuit(self, quantum_circuit: QuantumCircuit): pass
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Example of using the StochasticSwap pass.""" from qiskit.transpiler.passes import StochasticSwap from qiskit.transpiler import CouplingMap from qiskit.converters import circuit_to_dag from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit coupling = CouplingMap([[0, 1], [1, 2], [1, 3]]) qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") circ = QuantumCircuit(qr, cr) circ.cx(qr[1], qr[2]) circ.cx(qr[0], qr[3]) circ.measure(qr[0], cr[0]) circ.h(qr) circ.cx(qr[0], qr[1]) circ.cx(qr[2], qr[3]) circ.measure(qr[0], cr[0]) circ.measure(qr[1], cr[1]) circ.measure(qr[2], cr[2]) circ.measure(qr[3], cr[3]) dag = circuit_to_dag(circ) # ┌─┐┌───┐ ┌─┐ # q_0: |0>─────────────────■──────────────────┤M├┤ H ├──■─────┤M├ # ┌───┐ │ └╥┘└───┘┌─┴─┐┌─┐└╥┘ # q_1: |0>──■───────┤ H ├──┼───────────────────╫──────┤ X ├┤M├─╫─ # ┌─┴─┐┌───┐└───┘ │ ┌─┐ ║ └───┘└╥┘ ║ # q_2: |0>┤ X ├┤ H ├───────┼─────────■─────┤M├─╫────────────╫──╫─ # └───┘└───┘ ┌─┴─┐┌───┐┌─┴─┐┌─┐└╥┘ ║ ║ ║ # q_3: |0>───────────────┤ X ├┤ H ├┤ X ├┤M├─╫──╫────────────╫──╫─ # └───┘└───┘└───┘└╥┘ ║ ║ ║ ║ # c_0: 0 ═══════════════════════════════╬══╬══╩════════════╬══╩═ # ║ ║ ║ # c_1: 0 ═══════════════════════════════╬══╬═══════════════╩════ # ║ ║ # c_2: 0 ═══════════════════════════════╬══╩════════════════════ # ║ # c_3: 0 ═══════════════════════════════╩═══════════════════════ # # ┌─┐┌───┐ ┌─┐ # q_0: |0>────────────────────■──┤M├┤ H ├──────────────────■──┤M├────── # ┌─┴─┐└╥┘└───┘┌───┐┌───┐ ┌─┴─┐└╥┘┌─┐ # q_1: |0>──■───X───────────┤ X ├─╫──────┤ H ├┤ X ├─X────┤ X ├─╫─┤M├─── # ┌─┴─┐ │ ┌───┐└───┘ ║ └───┘└─┬─┘ │ └───┘ ║ └╥┘┌─┐ # q_2: |0>┤ X ├─┼──────┤ H ├──────╫─────────────■───┼──────────╫──╫─┤M├ # └───┘ │ ┌───┐└───┘ ║ │ ┌─┐ ║ ║ └╥┘ # q_3: |0>──────X─┤ H ├───────────╫─────────────────X─┤M├──────╫──╫──╫─ # └───┘ ║ └╥┘ ║ ║ ║ # c_0: 0 ════════════════════════╩════════════════════╬═══════╩══╬══╬═ # ║ ║ ║ # c_1: 0 ═════════════════════════════════════════════╬══════════╩══╬═ # ║ ║ # c_2: 0 ═════════════════════════════════════════════╬═════════════╩═ # ║ # c_3: 0 ═════════════════════════════════════════════╩═══════════════ # # # 2 # | # 0 - 1 - 3 # Build the expected output to verify the pass worked expected = QuantumCircuit(qr, cr) expected.cx(qr[1], qr[2]) expected.h(qr[2]) expected.swap(qr[0], qr[1]) expected.h(qr[0]) expected.cx(qr[1], qr[3]) expected.h(qr[3]) expected.measure(qr[1], cr[0]) expected.swap(qr[1], qr[3]) expected.cx(qr[2], qr[1]) expected.h(qr[3]) expected.swap(qr[0], qr[1]) expected.measure(qr[2], cr[2]) expected.cx(qr[3], qr[1]) expected.measure(qr[0], cr[3]) expected.measure(qr[3], cr[0]) expected.measure(qr[1], cr[1]) expected_dag = circuit_to_dag(expected) # Run the pass on the dag from the input circuit pass_ = StochasticSwap(coupling, 20, 999) after = pass_.run(dag) # Verify the output of the pass matches our expectation assert expected_dag == after
https://github.com/VoicuTomut/Qsiris-Quantum-Odyssey-and-Qiskit
VoicuTomut
import json import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import project_qsiris.conversion_gates as conv from project_qsiris.conversion_intermediates import OdysseyMoment def get_odyssey_nr_qubits(res): """ :param res: (puzzle)dictionary :return: (number of qubits from puzzle)int """ nr_q = res["PuzzleDefinition"]["QubitCapacity"] return nr_q def extract_odyssey_matrix(mat): """ :param mat: matrix of complex numbers in dictionary form :return: matrix ov 'complex' numbers #example: mat=[[{'Real': 0.0, 'Imaginary': 0.0, 'Magnitude': 0.0, 'Phase': 0.0}, {'Real': 1.0, 'Imaginary': 0.0, 'Magnitude': 1.0, 'Phase': 0.0}], [{'Real': 1.0, 'Imaginary': 0.0, 'Magnitude': 1.0, 'Phase': 0.0}, {'Real': 0.0, 'Imaginary': 0.0, 'Magnitude': 0.0, 'Phase': 0.0}]] g_mat = extract_odyssey_matrix(mat) print("matrice:\n",g_mat) """ mat_conv = [] for i in mat: linie = [] for j in i: linie.append(conv._odyssey_to_complex(j)) mat_conv.append(linie) return mat_conv def add_odyssey_moment(puzzle_gate, qc): """ :param puzzle_gate: string of gates :param qc: QuantumCircuit Qiskit Add gates from moment to the Qiskit circuit """ moment = OdysseyMoment(puzzle_gate) if len(moment.control_q) == 0: """ This is the default case """ for qubit in range(moment.nr_q): gate_name = moment.original_form[qubit]["GateInSlot"]["Name"] if gate_name == "X": qc.x(qubit) elif gate_name == "Y": qc.y(qubit) elif gate_name == "Z": qc.z(qubit) elif gate_name == "H": qc.h(qubit) elif gate_name == "I": qc.id(qubit) elif gate_name == "Filler": print( "The fillers are empty gates so they will not be converted to qiskit", qubit, ) else: unit = extract_odyssey_matrix( moment.original_form[qubit]["GateInSlot"]["DefinitionMatrix"] ) qubits = [k for k in moment.filler_q] qubits.append(qubit) qc.unitary(unit, qubits, moment.original_form[qubit]["GateInSlot"]["Name"]) if len(moment.filler_q) > 0: print( "This gate {} is not necessarily converted correctly." " The order of the qubits maybe reversed Please check! ".format( gate_name ) ) return """ If there are controls on the puzzle gate """ for i in range(moment.nr_q): if ( (moment.original_form[i]["GateInSlot"]["Name"] != "CTRL") and (moment.original_form[i]["GateInSlot"]["Name"] != "I") and (moment.original_form[i]["GateInSlot"]["Name"] != "Filler") ): control = moment.control_q.copy() qubits = [l for l in control] for l in range(len(moment.filler_q)): qubits.append(moment.filler_q[l]) qubits.append(i) unit = np.identity(2 ** len(qubits), dtype=complex) mat = extract_odyssey_matrix(moment.original_form[i]["GateInSlot"]["DefinitionMatrix"]) """ unit[-1][-1]=mat[1][1] unit[-1][-2]=mat[1][0] unit[-2][-1]=mat[0][1] unit[-2][-2]=mat[0][0] """ for k in range(1, len(mat) + 1): for j in range(1, len(mat) + 1): unit[-k][-j] = mat[-k][-j] qc.unitary( unit, qubits[::-1], "C " + str(moment.control_q) + " -> " + moment.original_form[i]["GateInSlot"]["Name"] + "[" + str(i) + "]", ) def load_oddysey_puzzle(path): file = open(path, "r") content = file.read() puzzle = json.loads(content) return puzzle def odyssey_to_qiskit(puzzle, incl_initial_state = False, use_barrier = False, incl_all_measurements = False): """ :param path: (puzzle) path to puzzle :param initial_state: (initial qubits state ) string of dictionaries :return: quantum circuit in qiskit equivalent with the circuit from puzzle """ nr_q = get_odyssey_nr_qubits(puzzle) qc = QuantumCircuit(QuantumRegister(nr_q), ClassicalRegister(nr_q)) if incl_initial_state != False: qc.initialize(incl_initial_state) for puzzle_gate in conv._transpose_list(puzzle["PuzzleGates"]): if use_barrier: qc.barrier() add_odyssey_moment(puzzle_gate, qc) if incl_all_measurements: for index in range(nr_q): qc.measure(qc.qregs[0][index], qc.cregs[0][nr_q - 1 - index]) return qc
https://github.com/Soumyo2121/Basic-Quantum-Algorithms
Soumyo2121
import numpy as np import math from qiskit.circuit import Parameter from qiskit import * from math import pi,cos,sin,tan,atan from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit.providers.aer import QasmSimulator def execute_circuit_sv(quantum_circuit): statevector_simulator = Aer.get_backend('statevector_simulator') result = execute(quantum_circuit, statevector_simulator).result() statevector_results = result.get_statevector(quantum_circuit) circuit_diagram = quantum_circuit.draw('mpl') b_sphere = plot_bloch_multivector(statevector_results) return statevector_results, circuit_diagram, b_sphere param_theta = Parameter('θ') n = int(input("Enter the number of qubits(Max no. 5): ")) bell = QuantumCircuit(n, name='entanglement') rot = int(input("Press 1 to select RX gate, 2 for RY gate")) if rot==1: bell.rx(param_theta,0) elif rot==2: bell.ry(param_theta,0) else: print("Please Enter the correct option") control = int(input("Press 1 to use CNOT gate and 2 for CY gate")) if control==1: for i in range (0,n-1): bell.cx(i,i+1) elif control==2: for j in range(0,n-1): bell.cy(j,j+1) else: print("Please press the correct option") import numpy as np from math import pi,cos,sin,tan,atan x = float(input("Enter the angle multiplier: ")) bell = bell.bind_parameters({param_theta: (x * np.pi)}) result, img, bsphere = execute_circuit_sv(bell) img bsphere print(result) from qiskit.quantum_info import DensityMatrix D = DensityMatrix(bell) print(D) from qiskit.quantum_info import entropy vn_entropy = entropy(D, base=2) print(vn_entropy) r = x / 0.5 if x % 0.5 == 0 and r % 2 != 0: print("Maximal Entanglement") else: print("Partial Entanglement")
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/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/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.visualization import dag_drawer q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) dag_drawer(dag)
https://github.com/0sophy1/Qiskit-Dev-Cert-lectures
0sophy1
a = 2 + 3j b = 5 - 2j print("a + b=", a+b) print("a * b=", a*b) a = 2 + 3j a_bar = 2 - 3j print("a + a_bar = ", a + a_bar) print("a * a_bar = ", a * a_bar) import matplotlib.pyplot as plt import numpy as np import math z1 = 3 + 4j x_min = 0 x_max = 5.0 y_min = 0 y_max = 5.0 def plot_complex_number_geometric_representation(z,x_min,x_max,y_min,y_max): fig = plt.figure() ax = plt.gca() a = [0.0,0.0] b = [z.real,z.imag] head_length = 0.2 dx = b[0] - a[0] dy = b[1] - a[1] vec_ab = [dx,dy] vec_ab_magnitude = math.sqrt(dx**2+dy**2) dx = dx / vec_ab_magnitude dy = dy / vec_ab_magnitude vec_ab_magnitude = vec_ab_magnitude - head_length ax.arrow(a[0], a[1], vec_ab_magnitude*dx, vec_ab_magnitude*dy, head_width=head_length, head_length=head_length, fc='black', ec='black') plt.xlim(x_min,x_max) plt.ylim(y_min,y_max) plt.grid(True,linestyle='-') plt.show() plot_complex_number_geometric_representation(z1,x_min,x_max,y_min,y_max) import numpy as np A = np.array([[1,2,3]]) B = np.array([[7], [10], [9]]) A+B A = np.array([[7], [10], [9]]) B = np.array([[1,2,3]]) C = np.array([[1, 2, 3], [5, 6, 7], [8,9,10]]) print("AB = ", np.matmul(A,B)) print("BA = ", np.matmul(B,A)) print("CA = ", np.matmul(C, A)) print("AC = ", np.matmul(A, C)) A = np.array([[1, 2], [3,4]]) B = np.array([[5, 6], [7,8]]) print("AB = \n", np.matmul(A,B)) print("BA = \n", np.matmul(B,A)) from scipy.linalg import orth from numpy import linalg as LA A = np.array([[1 + 3j, 2 - 1j], [3, 4 - 2j]]) data =orth(A) x, y = data[:, 0], data[:, 1] print("norm of x = %f" % LA.norm(x)) print("norm of y = %f" % LA.norm(y)) print("x dot y = ", np.vdot(x,y))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.quantumcircuitdata import CircuitInstruction from qiskit.circuit import Measure from qiskit.circuit.library import HGate, CXGate qr = QuantumRegister(2) cr = ClassicalRegister(2) instructions = [ CircuitInstruction(HGate(), [qr[0]], []), CircuitInstruction(CXGate(), [qr[0], qr[1]], []), CircuitInstruction(Measure(), [qr[0]], [cr[0]]), CircuitInstruction(Measure(), [qr[1]], [cr[1]]), ] circuit = QuantumCircuit.from_instructions(instructions) circuit.draw("mpl")
https://github.com/hephaex/Quantum-Computing-Awesome-List
hephaex
#initialization %matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import IBMQ from qiskit.compiler import transpile, assemble from qiskit.providers.ibmq import least_busy from qiskit.tools.jupyter import * from qiskit.tools.monitor import job_monitor from qiskit.visualization import * from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter provider = IBMQ.load_account() # load your IBM Quantum Experience account # If you are a member of the IBM Q Network, fill your hub, group, and project information to # get access to your premium devices. # provider = IBMQ.get_provider(hub='', group='', project='') from may4_challenge.ex2 import get_counts, show_final_answer num_qubits = 5 meas_calibs, state_labels = complete_meas_cal(range(num_qubits), circlabel='mcal') # find the least busy device that has at least 5 qubits 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 # run experiments on a real device shots = 8192 experiments = transpile(meas_calibs, backend=backend, optimization_level=3) job = backend.run(assemble(experiments, shots=shots)) print(job.job_id()) %qiskit_job_watcher # get measurement filter cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') meas_filter = meas_fitter.filter #print(meas_fitter.cal_matrix) meas_fitter.plot_calibration() # get noisy counts noisy_counts = get_counts(backend) plot_histogram(noisy_counts[0]) # apply measurement error mitigation and plot the mitigated counts mitigated_counts_0 = meas_filter.apply(noisy_counts[0]) plot_histogram([mitigated_counts_0, noisy_counts[0]]) # uncomment whatever answer you think is correct # answer1 = 'a' # answer1 = 'b' answer1 = 'c' # answer1 = 'd' # plot noisy counts plot_histogram(noisy_counts[1]) # apply measurement error mitigation # insert your code here to do measurement error mitigation on noisy_counts[1] mitigated_counts_1 = meas_filter.apply(noisy_counts[1]) plot_histogram([mitigated_counts_1, noisy_counts[1]]) # uncomment whatever answer you think is correct # answer2 = 'a' #answer2 = 'b' #answer2 = 'c' answer2 = 'd' # plot noisy counts plot_histogram(noisy_counts[2]) # apply measurement error mitigation # insert your code here to do measurement error mitigation on noisy_counts[2] mitigated_counts_2 = meas_filter.apply(noisy_counts[2]) plot_histogram([mitigated_counts_2, noisy_counts[2]]) # uncomment whatever answer you think is correct # answer3 = 'a' answer3 = 'b' #answer3 = 'c' # answer3 = 'd' # plot noisy counts plot_histogram(noisy_counts[3]) # apply measurement error mitigation # insert your code here to do measurement error mitigation on noisy_counts[3] mitigated_counts_3 = meas_filter.apply(noisy_counts[3]) plot_histogram([mitigated_counts_3, noisy_counts[3]]) # uncomment whatever answer you think is correct #answer4 = 'a' answer4 = 'b' #answer4 = 'c' #answer4 = 'd' # answer string show_final_answer(answer1, answer2, answer3, answer4)
https://github.com/tuf65651/quantum-research
tuf65651
# %matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from datetime import datetime # import math # Loading your IBM Q account(s) # IBMQ.load_account() backend = Aer.get_backend("qasm_simulator") # global n_reg # global m_reg # global scratch_a # global class_reg # global backend # global qc # global test_timestamp # def before_tests(): n_reg = QuantumRegister(6, 'n') m_reg = QuantumRegister(6, 'm') scratch_a = QuantumRegister(6, 'sca') class_reg = ClassicalRegister(6, 'y') qc = QuantumCircuit(n_reg, m_reg, scratch_a, class_reg) backend = Aer.get_backend('qasm_simulator') from ArithmaticFunctions import * # time_stamp = str(datetime.now()) test_timestamp = str(datetime.now()) def setup_each_addition(): n_reg = QuantumRegister(6, 'n') m_reg = QuantumRegister(6, 'm') scratch_a = QuantumRegister(6, 'sca') class_reg = ClassicalRegister(6, 'y') qc = QuantumCircuit(n_reg, m_reg, scratch_a, class_reg) # return {'n_reg': n_reg, 'm_reg': m_reg, 'scratch_a': scratch_a, 'class_reg': class_reg, 'qc': qc } def get_results_of_last_test(): # for bit in range(len(n_reg)): # qc.measure(n_reg[bit], class_reg[bit]) simulate = execute(qc, backend=backend, shots=1024).result() return simulate.get_counts() def verify_results(expected): if [expected] == list(results.keys()): print("PASSING - ", test_timestamp) else: print("FAILING - ", test_timestamp) print(f'Got - {results}') setup_each_addition() qc.x(m_reg[0]) CDKM_add(qc, n_reg, m_reg, scratch_a) qc.measure(m_reg, class_reg) results = get_results_of_last_test() verify_results('000001') setup_each_addition() qc.x(n_reg[0]) CDKM_add(qc, n_reg, m_reg, scratch_a) qc.measure(m_reg, class_reg) results = get_results_of_last_test() verify_results('000001') setup_each_addition() qc.x(n_reg[0]) qc.x(m_reg[0]) qc.barrier() CDKM_add(qc, n_reg, m_reg, scratch_a) qc.measure(n_reg, class_reg) results = get_results_of_last_test() # qc.draw() verify_results('000010') a = QuantumRegister(3, 'a') b = QuantumRegister(3, 'b') c = QuantumRegister(3, 'c') y = ClassicalRegister(3, 'y') circ = QuantumCircuit(a,b,c,y) circ.x(a[1]) circ.x(b[1]) MAJ(circ, bit_a=a[0], bit_b=b[0], bit_c=c[0]) MAJ(circ, bit_a=a[1], bit_b=b[1], bit_c=a[0]) circ.cx(a[1], c[1]) UMA(circ, bit_a=a[1], bit_b=b[1], bit_c=a[0]) UMA(circ, bit_a=a[0], bit_b=b[0], bit_c=c[0]) circ.measure(c, y) results = execute(circ, backend, shots=1024).result().get_counts() print(results) MAJ(circ, bit_a=a[0], bit_b=b[0], bit_c=c[0]) circ.draw() len(scratch_a) # setup_each_addition() qc.x(n_reg[0]) qc.x(n_reg[1]) # qc.x(m_reg[0]) qc.barrier() twos_compelement(qc, n_reg, scratch_a) twos_compelement(qc, n_reg, scratch_a) qc.measure(n_reg, class_reg) results = get_results_of_last_test() # qc.draw() results = execute(qc, backend, shots=1024).result().get_counts() print(results) qc.draw() a = QuantumRegister(4, 'a') b = QuantumRegister(4, 'b') c = QuantumRegister(4, 'c') d = QuantumRegister(4, 'd') y = ClassicalRegister(4, 'y') z = ClassicalRegister(4, 'z') qc = QuantumCircuit(a,b,c,d,y,z) qc.x(a[0]) qc.x(b[1]) qc.barrier() # twos_compelement(qc, a, c) CDKM_add(qc, a, b, c) # twos_compelement(qc, b, c) # twos_compelement(qc, a, c) qc.measure(a, y) qc.measure(b, z) results = execute(qc, backend, shots=1024).result().get_counts() print(results) qc.draw() qc.x(a[1]) qc.x(b[0]) qc.barrier() # twos_compelement(qc, a, c) sub_b_from_a_in_place(qc, a, b, c) # twos_compelement(qc, b, c) # twos_compelement(qc, a, c) qc.measure(c, y) # qc.measure(d, z) results = execute(qc, backend, shots=1024).result().get_counts() print(results) qc.x(a[1]) qc.x(b[1]) qc.barrier() # twos_compelement(qc, a, c) sub_b_from_a_in_place(qc, a, b, c) # twos_compelement(qc, b, c) # twos_compelement(qc, a, c) qc.measure(c, y) # qc.measure(d, z) results = execute(qc, backend, shots=1024).result().get_counts() print(results)
https://github.com/zapatacomputing/qe-qiskit
zapatacomputing
from qiskit import Aer, IBMQ, execute from qiskit import transpile, assemble from qiskit.tools.monitor import job_monitor from qiskit.tools.monitor import job_monitor import matplotlib.pyplot as plt from qiskit.visualization import plot_histogram, plot_state_city """ Qiskit backends to execute the quantum circuit """ def simulator(qc): """ Run on local simulator :param qc: quantum circuit :return: """ backend = Aer.get_backend("qasm_simulator") shots = 2048 tqc = transpile(qc, backend) qobj = assemble(tqc, shots=shots) job_sim = backend.run(qobj) qc_results = job_sim.result() return qc_results, shots def simulator_state_vector(qc): """ Select the StatevectorSimulator from the Aer provider :param qc: quantum circuit :return: statevector """ simulator = Aer.get_backend('statevector_simulator') # Execute and get counts result = execute(qc, simulator).result() state_vector = result.get_statevector(qc) return state_vector def real_quantum_device(qc): """ Use the IBMQ essex device :param qc: quantum circuit :return: """ provider = IBMQ.load_account() backend = provider.get_backend('ibmq_santiago') shots = 2048 TQC = transpile(qc, backend) qobj = assemble(TQC, shots=shots) job_exp = backend.run(qobj) job_monitor(job_exp) QC_results = job_exp.result() return QC_results, shots def counts(qc_results): """ Get counts representing the wave-function amplitudes :param qc_results: :return: dict keys are bit_strings and their counting values """ return qc_results.get_counts() def plot_results(qc_results): """ Visualizing wave-function amplitudes in a histogram :param qc_results: quantum circuit :return: """ plt.show(plot_histogram(qc_results.get_counts(), figsize=(8, 6), bar_labels=False)) def plot_state_vector(state_vector): """Visualizing state vector in the density matrix representation""" plt.show(plot_state_city(state_vector))
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 RYRZ(VariationalForm): """Layers of Y+Z rotations followed by entangling gates.""" CONFIGURATION = { 'name': 'RYRZ', 'description': 'RYRZ Variational Form', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'ryrz_schema', 'type': 'object', 'properties': { 'depth': { 'type': 'integer', 'default': 3, 'minimum': 1 }, '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) * 2 if self._skip_unentangled_qubits \ else self._num_qubits * 2 # for repeated block self._num_parameters += len(self._entangled_qubits) * depth * 2 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 circuit.u1(parameters[param_idx + 1], q[qubit]) # rz param_idx += 2 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 circuit.u1(parameters[param_idx + 1], q[qubit]) # rz param_idx += 2 circuit.barrier(q) return circuit
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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 linear reversible circuits synthesis functions.""" import unittest import numpy as np from ddt import ddt, data from qiskit import QuantumCircuit from qiskit.circuit.library import LinearFunction from qiskit.synthesis.linear import ( synth_cnot_count_full_pmh, synth_cnot_depth_line_kms, random_invertible_binary_matrix, check_invertible_binary_matrix, calc_inverse_matrix, ) from qiskit.synthesis.linear.linear_circuits_utils import transpose_cx_circ, optimize_cx_4_options from qiskit.test import QiskitTestCase @ddt class TestLinearSynth(QiskitTestCase): """Test the linear reversible circuit synthesis functions.""" def test_lnn_circuit(self): """Test the synthesis of a CX circuit with LNN connectivity.""" n = 5 qc = QuantumCircuit(n) for i in range(n - 1): qc.cx(i, i + 1) mat = LinearFunction(qc).linear for optimized in [True, False]: optimized_qc = optimize_cx_4_options( synth_cnot_count_full_pmh, mat, optimize_count=optimized ) self.assertEqual(optimized_qc.depth(), 4) self.assertEqual(optimized_qc.count_ops()["cx"], 4) def test_full_circuit(self): """Test the synthesis of a CX circuit with full connectivity.""" n = 5 qc = QuantumCircuit(n) for i in range(n): for j in range(i + 1, n): qc.cx(i, j) mat = LinearFunction(qc).linear for optimized in [True, False]: optimized_qc = optimize_cx_4_options( synth_cnot_count_full_pmh, mat, optimize_count=optimized ) self.assertEqual(optimized_qc.depth(), 4) self.assertEqual(optimized_qc.count_ops()["cx"], 4) def test_transpose_circ(self): """Test the transpose_cx_circ() function.""" n = 5 mat = random_invertible_binary_matrix(n, seed=1234) qc = synth_cnot_count_full_pmh(mat) transposed_qc = transpose_cx_circ(qc) transposed_mat = LinearFunction(transposed_qc).linear.astype(int) self.assertTrue((mat.transpose() == transposed_mat).all()) def test_example_circuit(self): """Test the synthesis of an example CX circuit which provides different CX count and depth for different optimization methods.""" qc = QuantumCircuit(9) qc.swap(8, 7) qc.swap(7, 6) qc.cx(5, 6) qc.cx(6, 5) qc.swap(4, 5) qc.cx(3, 4) qc.cx(4, 3) qc.swap(2, 3) qc.cx(1, 2) qc.cx(2, 1) qc.cx(0, 1) qc.cx(1, 0) mat = LinearFunction(qc).linear optimized_qc = optimize_cx_4_options(synth_cnot_count_full_pmh, mat, optimize_count=True) self.assertEqual(optimized_qc.depth(), 17) self.assertEqual(optimized_qc.count_ops()["cx"], 20) optimized_qc = optimize_cx_4_options(synth_cnot_count_full_pmh, mat, optimize_count=False) self.assertEqual(optimized_qc.depth(), 15) self.assertEqual(optimized_qc.count_ops()["cx"], 23) @data(5, 6) def test_invertible_matrix(self, n): """Test the functions for generating a random invertible matrix and inverting it.""" mat = random_invertible_binary_matrix(n, seed=1234) out = check_invertible_binary_matrix(mat) mat_inv = calc_inverse_matrix(mat, verify=True) mat_out = np.dot(mat, mat_inv) % 2 self.assertTrue(np.array_equal(mat_out, np.eye(n))) self.assertTrue(out) @data(5, 6) def test_synth_lnn_kms(self, num_qubits): """Test that synth_cnot_depth_line_kms produces the correct synthesis.""" rng = np.random.default_rng(1234) num_trials = 10 for _ in range(num_trials): mat = random_invertible_binary_matrix(num_qubits, seed=rng) mat = np.array(mat, dtype=bool) qc = synth_cnot_depth_line_kms(mat) mat1 = LinearFunction(qc).linear self.assertTrue((mat == mat1).all()) # Check that the circuit depth is bounded by 5*num_qubits depth = qc.depth() self.assertTrue(depth <= 5 * num_qubits) # Check that the synthesized circuit qc fits LNN connectivity for inst in qc.data: self.assertEqual(inst.operation.name, "cx") q0 = qc.find_bit(inst.qubits[0]).index q1 = qc.find_bit(inst.qubits[1]).index dist = abs(q0 - q1) self.assertEqual(dist, 1) if __name__ == "__main__": unittest.main()
https://github.com/AMevans12/Quantum-Codes-Qiskit-Module-
AMevans12
from qiskit import * qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) %matplotlib inline circuit.draw(output='mpl') # the quantum circuit has two qubits. they are indexed as qubits 0 and 1 circuit.h(0) circuit.cx(0,1) # order is control, target circuit.measure([0,1], [0,1]) # qubits [0,1] are measured and results are stored in classical bits [0,1] in order circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=simulator, shots=1024).result() from qiskit.visualization import plot_histogram import qiskit.quantum_info as qi plot_histogram(result.get_counts(circuit)) from qiskit import IBMQ IBMQ.save_account('e9857a49c124d22110b0c577754d160e984ce3f01e5ef110ae6295f3f6c4a6f337a129dfdcb5a1191a9b8c69317e9ae32ed4d196b744571d45453db7fb56d933') IBMQ.load_account() provider = IBMQ.get_provider(hub = 'ibm-q') qcomp = provider.get_backend('ibm_brisbane') import qiskit.tools.jupyter %qiskit_job_watcher job = execute(circuit, backend=qcomp) result = job.result() plot_histogram(result.get_counts(circuit))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can make the bars more transparent to better see the ones that are behind # if they overlap. import numpy as np from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_city from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) state = Statevector(qc) plot_state_city(state, alpha=0.6)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector qc = QuantumCircuit(2) qc.h(0) qc.x(1) state = Statevector(qc) plot_bloch_multivector(state)
https://github.com/Harcipan/QAI_GroverSim
Harcipan
# Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile from qiskit.visualization import * from ibm_quantum_widgets import * # qiskit-ibmq-provider has been deprecated. # Please see the Migration Guides in https://ibm.biz/provider_migration_guide for more detail. from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options # Loading your IBM Quantum account(s) service = QiskitRuntimeService(channel="ibm_quantum") # Invoke a primitive. For more details see https://docs.quantum.ibm.com/run/primitives # result = Sampler().run(circuits).result() import qiskit print(qiskit.__version__) from qiskit import QuantumCircuit qc = QuantumCircuit(3) qc.h(0) qc.h(1) qc.cx(1, 2) qc.measure_all() # Previous from qiskit import BasicAer backend = BasicAer.get_backend("statevector_simulator") statevector = backend.run(qc).result().get_statevector() # Current qc.remove_final_measurements() # no measurements allowed from qiskit.quantum_info import Statevector statevector = Statevector(qc) from qiskit import QuantumCircuit qc = QuantumCircuit(3) qc.h(0) qc.h(1) qc.cx(1, 2) qc.measure_all() """# Previous from qiskit import BasicAer backend = BasicAer.get_backend("qasm_simulator") result = backend.run(qc).result()""" # One current option from qiskit.providers.basic_provider import BasicProvider backend = BasicProvider().get_backend("basic_simulator") result = backend.run(qc).result() # Get counts from the result counts = result.get_counts() from qiskit.visualization import plot_histogram print(counts) data = [counts] plot_histogram(data) print("h") """# Another current option is to specify it directly from qiskit.providers.basic_provider import BasicSimulator backend = BasicSimulator() result = backend.run(qc).result()""" from qiskit import QuantumCircuit from qiskit.providers.basic_provider import BasicProvider from qiskit.visualization import plot_histogram # Create a quantum circuit qc = QuantumCircuit(3) qc.h(0) qc.h(1) qc.cx(1, 2) qc.measure_all() # Get the BasicSimulator backend from the BasicProvider backend = BasicProvider().get_backend("basic_simulator") # Simulate the quantum circuit result = backend.run(qc).result() # Get counts from the result counts = result.get_counts() # Plot the histogram plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# If you introduce a list with less colors than bars, the color of the bars will # alternate following the sequence from the list. import numpy as np from qiskit.quantum_info import DensityMatrix from qiskit import QuantumCircuit from qiskit.visualization import plot_state_paulivec qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0, 1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) matrix = DensityMatrix(qc) plot_state_paulivec(matrix, color=['crimson', 'midnightblue', 'seagreen'])
https://github.com/sathayen/qiskit-docker
sathayen
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit import Aer from qiskit import execute from qiskit.tools.visualization import circuit_drawer, plot_histogram qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.measure(qr, cr) # Draw the circuit circuit_drawer(qc) # Print qasm qc_qasm = qc.qasm() print(qc_qasm) # Run the circuit job = execute(qc, backend = Aer.get_backend('qasm_simulator'), shots=1024) # get status job.status # get results result = job.result() counts = result.get_counts() print("Probability = ", counts['00']/1024)
https://github.com/qiskit-community/community.qiskit.org
qiskit-community
#Import general libraries (needed for functions) import numpy as np import matplotlib.pyplot as plt from IPython import display #Import the RB Functions import qiskit.ignis.verification.randomized_benchmarking as rb #Import Qiskit classes import qiskit from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors.standard_errors import depolarizing_error, thermal_relaxation_error #Generate RB circuits (2Q RB) #number of qubits nQ=2 rb_opts = {} #Number of Cliffords in the sequence rb_opts['length_vector'] = [1, 10, 20, 50, 75, 100, 125, 150, 175, 200] #Number of seeds (random sequences) rb_opts['nseeds'] = 5 #Default pattern rb_opts['rb_pattern'] = [[0,1]] rb_circs, xdata = rb.randomized_benchmarking_seq(**rb_opts) print(rb_circs[0][0]) # Create a new circuit without the measurement qregs = rb_circs[0][-1].qregs cregs = rb_circs[0][-1].cregs qc = qiskit.QuantumCircuit(*qregs, *cregs) for i in rb_circs[0][-1][0:-nQ]: qc.data.append(i) # The Unitary is an identity (with a global phase) backend = qiskit.Aer.get_backend('unitary_simulator') basis_gates = ['u1','u2','u3','cx'] # use U,CX for now job = qiskit.execute(qc, backend=backend, basis_gates=basis_gates) print(np.around(job.result().get_unitary(),3)) # Run on a noisy simulator noise_model = NoiseModel() # Depolarizing_error dp = 0.005 noise_model.add_all_qubit_quantum_error(depolarizing_error(dp, 1), ['u1', 'u2', 'u3']) noise_model.add_all_qubit_quantum_error(depolarizing_error(2*dp, 2), 'cx') backend = qiskit.Aer.get_backend('qasm_simulator') # Create the RB fitter backend = qiskit.Aer.get_backend('qasm_simulator') basis_gates = ['u1','u2','u3','cx'] shots = 200 qobj_list = [] rb_fit = rb.RBFitter(None, xdata, rb_opts['rb_pattern']) for rb_seed,rb_circ_seed in enumerate(rb_circs): print('Compiling seed %d'%rb_seed) new_rb_circ_seed = qiskit.compiler.transpile(rb_circ_seed, basis_gates=basis_gates) qobj = qiskit.compiler.assemble(new_rb_circ_seed, shots=shots) print('Simulating seed %d'%rb_seed) job = backend.run(qobj, noise_model=noise_model, backend_options={'max_parallel_experiments': 0}) qobj_list.append(qobj) # Add data to the fitter rb_fit.add_data(job.result()) print('After seed %d, alpha: %f, EPC: %f'%(rb_seed,rb_fit.fit[0]['params'][1], rb_fit.fit[0]['epc'])) plt.figure(figsize=(8, 6)) ax = plt.subplot(1, 1, 1) # Plot the essence by calling plot_rb_data rb_fit.plot_rb_data(0, ax=ax, add_label=True, show_plt=False) # Add title and label ax.set_title('%d Qubit RB'%(nQ), fontsize=18) plt.show() #Count the number of single and 2Q gates in the 2Q Cliffords gates_per_cliff = rb.rb_utils.gates_per_clifford(qobj_list, xdata[0],basis_gates, rb_opts['rb_pattern'][0]) for i in range(len(basis_gates)): print("Number of %s gates per Clifford: %f"%(basis_gates[i], np.mean([gates_per_cliff[0][i],gates_per_cliff[1][i]]))) # Prepare lists of the number of qubits and the errors ngates = np.zeros(7) ngates[0:3] = gates_per_cliff[0][0:3] ngates[3:6] = gates_per_cliff[1][0:3] ngates[6] = gates_per_cliff[0][3] gate_qubits = np.array([0, 0, 0, 1, 1, 1, -1], dtype=int) gate_errs = np.zeros(len(gate_qubits)) gate_errs[[1, 4]] = dp/2 #convert from depolarizing error to epg (1Q) gate_errs[[2, 5]] = 2*dp/2 #convert from depolarizing error to epg (1Q) gate_errs[6] = dp*3/4 #convert from depolarizing error to epg (2Q) #Calculate the predicted epc pred_epc = rb.rb_utils.twoQ_clifford_error(ngates,gate_qubits,gate_errs) print("Predicted 2Q Error per Clifford: %e"%pred_epc)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. # pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module # pylint: disable=attribute-defined-outside-init,unsubscriptable-object import os from qiskit import QuantumCircuit from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.providers.fake_provider import GenericBackendV2 from qiskit.transpiler import CouplingMap from qiskit import qasm2 class UtilityScaleBenchmarks: params = ["cx", "cz", "ecr"] param_names = ["2q gate"] def setup(self, basis_gate): cmap = CouplingMap.from_heavy_hex(9) basis_gates = ["rz", "x", "sx", basis_gate, "id"] backend = GenericBackendV2( cmap.size(), basis_gates, coupling_map=cmap, control_flow=True, seed=12345678942 ) self.pm = generate_preset_pass_manager(2, backend, seed_transpiler=1234567845) qasm_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "qasm") self.qft_qasm = os.path.join(qasm_dir, "qft_N100.qasm") self.qft_qc = QuantumCircuit.from_qasm_file(self.qft_qasm) self.square_heisenberg_qasm = os.path.join(qasm_dir, "square_heisenberg_N100.qasm") self.square_heisenberg_qc = QuantumCircuit.from_qasm_file(self.square_heisenberg_qasm) self.qaoa_qasm = os.path.join(qasm_dir, "qaoa_barabasi_albert_N100_3reps.qasm") self.qaoa_qc = QuantumCircuit.from_qasm_file(self.qaoa_qasm) def time_parse_qft_n100(self, _): qasm2.load( self.qft_qasm, include_path=qasm2.LEGACY_INCLUDE_PATH, custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS, custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL, strict=False, ) def time_parse_square_heisenberg_n100(self, _): qasm2.load( self.square_heisenberg_qasm, include_path=qasm2.LEGACY_INCLUDE_PATH, custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS, custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL, strict=False, ) def time_parse_qaoa_n100(self, _): qasm2.load( self.qaoa_qasm, include_path=qasm2.LEGACY_INCLUDE_PATH, custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS, custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL, strict=False, ) def time_qft(self, _): self.pm.run(self.qft_qc) def track_qft_depth(self, basis_gate): res = self.pm.run(self.qft_qc) return res.depth(filter_function=lambda x: x.operation.name == basis_gate) def time_square_heisenberg(self, _): self.pm.run(self.square_heisenberg_qc) def track_square_heisenberg_depth(self, basis_gate): res = self.pm.run(self.square_heisenberg_qc) return res.depth(filter_function=lambda x: x.operation.name == basis_gate) def time_qaoa(self, _): self.pm.run(self.qaoa_qc) def track_qaoa_depth(self, basis_gate): res = self.pm.run(self.qaoa_qc) return res.depth(filter_function=lambda x: x.operation.name == basis_gate)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # 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.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # 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) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # 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>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors=scale_factors) print("created zne_qcs (length:", len(zne_qcs), ")") t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") 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 = 1 << 13 reps = 1 # unused # Number of trotter steps print("trotter step: ", num_steps) # execute: reps = 1 job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) # 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, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/swe-train/qiskit__qiskit
swe-train
# -*- 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/2lambda123/Qiskit-qiskit
2lambda123
# 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. """Filter ops from a circuit""" from typing import Callable from qiskit.dagcircuit import DAGCircuit, DAGOpNode from qiskit.transpiler.basepasses import TransformationPass from qiskit.transpiler.passes.utils import control_flow class FilterOpNodes(TransformationPass): """Remove all operations that match a filter function This transformation pass is used to remove any operations that matches a the provided filter function. Args: predicate: A given callable that will be passed the :class:`.DAGOpNode` for each node in the :class:`.DAGCircuit`. If the callable returns ``True`` the :class:`.DAGOpNode` is retained in the circuit and if it returns ``False`` it is removed from the circuit. Example: Filter out operations that are labelled ``"foo"`` .. plot:: :include-source: from qiskit import QuantumCircuit from qiskit.transpiler.passes import FilterOpNodes circuit = QuantumCircuit(1) circuit.x(0, label='foo') circuit.barrier() circuit.h(0) circuit = FilterOpNodes( lambda node: getattr(node.op, "label") != "foo" )(circuit) circuit.draw('mpl') """ def __init__(self, predicate: Callable[[DAGOpNode], bool]): super().__init__() self.predicate = predicate @control_flow.trivial_recurse def run(self, dag: DAGCircuit) -> DAGCircuit: """Run the RemoveBarriers pass on `dag`.""" for node in dag.op_nodes(): if not self.predicate(node): dag.remove_op_node(node) return dag
https://github.com/acfilok96/Quantum-Computation
acfilok96
from qiskit import * qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) %matplotlib inline circuit.draw(output='mpl') circuit.h(qr[0]) circuit.draw(output = 'mpl') circuit.cx(qr[0], qr[1]) circuit.draw(output='mpl') circuit.measure(qr, cr) circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') execute(circuit, backend=simulator) result = execute(circuit, backend=simulator).result() from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) from qiskit import IBMQ MY_API_TOKEN = "b32678329f7f6dd426b8cf18f20bea23c2cd056b0bee2b4bcf49744b612e598f20f7170a8da4bfd99b009b6fa59d596edea7a6926fd388be158843d8e******" IBMQ.save_account(MY_API_TOKEN, overwrite=True) IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider.backends() backend = provider.get_backend('ibmq_santiago') job =execute(circuit, backend= backend) from qiskit.tools.monitor import job_monitor job_monitor(job) result = job.result() # plot_histogram plot_histogram(result.get_counts(circuit))
https://github.com/Qiskit/feedback
Qiskit
import numpy as np from qiskit_dynamics.models import ( HamiltonianModel, LindbladModel, rotating_wave_approximation, ) from qiskit_dynamics.signals import Signal Omega_0 = 0.5 tau = 3 omega_0 = 1 nu = 1/(2*np.pi) #2\pi\nu = \omega_0 Omega = lambda t: Omega_0 * np.exp(-t**2/(2*tau**2)) drive_signal = Signal(Omega,nu,0) drive_operator = np.array([[[0,-1],[-1,0]]]) drift_operator = omega_0*np.array([[1,0],[0,-1]]) model = HamiltonianModel(drive_operator,drift=drift_operator,signals=[drive_signal]) print(model.evaluate(0)) model.set_evaluation_mode("sparse") print(model.evaluate(0)) model.rotating_frame = np.array([1,-1]) print(model(0)) rwa_model = rotating_wave_approximation(model, cutoff_freq=1/4) print(np.round(rwa_model(0),6)) model.rotating_frame = np.array([1,-1]) dis_op = np.array([[[0,0],[1,0]]]) rho = np.diag([1,0]) # excited state dis_model = LindbladModel.from_hamiltonian(model, dissipator_operators=dis_op, dissipator_signals=[1], evaluation_mode="dense") print(help(dis_model.set_evaluation_mode)) dis_model.set_evaluation_mode('dense') print(dis_model.evaluate_hamiltonian(0)) print(dis_model(0,rho)) dis_model.set_evaluation_mode('sparse') print(dis_model.evaluate_hamiltonian(0)) print(dis_model(0,rho)) rho_vec = rho.flatten(order="F") # vectorized operator using column stacking convention dis_model.set_evaluation_mode('dense_vectorized') print(dis_model(0)) print(dis_model(0) @ rho_vec) print(dis_model(0,rho_vec)) sig_vals = model.signals(0) model.set_evaluation_mode("dense") operator_collection = model._operator_collection print(type(operator_collection)) print(operator_collection.evaluate(sig_vals)) model.set_evaluation_mode("sparse") operator_collection = model._operator_collection print(type(operator_collection)) print(operator_collection.evaluate(sig_vals))
https://github.com/arnavdas88/QuGlassyIsing
arnavdas88
!pip install qiskit J = 4.0 B_x = 2.0 B_z = 0.0 import numpy as np from qiskit.providers.aer import AerSimulator, QasmSimulator from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.aqua.operators import * from qiskit.aqua import set_qiskit_aqua_logging, QuantumInstance from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE, NumPyEigensolver from qiskit.circuit import QuantumCircuit, ParameterVector from qiskit.visualization import plot_histogram Hamiltonian = J * (Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z) - B_z * (( Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ) ) - B_x * ( ( X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X )) ansatz = TwoLocal(num_qubits=36, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True) print(ansatz) backend = AerSimulator(method='matrix_product_state') quantum_instance = QuantumInstance(backend, shots = 8192, initial_layout = None, optimization_level = 3) optimizer = COBYLA(maxiter=10000, tol=0.000000001) vqe = VQE(Hamiltonian, ansatz, optimizer, include_custom = False) print('We are using:', quantum_instance.backend) vqe_result = vqe.run(quantum_instance) print(vqe['result']) plot_histogram(vqe_result['eigenstate']) import pickle filename = "2D_Ising_Model_CountsDIS1.pkl" a = {'vqe_result': vqe_result} #This saves the data with open(filename, 'wb') as handle: pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL) # This loads the data with open(filename, 'rb') as handle: b = pickle.load(handle)
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 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 Grover's algorithm.""" import itertools import unittest from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np from ddt import data, ddt, idata, unpack from qiskit import BasicAer, QuantumCircuit from qiskit_algorithms import AmplificationProblem, Grover from qiskit.circuit.library import GroverOperator, PhaseOracle from qiskit.primitives import Sampler from qiskit.quantum_info import Operator, Statevector from qiskit.utils import QuantumInstance, algorithm_globals from qiskit.utils.optionals import HAS_TWEEDLEDUM @ddt class TestAmplificationProblem(QiskitAlgorithmsTestCase): """Test the amplification problem.""" def setUp(self): super().setUp() oracle = QuantumCircuit(2) oracle.cz(0, 1) self._expected_grover_op = GroverOperator(oracle=oracle) @data("oracle_only", "oracle_and_stateprep") def test_groverop_getter(self, kind): """Test the default construction of the Grover operator.""" oracle = QuantumCircuit(2) oracle.cz(0, 1) if kind == "oracle_only": problem = AmplificationProblem(oracle, is_good_state=["11"]) expected = GroverOperator(oracle) else: stateprep = QuantumCircuit(2) stateprep.ry(0.2, [0, 1]) problem = AmplificationProblem( oracle, state_preparation=stateprep, is_good_state=["11"] ) expected = GroverOperator(oracle, stateprep) self.assertEqual(Operator(expected), Operator(problem.grover_operator)) @data("list_str", "list_int", "statevector", "callable") def test_is_good_state(self, kind): """Test is_good_state works on different input types.""" if kind == "list_str": is_good_state = ["01", "11"] elif kind == "list_int": is_good_state = [1] # means bitstr[1] == '1' elif kind == "statevector": is_good_state = Statevector(np.array([0, 1, 0, 1]) / np.sqrt(2)) else: def is_good_state(bitstr): # same as ``bitstr in ['01', '11']`` return bitstr[1] == "1" possible_states = [ "".join(list(map(str, item))) for item in itertools.product([0, 1], repeat=2) ] oracle = QuantumCircuit(2) problem = AmplificationProblem(oracle, is_good_state=is_good_state) expected = [state in ["01", "11"] for state in possible_states] actual = [problem.is_good_state(state) for state in possible_states] self.assertListEqual(expected, actual) @ddt class TestGrover(QiskitAlgorithmsTestCase): """Test for the functionality of Grover""" def setUp(self): super().setUp() with self.assertWarns(DeprecationWarning): self.statevector = QuantumInstance( BasicAer.get_backend("statevector_simulator"), seed_simulator=12, seed_transpiler=32 ) self.qasm = QuantumInstance( BasicAer.get_backend("qasm_simulator"), seed_simulator=12, seed_transpiler=32 ) self._sampler = Sampler() self._sampler_with_shots = Sampler(options={"shots": 1024, "seed": 123}) algorithm_globals.random_seed = 123 @unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test") @data("ideal", "shots", False) def test_implicit_phase_oracle_is_good_state(self, use_sampler): """Test implicit default for is_good_state with PhaseOracle.""" grover = self._prepare_grover(use_sampler) oracle = PhaseOracle("x & y") problem = AmplificationProblem(oracle) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "11") @idata(itertools.product(["ideal", "shots", False], [[1, 2, 3], None, 2])) @unpack def test_iterations_with_good_state(self, use_sampler, iterations): """Test the algorithm with different iteration types and with good state""" grover = self._prepare_grover(use_sampler, iterations) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @idata(itertools.product(["shots", False], [[1, 2, 3], None, 2])) @unpack def test_iterations_with_good_state_sample_from_iterations(self, use_sampler, iterations): """Test the algorithm with different iteration types and with good state""" grover = self._prepare_grover(use_sampler, iterations, sample_from_iterations=True) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @data("ideal", "shots", False) def test_fixed_iterations_without_good_state(self, use_sampler): """Test the algorithm with iterations as an int and without good state""" grover = self._prepare_grover(use_sampler, iterations=2) problem = AmplificationProblem(Statevector.from_label("111")) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @idata(itertools.product(["ideal", "shots", False], [[1, 2, 3], None])) @unpack def test_iterations_without_good_state(self, use_sampler, iterations): """Test the correct error is thrown for none/list of iterations and without good state""" grover = self._prepare_grover(use_sampler, iterations=iterations) problem = AmplificationProblem(Statevector.from_label("111")) with self.assertRaisesRegex( TypeError, "An is_good_state function is required with the provided oracle" ): if not use_sampler: with self.assertWarns(DeprecationWarning): grover.amplify(problem) else: grover.amplify(problem) @data("ideal", "shots", False) def test_iterator(self, use_sampler): """Test running the algorithm on an iterator.""" # step-function iterator def iterator(): wait, value, count = 3, 1, 0 while True: yield value count += 1 if count % wait == 0: value += 1 grover = self._prepare_grover(use_sampler, iterations=iterator()) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @data("ideal", "shots", False) def test_growth_rate(self, use_sampler): """Test running the algorithm on a growth rate""" grover = self._prepare_grover(use_sampler, growth_rate=8 / 7) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @data("ideal", "shots", False) def test_max_num_iterations(self, use_sampler): """Test the iteration stops when the maximum number of iterations is reached.""" def zero(): while True: yield 0 grover = self._prepare_grover(use_sampler, iterations=zero()) n = 5 problem = AmplificationProblem(Statevector.from_label("1" * n), is_good_state=["1" * n]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(len(result.iterations), 2**n) @data("ideal", "shots", False) def test_max_power(self, use_sampler): """Test the iteration stops when the maximum power is reached.""" lam = 10.0 grover = self._prepare_grover(use_sampler, growth_rate=lam) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) result = grover.amplify(problem) self.assertEqual(len(result.iterations), 0) @data("ideal", "shots", False) def test_run_circuit_oracle(self, use_sampler): """Test execution with a quantum circuit oracle""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) grover = self._prepare_grover(use_sampler) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) @data("ideal", "shots", False) def test_run_state_vector_oracle(self, use_sampler): """Test execution with a state vector oracle""" mark_state = Statevector.from_label("11") problem = AmplificationProblem(mark_state, is_good_state=["11"]) grover = self._prepare_grover(use_sampler) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) @data("ideal", "shots", False) def test_run_custom_grover_operator(self, use_sampler): """Test execution with a grover operator oracle""" oracle = QuantumCircuit(2) oracle.cz(0, 1) grover_op = GroverOperator(oracle) problem = AmplificationProblem( oracle=oracle, grover_operator=grover_op, is_good_state=["11"] ) grover = self._prepare_grover(use_sampler) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) def test_optimal_num_iterations(self): """Test optimal_num_iterations""" num_qubits = 7 for num_solutions in range(1, 2**num_qubits): amplitude = np.sqrt(num_solutions / 2**num_qubits) expected = round(np.arccos(amplitude) / (2 * np.arcsin(amplitude))) actual = Grover.optimal_num_iterations(num_solutions, num_qubits) self.assertEqual(actual, expected) def test_construct_circuit(self): """Test construct_circuit""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) grover = Grover() constructed = grover.construct_circuit(problem, 2, measurement=False) grover_op = GroverOperator(oracle) expected = QuantumCircuit(2) expected.h([0, 1]) expected.compose(grover_op.power(2), inplace=True) self.assertTrue(Operator(constructed).equiv(Operator(expected))) @data("ideal", "shots", False) def test_circuit_result(self, use_sampler): """Test circuit_result""" oracle = QuantumCircuit(2) oracle.cz(0, 1) # is_good_state=['00'] is intentionally selected to obtain a list of results problem = AmplificationProblem(oracle, is_good_state=["00"]) grover = self._prepare_grover(use_sampler, iterations=[1, 2, 3, 4]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) if use_sampler: for i, dist in enumerate(result.circuit_results): keys, values = zip(*sorted(dist.items())) if i in (0, 3): self.assertTupleEqual(keys, ("11",)) np.testing.assert_allclose(values, [1], atol=0.2) else: self.assertTupleEqual(keys, ("00", "01", "10", "11")) np.testing.assert_allclose(values, [0.25, 0.25, 0.25, 0.25], atol=0.2) else: expected_results = [ {"11": 1024}, {"00": 238, "01": 253, "10": 263, "11": 270}, {"00": 238, "01": 253, "10": 263, "11": 270}, {"11": 1024}, ] self.assertEqual(result.circuit_results, expected_results) @data("ideal", "shots", False) def test_max_probability(self, use_sampler): """Test max_probability""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) grover = self._prepare_grover(use_sampler) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertAlmostEqual(result.max_probability, 1.0) @unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test") @data("ideal", "shots", False) def test_oracle_evaluation(self, use_sampler): """Test oracle_evaluation for PhaseOracle""" oracle = PhaseOracle("x1 & x2 & (not x3)") problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring) grover = self._prepare_grover(use_sampler) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertTrue(result.oracle_evaluation) self.assertEqual("011", result.top_measurement) def test_sampler_setter(self): """Test sampler setter""" grover = Grover() grover.sampler = self._sampler self.assertEqual(grover.sampler, self._sampler) def _prepare_grover( self, use_sampler, iterations=None, growth_rate=None, sample_from_iterations=False ): """Prepare Grover instance for test""" if use_sampler == "ideal": grover = Grover( sampler=self._sampler, iterations=iterations, growth_rate=growth_rate, sample_from_iterations=sample_from_iterations, ) elif use_sampler == "shots": grover = Grover( sampler=self._sampler_with_shots, iterations=iterations, growth_rate=growth_rate, sample_from_iterations=sample_from_iterations, ) else: with self.assertWarns(DeprecationWarning): grover = Grover( quantum_instance=self.qasm, iterations=iterations, growth_rate=growth_rate, sample_from_iterations=sample_from_iterations, ) return grover if __name__ == "__main__": unittest.main()
https://github.com/ctuning/ck-qiskit
ctuning
# -*- coding: utf-8 -*- # Copyright 2017, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. """ The eval_hamiltonian function has been borrowed from QISKit's tools/apps/optimization.py and slightly modified by dividiti to fit our benchmarking needs. """ import uuid import copy import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.extensions.standard import h, x, y, z from qiskit.tools.apps.optimization import make_Hamiltonian, group_paulis, measure_pauli_z def eval_hamiltonian(Q_program, hamiltonian, input_circuit, shots, device, timeout=60): """Calculates the average value of a Hamiltonian on a state created by the input circuit Args: Q_program (QuantumProgram): QuantumProgram object used to run the input circuit. hamiltonian (array or matrix or list): a representation of the Hamiltonian or observables to be measured. If it is a list, it is a list of Pauli operators grouped into tpb sets. input_circuit (QuantumCircuit): input circuit. shots (int): number of shots considered in the averaging. If 1 the averaging is exact. device (str): the backend used to run the simulation. Returns: float: Average value of the Hamiltonian or observable. """ energy = 0 q_execution_times = [] if 'statevector' in device: # Hamiltonian is not a pauli_list grouped into tpb sets if not isinstance(hamiltonian, list): circuit = ['c' + str(uuid.uuid4())] # unique random circuit for no collision Q_program.add_circuit(circuit[0], input_circuit) result = Q_program.execute(circuit, device, shots=shots, timeout=timeout, config={"data": ["statevector"]}) statevector = result.get_data(circuit[0]).get('statevector') if statevector is None: statevector = result.get_data( circuit[0]).get('statevector') if statevector: statevector = statevector[0] # Diagonal Hamiltonian represented by 1D array if (hamiltonian.shape[0] == 1 or np.shape(np.shape(np.array(hamiltonian))) == (1,)): energy = np.sum(hamiltonian * np.absolute(statevector) ** 2) # Hamiltonian represented by square matrix elif hamiltonian.shape[0] == hamiltonian.shape[1]: energy = np.inner(np.conjugate(statevector), np.dot(hamiltonian, statevector)) # Hamiltonian represented by a Pauli list else: circuits = [] circuits_labels = [] circuits.append(input_circuit) # Trial circuit w/o the final rotations circuits_labels.append('circuit_label0' + str(uuid.uuid4())) Q_program.add_circuit(circuits_labels[0], circuits[0]) # Execute trial circuit with final rotations for each Pauli in # hamiltonian and store from circuits[1] on n_qubits = input_circuit.regs['q'].size q = QuantumRegister(n_qubits, "q") i = 1 for p in hamiltonian: circuits.append(copy.deepcopy(input_circuit)) for j in range(n_qubits): if p[1].v[j] == 0 and p[1].w[j] == 1: circuits[i].x(q[j]) elif p[1].v[j] == 1 and p[1].w[j] == 0: circuits[i].z(q[j]) elif p[1].v[j] == 1 and p[1].w[j] == 1: circuits[i].y(q[j]) circuits_labels.append('circuit_label' + str(i) + str(uuid.uuid4())) Q_program.add_circuit(circuits_labels[i], circuits[i]) i += 1 result = Q_program.execute(circuits_labels, device, shots=shots, timeout=timeout) # no Pauli final rotations statevector_0 = result.get_data( circuits_labels[0])['statevector'] i = 1 for p in hamiltonian: statevector_i = result.get_data( circuits_labels[i])['statevector'] # inner product with final rotations of (i-1)-th Pauli energy += p[0] * np.inner(np.conjugate(statevector_0), statevector_i) i += 1 # finite number of shots and hamiltonian grouped in tpb sets else: circuits = [] circuits_labels = [] n = int(len(hamiltonian[0][0][1].v)) q = QuantumRegister(n, "q") c = ClassicalRegister(n, "c") i = 0 for tpb_set in hamiltonian: circuits.append(copy.deepcopy(input_circuit)) circuits_labels.append('tpb_circuit_' + str(i) + str(uuid.uuid4())) for j in range(n): # Measure X if tpb_set[0][1].v[j] == 0 and tpb_set[0][1].w[j] == 1: circuits[i].h(q[j]) # Measure Y elif tpb_set[0][1].v[j] == 1 and tpb_set[0][1].w[j] == 1: circuits[i].s(q[j]).inverse() circuits[i].h(q[j]) circuits[i].measure(q[j], c[j]) Q_program.add_circuit(circuits_labels[i], circuits[i]) i += 1 result = Q_program.execute(circuits_labels, device, shots=shots, timeout=timeout) for j, _ in enumerate(hamiltonian): # print( "Q execution data [{}] = {}".format(j, result.get_data(circuits_labels[j]))) q_execution_time = result.get_data(circuits_labels[j]).get('time') if q_execution_time: q_execution_times.append( q_execution_time ) for k, _ in enumerate(hamiltonian[j]): energy += hamiltonian[j][k][0] *\ measure_pauli_z(result.get_counts( circuits_labels[j]), hamiltonian[j][k][1]) return energy, q_execution_times
https://github.com/Ilan-Bondarevsky/qiskit_algorithm
Ilan-Bondarevsky
import sys import os current_dir = os.getcwd() sys.path.append(current_dir) from quantum_circuit import QuantumCircuit from qiskit import QuantumRegister, AncillaRegister from bit_functions import full_bitfield, get_qubit_list from Grover.grover_cirq import grover_circuit class find_num(grover_circuit): def __init__(self): super().__init__() @staticmethod def num_oracle(nqubits: int, winner_num : int) -> QuantumCircuit: bit_list = full_bitfield(winner_num, nqubits)[::-1] if nqubits < len(bit_list): raise Exception("The number needs more qubits!") index_list = [(index, int(not val)) for index, val in enumerate(bit_list)] qc = grover_circuit.oracle(nqubits, set_change_value=index_list) qc.name = f"Num_Oracle ({winner_num})" return qc @staticmethod def series_num_oracle(nqubits : int, winner_list :list , block_diagram = True) -> QuantumCircuit: qc = QuantumCircuit(nqubits) for num in winner_list: cur_qc = find_num.num_oracle(nqubits, num) if block_diagram: qc.append(cur_qc, qc.qubits) else: qc.barrier(qc.qubits) qc = qc.compose(cur_qc, qc.qubits) qc.barrier(qc.qubits) qc.name = f"Oracle {list(winner_list)}" return qc def calculation_logic(self) -> QuantumCircuit: pass def build_iteration(self, winner_num_list : list | int = [], circuit_nqubits : int = 0, block_diagram=True) -> None: ''' Build the iteration for the Grover circuit for the winner list :param circuit_nqubits = The number of qubits in the circuits (Minimum the vnumber needed for max value in the winner list) ''' if not isinstance(winner_num_list,list): winner_num_list = [winner_num_list] if not len(winner_num_list): raise Exception("Winner list is empty!") max_winner_qubit_needed = len(full_bitfield(max(winner_num_list))) circuit_nqubits = max(max_winner_qubit_needed, circuit_nqubits) qc = find_num.series_num_oracle(circuit_nqubits, winner_num_list, block_diagram) qubits = get_qubit_list(qc) diffuser_qc = grover_circuit.diffuser(len(qubits)) qc.add_register(diffuser_qc.ancillas) if block_diagram: qc.append(diffuser_qc, qubits + list(diffuser_qc.ancillas)) else: qc.barrier(qc.qubits) qc = qc.compose(diffuser_qc, qubits + list(diffuser_qc.ancillas)) qc.barrier(qc.qubits) qc.name = "Grover_Find_Num_Iteration" self.iteration_qc = qc class find_num_list(grover_circuit): def __init__(self): super().__init__() def __index_data_cirq(self, index : int, value : int, index_nqubits : int, value_nqubits : int) -> QuantumCircuit: ''' Build a circuit to check a specific index and its value\n For 0, It will use X gates and cx gates for every value ''' #https://arxiv.org/pdf/1502.04943.pdf qc = QuantumCircuit(QuantumRegister(index_nqubits, 'index'), AncillaRegister(value_nqubits, 'value')) index_bit_field = full_bitfield(index, index_nqubits)[::-1] value_bit_field = full_bitfield(value, value_nqubits)[::-1] for i in [i for i, _ in enumerate(index_bit_field) if not index_bit_field[i]]: qc.x(i) for bit in [i for i, _ in enumerate(value_bit_field) if value_bit_field[i]]: qc.mcx(list(range(len(index_bit_field))), qc.ancillas[bit]) for i in [i for i, _ in enumerate(index_bit_field) if not index_bit_field[i]]: qc.x(i) qc.name = f"[I = {index}, Val = {value}]" return qc def calculation_logic(self, num_array : list = [], block_diagram : bool = True) -> None: ''' Return a Calculation Circuit for the find_num_list Grover circuit. ''' if num_array is None or not len(num_array): return data_qc = QuantumCircuit( QuantumRegister(len(full_bitfield(len(num_array) - 1)), 'index'), AncillaRegister(len(full_bitfield(max(num_array))), 'data') ) value_qubit_length = len(data_qc.ancillas) index_qubit_length = len(get_qubit_list(data_qc)) for index, data in enumerate(num_array): if block_diagram: data_qc.append(self.__index_data_cirq(index, data, index_qubit_length, value_qubit_length), data_qc.qubits) else: data_qc.barrier(data_qc.qubits) data_qc = data_qc.compose(self.__index_data_cirq(index, data, index_qubit_length, value_qubit_length), data_qc.qubits) data_qc.name = f"Data {num_array}" self.calculation_qc = data_qc def build_iteration(self, winner_list = [], num_array : list = [], block_diagram=True, default_value:int = 0): ''' Build a iteration for the Find_Num_In_List Grover circuit : param default_value is the default number in winner list, can search for it ONLY when the list is the length of 2 powered by N ''' if not len(num_array): raise Exception(f"The number array is empty!") if not len(winner_list): raise Exception(f"The winner list is empty!") if default_value in winner_list and pow(2, (len(num_array) - 1).bit_length()) != len(num_array): raise Exception(f"The winner list has a value of {default_value} when the number list is not the size of 2 powered by an N") self.calculation_logic(num_array, block_diagram) qc = QuantumCircuit(self.calculation_qc.qubits) if block_diagram: qc.append(self.calculation_qc, qc.qubits) oracle = find_num.series_num_oracle(len(qc.ancillas), winner_list, block_diagram) qc.append(oracle, qc.ancillas) qc.append(self.calculation_qc.inverse(), qc.qubits) else: qc = qc.compose(self.calculation_qc, qc.qubits) qc.barrier(qc.qubits) oracle = find_num.series_num_oracle(len(qc.ancillas), winner_list, block_diagram) qc = qc.compose(oracle, qc.ancillas) qc.barrier(qc.qubits) qc = qc.compose(self.calculation_qc.inverse(), qc.qubits) qubits = get_qubit_list(qc) diffuser_qc = grover_circuit.diffuser(len(qubits)) qc.add_register(diffuser_qc.ancillas) if block_diagram: qc.append(diffuser_qc, qubits + list(diffuser_qc.ancillas)) else: qc.barrier(qc.qubits) qc = qc.compose(diffuser_qc, qubits + list(diffuser_qc.ancillas)) qc.barrier(qc.qubits) qc.name = "Grover_Find_Num_List_Iteration" self.iteration_qc = qc if __name__ == "__main__": x = find_num() x.build_iteration([5], 4, block_diagram=False) x.create_grover(num_solutions=1,block_diagram=False) print(x.measure_qc[0].draw()) x = find_num_list() x.build_iteration(winner_list=[5],num_array = [2,5,3,1], block_diagram=False) x.create_grover(num_solutions=1,block_diagram=False) print(x.measure_qc[0].draw())
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit qc = QuantumCircuit(12) for idx in range(5): qc.h(idx) qc.cx(idx, idx+5) qc.cx(1, 7) qc.x(8) qc.cx(1, 9) qc.x(7) qc.cx(1, 11) qc.swap(6, 11) qc.swap(6, 9) qc.swap(6, 10) qc.x(6) qc.draw('mpl')
https://github.com/rigetti/qiskit-rigetti
rigetti
############################################################################## # Copyright 2021 Rigetti Computing # # 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 pytest from qiskit import execute, QuantumCircuit, QuantumRegister, ClassicalRegister, transpile from qiskit.providers import JobStatus from qiskit.circuit import Parameter, Qubit from qiskit.circuit.library import CZGate from qiskit_rigetti import RigettiQCSProvider, RigettiQCSBackend, QuilCircuit from qiskit_rigetti.gates import XYGate def test_run(backend: RigettiQCSBackend): circuit = make_circuit() job = execute(circuit, backend, shots=10) assert job.backend() is backend result = job.result() assert job.status() == JobStatus.DONE assert result.backend_name == backend.configuration().backend_name assert result.results[0].header.name == circuit.name assert result.results[0].shots == 10 assert result.get_counts().keys() == {"00"} def test_run__multiple_circuits(backend: RigettiQCSBackend): circuit1 = make_circuit(num_qubits=2) circuit2 = make_circuit(num_qubits=3) job = execute([circuit1, circuit2], backend, shots=10) assert job.backend() is backend result = job.result() assert job.status() == JobStatus.DONE assert result.backend_name == backend.configuration().backend_name assert len(result.results) == 2 assert result.results[0].header.name == circuit1.name assert result.results[0].shots == 10 assert result.get_counts(0).keys() == {"00"} assert result.results[1].header.name == circuit2.name assert result.results[1].shots == 10 assert result.get_counts(1).keys() == {"000"} def test_run__parametric_circuits(backend: RigettiQCSBackend): t = Parameter("t") circuit1 = QuantumCircuit(QuantumRegister(1, "q"), ClassicalRegister(1, "ro")) circuit1.rx(t, 0) circuit1.measure([0], [0]) circuit2 = QuantumCircuit(QuantumRegister(1, "q"), ClassicalRegister(1, "ro")) circuit2.ry(t, 0) circuit2.measure([0], [0]) job = execute( [circuit1, circuit2], backend, shots=1000, parameter_binds=[ {t: 1.0}, {t: 2.0}, ], ) assert job.backend() is backend result = job.result() assert job.status() == JobStatus.DONE assert result.backend_name == backend.configuration().backend_name assert len(result.results) == 4 assert result.results[0].shots == 1000 assert result.get_counts(0).keys() == {"0", "1"} assert result.results[1].shots == 1000 assert result.get_counts(1).keys() == {"0", "1"} assert result.results[2].shots == 1000 assert result.get_counts(2).keys() == {"0", "1"} assert result.results[3].shots == 1000 assert result.get_counts(3).keys() == {"0", "1"} def test_run__readout_register_not_named_ro(backend: RigettiQCSBackend): circuit = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "not_ro")) circuit.measure([0, 1], [0, 1]) qasm_before = circuit.qasm() job = execute(circuit, backend, shots=10) assert circuit.qasm() == qasm_before, "should not modify original circuit" assert job.backend() is backend result = job.result() assert job.status() == JobStatus.DONE assert result.backend_name == backend.configuration().backend_name assert result.results[0].header.name == circuit.name assert result.results[0].shots == 10 assert result.get_counts().keys() == {"00"} def test_run__multiple_registers__single_readout(backend: RigettiQCSBackend): readout_reg = ClassicalRegister(2, "not_ro") circuit = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c"), readout_reg) circuit.measure([0, 1], [readout_reg[0], readout_reg[1]]) qasm_before = circuit.qasm() job = execute(circuit, backend, shots=10) assert circuit.qasm() == qasm_before, "should not modify original circuit" assert job.backend() is backend result = job.result() assert job.status() == JobStatus.DONE assert result.backend_name == backend.configuration().backend_name assert result.results[0].header.name == circuit.name assert result.results[0].shots == 10 assert result.get_counts().keys() == {"00"} def test_run__multiple_readout_registers(backend: RigettiQCSBackend): qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") cr2 = ClassicalRegister(1, "c2") circuit = QuantumCircuit(qr, cr, cr2) circuit.measure([qr[0], qr[1]], [cr[0], cr2[0]]) with pytest.raises(RuntimeError, match="Multiple readout registers are unsupported on QCSBackend; found c, c2"): execute(circuit, backend, shots=10) def test_run__no_measurments(backend: RigettiQCSBackend): qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) with pytest.raises(RuntimeError, match="Circuit has no measurements"): execute(circuit, backend, shots=10) def test_run__backend_coupling_map(): backend = RigettiQCSProvider().get_simulator(num_qubits=3) assert backend.configuration().coupling_map assert [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)] == sorted(backend.configuration().coupling_map) assert [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)] == sorted(backend.coupling_map.get_edges()) def test_decomposition(backend: RigettiQCSBackend): """Test that CZGate remains after the transpile.""" circuit = QuilCircuit(2, 2) circuit.cz(0, 1) circuit.measure_all() circuit = transpile(circuit, backend=backend) job = execute(circuit, backend, shots=1) job.result() # Just make sure nothing throws an exception so the circuit is valid assert job.status() == JobStatus.DONE assert len(circuit.data) == 4 # CZ, BARRIER, MEASURE, MEASURE assert circuit.data[0][0] == CZGate() @pytest.fixture def backend(): return RigettiQCSProvider().get_simulator(num_qubits=3) def make_circuit(*, num_qubits: int = 2): circuit = QuantumCircuit(QuantumRegister(num_qubits, "q"), ClassicalRegister(num_qubits, "ro")) circuit.measure(list(range(num_qubits)), list(range(num_qubits))) return circuit
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
p = 0.2 import numpy as np from qiskit.circuit import QuantumCircuit class BernoulliA(QuantumCircuit): """A circuit representing the Bernoulli A operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(theta_p, 0) class BernoulliQ(QuantumCircuit): """A circuit representing the Bernoulli Q operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit self._theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(2 * self._theta_p, 0) def power(self, k): # implement the efficient power of Q q_k = QuantumCircuit(1) q_k.ry(2 * k * self._theta_p, 0) return q_k A = BernoulliA(p) Q = BernoulliQ(p) from qiskit.algorithms import EstimationProblem problem = EstimationProblem( state_preparation=A, # A operator grover_operator=Q, # Q operator objective_qubits=[0], # the "good" state Psi1 is identified as measuring |1> in qubit 0 ) from qiskit.primitives import Sampler sampler = Sampler() from qiskit.algorithms import AmplitudeEstimation ae = AmplitudeEstimation( num_eval_qubits=3, # the number of evaluation qubits specifies circuit width and accuracy sampler=sampler, ) ae_result = ae.estimate(problem) print(ae_result.estimation) import matplotlib.pyplot as plt # plot estimated values gridpoints = list(ae_result.samples.keys()) probabilities = list(ae_result.samples.values()) plt.bar(gridpoints, probabilities, width=0.5 / len(probabilities)) plt.axvline(p, color="r", ls="--") plt.xticks(size=15) plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15) plt.title("Estimated Values", size=15) plt.ylabel("Probability", size=15) plt.xlabel(r"Amplitude $a$", size=15) plt.ylim((0, 1)) plt.grid() plt.show() print("Interpolated MLE estimator:", ae_result.mle) ae_circuit = ae.construct_circuit(problem) ae_circuit.decompose().draw( "mpl", style="iqx" ) # decompose 1 level: exposes the Phase estimation circuit! from qiskit import transpile basis_gates = ["h", "ry", "cry", "cx", "ccx", "p", "cp", "x", "s", "sdg", "y", "t", "cz"] transpile(ae_circuit, basis_gates=basis_gates, optimization_level=2).draw("mpl", style="iqx") from qiskit.algorithms import IterativeAmplitudeEstimation iae = IterativeAmplitudeEstimation( epsilon_target=0.01, # target accuracy alpha=0.05, # width of the confidence interval sampler=sampler, ) iae_result = iae.estimate(problem) print("Estimate:", iae_result.estimation) iae_circuit = iae.construct_circuit(problem, k=3) iae_circuit.draw("mpl", style="iqx") from qiskit.algorithms import MaximumLikelihoodAmplitudeEstimation mlae = MaximumLikelihoodAmplitudeEstimation( evaluation_schedule=3, # log2 of the maximal Grover power sampler=sampler, ) mlae_result = mlae.estimate(problem) print("Estimate:", mlae_result.estimation) from qiskit.algorithms import FasterAmplitudeEstimation fae = FasterAmplitudeEstimation( delta=0.01, # target accuracy maxiter=3, # determines the maximal power of the Grover operator sampler=sampler, ) fae_result = fae.estimate(problem) print("Estimate:", fae_result.estimation) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(range(2)) qc.measure(range(2), range(2)) # apply x gate if the classical register has the value 2 (10 in binary) qc.x(0).c_if(cr, 2) # apply y gate if bit 0 is set to 1 qc.y(1).c_if(0, 1) qc.draw('mpl')
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!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/derivation/ThinkQuantum
derivation
import numpy as np from numpy import pi import matplotlib.pyplot as plt import matplotlib.image as mpimg from skimage.transform import resize filename = './schrodin_yang.png' im = mpimg.imread(filename) n_pixels = 2**5 im = resize(im, (n_pixels, n_pixels)) data = im[:,:,0].ravel() fig, ax = plt.subplots() ax.imshow(im) n_qubits = int(np.log2(len(data))) from qiskit_aqua.components.initial_states import Custom init_state = Custom(n_qubits, state_vector=data) circ = init_state.construct_circuit('circuit') qr = circ.qregs # circ.draw() circ.h(qr[0][0]) from qiskit import BasicAer, execute simulator = BasicAer.get_backend('statevector_simulator') sim_result = execute(circ, simulator).result() final_state = sim_result.get_statevector(circ) edge = np.real(final_state) n_rows = int(np.sqrt(len(edge))) n_cols = n_rows edge = edge.reshape(n_rows, n_cols) edge[:,::2] = 0 fig, ax = plt.subplots(1,2) ax[0].imshow(edge) ax[1].imshow(im)
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/swe-bench/Qiskit__qiskit
swe-bench
# 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. """Test the VF2Layout pass""" import rustworkx from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit import ControlFlowOp from qiskit.circuit.library import CXGate, XGate from qiskit.transpiler import CouplingMap, Layout, TranspilerError from qiskit.transpiler.passes.layout.vf2_post_layout import VF2PostLayout, VF2PostLayoutStopReason from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeLima, FakeYorktown, FakeLimaV2, FakeYorktownV2 from qiskit.circuit import Qubit from qiskit.compiler.transpiler import transpile from qiskit.transpiler.target import Target, InstructionProperties class TestVF2PostLayout(QiskitTestCase): """Tests the VF2Layout pass""" seed = 42 def assertLayout(self, dag, coupling_map, property_set): """Checks if the circuit in dag was a perfect layout in property_set for the given coupling_map""" self.assertEqual( property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.SOLUTION_FOUND ) layout = property_set["post_layout"] edges = coupling_map.graph.edge_list() def run(dag, wire_map): for gate in dag.two_qubit_ops(): if dag.has_calibration_for(gate) or isinstance(gate.op, ControlFlowOp): continue physical_q0 = wire_map[gate.qargs[0]] physical_q1 = wire_map[gate.qargs[1]] self.assertTrue((physical_q0, physical_q1) in edges) for node in dag.op_nodes(ControlFlowOp): for block in node.op.blocks: inner_wire_map = { inner: wire_map[outer] for outer, inner in zip(node.qargs, block.qubits) } run(circuit_to_dag(block), inner_wire_map) run(dag, {bit: layout[bit] for bit in dag.qubits if bit in layout}) def assertLayoutV2(self, dag, target, property_set): """Checks if the circuit in dag was a perfect layout in property_set for the given coupling_map""" self.assertEqual( property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.SOLUTION_FOUND ) layout = property_set["post_layout"] def run(dag, wire_map): for gate in dag.two_qubit_ops(): if dag.has_calibration_for(gate) or isinstance(gate.op, ControlFlowOp): continue physical_q0 = wire_map[gate.qargs[0]] physical_q1 = wire_map[gate.qargs[1]] qargs = (physical_q0, physical_q1) self.assertTrue(target.instruction_supported(gate.name, qargs)) for node in dag.op_nodes(ControlFlowOp): for block in node.op.blocks: inner_wire_map = { inner: wire_map[outer] for outer, inner in zip(node.qargs, block.qubits) } run(circuit_to_dag(block), inner_wire_map) run(dag, {bit: layout[bit] for bit in dag.qubits if bit in layout}) def test_no_constraints(self): """Test we raise at runtime if no target or coupling graph specified.""" qc = QuantumCircuit(2) empty_pass = VF2PostLayout() with self.assertRaises(TranspilerError): empty_pass.run(circuit_to_dag(qc)) def test_no_backend_properties(self): """Test we raise at runtime if no properties are provided with a coupling graph.""" qc = QuantumCircuit(2) empty_pass = VF2PostLayout(coupling_map=CouplingMap([(0, 1), (1, 2)])) with self.assertRaises(TranspilerError): empty_pass.run(circuit_to_dag(qc)) def test_empty_circuit(self): """Test no solution found for empty circuit""" qc = QuantumCircuit(2, 2) backend = FakeLima() cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props) vf2_pass.run(circuit_to_dag(qc)) self.assertEqual( vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.NO_SOLUTION_FOUND, ) def test_empty_circuit_v2(self): """Test no solution found for empty circuit with v2 backend""" qc = QuantumCircuit(2, 2) backend = FakeLimaV2() vf2_pass = VF2PostLayout(target=backend.target) vf2_pass.run(circuit_to_dag(qc)) self.assertEqual( vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.NO_SOLUTION_FOUND, ) def test_skip_3q_circuit(self): """Test that the pass is a no-op on circuits with >2q gates.""" qc = QuantumCircuit(3) qc.ccx(0, 1, 2) backend = FakeLima() cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props) vf2_pass.run(circuit_to_dag(qc)) self.assertEqual( vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q ) def test_skip_3q_circuit_control_flow(self): """Test that the pass is a no-op on circuits with >2q gates.""" qc = QuantumCircuit(3) with qc.for_loop((1,)): qc.ccx(0, 1, 2) backend = FakeLima() cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props) vf2_pass.run(circuit_to_dag(qc)) self.assertEqual( vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q ) def test_skip_3q_circuit_v2(self): """Test that the pass is a no-op on circuits with >2q gates with a target.""" qc = QuantumCircuit(3) qc.ccx(0, 1, 2) backend = FakeLimaV2() vf2_pass = VF2PostLayout(target=backend.target) vf2_pass.run(circuit_to_dag(qc)) self.assertEqual( vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q ) def test_skip_3q_circuit_control_flow_v2(self): """Test that the pass is a no-op on circuits with >2q gates with a target.""" qc = QuantumCircuit(3) with qc.for_loop((1,)): qc.ccx(0, 1, 2) backend = FakeLimaV2() vf2_pass = VF2PostLayout(target=backend.target) vf2_pass.run(circuit_to_dag(qc)) self.assertEqual( vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q ) def test_best_mapping_ghz_state_full_device_multiple_qregs(self): """Test best mappings with multiple registers""" backend = FakeLima() qr_a = QuantumRegister(2) qr_b = QuantumRegister(3) qc = QuantumCircuit(qr_a, qr_b) qc.h(qr_a[0]) qc.cx(qr_a[0], qr_a[1]) qc.cx(qr_a[0], qr_b[0]) qc.cx(qr_a[0], qr_b[1]) qc.cx(qr_a[0], qr_b[2]) qc.measure_all() tqc = transpile(qc, backend, seed_transpiler=self.seed, layout_method="trivial") initial_layout = tqc._layout dag = circuit_to_dag(tqc) cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() pass_ = VF2PostLayout(coupling_map=cmap, properties=props, seed=self.seed) pass_.run(dag) self.assertLayout(dag, cmap, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) def test_2q_circuit_5q_backend(self): """A simple example, without considering the direction 0 - 1 qr1 - qr0 """ backend = FakeYorktown() qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 tqc = transpile(circuit, backend, layout_method="dense") initial_layout = tqc._layout dag = circuit_to_dag(tqc) cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() pass_ = VF2PostLayout(coupling_map=cmap, properties=props, seed=self.seed) pass_.run(dag) self.assertLayout(dag, cmap, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) def test_2q_circuit_5q_backend_controlflow(self): """A simple example, without considering the direction 0 - 1 qr1 - qr0 """ backend = FakeYorktown() circuit = QuantumCircuit(2, 1) with circuit.for_loop((1,)): circuit.cx(1, 0) # qr1 -> qr0 with circuit.if_test((circuit.clbits[0], True)) as else_: pass with else_: with circuit.while_loop((circuit.clbits[0], True)): circuit.cx(1, 0) # qr1 -> qr0 initial_layout = Layout(dict(enumerate(circuit.qubits))) circuit._layout = initial_layout dag = circuit_to_dag(circuit) cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() pass_ = VF2PostLayout(coupling_map=cmap, properties=props, seed=self.seed) pass_.run(dag) self.assertLayout(dag, cmap, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) def test_2q_circuit_5q_backend_max_trials(self): """A simple example, without considering the direction 0 - 1 qr1 - qr0 """ max_trials = 11 backend = FakeYorktown() qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 tqc = transpile(circuit, backend, layout_method="dense") initial_layout = tqc._layout dag = circuit_to_dag(tqc) cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() pass_ = VF2PostLayout( coupling_map=cmap, properties=props, seed=self.seed, max_trials=max_trials ) with self.assertLogs( "qiskit.transpiler.passes.layout.vf2_post_layout", level="DEBUG" ) as cm: pass_.run(dag) self.assertIn( f"DEBUG:qiskit.transpiler.passes.layout.vf2_post_layout:Trial {max_trials} " f"is >= configured max trials {max_trials}", cm.output, ) self.assertLayout(dag, cmap, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) def test_best_mapping_ghz_state_full_device_multiple_qregs_v2(self): """Test best mappings with multiple registers""" backend = FakeLimaV2() qr_a = QuantumRegister(2) qr_b = QuantumRegister(3) qc = QuantumCircuit(qr_a, qr_b) qc.h(qr_a[0]) qc.cx(qr_a[0], qr_a[1]) qc.cx(qr_a[0], qr_b[0]) qc.cx(qr_a[0], qr_b[1]) qc.cx(qr_a[0], qr_b[2]) qc.measure_all() tqc = transpile(qc, backend, seed_transpiler=self.seed, layout_method="trivial") initial_layout = tqc._layout dag = circuit_to_dag(tqc) pass_ = VF2PostLayout(target=backend.target, seed=self.seed) pass_.run(dag) self.assertLayoutV2(dag, backend.target, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) def test_2q_circuit_5q_backend_v2(self): """A simple example, without considering the direction 0 - 1 qr1 - qr0 """ backend = FakeYorktownV2() qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 tqc = transpile(circuit, backend, layout_method="dense") initial_layout = tqc._layout dag = circuit_to_dag(tqc) pass_ = VF2PostLayout(target=backend.target, seed=self.seed) pass_.run(dag) self.assertLayoutV2(dag, backend.target, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) def test_2q_circuit_5q_backend_v2_control_flow(self): """A simple example, without considering the direction 0 - 1 qr1 - qr0 """ backend = FakeYorktownV2() circuit = QuantumCircuit(2, 1) with circuit.for_loop((1,)): circuit.cx(1, 0) # qr1 -> qr0 with circuit.if_test((circuit.clbits[0], True)) as else_: pass with else_: with circuit.while_loop((circuit.clbits[0], True)): circuit.cx(1, 0) # qr1 -> qr0 initial_layout = Layout(dict(enumerate(circuit.qubits))) circuit._layout = initial_layout dag = circuit_to_dag(circuit) pass_ = VF2PostLayout(target=backend.target, seed=self.seed) pass_.run(dag) self.assertLayoutV2(dag, backend.target, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) def test_target_invalid_2q_gate(self): """Test that we don't find a solution with a gate outside target.""" backend = FakeYorktownV2() qc = QuantumCircuit(2) qc.ecr(0, 1) dag = circuit_to_dag(qc) pass_ = VF2PostLayout(target=backend.target, seed=self.seed) pass_.run(dag) self.assertEqual( pass_.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.NO_SOLUTION_FOUND, ) def test_target_invalid_2q_gate_control_flow(self): """Test that we don't find a solution with a gate outside target.""" backend = FakeYorktownV2() qc = QuantumCircuit(2) with qc.for_loop((1,)): qc.ecr(0, 1) dag = circuit_to_dag(qc) pass_ = VF2PostLayout(target=backend.target, seed=self.seed) pass_.run(dag) self.assertEqual( pass_.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.NO_SOLUTION_FOUND, ) def test_target_no_error(self): """Test that running vf2layout on a pass against a target with no error rates works.""" n_qubits = 15 target = Target() target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)}) vf2_pass = VF2PostLayout(target=target) circuit = QuantumCircuit(2) circuit.cx(0, 1) dag = circuit_to_dag(circuit) vf2_pass.run(dag) self.assertNotIn("post_layout", vf2_pass.property_set) def test_target_some_error(self): """Test that running vf2layout on a pass against a target with some error rates works.""" n_qubits = 15 target = Target() target.add_instruction( XGate(), {(i,): InstructionProperties(error=0.00123) for i in range(n_qubits)} ) target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)}) vf2_pass = VF2PostLayout(target=target, seed=1234, strict_direction=False) circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) dag = circuit_to_dag(circuit) vf2_pass.run(dag) # No layout selected because nothing will beat initial layout self.assertNotIn("post_layout", vf2_pass.property_set) class TestVF2PostLayoutScoring(QiskitTestCase): """Test scoring heuristic function for VF2PostLayout.""" def test_empty_score(self): """Test error rate is 0 for empty circuit.""" bit_map = {} reverse_bit_map = {} im_graph = rustworkx.PyDiGraph() backend = FakeYorktownV2() vf2_pass = VF2PostLayout(target=backend.target) layout = Layout() score = vf2_pass._score_layout(layout, bit_map, reverse_bit_map, im_graph) self.assertEqual(0, score) def test_all_1q_score(self): """Test error rate for all 1q input.""" bit_map = {Qubit(): 0, Qubit(): 1} reverse_bit_map = {v: k for k, v in bit_map.items()} im_graph = rustworkx.PyDiGraph() im_graph.add_node({"sx": 1}) im_graph.add_node({"sx": 1}) backend = FakeYorktownV2() vf2_pass = VF2PostLayout(target=backend.target) layout = Layout(bit_map) score = vf2_pass._score_layout(layout, bit_map, reverse_bit_map, im_graph) self.assertAlmostEqual(0.002925, score, places=5) class TestVF2PostLayoutUndirected(QiskitTestCase): """Tests the VF2Layout pass""" seed = 42 def assertLayout(self, dag, coupling_map, property_set): """Checks if the circuit in dag was a perfect layout in property_set for the given coupling_map""" self.assertEqual( property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.SOLUTION_FOUND ) layout = property_set["post_layout"] for gate in dag.two_qubit_ops(): if dag.has_calibration_for(gate): continue physical_q0 = layout[gate.qargs[0]] physical_q1 = layout[gate.qargs[1]] self.assertTrue(coupling_map.graph.has_edge(physical_q0, physical_q1)) def assertLayoutV2(self, dag, target, property_set): """Checks if the circuit in dag was a perfect layout in property_set for the given coupling_map""" self.assertEqual( property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.SOLUTION_FOUND ) layout = property_set["post_layout"] for gate in dag.two_qubit_ops(): if dag.has_calibration_for(gate): continue physical_q0 = layout[gate.qargs[0]] physical_q1 = layout[gate.qargs[1]] qargs = (physical_q0, physical_q1) self.assertTrue(target.instruction_supported(gate.name, qargs)) def test_no_constraints(self): """Test we raise at runtime if no target or coupling graph specified.""" qc = QuantumCircuit(2) empty_pass = VF2PostLayout(strict_direction=False) with self.assertRaises(TranspilerError): empty_pass.run(circuit_to_dag(qc)) def test_no_backend_properties(self): """Test we raise at runtime if no properties are provided with a coupling graph.""" qc = QuantumCircuit(2) empty_pass = VF2PostLayout( coupling_map=CouplingMap([(0, 1), (1, 2)]), strict_direction=False ) with self.assertRaises(TranspilerError): empty_pass.run(circuit_to_dag(qc)) def test_empty_circuit(self): """Test no solution found for empty circuit""" qc = QuantumCircuit(2, 2) backend = FakeLima() cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props, strict_direction=False) vf2_pass.run(circuit_to_dag(qc)) self.assertEqual( vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.NO_SOLUTION_FOUND, ) def test_empty_circuit_v2(self): """Test no solution found for empty circuit with v2 backend""" qc = QuantumCircuit(2, 2) backend = FakeLimaV2() vf2_pass = VF2PostLayout(target=backend.target, strict_direction=False) vf2_pass.run(circuit_to_dag(qc)) self.assertEqual( vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.NO_SOLUTION_FOUND, ) def test_skip_3q_circuit(self): """Test that the pass is a no-op on circuits with >2q gates.""" qc = QuantumCircuit(3) qc.ccx(0, 1, 2) backend = FakeLima() cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props, strict_direction=False) vf2_pass.run(circuit_to_dag(qc)) self.assertEqual( vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q ) def test_skip_3q_circuit_v2(self): """Test that the pass is a no-op on circuits with >2q gates with a target.""" qc = QuantumCircuit(3) qc.ccx(0, 1, 2) backend = FakeLimaV2() vf2_pass = VF2PostLayout(target=backend.target, strict_direction=False) vf2_pass.run(circuit_to_dag(qc)) self.assertEqual( vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q ) def test_best_mapping_ghz_state_full_device_multiple_qregs(self): """Test best mappings with multiple registers""" backend = FakeLima() qr_a = QuantumRegister(2) qr_b = QuantumRegister(3) qc = QuantumCircuit(qr_a, qr_b) qc.h(qr_a[0]) qc.cx(qr_a[0], qr_a[1]) qc.cx(qr_a[0], qr_b[0]) qc.cx(qr_a[0], qr_b[1]) qc.cx(qr_a[0], qr_b[2]) qc.measure_all() tqc = transpile(qc, backend, seed_transpiler=self.seed, layout_method="trivial") initial_layout = tqc._layout dag = circuit_to_dag(tqc) cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() pass_ = VF2PostLayout( coupling_map=cmap, properties=props, seed=self.seed, strict_direction=False ) pass_.run(dag) self.assertLayout(dag, cmap, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) def test_2q_circuit_5q_backend(self): """A simple example, without considering the direction 0 - 1 qr1 - qr0 """ backend = FakeYorktown() qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 tqc = transpile(circuit, backend, layout_method="dense") initial_layout = tqc._layout dag = circuit_to_dag(tqc) cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() pass_ = VF2PostLayout( coupling_map=cmap, properties=props, seed=self.seed, strict_direction=False ) pass_.run(dag) self.assertLayout(dag, cmap, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) def test_best_mapping_ghz_state_full_device_multiple_qregs_v2(self): """Test best mappings with multiple registers""" backend = FakeLimaV2() qr_a = QuantumRegister(2) qr_b = QuantumRegister(3) qc = QuantumCircuit(qr_a, qr_b) qc.h(qr_a[0]) qc.cx(qr_a[0], qr_a[1]) qc.cx(qr_a[0], qr_b[0]) qc.cx(qr_a[0], qr_b[1]) qc.cx(qr_a[0], qr_b[2]) qc.measure_all() tqc = transpile(qc, backend, seed_transpiler=self.seed, layout_method="trivial") initial_layout = tqc._layout dag = circuit_to_dag(tqc) pass_ = VF2PostLayout(target=backend.target, seed=self.seed, strict_direction=False) pass_.run(dag) self.assertLayoutV2(dag, backend.target, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) def test_2q_circuit_5q_backend_v2(self): """A simple example, without considering the direction 0 - 1 qr1 - qr0 """ backend = FakeYorktownV2() qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 tqc = transpile(circuit, backend, layout_method="dense") initial_layout = tqc._layout dag = circuit_to_dag(tqc) pass_ = VF2PostLayout(target=backend.target, seed=self.seed, strict_direction=False) pass_.run(dag) self.assertLayoutV2(dag, backend.target, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)
https://github.com/anpaschool/quantum-computing
anpaschool
from qiskit import * from math import pi import numpy as np from qiskit.visualization import * import matplotlib.pyplot as plt from qutip import * q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(0) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(0) qc.h(0) qc.draw(output='mpl') # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() # Show the results print(result.get_unitary(qc, decimals=3)) H = np.array([[ 0.707+0.j, 0.707-0.j],[ 0.707+0.j, -0.707+0.j]]) np.dot(H,H) q = QuantumRegister(1) qc = QuantumCircuit(q) qc.barrier() qc0 = qc.copy() qc.h(0) qc.barrier() qc1 = qc.copy() qc.x(0) qc.barrier() qc2 = qc.copy() qc.y(0) qc.barrier() qc3 = qc.copy() qc.z(0) qc.barrier() qc4 = qc.copy() qc.draw(output='mpl') # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() # Show the results print(result.get_unitary(qc, decimals=3)) X = sigmax() Y = sigmay() Z = sigmaz() H = np.array([[ 0.707+0.j, 0.707-0.j],[ 0.707+0.j, -0.707+0.j]]) np.dot(np.dot(Z,Y),np.dot(X,H)) backend = Aer.get_backend('statevector_simulator') for qc in [qc0,qc1,qc2,qc3,qc4]: out = execute(qc,backend).result().get_statevector() print(out)
https://github.com/unitaryfund/mitiq
unitaryfund
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. """Defines input / output types for a quantum computer (simulator): * SUPPORTED_PROGRAM_TYPES: All supported packages / circuits which Mitiq can interface with, * QPROGRAM: All supported packages / circuits which are installed in the environment Mitiq is run in, and * QuantumResult: An object returned by a quantum computer (simulator) running a quantum program from which expectation values to be mitigated can be computed. Note this includes expectation values themselves. """ from collections import Counter from dataclasses import dataclass from enum import Enum, EnumMeta from typing import ( Any, Dict, Iterable, List, Optional, Sequence, Tuple, Type, Union, cast, ) import numpy as np import numpy.typing as npt from cirq import Circuit as _Circuit class EnhancedEnumMeta(EnumMeta): def __str__(cls) -> str: return ", ".join([member.value for member in cast(Type[Enum], cls)]) class EnhancedEnum(Enum, metaclass=EnhancedEnumMeta): # This is for backwards compatibility with the old representation # of SUPPORTED_PROGRAM_TYPES, which was a dictionary @classmethod def keys(cls) -> Iterable[str]: return [member.value for member in cls] # Supported quantum programs. class SUPPORTED_PROGRAM_TYPES(EnhancedEnum): BRAKET = "braket" CIRQ = "cirq" PENNYLANE = "pennylane" PYQUIL = "pyquil" QIBO = "qibo" QISKIT = "qiskit" try: from pyquil import Program as _Program except ImportError: # pragma: no cover _Program = _Circuit # type: ignore try: from qiskit import QuantumCircuit as _QuantumCircuit except ImportError: # pragma: no cover _QuantumCircuit = _Circuit try: from braket.circuits import Circuit as _BKCircuit except ImportError: # pragma: no cover _BKCircuit = _Circuit try: from pennylane.tape import QuantumTape as _QuantumTape except ImportError: # pragma: no cover _QuantumTape = _Circuit try: from qibo.models.circuit import Circuit as _QiboCircuit except ImportError: # pragma: no cover _QiboCircuit = _Circuit # Supported + installed quantum programs. QPROGRAM = Union[ _Circuit, _Program, _QuantumCircuit, _BKCircuit, _QuantumTape, _QiboCircuit ] # Define MeasurementResult, a result obtained by measuring qubits on a quantum # computer. Bitstring = Union[str, List[int]] @dataclass class MeasurementResult: """Mitiq object for collecting the bitstrings sampled from a quantum computer when executing a circuit. This is one of the possible types (see :class:`~mitiq.typing.QuantumResult`) that an :class:`.Executor` can return. Args: result: The sequence of measured bitstrings. qubit_indices: The qubit indices associated to each bit in a bitstring (from left to right). If not given, Mitiq assumes the default ordering ``tuple(range(self.nqubits))``, where ``self.nqubits`` is the bitstring length deduced from ``result``. Note: Use caution when selecting the default option for ``qubit_indices``, especially when estimating an :class:`.Observable` acting on a subset of qubits. In this case Mitiq only applies measurement gates to the specific qubits and, therefore, it is essential to specify the corresponding ``qubit_indices``. """ result: Sequence[Bitstring] qubit_indices: Optional[Tuple[int, ...]] = None def __post_init__(self) -> None: # Validate arguments symbols = set(b for bits in self.result for b in bits) if not (symbols.issubset({0, 1}) or symbols.issubset({"0", "1"})): raise ValueError("Bitstrings should look like '011' or [0, 1, 1].") if symbols.issubset({"0", "1"}): # Convert to list of integers int_result = [[int(b) for b in bits] for bits in self.result] self.result: List[List[int]] = list(int_result) if isinstance(self.result, np.ndarray): self.result = self.result.tolist() self._bitstrings = np.array(self.result) if not self.qubit_indices: self.qubit_indices = tuple(range(self.nqubits)) else: if len(self.qubit_indices) != self.nqubits: raise ValueError( f"MeasurementResult has {self.nqubits} qubit(s) but there " f"are {len(self.qubit_indices)} `qubit_indices`." ) self._measurements = dict(zip(self.qubit_indices, self._bitstrings.T)) @property def shots(self) -> int: return self._bitstrings.shape[0] @property def nqubits(self) -> int: return ( self._bitstrings.shape[1] if len(self._bitstrings.shape) >= 2 else 0 ) @property def asarray(self) -> npt.NDArray[np.int64]: return self._bitstrings @classmethod def from_counts( cls, counts: Dict[str, int], qubit_indices: Optional[Tuple[int, ...]] = None, ) -> "MeasurementResult": """Initializes a ``MeasurementResult`` from a dictionary of counts. **Example**:: MeasurementResult.from_counts({"00": 175, "11": 177}) """ counter = Counter(counts) return cls(list(counter.elements()), qubit_indices) def get_counts(self) -> Dict[str, int]: """Returns a Python dictionary whose keys are the measured bitstrings and whose values are the counts. """ strings = ["".join(map(str, bits)) for bits in self.result] return dict(Counter(strings)) def prob_distribution(self) -> Dict[str, float]: """Returns a Python dictionary whose keys are the measured bitstrings and whose values are their empirical frequencies. """ return {k: v / self.shots for k, v in self.get_counts().items()} def to_dict(self) -> Dict[str, Any]: """Exports data to a Python dictionary. Note: Information about the order measurements is not preserved. """ return { "nqubits": self.nqubits, "qubit_indices": self.qubit_indices, "shots": self.shots, "counts": self.get_counts(), } @classmethod def from_dict(cls, data: Dict[str, Any]) -> "MeasurementResult": """Loads a ``MeasurementResult`` from a Python dictionary. Note: Only ``data["counts"]`` and ``data["qubit_indices"]`` are used by this method. Total shots and number of qubits are deduced. """ return cls.from_counts(data["counts"], data["qubit_indices"]) def filter_qubits(self, qubit_indices: List[int]) -> npt.NDArray[np.int64]: """Returns the bitstrings associated to a subset of qubits.""" return np.array([self._measurements[i] for i in qubit_indices]).T def __repr__(self) -> str: # We redefine __repr__ in this way to avoid very long output strings. return "MeasurementResult: " + str(self.to_dict()) # An `executor` function inputs a quantum program and outputs an object from # which expectation values can be computed. Explicitly, this object can be one # of the following types: QuantumResult = Union[ float, # The expectation value itself. MeasurementResult, # Sampled bitstrings. np.ndarray, # Density matrix. # TODO: Support the following: # Sequence[np.ndarray], # Wavefunctions sampled via quantum trajectories. ]
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit, transpile from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') qc_transpiled = transpile(qc, backend) result = backend.run(qc, shots = 8192).result()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(0) qc.measure(0, 0) qc.draw('mpl')
https://github.com/AnkRaw/Quantum-Convolutional-Neural-Network
AnkRaw
# Importing Libraries import torch from torch import cat, no_grad, manual_seed from torch.utils.data import DataLoader from torchvision import transforms import torch.optim as optim from torch.nn import ( Module, Conv2d, Linear, Dropout2d, NLLLoss ) import torch.nn.functional as F import numpy as np import matplotlib.pyplot as plt from qiskit_machine_learning.neural_networks import EstimatorQNN from qiskit_machine_learning.connectors import TorchConnector from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit import QuantumCircuit from qiskit.visualization import circuit_drawer # Imports for CIFAR-10s from torchvision.datasets import CIFAR10 from torchvision import transforms def prepare_data(X, labels_to_keep, batch_size): # Filtering out labels (originally 0-9), leaving only labels 0 and 1 filtered_indices = [i for i in range(len(X.targets)) if X.targets[i] in labels_to_keep] X.data = X.data[filtered_indices] X.targets = [X.targets[i] for i in filtered_indices] # Defining dataloader with filtered data loader = DataLoader(X, batch_size=batch_size, shuffle=True) return loader # Set seed for reproducibility manual_seed(42) # CIFAR-10 data transformation transform = transforms.Compose([ transforms.ToTensor(), # convert the images to tensors transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) # Normalization usign mean and std. ]) labels_to_keep = [0, 1] batch_size = 1 # Preparing Train Data X_train = CIFAR10(root="./data", train=True, download=True, transform=transform) train_loader = prepare_data(X_train, labels_to_keep, batch_size) # Preparing Test Data X_test = CIFAR10(root="./data", train=False, download=True, transform=transform) test_loader = prepare_data(X_test, labels_to_keep, batch_size) print(f"Training dataset size: {len(train_loader.dataset)}") print(f"Test dataset size: {len(test_loader.dataset)}") # Defining and creating QNN def create_qnn(): feature_map = ZZFeatureMap(2) # ZZFeatureMap with 2 bits, entanglement between qubits based on the pairwise product of input features. ansatz = RealAmplitudes(2, reps=1) # parameters (angles, in the case of RealAmplitudes) that are adjusted during the training process to optimize the quantum model for a specific task. qc = QuantumCircuit(2) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) qnn = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, input_gradients=True, ) return qnn qnn = create_qnn() # Visualizing the QNN circuit circuit_drawer(qnn.circuit, output='mpl') # Defining torch NN module class Net(Module): def __init__(self, qnn): super().__init__() self.conv1 = Conv2d(3, 16, kernel_size=3, padding=1) self.conv2 = Conv2d(16, 32, kernel_size=3, padding=1) self.dropout = Dropout2d() self.fc1 = Linear(32 * 8 * 8, 64) self.fc2 = Linear(64, 2) # 2-dimensional input to QNN self.qnn = TorchConnector(qnn) self.fc3 = Linear(1, 1) # 1-dimensional output from QNN def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(x.shape[0], -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.qnn(x) x = self.fc3(x) return cat((x, 1 - x), -1) # Creating model model = Net(qnn) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model.to(device) # Defining model, optimizer, and loss function optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = NLLLoss() # Starting training epochs = 10 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): data, target = data.to(device), target.to(device) # Move data to GPU optimizer.zero_grad(set_to_none=True) output = model(data) loss = loss_func(output, target) loss.backward() optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss) / len(total_loss)) print("Training [{:.0f}%]\tLoss: {:.4f}".format(100.0 * (epoch + 1) / epochs, loss_list[-1])) # Plotting loss convergence plt.plot(loss_list) plt.title("Hybrid NN Training Convergence") plt.xlabel("Training Iterations") plt.ylabel("Neg. Log Likelihood Loss") plt.show() # Saving the model torch.save( model.state_dict(), "model_cifar10_10EPOCHS.pt") # Loading the model qnn_cifar10 = create_qnn() model_cifar10 = Net(qnn_cifar10) model_cifar10.load_state_dict(torch.load("model_cifar10.pt")) correct = 0 total = 0 model_cifar10.eval() with torch.no_grad(): for data, target in test_loader: output = model_cifar10(data) _, predicted = torch.max(output.data, 1) total += target.size(0) correct += (predicted == target).sum().item() # Calculating and print test accuracy test_accuracy = correct / total * 100 print(f"Test Accuracy: {test_accuracy:.2f}%") # Plotting predicted labels n_samples_show = 6 count = 0 fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) model_cifar10.eval() with no_grad(): for batch_idx, (data, target) in enumerate(test_loader): if count == n_samples_show: break output = model_cifar10(data) if len(output.shape) == 1: output = output.reshape(1, *output.shape) pred = output.argmax(dim=1, keepdim=True) axes[count].imshow(np.transpose(data[0].numpy(), (1, 2, 0))) axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title("Predicted {0}\n Actual {1}".format(pred.item(), target.item())) count += 1 plt.show()
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. """ Quantum Phase Estimation Circuit. """ import numpy as np from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit.aqua import Operator, AquaError class PhaseEstimationCircuit: def __init__( self, operator=None, state_in=None, iqft=None, num_time_slices=1, num_ancillae=1, expansion_mode='trotter', expansion_order=1, evo_time=2*np.pi, state_in_circuit_factory=None, unitary_circuit_factory=None, shallow_circuit_concat=False, pauli_list=None ): """ Constructor. Args: operator (Operator): the hamiltonian Operator object state_in (InitialState): the InitialState pluggable component representing the initial quantum state iqft (IQFT): the Inverse Quantum Fourier Transform pluggable component num_time_slices (int): the number of time slices num_ancillae (int): the number of ancillary qubits to use for the measurement expansion_mode (str): the expansion mode (trotter|suzuki) expansion_order (int): the suzuki expansion order evo_time (float): the evolution time state_in_circuit_factory (CircuitFactory): the initial state represented by a CircuitFactory object unitary_circuit_factory (CircuitFactory): the problem unitary represented by a CircuitFactory object shallow_circuit_concat (bool): indicate whether to use shallow (cheap) mode for circuit concatenation pauli_list ([Pauli]): the flat list of paulis for the operator """ if ( operator is not None and unitary_circuit_factory is not None ) or ( operator is None and unitary_circuit_factory is None ): raise AquaError('Please supply either an operator or a unitary circuit factory but not both.') self._operator = operator if operator is not None: self._pauli_list = operator.get_flat_pauli_list() if pauli_list is None else pauli_list self._unitary_circuit_factory = unitary_circuit_factory self._state_in = state_in self._state_in_circuit_factory = state_in_circuit_factory self._iqft = iqft self._num_time_slices = num_time_slices self._num_ancillae = num_ancillae self._expansion_mode = expansion_mode self._expansion_order = expansion_order self._evo_time = evo_time self._shallow_circuit_concat = shallow_circuit_concat self._ancilla_phase_coef = 1 self._state_register = None self._ancillary_register = None self._auxiliary_register = None self._circuit = None def construct_circuit( self, state_register=None, ancillary_register=None, auxiliary_register=None, measurement=False, ): """ Construct the Phase Estimation circuit Args: state_register (QuantumRegister): the optional register to use for the quantum state ancillary_register (QuantumRegister): the optional register to use for the ancillary measurement qubits auxiliary_register (QuantumRegister): an optional auxiliary quantum register measurement (bool): Boolean flag to indicate if measurement should be included in the circuit. Returns: the QuantumCircuit object for the constructed circuit """ if self._circuit is None: if ancillary_register is None: a = QuantumRegister(self._num_ancillae, name='a') else: a = ancillary_register self._ancillary_register = a if state_register is None: if self._operator is not None: q = QuantumRegister(self._operator.num_qubits, name='q') elif self._unitary_circuit_factory is not None: q = QuantumRegister(self._unitary_circuit_factory.num_target_qubits, name='q') else: raise RuntimeError('Missing operator specification.') else: q = state_register self._state_register = q qc = QuantumCircuit(a, q) if auxiliary_register is None: num_aux_qubits, aux = 0, None if self._state_in_circuit_factory is not None: num_aux_qubits = self._state_in_circuit_factory.required_ancillas() if self._unitary_circuit_factory is not None: num_aux_qubits = max(num_aux_qubits, self._unitary_circuit_factory.required_ancillas_controlled()) if num_aux_qubits > 0: aux = QuantumRegister(num_aux_qubits, name='aux') qc.add_register(aux) else: aux = auxiliary_register qc.add_register(aux) # initialize state_in if self._state_in is not None: qc.data += self._state_in.construct_circuit('circuit', q).data elif self._state_in_circuit_factory is not None: self._state_in_circuit_factory.build(qc, q, aux) # Put all ancillae in uniform superposition qc.u2(0, np.pi, a) # phase kickbacks via dynamics if self._operator is not None: # check for identify paulis to get its coef for applying global phase shift on ancillae later num_identities = 0 for p in self._pauli_list: if np.all(np.logical_not(p[1].z)) and np.all(np.logical_not(p[1].x)): num_identities += 1 if num_identities > 1: raise RuntimeError('Multiple identity pauli terms are present.') self._ancilla_phase_coef = p[0].real if isinstance(p[0], complex) else p[0] if len(self._pauli_list) == 1: slice_pauli_list = self._pauli_list else: if self._expansion_mode == 'trotter': slice_pauli_list = self._pauli_list elif self._expansion_mode == 'suzuki': slice_pauli_list = Operator._suzuki_expansion_slice_pauli_list( self._pauli_list, 1, self._expansion_order ) else: raise ValueError('Unrecognized expansion mode {}.'.format(self._expansion_mode)) for i in range(self._num_ancillae): qc_evolutions = Operator.construct_evolution_circuit( slice_pauli_list, -self._evo_time, self._num_time_slices, q, a, ctl_idx=i, shallow_slicing=self._shallow_circuit_concat ) if self._shallow_circuit_concat: qc.data += qc_evolutions.data else: qc += qc_evolutions # global phase shift for the ancilla due to the identity pauli term qc.u1(self._evo_time * self._ancilla_phase_coef * (2 ** i), a[i]) elif self._unitary_circuit_factory is not None: for i in range(self._num_ancillae): self._unitary_circuit_factory.build_controlled_power(qc, q, a[i], 2 ** i, aux) # inverse qft on ancillae self._iqft.construct_circuit(mode='circuit', qubits=a, circuit=qc, do_swaps=False) if measurement: c_ancilla = ClassicalRegister(self._num_ancillae, name='ca') qc.add_register(c_ancilla) # qc.barrier(a) qc.measure(a, c_ancilla) self._circuit = qc return self._circuit @property def state_register(self): return self._state_register @property def ancillary_register(self): return self._ancillary_register @property def auxiliary_register(self): return self._auxiliary_register
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.problems.second_quantization.lattice.lattices import LineLattice from qiskit_nature.problems.second_quantization.lattice.models import FermiHubbardModel line = LineLattice(2) fermi = FermiHubbardModel.uniform_parameters(line, 2.0, 4.0, 3.0) print(fermi.second_q_ops()) # Note: the trailing `s` from qiskit_nature.second_q.hamiltonians.lattices import LineLattice from qiskit_nature.second_q.hamiltonians import FermiHubbardModel line = LineLattice(2) fermi = FermiHubbardModel(line.uniform_parameters(2.0, 4.0), 3.0) print(fermi.second_q_op()) # Note: NO trailing `s` import numpy as np from qiskit_nature.problems.second_quantization.lattice.models import FermiHubbardModel interaction = np.array([[4.0, 2.0], [2.0, 4.0]]) fermi = FermiHubbardModel.from_parameters(interaction, 3.0) print(fermi.second_q_ops()) # Note: the trailing `s` import numpy as np from qiskit_nature.second_q.hamiltonians.lattices import Lattice from qiskit_nature.second_q.hamiltonians import FermiHubbardModel interaction = np.array([[4.0, 2.0], [2.0, 4.0]]) lattice = Lattice.from_adjacency_matrix(interaction) fermi = FermiHubbardModel(lattice, 3.0) print(fermi.second_q_op()) # Note: NO trailing `s` from qiskit_nature.problems.second_quantization.lattice.lattices import LineLattice from qiskit_nature.problems.second_quantization.lattice.models import IsingModel line = LineLattice(2) ising = IsingModel.uniform_parameters(line, 2.0, 4.0) print(ising.second_q_ops()) # Note: the trailing `s` from qiskit_nature.second_q.hamiltonians.lattices import LineLattice from qiskit_nature.second_q.hamiltonians import IsingModel line = LineLattice(2) ising = IsingModel(line.uniform_parameters(2.0, 4.0)) print(ising.second_q_op()) # Note: NO trailing `s` import numpy as np from qiskit_nature.problems.second_quantization.lattice.models import IsingModel interaction = np.array([[4.0, 2.0], [2.0, 4.0]]) ising = IsingModel.from_parameters(interaction) print(ising.second_q_ops()) # Note: the trailing `s` import numpy as np from qiskit_nature.second_q.hamiltonians.lattices import Lattice from qiskit_nature.second_q.hamiltonians import IsingModel interaction = np.array([[4.0, 2.0], [2.0, 4.0]]) lattice = Lattice.from_adjacency_matrix(interaction) ising = IsingModel(lattice) print(ising.second_q_op()) # Note: NO trailing `s` import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """ Core module of the timeline drawer. This module provides the `DrawerCanvas` which is a collection of drawings. The canvas instance is not just a container of drawing objects, as it also performs data processing like binding abstract coordinates. Initialization ~~~~~~~~~~~~~~ The `DataCanvas` is not exposed to users as they are implicitly initialized in the interface function. It is noteworthy that the data canvas is agnostic to plotters. This means once the canvas instance is initialized we can reuse this data among multiple plotters. The canvas is initialized with a stylesheet. ```python canvas = DrawerCanvas(stylesheet=stylesheet) canvas.load_program(sched) canvas.update() ``` Once all properties are set, `.update` method is called to apply changes to drawings. Update ~~~~~~ To update the image, a user can set new values to canvas and then call the `.update` method. ```python canvas.set_time_range(2000, 3000) canvas.update() ``` All stored drawings are updated accordingly. The plotter API can access to drawings with `.collections` property of the canvas instance. This returns an iterator of drawings with the unique data key. If a plotter provides object handler for plotted shapes, the plotter API can manage the lookup table of the handler and the drawings by using this data key. """ from __future__ import annotations import warnings from collections.abc import Iterator from copy import deepcopy from functools import partial from enum import Enum import numpy as np from qiskit import circuit from qiskit.visualization.exceptions import VisualizationError from qiskit.visualization.timeline import drawings, types from qiskit.visualization.timeline.stylesheet import QiskitTimelineStyle class DrawerCanvas: """Data container for drawings.""" def __init__(self, stylesheet: QiskitTimelineStyle): """Create new data container.""" # stylesheet self.formatter = stylesheet.formatter self.generator = stylesheet.generator self.layout = stylesheet.layout # drawings self._collections: dict[str, drawings.ElementaryData] = {} self._output_dataset: dict[str, drawings.ElementaryData] = {} # vertical offset of bits self.bits: list[types.Bits] = [] self.assigned_coordinates: dict[types.Bits, float] = {} # visible controls self.disable_bits: set[types.Bits] = set() self.disable_types: set[str] = set() # time self._time_range = (0, 0) # graph height self.vmax = 0 self.vmin = 0 @property def time_range(self) -> tuple[int, int]: """Return current time range to draw. Calculate net duration and add side margin to edge location. Returns: Time window considering side margin. """ t0, t1 = self._time_range duration = t1 - t0 new_t0 = t0 - duration * self.formatter["margin.left_percent"] new_t1 = t1 + duration * self.formatter["margin.right_percent"] return new_t0, new_t1 @time_range.setter def time_range(self, new_range: tuple[int, int]): """Update time range to draw.""" self._time_range = new_range @property def collections(self) -> Iterator[tuple[str, drawings.ElementaryData]]: """Return currently active entries from drawing data collection. The object is returned with unique name as a key of an object handler. When the horizontal coordinate contains `AbstractCoordinate`, the value is substituted by current time range preference. """ yield from self._output_dataset.items() def add_data(self, data: drawings.ElementaryData): """Add drawing to collections. If the given object already exists in the collections, this interface replaces the old object instead of adding new entry. Args: data: New drawing to add. """ if not self.formatter["control.show_clbits"]: data.bits = [b for b in data.bits if not isinstance(b, circuit.Clbit)] self._collections[data.data_key] = data # pylint: disable=cyclic-import def load_program(self, program: circuit.QuantumCircuit): """Load quantum circuit and create drawing.. Args: program: Scheduled circuit object to draw. Raises: VisualizationError: When circuit is not scheduled. """ not_gate_like = (circuit.Barrier,) if getattr(program, "_op_start_times") is None: # Run scheduling for backward compatibility from qiskit import transpile from qiskit.transpiler import InstructionDurations, TranspilerError warnings.warn( "Visualizing un-scheduled circuit with timeline drawer has been deprecated. " "This circuit should be transpiled with scheduler though it consists of " "instructions with explicit durations.", DeprecationWarning, ) try: program = transpile( program, scheduling_method="alap", instruction_durations=InstructionDurations(), optimization_level=0, ) except TranspilerError as ex: raise VisualizationError( f"Input circuit {program.name} is not scheduled and it contains " "operations with unknown delays. This cannot be visualized." ) from ex for t0, instruction in zip(program.op_start_times, program.data): bits = list(instruction.qubits) + list(instruction.clbits) for bit_pos, bit in enumerate(bits): if not isinstance(instruction.operation, not_gate_like): # Generate draw object for gates gate_source = types.ScheduledGate( t0=t0, operand=instruction.operation, duration=instruction.operation.duration, bits=bits, bit_position=bit_pos, ) for gen in self.generator["gates"]: obj_generator = partial(gen, formatter=self.formatter) for datum in obj_generator(gate_source): self.add_data(datum) if len(bits) > 1 and bit_pos == 0: # Generate draw object for gate-gate link line_pos = t0 + 0.5 * instruction.operation.duration link_source = types.GateLink( t0=line_pos, opname=instruction.operation.name, bits=bits ) for gen in self.generator["gate_links"]: obj_generator = partial(gen, formatter=self.formatter) for datum in obj_generator(link_source): self.add_data(datum) if isinstance(instruction.operation, circuit.Barrier): # Generate draw object for barrier barrier_source = types.Barrier(t0=t0, bits=bits, bit_position=bit_pos) for gen in self.generator["barriers"]: obj_generator = partial(gen, formatter=self.formatter) for datum in obj_generator(barrier_source): self.add_data(datum) self.bits = list(program.qubits) + list(program.clbits) for bit in self.bits: for gen in self.generator["bits"]: # Generate draw objects for bit obj_generator = partial(gen, formatter=self.formatter) for datum in obj_generator(bit): self.add_data(datum) # update time range t_end = max(program.duration, self.formatter["margin.minimum_duration"]) self.set_time_range(t_start=0, t_end=t_end) def set_time_range(self, t_start: int, t_end: int): """Set time range to draw. Args: t_start: Left boundary of drawing in units of cycle time. t_end: Right boundary of drawing in units of cycle time. """ self.time_range = (t_start, t_end) def set_disable_bits(self, bit: types.Bits, remove: bool = True): """Interface method to control visibility of bits. Specified object in the blocked list will not be shown. Args: bit: A qubit or classical bit object to disable. remove: Set `True` to disable, set `False` to enable. """ if remove: self.disable_bits.add(bit) else: self.disable_bits.discard(bit) def set_disable_type(self, data_type: types.DataTypes, remove: bool = True): """Interface method to control visibility of data types. Specified object in the blocked list will not be shown. Args: data_type: A drawing data type to disable. remove: Set `True` to disable, set `False` to enable. """ if isinstance(data_type, Enum): data_type_str = str(data_type.value) else: data_type_str = data_type if remove: self.disable_types.add(data_type_str) else: self.disable_types.discard(data_type_str) def update(self): """Update all collections. This method should be called before the canvas is passed to the plotter. """ self._output_dataset.clear() self.assigned_coordinates.clear() # update coordinate y0 = -self.formatter["margin.top"] for bit in self.layout["bit_arrange"](self.bits): # remove classical bit if isinstance(bit, circuit.Clbit) and not self.formatter["control.show_clbits"]: continue # remove idle bit if not self._check_bit_visible(bit): continue offset = y0 - 0.5 self.assigned_coordinates[bit] = offset y0 = offset - 0.5 self.vmax = 0 self.vmin = y0 - self.formatter["margin.bottom"] # add data temp_gate_links = {} temp_data = {} for data_key, data in self._collections.items(): # deep copy to keep original data hash new_data = deepcopy(data) new_data.xvals = self._bind_coordinate(data.xvals) new_data.yvals = self._bind_coordinate(data.yvals) if data.data_type == str(types.LineType.GATE_LINK.value): temp_gate_links[data_key] = new_data else: temp_data[data_key] = new_data # update horizontal offset of gate links temp_data.update(self._check_link_overlap(temp_gate_links)) # push valid data for data_key, data in temp_data.items(): if self._check_data_visible(data): self._output_dataset[data_key] = data def _check_data_visible(self, data: drawings.ElementaryData) -> bool: """A helper function to check if the data is visible. Args: data: Drawing object to test. Returns: Return `True` if the data is visible. """ _barriers = [str(types.LineType.BARRIER.value)] _delays = [str(types.BoxType.DELAY.value), str(types.LabelType.DELAY.value)] def _time_range_check(_data): """If data is located outside the current time range.""" t0, t1 = self.time_range if np.max(_data.xvals) < t0 or np.min(_data.xvals) > t1: return False return True def _associated_bit_check(_data): """If any associated bit is not shown.""" if all(bit not in self.assigned_coordinates for bit in _data.bits): return False return True def _data_check(_data): """If data is valid.""" if _data.data_type == str(types.LineType.GATE_LINK.value): active_bits = [bit for bit in _data.bits if bit not in self.disable_bits] if len(active_bits) < 2: return False elif _data.data_type in _barriers and not self.formatter["control.show_barriers"]: return False elif _data.data_type in _delays and not self.formatter["control.show_delays"]: return False return True checks = [_time_range_check, _associated_bit_check, _data_check] if all(check(data) for check in checks): return True return False def _check_bit_visible(self, bit: types.Bits) -> bool: """A helper function to check if the bit is visible. Args: bit: Bit object to test. Returns: Return `True` if the bit is visible. """ _gates = [str(types.BoxType.SCHED_GATE.value), str(types.SymbolType.FRAME.value)] if bit in self.disable_bits: return False if self.formatter["control.show_idle"]: return True for data in self._collections.values(): if bit in data.bits and data.data_type in _gates: return True return False def _bind_coordinate(self, vals: Iterator[types.Coordinate]) -> np.ndarray: """A helper function to bind actual coordinates to an `AbstractCoordinate`. Args: vals: Sequence of coordinate objects associated with a drawing. Returns: Numpy data array with substituted values. """ def substitute(val: types.Coordinate): if val == types.AbstractCoordinate.LEFT: return self.time_range[0] if val == types.AbstractCoordinate.RIGHT: return self.time_range[1] if val == types.AbstractCoordinate.TOP: return self.vmax if val == types.AbstractCoordinate.BOTTOM: return self.vmin raise VisualizationError(f"Coordinate {val} is not supported.") try: return np.asarray(vals, dtype=float) except TypeError: return np.asarray(list(map(substitute, vals)), dtype=float) def _check_link_overlap( self, links: dict[str, drawings.GateLinkData] ) -> dict[str, drawings.GateLinkData]: """Helper method to check overlap of bit links. This method dynamically shifts horizontal position of links if they are overlapped. """ duration = self.time_range[1] - self.time_range[0] allowed_overlap = self.formatter["margin.link_interval_percent"] * duration # return y coordinates def y_coords(link: drawings.GateLinkData): return np.array([self.assigned_coordinates.get(bit, np.nan) for bit in link.bits]) # group overlapped links overlapped_group: list[list[str]] = [] data_keys = list(links.keys()) while len(data_keys) > 0: ref_key = data_keys.pop() overlaps = set() overlaps.add(ref_key) for key in data_keys[::-1]: # check horizontal overlap if np.abs(links[ref_key].xvals[0] - links[key].xvals[0]) < allowed_overlap: # check vertical overlap y0s = y_coords(links[ref_key]) y1s = y_coords(links[key]) v1 = np.nanmin(y0s) - np.nanmin(y1s) v2 = np.nanmax(y0s) - np.nanmax(y1s) v3 = np.nanmin(y0s) - np.nanmax(y1s) v4 = np.nanmax(y0s) - np.nanmin(y1s) if not (v1 * v2 > 0 and v3 * v4 > 0): overlaps.add(data_keys.pop(data_keys.index(key))) overlapped_group.append(list(overlaps)) # renew horizontal offset new_links = {} for overlaps in overlapped_group: if len(overlaps) > 1: xpos_mean = np.mean([links[key].xvals[0] for key in overlaps]) # sort link key by y position sorted_keys = sorted(overlaps, key=lambda x: np.nanmax(y_coords(links[x]))) x0 = xpos_mean - 0.5 * allowed_overlap * (len(overlaps) - 1) for ind, key in enumerate(sorted_keys): data = links[key] data.xvals = [x0 + ind * allowed_overlap] new_links[key] = data else: key = overlaps[0] new_links[key] = links[key] return {key: new_links[key] for key in links.keys()}
https://github.com/Fergus-Hayes/qiskit_tools
Fergus-Hayes
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ from qiskit.circuit.library import StatePreparation, RYGate from qiskit.quantum_info import Statevector import qiskit_tools as qt import numpy as np import matplotlib.pyplot as plt import matplotlib from tqdm import tqdm from datetime import datetime # Shake things up by changing the random seed rseed = int(datetime.now().timestamp()) np.random.seed(rseed) from sklearn.gaussian_process.kernels import RBF from sklearn.gaussian_process import GaussianProcessRegressor matplotlib.rcParams['mathtext.fontset'] = 'stix' matplotlib.rcParams['font.family'] = 'STIXGeneral' width=0.75 color='black' fontsize=28 ticksize=22 figsize=(10,8) N = 4 n = int(np.ceil(np.log2(N))) xmin, xmax = 0, 8 X_train = np.linspace(start=xmin, stop=xmax, num=2**n).reshape(-1, 1) def y_targ(x): return np.squeeze(x*np.sin(x)) noise_std = 0.75 y_train = y_targ(X_train) + np.random.normal(0,noise_std,N) Nast = 16 X = np.linspace(start=xmin, stop=xmax, num=Nast).reshape(-1, 1) y = y_targ(X) def SEK(X1, X2, ls=1.0, sig=1.0): sqdist = np.sum(X1**2, 1).reshape(-1, 1) + np.sum(X2**2, 1) - 2 * np.dot(X1, X2.T) return sig * np.exp(-0.5 * sqdist / ls**2) sigma = 2*noise_std ls = 2.**(-(xmax-xmin)/Nast) def posterior(X_s, X_train, Y_train, l=1.0, sigma_f=1.0, sigma_y=1e-8): K = SEK(X_train, X_train, l, sigma_f) + sigma_y**2 * np.eye(len(X_train)) K_s = SEK(X_train, X_s, l, sigma_f) K_ss = SEK(X_s, X_s, l, sigma_f) K_inv = np.linalg.inv(K) mu_s = K_s.T.dot(K_inv).dot(Y_train) cov_s = K_ss - K_s.T.dot(K_inv).dot(K_s) return mu_s, cov_s mean_prediction, cov_s = posterior(X, X_train, y_train, l=ls, sigma_f=sigma, sigma_y=noise_std) std_prediction = np.diag(cov_s) fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111) ax.plot(X, y, label=r"$f(x) = x \sin(x)$", linestyle="dotted") ax.errorbar( X_train, y_train, noise_std, linestyle="None", color="tab:blue", marker=".", markersize=10, label="Observations", ) ax.plot(X, mean_prediction, label="Mean prediction", marker='.') ax.fill_between( X.ravel(), mean_prediction - 1.96 * std_prediction, mean_prediction + 1.96 * std_prediction, color="tab:orange", alpha=0.5, label=r"95% confidence interval", ) ax.legend() ax.set_xlabel("$x$") ax.set_ylabel("$f(x)$") plt.show() # Pick the middle x* to evaluate u_ind = (len(X)//2) - 1 # Define v and u v = y_train u = SEK(X, X_train, ls, sig=sigma)[u_ind] # Determine normalisation of v and u v_norm = np.sqrt(np.sum(np.abs(v)**2)) u_norm = np.sqrt(np.sum(np.abs(u)**2)) # Normalised vectors v and u v_ = v/v_norm u_ = u/u_norm # Determine A A = SEK(X_train, X_train, ls, sig=sigma) + (np.eye(len(X_train))*noise_std**2) kappa = np.linalg.cond(A) lambda_min = np.min(np.abs(np.linalg.eigvals(A))) lambda_max = np.max(np.abs(np.linalg.eigvals(A))) # Choose a success probability of determining eigenvalue estimation p_suc = 0.99 # Determine the number of ancillary qubits to ensure the given success probability nanc = n + int(np.ceil(np.log2(2. + 1./(2.*(1-p_suc))))) phase = True # Calculate the new scale of the relative magnitudes of maximum and minimum eigenvalues rescale = int((2**(nanc-phase)-1)/kappa) # Make sure this scaling is not vanishingly small if rescale < 1.e-7: rescale = 1 # determine the number of integer qubits required nint = qt.get_nint(rescale) # Assert that the number of integer qubits is equal to or greater than the number of ancillary qubits assigned if nint < nanc - phase: nint = nanc - phase # We can determine the scaling of the rotation of step 3 (variable c) scaling = qt.bin_to_dec(qt.my_binary_repr(rescale, nint=nint, n=nint, phase=False), nint=0, phase=False) t0 = scaling / (lambda_min * (2**phase)) t = 2 * np.pi * t0 qcont = QuantumRegister(1, 'cont') qtarg = QuantumRegister(1, 'targ') qreg = QuantumRegister(n, 'x') qanc = QuantumRegister(nanc, 'anc') circ = QuantumCircuit(qanc, qtarg, qreg, qcont) circ.h(qcont); circ.barrier(); prepv_gate = StatePreparation(Statevector(v_)).control(1) circ.append(prepv_gate, [qcont, *qreg]); circ.barrier(); circ.x(qcont); circ.cx(qcont, qtarg); circ.barrier(); prepu_gate = StatePreparation(Statevector(u_)).control(1) circ.append(prepu_gate, [qcont, *qreg]); circ.x(qcont); circ.barrier(); hhl_gate = qt.HHL(circ, qreg, qanc, qtarg, A, t=t, scaling=scaling, wrap=True).control(1) circ.append(hhl_gate, [qcont, *qreg, *qanc, qtarg]); circ.draw('latex') backend = Aer.get_backend('statevector_simulator') job = execute(circ, backend) result = job.result() state_vector = np.asarray(result.get_statevector()) state_v = np.asarray(state_vector).reshape((2**1, 2**n, 2**1, 2**nanc)).T state_v = state_v[0,1,:,1] targ_v = np.matmul(np.linalg.inv(A),v_)*np.sqrt(2.) fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111) plt.scatter(np.arange(2**n), targ_v, marker='o', color='red') plt.scatter(np.arange(2**n), state_v.real, marker='.', color='black') ax.set_ylabel('Amplitude', fontsize=fontsize); ax.tick_params(axis='both', labelsize=ticksize); state_u = np.asarray(state_vector).reshape((2**1, 2**n, 2**1, 2**nanc)).T state_u = state_u[0,1,:,0] targ_u = u_/np.sqrt(2.) fig = plt.figure(figsize=np.array(figsize)) ax = fig.add_subplot(111) plt.scatter(np.arange(2**n), targ_u, marker='o', color='red') plt.scatter(np.arange(2**n), state_u.real, marker='.', color='black') ax.set_ylabel('Amplitude', fontsize=fontsize); ax.tick_params(axis='both', labelsize=ticksize); state_v = np.asarray(state_vector).reshape((2**1, 2**n, 2**1, 2**nanc)).T state_v = state_v[0,1].T X_matrix = np.array([[0,1],[1,0]]) mu_out = np.matmul(state_v.flatten(),np.matmul(X_matrix, state_v.real).flatten()).real*(u_norm*v_norm*scaling/np.sqrt(2.)) print(mu_out, mean_prediction[u_ind]) mus = [] stds = [] for i in tqdm(np.arange(Nast)): v = y_train u = SEK(X, X_train, ls, sig=sigma)[i] v_norm = np.sqrt(np.sum(np.abs(v)**2)) u_norm = np.sqrt(np.sum(np.abs(u)**2)) v_ = v/v_norm u_ = u/u_norm v_gate = StatePreparation(Statevector(v_)) u_gate = StatePreparation(Statevector(u_)) qcont = QuantumRegister(1, 'cont') qtarg = QuantumRegister(1, 'targ') qreg = QuantumRegister(n, 'reg') qanc = QuantumRegister(nanc, 'anc') circ = QuantumCircuit(qanc, qtarg, qreg, qcont) QGPR_gate = qt.QGPR(circ, qreg, qanc, qtarg, qcont, v_gate, u_gate, A, t, scaling, wrap=True) circ.append(QGPR_gate, [*qreg, *qanc, qtarg, qcont]); backend = Aer.get_backend('statevector_simulator') job = execute(circ, backend) result = job.result() state_vector = np.asarray(result.get_statevector()) state_v = np.asarray(state_vector).reshape((2**1, 2**n, 2**1, 2**nanc)).T[0,1].T mus.append(np.matmul(state_v.flatten(),np.matmul(X_matrix, state_v.real).flatten()).real*(u_norm*v_norm*scaling/np.sqrt(2))) qcont = QuantumRegister(1, 'cont') qtarg = QuantumRegister(1, 'targ') qreg = QuantumRegister(n, 'reg') qanc = QuantumRegister(nanc, 'anc') circ = QuantumCircuit(qanc, qtarg, qreg, qcont) QGPR_gate = qt.QGPR(circ, qreg, qanc, qtarg, qcont, u_gate, u_gate, A, t, scaling, wrap=True) circ.append(QGPR_gate, [*qreg, *qanc, qtarg, qcont]); backend = Aer.get_backend('statevector_simulator') job = execute(circ, backend) result = job.result() state_vector = np.asarray(result.get_statevector()) state_v = np.asarray(state_vector).reshape((2**1, 2**n, 2**1, 2**nanc)).T[0,1].T M_exp = np.matmul(state_v.flatten(),np.matmul(X_matrix, state_v.real).flatten()).real*((u_norm**2)*scaling/np.sqrt(2)) stds.append(SEK(X, X, ls, sig=sigma)[i,i]-M_exp) mus = np.array(mus) stds = np.array(stds) fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111) ax.plot(X, y, label=r"$f(x) = x \sin(x)$", linestyle="dotted") ax.errorbar( X_train, y_train, noise_std, linestyle="None", color="tab:blue", marker=".", markersize=10, label="Observations", ) ax.plot(X, mean_prediction, marker='.', label="Classical mean prediction") ax.fill_between( X.ravel(), mean_prediction - 1.96 * std_prediction, mean_prediction + 1.96 * std_prediction, color="tab:orange", alpha=0.5, label=r"95% confidence interval", ) ax.plot(X, mus, color='violet', marker='.', label="Quantum mean prediction") ax.fill_between( X.ravel(), mus - 1.96 * stds, mus + 1.96 * stds, color="tab:purple", alpha=0.5, label=r"95% confidence interval", ) ax.legend() ax.set_xlabel("$x$") ax.set_ylabel("$f(x)$") plt.show()
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. """Tests for Kraus quantum channel representation class.""" import copy import unittest import numpy as np from numpy.testing import assert_allclose from qiskit import QiskitError from qiskit.quantum_info.states import DensityMatrix from qiskit.quantum_info import Kraus from .channel_test_case import ChannelTestCase class TestKraus(ChannelTestCase): """Tests for Kraus channel representation.""" def test_init(self): """Test initialization""" # Initialize from unitary chan = Kraus(self.UI) assert_allclose(chan.data, [self.UI]) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) # Initialize from Kraus chan = Kraus(self.depol_kraus(0.5)) assert_allclose(chan.data, self.depol_kraus(0.5)) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) # Initialize from Non-CPTP kraus_l, kraus_r = [self.UI, self.UX], [self.UY, self.UZ] chan = Kraus((kraus_l, kraus_r)) assert_allclose(chan.data, (kraus_l, kraus_r)) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) # Initialize with redundant second op chan = Kraus((kraus_l, kraus_l)) assert_allclose(chan.data, kraus_l) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) # Initialize from rectangular kraus = [np.zeros((4, 2))] chan = Kraus(kraus) assert_allclose(chan.data, kraus) self.assertEqual(chan.dim, (2, 4)) self.assertIsNone(chan.num_qubits) # Wrong input or output dims should raise exception self.assertRaises(QiskitError, Kraus, kraus, input_dims=4, output_dims=4) def test_circuit_init(self): """Test initialization from a circuit.""" circuit, target = self.simple_circuit_no_measure() op = Kraus(circuit) target = Kraus(target) self.assertEqual(op, target) def test_circuit_init_except(self): """Test initialization from circuit with measure raises exception.""" circuit = self.simple_circuit_with_measure() self.assertRaises(QiskitError, Kraus, circuit) def test_equal(self): """Test __eq__ method""" kraus = [self.rand_matrix(2, 2) for _ in range(2)] self.assertEqual(Kraus(kraus), Kraus(kraus)) def test_copy(self): """Test copy method""" mat = np.eye(2) with self.subTest("Deep copy"): orig = Kraus(mat) cpy = orig.copy() cpy._data[0][0][0, 0] = 0.0 self.assertFalse(cpy == orig) with self.subTest("Shallow copy"): orig = Kraus(mat) clone = copy.copy(orig) clone._data[0][0][0, 0] = 0.0 self.assertTrue(clone == orig) def test_clone(self): """Test clone method""" mat = np.eye(4) orig = Kraus(mat) clone = copy.copy(orig) clone._data[0][0][0, 0] = 0.0 self.assertTrue(clone == orig) def test_is_cptp(self): """Test is_cptp method.""" self.assertTrue(Kraus(self.depol_kraus(0.5)).is_cptp()) self.assertTrue(Kraus(self.UX).is_cptp()) # Non-CPTP should return false self.assertFalse(Kraus(([self.UI], [self.UX])).is_cptp()) self.assertFalse(Kraus([self.UI, self.UX]).is_cptp()) def test_conjugate(self): """Test conjugate method.""" kraus_l, kraus_r = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4) # Single Kraus list targ = Kraus([np.conjugate(k) for k in kraus_l]) chan1 = Kraus(kraus_l) chan = chan1.conjugate() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (2, 4)) # Double Kraus list targ = Kraus(([np.conjugate(k) for k in kraus_l], [np.conjugate(k) for k in kraus_r])) chan1 = Kraus((kraus_l, kraus_r)) chan = chan1.conjugate() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (2, 4)) def test_transpose(self): """Test transpose method.""" kraus_l, kraus_r = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4) # Single Kraus list targ = Kraus([np.transpose(k) for k in kraus_l]) chan1 = Kraus(kraus_l) chan = chan1.transpose() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (4, 2)) # Double Kraus list targ = Kraus(([np.transpose(k) for k in kraus_l], [np.transpose(k) for k in kraus_r])) chan1 = Kraus((kraus_l, kraus_r)) chan = chan1.transpose() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (4, 2)) def test_adjoint(self): """Test adjoint method.""" kraus_l, kraus_r = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4) # Single Kraus list targ = Kraus([np.transpose(k).conj() for k in kraus_l]) chan1 = Kraus(kraus_l) chan = chan1.adjoint() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (4, 2)) # Double Kraus list targ = Kraus( ([np.transpose(k).conj() for k in kraus_l], [np.transpose(k).conj() for k in kraus_r]) ) chan1 = Kraus((kraus_l, kraus_r)) chan = chan1.adjoint() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (4, 2)) def test_compose_except(self): """Test compose different dimension exception""" self.assertRaises(QiskitError, Kraus(np.eye(2)).compose, Kraus(np.eye(4))) self.assertRaises(QiskitError, Kraus(np.eye(2)).compose, 2) def test_compose(self): """Test compose method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Kraus(self.UX) chan2 = Kraus(self.UY) chan = chan1.compose(chan2) targ = rho & Kraus(self.UZ) self.assertEqual(rho & chan, targ) # 50% depolarizing channel chan1 = Kraus(self.depol_kraus(0.5)) chan = chan1.compose(chan1) targ = rho & Kraus(self.depol_kraus(0.75)) self.assertEqual(rho & chan, targ) # Compose different dimensions kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(4, 2, 4) chan1 = Kraus(kraus1) chan2 = Kraus(kraus2) targ = rho & chan1 & chan2 chan = chan1.compose(chan2) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho & chan, targ) chan = chan1 & chan2 self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho & chan, targ) def test_dot(self): """Test dot method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Kraus(self.UX) chan2 = Kraus(self.UY) targ = rho.evolve(Kraus(self.UZ)) self.assertEqual(rho.evolve(chan1.dot(chan2)), targ) self.assertEqual(rho.evolve(chan1 @ chan2), targ) # 50% depolarizing channel chan1 = Kraus(self.depol_kraus(0.5)) targ = rho & Kraus(self.depol_kraus(0.75)) self.assertEqual(rho.evolve(chan1.dot(chan1)), targ) self.assertEqual(rho.evolve(chan1 @ chan1), targ) # Compose different dimensions kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(4, 2, 4) chan1 = Kraus(kraus1) chan2 = Kraus(kraus2) targ = rho & chan1 & chan2 self.assertEqual(rho.evolve(chan2.dot(chan1)), targ) self.assertEqual(rho.evolve(chan2 @ chan1), targ) def test_compose_front(self): """Test deprecated front compose method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Kraus(self.UX) chan2 = Kraus(self.UY) chan = chan1.compose(chan2, front=True) targ = rho & Kraus(self.UZ) self.assertEqual(rho & chan, targ) # 50% depolarizing channel chan1 = Kraus(self.depol_kraus(0.5)) chan = chan1.compose(chan1, front=True) targ = rho & Kraus(self.depol_kraus(0.75)) self.assertEqual(rho & chan, targ) # Compose different dimensions kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(4, 2, 4) chan1 = Kraus(kraus1) chan2 = Kraus(kraus2) targ = rho & chan1 & chan2 chan = chan2.compose(chan1, front=True) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho & chan, targ) def test_expand(self): """Test expand method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = Kraus(self.UI) chan2 = Kraus(self.UX) # X \otimes I chan = chan1.expand(chan2) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init & chan, rho_targ) # I \otimes X chan = chan2.expand(chan1) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init & chan, rho_targ) # Completely depolarizing chan_dep = Kraus(self.depol_kraus(1)) chan = chan_dep.expand(chan_dep) rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init & chan, rho_targ) def test_tensor(self): """Test tensor method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = Kraus(self.UI) chan2 = Kraus(self.UX) # X \otimes I chan = chan2.tensor(chan1) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init & chan, rho_targ) # I \otimes X chan = chan1.tensor(chan2) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init & chan, rho_targ) # Completely depolarizing chan_dep = Kraus(self.depol_kraus(1)) chan = chan_dep.tensor(chan_dep) rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init & chan, rho_targ) def test_power(self): """Test power method.""" # 10% depolarizing channel rho = DensityMatrix(np.diag([1, 0])) p_id = 0.9 chan = Kraus(self.depol_kraus(1 - p_id)) # Compose 3 times p_id3 = p_id**3 chan3 = chan.power(3) targ3a = rho & chan & chan & chan self.assertEqual(rho & chan3, targ3a) targ3b = rho & Kraus(self.depol_kraus(1 - p_id3)) self.assertEqual(rho & chan3, targ3b) def test_add(self): """Test add method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4) # Random Single-Kraus maps chan1 = Kraus(kraus1) chan2 = Kraus(kraus2) targ = (rho & chan1) + (rho & chan2) chan = chan1._add(chan2) self.assertEqual(rho & chan, targ) chan = chan1 + chan2 self.assertEqual(rho & chan, targ) # Random Single-Kraus maps chan = Kraus((kraus1, kraus2)) targ = 2 * (rho & chan) chan = chan._add(chan) self.assertEqual(rho & chan, targ) def test_add_qargs(self): """Test add method with qargs.""" rho = DensityMatrix(self.rand_rho(8)) kraus = self.rand_kraus(8, 8, 4) kraus0 = self.rand_kraus(2, 2, 4) op = Kraus(kraus) op0 = Kraus(kraus0) eye = Kraus(self.UI) with self.subTest(msg="qargs=[0]"): value = op + op0([0]) target = op + eye.tensor(eye).tensor(op0) self.assertEqual(rho & value, rho & target) with self.subTest(msg="qargs=[1]"): value = op + op0([1]) target = op + eye.tensor(op0).tensor(eye) self.assertEqual(rho & value, rho & target) with self.subTest(msg="qargs=[2]"): value = op + op0([2]) target = op + op0.tensor(eye).tensor(eye) self.assertEqual(rho & value, rho & target) def test_sub_qargs(self): """Test sub method with qargs.""" rho = DensityMatrix(self.rand_rho(8)) kraus = self.rand_kraus(8, 8, 4) kraus0 = self.rand_kraus(2, 2, 4) op = Kraus(kraus) op0 = Kraus(kraus0) eye = Kraus(self.UI) with self.subTest(msg="qargs=[0]"): value = op - op0([0]) target = op - eye.tensor(eye).tensor(op0) self.assertEqual(rho & value, rho & target) with self.subTest(msg="qargs=[1]"): value = op - op0([1]) target = op - eye.tensor(op0).tensor(eye) self.assertEqual(rho & value, rho & target) with self.subTest(msg="qargs=[2]"): value = op - op0([2]) target = op - op0.tensor(eye).tensor(eye) self.assertEqual(rho & value, rho & target) def test_subtract(self): """Test subtract method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4) # Random Single-Kraus maps chan1 = Kraus(kraus1) chan2 = Kraus(kraus2) targ = (rho & chan1) - (rho & chan2) chan = chan1 - chan2 self.assertEqual(rho & chan, targ) # Random Single-Kraus maps chan = Kraus((kraus1, kraus2)) targ = 0 * (rho & chan) chan = chan - chan self.assertEqual(rho & chan, targ) def test_multiply(self): """Test multiply method.""" # Random initial state and Kraus ops rho = DensityMatrix(self.rand_rho(2)) val = 0.5 kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4) # Single Kraus set chan1 = Kraus(kraus1) targ = val * (rho & chan1) chan = chan1._multiply(val) self.assertEqual(rho & chan, targ) chan = val * chan1 self.assertEqual(rho & chan, targ) targ = (rho & chan1) * val chan = chan1 * val self.assertEqual(rho & chan, targ) # Double Kraus set chan2 = Kraus((kraus1, kraus2)) targ = val * (rho & chan2) chan = chan2._multiply(val) self.assertEqual(rho & chan, targ) chan = val * chan2 self.assertEqual(rho & chan, targ) def test_multiply_except(self): """Test multiply method raises exceptions.""" chan = Kraus(self.depol_kraus(1)) self.assertRaises(QiskitError, chan._multiply, "s") self.assertRaises(QiskitError, chan.__rmul__, "s") self.assertRaises(QiskitError, chan._multiply, chan) self.assertRaises(QiskitError, chan.__rmul__, chan) def test_negate(self): """Test negate method""" rho = DensityMatrix(np.diag([1, 0])) targ = DensityMatrix(np.diag([-0.5, -0.5])) chan = -Kraus(self.depol_kraus(1)) self.assertEqual(rho & chan, targ) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import qiskit.qasm3 program = """ OPENQASM 3.0; include "stdgates.inc"; input float[64] a; qubit[3] q; bit[2] mid; bit[3] out; let aliased = q[0:1]; gate my_gate(a) c, t { gphase(a / 2); ry(a) c; cx c, t; } gate my_phase(a) c { ctrl @ inv @ gphase(a) c; } my_gate(a * 2) aliased[0], q[{1, 2}][0]; measure q[0] -> mid[0]; measure q[1] -> mid[1]; while (mid == "00") { reset q[0]; reset q[1]; my_gate(a) q[0], q[1]; my_phase(a - pi/2) q[1]; mid[0] = measure q[0]; mid[1] = measure q[1]; } if (mid[0]) { let inner_alias = q[{0, 1}]; reset inner_alias; } out = measure q; """ circuit = qiskit.qasm3.loads(program) circuit.draw("mpl")
https://github.com/chaitanya-bhargava/QiskitSolutions
chaitanya-bhargava
## 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)