repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, IBMQ, execute, transpile, Aer from qiskit.providers.aer import QasmSimulator from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.compiler import transpile # 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.h(1) qc.cx(1,0) qc.rx(dt, 1) qc.rz(- dt, 1) qc.rz(dt, 0) qc.cx(1,0) qc.h(1) qc.rx(dt, [1]) qc.rz(-dt, [0,1]) qc.rx(-dt, [0,1]) 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 # 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) # YOUR TROTTERIZATION GOES HERE -- FINISH (end of example) # The final time of the state evolution target_time = np.pi # Number of trotter steps trotter_steps = 4 ### CAN BE >= 4 # Initialize quantum circuit for 3 qubits qr = QuantumRegister(3) cr = ClassicalRegister(3) qc = QuantumCircuit(qr, cr) # 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>) # init state |10> (= |110>) qc.x(1) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Simulate time evolution under H_heis3 Hamiltonian for _ in range(trotter_steps): qc.append(Trot_gate, [qr[1], qr[2]]) qc.cx(qr[1], qr[0]) qc.cx(qr[2], qr[1]) # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / trotter_steps}) qc.measure(qr, cr) t0_qc = transpile(qc, optimization_level=0, basis_gates=["sx","rz","cx"]) # t0_qc.draw("mpl") t0_qc = t0_qc.reverse_bits() # t0_qc.draw("mpl") shots = 8192 reps = 1 # WE USE A NOISELESS SIMULATION HERE backend = Aer.get_backend('qasm_simulator') jobs = [] for _ in range(reps): # execute job = execute(t0_qc, backend=backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) counts_110 = [] # counts_10 = [] for trotter_steps in range(1, 15, 1): print("number of trotter steps: ", trotter_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(3) cr = ClassicalRegister(3) qc = QuantumCircuit(qr, cr) # 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>) # init state |10> (= |110>) qc.x(1) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Simulate time evolution under H_heis3 Hamiltonian for _ in range(0, trotter_steps + 1): qc.append(Trot_gate, [qr[1], qr[2]]) qc.cx(qr[1], qr[0]) qc.cx(qr[2], qr[1]) # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / trotter_steps}) t0_qc = transpile(qc, optimization_level=0, basis_gates=["sx","rz","cx"]) t0_qc = t0_qc.reverse_bits() t0_qc.measure(qr, cr) print("circuit depth: ", t0_qc.depth()) job = execute(t0_qc, backend=backend, shots=shots, optimization_level=0) print("pribability distribution: ", job.result().get_counts()) counts_110.append(job.result().get_counts().get("110", 0)) # counts_10.append(job.result().get_counts().get("10", 0)) print() plt.plot(range(1,15), counts_110) plt.xlabel("trotter steps") plt.ylabel("shot counts of 110") plt.title("counts of |110>") plt.plot(range(1,15), counts_01) plt.xlabel("trotter steps") plt.ylabel("shot counts of 01") plt.title("counts of |01>")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw, IQXDebugging from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial') draw(qc, style=IQXDebugging())
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
#!/usr/bin/env python3 # Author: Daniel Escanez-Exposito from qiskit import execute, QuantumCircuit, QuantumRegister, ClassicalRegister from crypto.e91.sender import Sender from crypto.e91.receiver import Receiver from crypto.e91.eavesdropper import Eveasdropper import binascii E91_SIMULATOR = 'E91 SIMULATOR' ## An implementation of the E91 protocol ## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html class E91Algorithm: ## Get the simplest (and maximal) example of quantum entanglement * (- 1j) def get_bell_pair(self, qr, cr): circuit = QuantumCircuit(qr, cr) circuit.x([0, 1]) circuit.h(0) circuit.cx(0, 1) circuit.s([0, 1]) return circuit ## Generate a key for Alice and Bob def generate_key(self, backend, original_bits_size, verbose): # Initialize the bell pair, quantum and classical registers qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(4, name="cr") singlet = self.get_bell_pair(qr, cr) # Initialize entities Alice, Eve and Bob alice = Sender('Alice', original_bits_size, qr, cr) alice.set_axes() eve = Eveasdropper('Eve', original_bits_size, qr, cr) eve.set_axes(density=self.measure_density) bob = Receiver('Bob', original_bits_size, qr, cr) bob.set_axes() # Create circuits and get results circuits = [] for i in range(original_bits_size): if eve.axes[i] != None: eve_measure = eve.measurements[eve.axes[i][0]] + eve.measurements[eve.axes[i][1]] else: eve_measure = QuantumCircuit(qr, cr) alice_measure = alice.measurements[alice.axes[i]] bob_measure = bob.measurements[bob.axes[i]] circuit = singlet + eve_measure + alice_measure + bob_measure eve_measure_name = '_' + eve.axes[i][0] + '-' + eve.axes[i][1] if eve.axes[i] != None else '' circuit.name = str(i) + ':' + alice.axes[i] + '_' + bob.axes[i] + eve_measure_name circuits.append(circuit) result = execute(circuits, backend=backend, shots=1).result() alice.create_values(result, circuits) bob.create_values(result, circuits) eve.create_values(result, circuits) # Publish the measurements # Obtain values from the circuit measurements count = [[0, 0, 0, 0], # XW observable [0, 0, 0, 0], # XV observable [0, 0, 0, 0], # ZW observable [0, 0, 0, 0]] # ZV observable alice.key = []; eve.key = []; bob.key = [] for i in range(original_bits_size): # If Alice and Bob have measured the spin projections onto the a_2/b_1 or a_3/b_2 directions if (alice.axes[i] == 'a2' and bob.axes[i] == 'b1') or \ (alice.axes[i] == 'a3' and bob.axes[i] == 'b2'): alice.key.append(alice.values[i]) bob.key.append(0 if bob.values[i] == 1 else 1) if eve.values[i] != [None, None]: eve.key.append([eve.values[i][0], 0 if eve.values[i][1] == 1 else 1]) else: eve.key.append([None, None]) else: eve.key.append([None, None]) if (alice.axes[i] == 'a1' or alice.axes[i] == 'a3') and (bob.axes[i] == 'b1' or bob.axes[i] == 'b3'): res = list(result.get_counts(circuits[i]).keys())[0] j = 2 * int(alice.axes[i] == 'a3') + int(bob.axes[i] == 'b3') k = int(res[-2:], base=2) count[j][k] += 1 corr = self.compute_corr(count) keyLength = len(alice.key) info = self.get_mismatches_info(alice, eve, bob) if verbose: alice.show_values() alice.show_measurements() alice.show_axes() eve.show_values() eve.show_measurements() eve.show_axes() bob.show_values() bob.show_measurements() bob.show_axes() alice.show_key() bob.show_key() print('\nNumber of mismatching bits: ' + str(info['alice_bob_key_mismatches'])) print('\nEve\'s knowledge of Alice\'s key: ' + str(round(info['eve_alice_knowledge'] * 100, 2)) + '%') print('Eve\'s knowledge of Bob\'s key: ' + str(round(info['eve_bob_knowledge'] * 100, 2)) + '%') # CHSH inequality test print('CHSH correlation:', corr) # Key length test print('Key length:', len(alice.key)) print('\nCHSH correlation should be close to -2 * √2 ~= -2.8282') print('Key length should be close to', original_bits_size, '* 2 / 9 =', original_bits_size * 2 / 9) if alice.check_corr(corr): alice.confirm_key() bob.confirm_key() if verbose: print('\nCHSH correlation is in −2√2 · (1 ± 0.1)') print('\nFinal Keys') alice.show_key() bob.show_key() print('\nSecure Communication!') elif verbose: print('\nCHSH correlation is not in −2√2 · (1 ± 0.1)') print('Unsecure Communication! Eve has been detected intercepting messages\n') return alice, bob, corr def get_mismatches_info(self, alice, eve, bob): keyLength = len(alice.key) info = { 'alice_bob_key_mismatches': 0, 'eve_alice_key_mismatches': 0, 'eve_bob_key_mismatches': 0, 'eve_alice_knowledge': 0, 'eve_bob_knowledge': 0 } for j in range(keyLength): if alice.key[j] != bob.key[j]: info['alice_bob_key_mismatches'] += 1 if j < len(eve.key): if eve.key[j][0] != alice.key[j]: info['eve_alice_key_mismatches'] += 1 if eve.key[j][1] != bob.key[j]: info['eve_bob_key_mismatches'] += 1 if keyLength > 0 and len(eve.key) > 0: # Eve's knowledge of Bob's key info['eve_alice_knowledge'] = (keyLength - info['eve_alice_key_mismatches']) / keyLength # Eve's knowledge of Alice's key info['eve_bob_knowledge'] = (keyLength - info['eve_bob_key_mismatches']) / keyLength return info ## Calculate correlation def compute_corr(self, count): # Number of the results obtained from the measurements in a particular basis total = [sum(count[0]), sum(count[1]), sum(count[2]), sum(count[3])] check_total = list(map(lambda x: x == 0, total)) if any(check_total): return float('-inf') # Expectation values of XW, XV, ZW and ZV observables expect11 = (count[0][0] - count[0][1] - count[0][2] + count[0][3]) / total[0] # -1 / sqrt(2) expect13 = (count[1][0] - count[1][1] - count[1][2] + count[1][3]) / total[1] # 1 / sqrt(2) expect31 = (count[2][0] - count[2][1] - count[2][2] + count[2][3]) / total[2] # -1 / sqrt(2) expect33 = (count[3][0] - count[3][1] - count[3][2] + count[3][3]) / total[3] # -1 / sqrt(2) return expect11 - expect13 + expect31 + expect33 # Calculate the CHSC correlation value ## Run the implementation of E91 protocol def run(self, message, backend, original_bits_size, measure_density, n_bits, verbose): ## The original size of the message self.original_bits_size = original_bits_size ## The probability of an interception occurring self.measure_density = measure_density alice, bob, corr = self.generate_key(backend, original_bits_size, verbose) if not (alice.is_safe_key and bob.is_safe_key): if verbose: print('❌ Message not send') return False, corr alice.generate_otp(n_bits) bob.generate_otp(n_bits) encoded_message = alice.xor_otp_message(message) decoded_message = bob.xor_otp_message(encoded_message) if verbose: alice.show_otp() bob.show_otp() print('\nInitial Message:') print(message) print('Encoded Message:') print(encoded_message) print('💡 Decoded Message:') print(decoded_message) if message == decoded_message: print('\n✅ The initial message and the decoded message are identical') else: print('\n❌ The initial message and the decoded message are different') return True, corr
https://github.com/kaelynj/Qiskit-HubbardModel
kaelynj
#Jupyter notebook to check if imports work correctly %matplotlib inline import sys sys.path.append('./src') import HubbardEvolutionChain as hc import ClassicalHubbardEvolutionChain as chc from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer, QuantumRegister, ClassicalRegister from qiskit.compiler import transpile, assemble from qiskit.quantum_info import Operator from qiskit.tools.monitor import job_monitor from qiskit.tools.jupyter import * import qiskit.visualization as qvis import random as rand import scipy.linalg as la provider = IBMQ.load_account() import matplotlib.pyplot as plt import matplotlib.colors as mcolors import numpy as np from matplotlib import rcParams rcParams['text.usetex'] = True def get_bin(x, n=0): """ Get the binary representation of x. Parameters: x (int), n (int, number of digits)""" binry = format(x, 'b').zfill(n) sup = list( reversed( binry[0:int(len(binry)/2)] ) ) sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) ) return format(x, 'b').zfill(n) #Energy Measurement Functions #Measure the total repulsion from circuit run def measure_repulsion(U, num_sites, results, shots): repulsion = 0. #Figure out how to include different hoppings later for state in results: for i in range( int( len(state)/2 ) ): if state[i]=='1': if state[i+num_sites]=='1': repulsion += U*results.get(state)/shots return repulsion def measure_hopping(hopping, pairs, circuit, num_qubits): #Add diagonalizing circuit for pair in pairs: circuit.cnot(pair[0],pair[1]) circuit.ch(pair[1],pair[0]) circuit.cnot(pair[0],pair[1]) #circuit.measure(pair[0],pair[0]) #circuit.measure(pair[1],pair[1]) circuit.measure_all() #Run circuit backend = Aer.get_backend('qasm_simulator') shots = 8192 max_credits = 10 #Max number of credits to spend on execution #print("Computing Hopping") hop_exp = execute(circuit, backend=backend, shots=shots, max_credits=max_credits) job_monitor(hop_exp) result = hop_exp.result() counts = result.get_counts(circuit) #print(counts) #Compute energy #print(pairs) for pair in pairs: hop_eng = 0. #print('Pair is: ',pair) for state in counts: #print('State is: ',state,' Index at pair[0]: ',num_qubits-1-pair[0],' Val: ',state[num_qubits-pair[0]]) if state[num_qubits-1-pair[0]]=='1': prob_01 = counts.get(state)/shots #print('Check state is: ',state) for comp_state in counts: #print('Comp State is: ',state,' Index at pair[0]: ',num_qubits-1-pair[1],' Val: ',comp_state[num_qubits-pair[0]]) if comp_state[num_qubits-1-pair[1]]=='1': #print('Comp state is: ',comp_state) hop_eng += -hopping*(prob_01 - counts.get(comp_state)/shots) return hop_eng #nsites, excitations, total_time, dt, hop, U, trotter_steps dt = 0.25 #Delta t total_time = 5. #time_steps = int(T/dt) hop = 1.0 #Hopping parameter #t = [1.0, 2.] U = 2. #On-Site repulsion #time_steps = 10 nsites = 3 trotter_steps = 1000 excitations = np.array([1]) numq = 2*nsites num_steps = int(total_time/dt) print('Num Steps: ',num_steps) print('Total Time: ', total_time) data = np.zeros((2**numq, num_steps)) energies = np.zeros(num_steps) for t_step in range(0, num_steps): #Create circuit with t_step number of steps q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #=========USE THIS REGION TO SET YOUR INITIAL STATE============== #Loop over each excitation for flip in excitations: qcirc.x(flip) #=============================================================== qcirc.barrier() #Append circuit with Trotter steps needed hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps) #Measure the circuit for i in range(numq): qcirc.measure(i, i) #Choose provider and backend provider = IBMQ.get_provider() #backend = Aer.get_backend('statevector_simulator') backend = Aer.get_backend('qasm_simulator') #backend = provider.get_backend('ibmq_qasm_simulator') #backend = provider.get_backend('ibmqx4') #backend = provider.get_backend('ibmqx2') #backend = provider.get_backend('ibmq_16_melbourne') shots = 8192 max_credits = 10 #Max number of credits to spend on execution job_exp = execute(qcirc, backend=backend, shots=shots, max_credits=max_credits) #job_monitor(job_exp) result = job_exp.result() counts = result.get_counts(qcirc) print(result.get_counts(qcirc)) print("Job: ",t_step+1, " of ", num_steps," computing energy...") #Store results in data array and normalize them for i in range(2**numq): if counts.get(get_bin(i,numq)) is None: dat = 0 else: dat = counts.get(get_bin(i,numq)) data[i,t_step] = dat/shots #======================================================= #Compute energy of system #Compute repulsion energies repulsion_energy = measure_repulsion(U, nsites, counts, shots) print('Repulsion: ', repulsion_energy) #Compute hopping energies #Get list of hopping pairs even_pairs = [] for i in range(0,nsites-1,2): #up_pair = [i, i+1] #dwn_pair = [i+nsites, i+nsites+1] even_pairs.append([i, i+1]) even_pairs.append([i+nsites, i+nsites+1]) odd_pairs = [] for i in range(1,nsites-1,2): odd_pairs.append([i, i+1]) odd_pairs.append([i+nsites, i+nsites+1]) #Start with even hoppings, initialize circuit and find hopping pairs q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #Loop over each excitation for flip in excitations: qcirc.x(flip) qcirc.barrier() #Append circuit with Trotter steps needed hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps) '''for pair in odd_pairs: qcirc.cnot(pair[0],pair[1]) qcirc.ch(pair[1],pair[0]) qcirc.cnot(pair[0],pair[1]) qcirc.measure(pair[0],pair[0]) qcirc.measure(pair[1],pair[1]) #circuit.draw() print(t_step) ''' #break even_hopping = measure_hopping(hop, even_pairs, qcirc, numq) print('Even hopping: ', even_hopping) #=============================================================== #Now do the same for the odd hoppings #Start with even hoppings, initialize circuit and find hopping pairs q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #Loop over each excitation for flip in excitations: qcirc.x(flip) qcirc.barrier() #Append circuit with Trotter steps needed hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps) odd_hopping = measure_hopping(hop, odd_pairs, qcirc, numq) print('Odd hopping: ',odd_hopping) total_energy = repulsion_energy + even_hopping + odd_hopping print(total_energy) energies[t_step] = total_energy print("Total Energy is: ", total_energy) print("Job: ",t_step+1, " of ", num_steps," complete") #qcirc.draw() plt.plot(energies) print(np.ptp(energies)) #Trotter Steps=1000 plt.plot(energies) print(np.ptp(energies)) #Trotter Steps=100 plt.plot(energies) print(np.ptp(energies)) #Trotter Steps=50 plt.plot(energies) print(np.ptp(energies)) #Trotter Steps=10 plt.plot(energies) print(np.ptp(energies)) #Trotter Steps=100
https://github.com/rickapocalypse/final_paper_qiskit_sat
rickapocalypse
from qiskit import * import matplotlib.pyplot as plt from qiskit.circuit import QuantumCircuit from qiskit.tools.visualization import plot_histogram from qiskit.tools.monitor import job_monitor qc = QuantumCircuit(2,2) # Bell Gate bell = QuantumCircuit(2) bell.h(0) bell.cx(0,1) bell.to_gate() bell.name = 'Bell state' # Measure Bell measure = QuantumCircuit(2) measure.cx(0,1) measure.h(0) measure.to_gate() measure.name = 'Measure in Bell state' qc.append(bell,[0,1]) qc.append(measure,[0,1]) qc.measure([0,1], [0,1]) bell.draw(output='mpl') measure.draw(output='mpl') qc.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend = simulator).result() plot_histogram(result.get_counts(qc)) plt.show() IBMQ.load_account() host = IBMQ.get_provider('ibm-q') quantum_computer = host.get_backend('ibmq_santiago') result_qcomputer = execute(qc, backend= quantum_computer) job_monitor(result_qcomputer) result_qcomputer = result_qcomputer.result() plot_histogram(result_qcomputer) plt.show()
https://github.com/UST-QuAntiL/nisq-analyzer-content
UST-QuAntiL
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit # https://quantum-circuit.com/app_details/about/bw5r9HTiTHvQHtCB5 qc = QuantumCircuit() q = QuantumRegister(5, 'q') c = ClassicalRegister(3, 'c') qc.add_register(q) qc.add_register(c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[1]) qc.cx(q[2], q[3]) qc.cu1(0, q[1], q[0]) qc.cx(q[2], q[4]) qc.h(q[0]) qc.cu1(0, q[1], q[2]) qc.cu1(0, q[0], q[2]) qc.h(q[2]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) def get_circuit(**kwargs): """Get circuit of Shor with input 15.""" return qc
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 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. """StateFn Class""" from typing import Callable, Dict, List, Optional, Set, Tuple, Union import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Instruction, ParameterExpression from qiskit.opflow.operator_base import OperatorBase from qiskit.quantum_info import Statevector from qiskit.result import Result from qiskit.utils.deprecation import deprecate_func class StateFn(OperatorBase): r""" Deprecated: A class for representing state functions and measurements. State functions are defined to be complex functions over a single binary string (as compared to an operator, which is defined as a function over two binary strings, or a function taking a binary function to another binary function). This function may be called by the eval() method. Measurements are defined to be functionals over StateFns, taking them to real values. Generally, this real value is interpreted to represent the probability of some classical state (binary string) being observed from a probabilistic or quantum system represented by a StateFn. This leads to the equivalent definition, which is that a measurement m is a function over binary strings producing StateFns, such that the probability of measuring a given binary string b from a system with StateFn f is equal to the inner product between f and m(b). NOTE: State functions here are not restricted to wave functions, as there is no requirement of normalization. """ def __init_subclass__(cls): cls.__new__ = lambda cls, *args, **kwargs: super().__new__(cls) @staticmethod # pylint: disable=unused-argument def __new__( cls, primitive: Union[ str, dict, Result, list, np.ndarray, Statevector, QuantumCircuit, Instruction, OperatorBase, ] = None, coeff: Union[complex, ParameterExpression] = 1.0, is_measurement: bool = False, ) -> "StateFn": """A factory method to produce the correct type of StateFn subclass based on the primitive passed in. Primitive, coeff, and is_measurement arguments are passed into subclass's init() as-is automatically by new(). Args: primitive: The primitive which defines the behavior of the underlying State function. coeff: A coefficient by which the state function is multiplied. is_measurement: Whether the StateFn is a measurement operator Returns: The appropriate StateFn subclass for ``primitive``. Raises: TypeError: Unsupported primitive type passed. """ # Prevents infinite recursion when subclasses are created if cls.__name__ != StateFn.__name__: return super().__new__(cls) # pylint: disable=cyclic-import if isinstance(primitive, (str, dict, Result)): from .dict_state_fn import DictStateFn return DictStateFn.__new__(DictStateFn) if isinstance(primitive, (list, np.ndarray, Statevector)): from .vector_state_fn import VectorStateFn return VectorStateFn.__new__(VectorStateFn) if isinstance(primitive, (QuantumCircuit, Instruction)): from .circuit_state_fn import CircuitStateFn return CircuitStateFn.__new__(CircuitStateFn) if isinstance(primitive, OperatorBase): from .operator_state_fn import OperatorStateFn return OperatorStateFn.__new__(OperatorStateFn) raise TypeError( "Unsupported primitive type {} passed into StateFn " "factory constructor".format(type(primitive)) ) # TODO allow normalization somehow? @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, primitive: Union[ str, dict, Result, list, np.ndarray, Statevector, QuantumCircuit, Instruction, OperatorBase, ] = None, coeff: Union[complex, ParameterExpression] = 1.0, is_measurement: bool = False, ) -> None: """ Args: primitive: The primitive which defines the behavior of the underlying State function. coeff: A coefficient by which the state function is multiplied. is_measurement: Whether the StateFn is a measurement operator """ super().__init__() self._primitive = primitive self._is_measurement = is_measurement self._coeff = coeff @property def primitive(self): """The primitive which defines the behavior of the underlying State function.""" return self._primitive @property def coeff(self) -> Union[complex, ParameterExpression]: """A coefficient by which the state function is multiplied.""" return self._coeff @property def is_measurement(self) -> bool: """Whether the StateFn object is a measurement Operator.""" return self._is_measurement @property def settings(self) -> Dict: """Return settings.""" return { "primitive": self._primitive, "coeff": self._coeff, "is_measurement": self._is_measurement, } def primitive_strings(self) -> Set[str]: raise NotImplementedError @property def num_qubits(self) -> int: raise NotImplementedError def add(self, other: OperatorBase) -> OperatorBase: raise NotImplementedError def adjoint(self) -> OperatorBase: raise NotImplementedError def _expand_dim(self, num_qubits: int) -> "StateFn": raise NotImplementedError def permute(self, permutation: List[int]) -> OperatorBase: """Permute the qubits of the state function. Args: permutation: A list defining where each qubit should be permuted. The qubit at index j of the circuit should be permuted to position permutation[j]. Returns: A new StateFn containing the permuted primitive. """ raise NotImplementedError def equals(self, other: OperatorBase) -> bool: if not isinstance(other, type(self)) or not self.coeff == other.coeff: return False return self.primitive == other.primitive # Will return NotImplementedError if not supported def mul(self, scalar: Union[complex, ParameterExpression]) -> OperatorBase: if not isinstance(scalar, (int, float, complex, ParameterExpression)): raise ValueError( "Operators can only be scalar multiplied by float or complex, not " "{} of type {}.".format(scalar, type(scalar)) ) if hasattr(self, "from_operator"): return self.__class__( self.primitive, coeff=self.coeff * scalar, is_measurement=self.is_measurement, from_operator=self.from_operator, ) else: return self.__class__( self.primitive, coeff=self.coeff * scalar, is_measurement=self.is_measurement ) def tensor(self, other: OperatorBase) -> OperatorBase: r""" Return tensor product between self and other, overloaded by ``^``. Note: You must be conscious of Qiskit's big-endian bit printing convention. Meaning, Plus.tensor(Zero) produces a \|+⟩ on qubit 0 and a \|0⟩ on qubit 1, or \|+⟩⨂\|0⟩, but would produce a QuantumCircuit like \|0⟩-- \|+⟩-- Because Terra prints circuits and results with qubit 0 at the end of the string or circuit. Args: other: The ``OperatorBase`` to tensor product with self. Returns: An ``OperatorBase`` equivalent to the tensor product of self and other. """ raise NotImplementedError def tensorpower(self, other: int) -> Union[OperatorBase, int]: if not isinstance(other, int) or other <= 0: raise TypeError("Tensorpower can only take positive int arguments") temp = StateFn( self.primitive, coeff=self.coeff, is_measurement=self.is_measurement ) # type: OperatorBase for _ in range(other - 1): temp = temp.tensor(self) return temp def _expand_shorter_operator_and_permute( self, other: OperatorBase, permutation: Optional[List[int]] = None ) -> Tuple[OperatorBase, OperatorBase]: # pylint: disable=cyclic-import from ..operator_globals import Zero if self == StateFn({"0": 1}, is_measurement=True): # Zero is special - we'll expand it to the correct qubit number. return StateFn("0" * other.num_qubits, is_measurement=True), other elif other == Zero: # Zero is special - we'll expand it to the correct qubit number. return self, StateFn("0" * self.num_qubits) return super()._expand_shorter_operator_and_permute(other, permutation) def to_matrix(self, massive: bool = False) -> np.ndarray: raise NotImplementedError def to_density_matrix(self, massive: bool = False) -> np.ndarray: """Return matrix representing product of StateFn evaluated on pairs of basis states. Overridden by child classes. Args: massive: Whether to allow large conversions, e.g. creating a matrix representing over 16 qubits. Returns: The NumPy array representing the density matrix of the State function. Raises: ValueError: If massive is set to False, and exponentially large computation is needed. """ raise NotImplementedError def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: r""" Composition (Linear algebra-style: A@B(x) = A(B(x))) is not well defined for states in the binary function model, but is well defined for measurements. Args: other: The Operator to compose with self. permutation: ``List[int]`` which defines permutation on other operator. front: If front==True, return ``other.compose(self)``. Returns: An Operator equivalent to the function composition of self and other. Raises: ValueError: If self is not a measurement, it cannot be composed from the right. """ # TODO maybe allow outers later to produce density operators or projectors, but not yet. if not self.is_measurement and not front: raise ValueError( "Composition with a Statefunction in the first operand is not defined." ) new_self, other = self._expand_shorter_operator_and_permute(other, permutation) if front: return other.compose(self) # TODO maybe include some reduction here in the subclasses - vector and Op, op and Op, etc. from ..primitive_ops.circuit_op import CircuitOp if self.primitive == {"0" * self.num_qubits: 1.0} and isinstance(other, CircuitOp): # Returning CircuitStateFn return StateFn( other.primitive, is_measurement=self.is_measurement, coeff=self.coeff * other.coeff ) from ..list_ops.composed_op import ComposedOp if isinstance(other, ComposedOp): return ComposedOp([new_self] + other.oplist, coeff=new_self.coeff * other.coeff) return ComposedOp([new_self, other]) def power(self, exponent: int) -> OperatorBase: """Compose with Self Multiple Times, undefined for StateFns. Args: exponent: The number of times to compose self with self. Raises: ValueError: This function is not defined for StateFns. """ raise ValueError("Composition power over Statefunctions or Measurements is not defined.") def __str__(self) -> str: prim_str = str(self.primitive) if self.coeff == 1.0: return "{}({})".format( "StateFunction" if not self.is_measurement else "Measurement", self.coeff ) else: return "{}({}) * {}".format( "StateFunction" if not self.is_measurement else "Measurement", self.coeff, prim_str ) def __repr__(self) -> str: return "{}({}, coeff={}, is_measurement={})".format( self.__class__.__name__, repr(self.primitive), self.coeff, self.is_measurement ) def eval( self, front: Optional[ Union[str, Dict[str, complex], np.ndarray, OperatorBase, Statevector] ] = None, ) -> Union[OperatorBase, complex]: raise NotImplementedError @property def parameters(self): params = set() if isinstance(self.primitive, (OperatorBase, QuantumCircuit)): params.update(self.primitive.parameters) if isinstance(self.coeff, ParameterExpression): params.update(self.coeff.parameters) return params def assign_parameters(self, param_dict: dict) -> OperatorBase: param_value = self.coeff if isinstance(self.coeff, ParameterExpression): unrolled_dict = self._unroll_param_dict(param_dict) if isinstance(unrolled_dict, list): from ..list_ops.list_op import ListOp return ListOp([self.assign_parameters(param_dict) for param_dict in unrolled_dict]) if self.coeff.parameters <= set(unrolled_dict.keys()): binds = {param: unrolled_dict[param] for param in self.coeff.parameters} param_value = float(self.coeff.bind(binds)) return self.traverse(lambda x: x.assign_parameters(param_dict), coeff=param_value) # Try collapsing primitives where possible. Nothing to collapse here. def reduce(self) -> OperatorBase: return self def traverse( self, convert_fn: Callable, coeff: Optional[Union[complex, ParameterExpression]] = None ) -> OperatorBase: r""" Apply the convert_fn to the internal primitive if the primitive is an Operator (as in the case of ``OperatorStateFn``). Otherwise do nothing. Used by converters. Args: convert_fn: The function to apply to the internal OperatorBase. coeff: A coefficient to multiply by after applying convert_fn. If it is None, self.coeff is used instead. Returns: The converted StateFn. """ if coeff is None: coeff = self.coeff if isinstance(self.primitive, OperatorBase): return StateFn( convert_fn(self.primitive), coeff=coeff, is_measurement=self.is_measurement ) else: return self def to_matrix_op(self, massive: bool = False) -> OperatorBase: """Return a ``VectorStateFn`` for this ``StateFn``. Args: massive: Whether to allow large conversions, e.g. creating a matrix representing over 16 qubits. Returns: A VectorStateFn equivalent to self. """ # pylint: disable=cyclic-import from .vector_state_fn import VectorStateFn return VectorStateFn(self.to_matrix(massive=massive), is_measurement=self.is_measurement) def to_circuit_op(self) -> OperatorBase: """Returns a ``CircuitOp`` equivalent to this Operator.""" raise NotImplementedError # TODO to_dict_op def sample( self, shots: int = 1024, massive: bool = False, reverse_endianness: bool = False ) -> Dict[str, float]: """Sample the state function as a normalized probability distribution. Returns dict of bitstrings in order of probability, with values being probability. Args: shots: The number of samples to take to approximate the State function. massive: Whether to allow large conversions, e.g. creating a matrix representing over 16 qubits. reverse_endianness: Whether to reverse the endianness of the bitstrings in the return dict to match Terra's big-endianness. Returns: A dict containing pairs sampled strings from the State function and sampling frequency divided by shots. """ raise NotImplementedError
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Clifford, random_clifford qc = QuantumCircuit(3) cliff = random_clifford(2) qc.append(cliff, [0, 1]) qc.ccx(0, 1, 2) qc.draw('mpl')
https://github.com/hamburgerguy/Quantum-Algorithm-Implementations
hamburgerguy
"""Qiskit code for running Simon's algorithm on quantum hardware for 2 qubits and b = '11' """ # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, execute # import basic plot tools from qiskit.visualization import plot_histogram from qiskit_textbook.tools import simon_oracle #set b equal to '11' b = '11' #1) initialize qubits n = 2 simon_circuit_2 = QuantumCircuit(n*2, n) #2) Apply Hadamard gates before querying the oracle simon_circuit_2.h(range(n)) #3) Query oracle simon_circuit_2 += simon_oracle(b) #5) Apply Hadamard gates to the input register simon_circuit_2.h(range(n)) #3) and 6) Measure qubits simon_circuit_2.measure(range(n), range(n)) # Load saved IBMQ accounts and get the least busy backend device IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= n and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Execute and monitor the job from qiskit.tools.monitor import job_monitor shots = 1024 job = execute(simon_circuit_2, backend=backend, shots=shots, optimization_level=3) job_monitor(job, interval = 2) # Get results and plot counts device_counts = job.result().get_counts() plot_histogram(device_counts) #additionally, function for calculating dot product of results def bdotz(b, z): accum = 0 for i in range(len(b)): accum += int(b[i]) * int(z[i]) return (accum % 2) print('b = ' + b) for z in device_counts: print( '{}.{} = {} (mod 2) ({:.1f}%)'.format(b, z, bdotz(b,z), device_counts[z]*100/shots)) #the most significant results are those for which b dot z=0(mod 2). '''b = 11 11.00 = 0 (mod 2) (45.0%) 11.01 = 1 (mod 2) (6.2%) 11.10 = 1 (mod 2) (6.4%) 11.11 = 0 (mod 2) (42.4%)'''
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
############################# # Pauli channel on IBMQX2 # ############################# from qiskit import QuantumRegister, QuantumCircuit # Quantum register q = QuantumRegister(5, name="q") # Quantum circuit pauli = QuantumCircuit(q) # Pauli channel acting on q_2 ## Qubit identification system = 2 a_0 = 3 a_1 = 4 ## Define rotation angles theta_1 = 0.0 theta_2 = 0.0 theta_3 = 0.0 ## Construct circuit pauli.ry(theta_1, q[a_0]) pauli.cx(q[a_0], q[a_1]) pauli.ry(theta_2, q[a_0]) pauli.ry(theta_3, q[a_1]) pauli.cx(q[a_0], q[system]) pauli.cy(q[a_1], q[system]) # Draw circuit pauli.draw(output='mpl') #################################### # Depolarizing channel on IBMQX2 # #################################### # Quantum register q = QuantumRegister(5, name="q") # Quantum circuit depolarizing = QuantumCircuit(q) # Depolarizing channel acting on q_2 ## Qubit identification system = 2 a_0 = 1 a_1 = 3 a_2 = 4 ## Define rotation angles theta = 0.0 ## Construct circuit depolarizing.ry(theta, q[a_0]) depolarizing.ry(theta, q[a_1]) depolarizing.ry(theta, q[a_2]) depolarizing.cx(q[a_0], q[system]) depolarizing.cy(q[a_1], q[system]) depolarizing.cz(q[a_2], q[system]) # Draw circuit depolarizing.draw(output='mpl') ####################### # ZZ pump on IBMQX2 # ####################### # Quantum register q = QuantumRegister(5, name='q') # Quantum circuit zz = QuantumCircuit(q) # ZZ pump acting on system qubits ## Qubit identification system = [2, 1] a_zz = 0 ## Define pump efficiency ## and corresponding rotation p = 0.5 theta = 2 * np.arcsin(np.sqrt(p)) ## Construct circuit ### Map information to ancilla zz.cx(q[system[0]], q[system[1]]) zz.x(q[a_zz]) zz.cx(q[system[1]], q[a_zz]) ### Conditional rotation zz.cu3(theta, 0.0, 0.0, q[a_zz], q[system[1]]) ### Inverse mapping zz.cx(q[system[1]], q[a_zz]) zz.cx(q[system[0]], q[system[1]]) # Draw circuit zz.draw(output='mpl') ####################### # XX pump on IBMQX2 # ####################### # Quantum register q = QuantumRegister(5, name='q') # Quantum circuit xx = QuantumCircuit(q) # XX pump acting on system qubits ## Qubit identification system = [2, 1] a_xx = 4 ## Define pump efficiency ## and corresponding rotation p = 0.5 theta = 2 * np.arcsin(np.sqrt(p)) ## Construct circuit ### Map information to ancilla xx.cx(q[system[0]], q[system[1]]) xx.h(q[system[0]]) xx.x(q[a_xx]) xx.cx(q[system[0]], q[a_xx]) ### Conditional rotation xx.cu3(theta, 0.0, 0.0, q[a_xx], q[system[0]]) ### Inverse mapping xx.cx(q[system[0]], q[a_xx]) xx.h(q[system[0]]) xx.cx(q[system[0]], q[system[1]]) # Draw circuit xx.draw(output='mpl') ########################### # ZZ-XX pumps on IBMQX2 # ########################### # Quantum register q = QuantumRegister(5, name='q') # Quantum circuit zz_xx = QuantumCircuit(q) # ZZ and XX pumps acting on system qubits ## Qubit identification system = [2, 1] a_zz = 0 a_xx = 4 ## Define pump efficiency ## and corresponding rotation p = 0.5 theta = 2 * np.arcsin(np.sqrt(p)) ## Construct circuit ## ZZ pump ### Map information to ancilla zz_xx.cx(q[system[0]], q[system[1]]) zz_xx.x(q[a_zz]) zz_xx.cx(q[system[1]], q[a_zz]) ### Conditional rotation zz_xx.cu3(theta, 0.0, 0.0, q[a_zz], q[system[1]]) ### Inverse mapping zz_xx.cx(q[system[1]], q[a_zz]) #zz_xx.cx(q[system[0]], q[system[1]]) ## XX pump ### Map information to ancilla #zz_xx.cx(q[system[0]], q[system[1]]) zz_xx.h(q[system[0]]) zz_xx.x(q[a_xx]) zz_xx.cx(q[system[0]], q[a_xx]) ### Conditional rotation zz_xx.cu3(theta, 0.0, 0.0, q[a_xx], q[system[0]]) ### Inverse mapping zz_xx.cx(q[system[0]], q[a_xx]) zz_xx.h(q[system[0]]) zz_xx.cx(q[system[0]], q[system[1]]) # Draw circuit zz_xx.draw(output='mpl')
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.circuit.library.standard_gates import CHGate, U2Gate, CXGate from qiskit.converters import dag_to_circuit 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) circuit = dag_to_circuit(dag) circuit.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_hinton qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3 , 0) qc.rx(np.pi/5, 1) state = DensityMatrix(qc) plot_state_hinton(state, title="New Hinton Plot")
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 logging import numpy as np from qiskit import QuantumRegister, QuantumCircuit from qiskit.aqua.components.initial_states import InitialState logger = logging.getLogger(__name__) class HartreeFock(InitialState): """A Hartree-Fock initial state.""" CONFIGURATION = { 'name': 'HartreeFock', 'description': 'Hartree-Fock initial state', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'hf_state_schema', 'type': 'object', 'properties': { 'num_orbitals': { 'type': 'integer', 'default': 4, 'minimum': 1 }, 'num_particles': { 'type': 'integer', 'default': 2, 'minimum': 1 }, 'qubit_mapping': { 'type': 'string', 'default': 'parity', 'oneOf': [ {'enum': ['jordan_wigner', 'parity', 'bravyi_kitaev']} ] }, 'two_qubit_reduction': { 'type': 'boolean', 'default': True } }, 'additionalProperties': False } } def __init__(self, num_qubits, num_orbitals, num_particles, qubit_mapping='parity', two_qubit_reduction=True, sq_list=None): """Constructor. Args: num_qubits (int): number of qubits num_orbitals (int): number of spin orbitals qubit_mapping (str): mapping type for qubit operator two_qubit_reduction (bool): flag indicating whether or not two qubit is reduced num_particles (int): number of particles sq_list ([int]): position of the single-qubit operators that anticommute with the cliffords Raises: ValueError: wrong setting in num_particles and num_orbitals. ValueError: wrong setting for computed num_qubits and supplied num_qubits. """ self.validate(locals()) super().__init__() self._sq_list = sq_list self._qubit_tapering = False if self._sq_list is None else True self._qubit_mapping = qubit_mapping.lower() self._two_qubit_reduction = two_qubit_reduction if self._qubit_mapping != 'parity': if self._two_qubit_reduction: logger.warning("two_qubit_reduction only works with parity qubit mapping " "but you have {}. We switch two_qubit_reduction " "to False.".format(self._qubit_mapping)) self._two_qubit_reduction = False self._num_orbitals = num_orbitals self._num_particles = num_particles if self._num_particles > self._num_orbitals: raise ValueError("# of particles must be less than or equal to # of orbitals.") self._num_qubits = num_orbitals - 2 if self._two_qubit_reduction else self._num_orbitals self._num_qubits = self._num_qubits \ if not self._qubit_tapering else self._num_qubits - len(sq_list) if self._num_qubits != num_qubits: raise ValueError("Computed num qubits {} does not match " "actual {}".format(self._num_qubits, num_qubits)) self._bitstr = None def _build_bitstr(self): half_orbitals = self._num_orbitals // 2 bitstr = np.zeros(self._num_orbitals, np.bool) bitstr[-int(np.ceil(self._num_particles / 2)):] = True bitstr[-(half_orbitals + int(np.floor(self._num_particles / 2))):-half_orbitals] = True if self._qubit_mapping == 'parity': new_bitstr = bitstr.copy() t = np.triu(np.ones((self._num_orbitals, self._num_orbitals))) new_bitstr = t.dot(new_bitstr.astype(np.int)) % 2 bitstr = np.append(new_bitstr[1:half_orbitals], new_bitstr[half_orbitals + 1:]) \ if self._two_qubit_reduction else new_bitstr elif self._qubit_mapping == 'bravyi_kitaev': binary_superset_size = int(np.ceil(np.log2(self._num_orbitals))) beta = 1 basis = np.asarray([[1, 0], [0, 1]]) for i in range(binary_superset_size): beta = np.kron(basis, beta) beta[0, :] = 1 beta = beta[:self._num_orbitals, :self._num_orbitals] new_bitstr = beta.dot(bitstr.astype(int)) % 2 bitstr = new_bitstr.astype(np.bool) if self._qubit_tapering: sq_list = (len(bitstr) - 1) - np.asarray(self._sq_list) bitstr = np.delete(bitstr, sq_list) self._bitstr = bitstr.astype(np.bool) def construct_circuit(self, mode, register=None): """ Construct the statevector of desired initial state. Args: mode (string): `vector` or `circuit`. The `vector` mode produces the vector. While the `circuit` constructs the quantum circuit corresponding that vector. register (QuantumRegister): register for circuit construction. Returns: QuantumCircuit or numpy.ndarray: statevector. Raises: ValueError: when mode is not 'vector' or 'circuit'. """ if self._bitstr is None: self._build_bitstr() if mode == 'vector': state = 1.0 one = np.asarray([0.0, 1.0]) zero = np.asarray([1.0, 0.0]) for k in self._bitstr[::-1]: state = np.kron(one if k else zero, state) return state elif mode == 'circuit': if register is None: register = QuantumRegister(self._num_qubits, name='q') quantum_circuit = QuantumCircuit(register) for qubit_idx, bit in enumerate(self._bitstr[::-1]): if bit: quantum_circuit.u3(np.pi, 0.0, np.pi, register[qubit_idx]) return quantum_circuit else: raise ValueError('Mode should be either "vector" or "circuit"') @property def bitstr(self): """Getter of the bit string represented the statevector.""" if self._bitstr is None: self._build_bitstr() return self._bitstr
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt import numpy as np from qiskit.circuit import ParameterVector from qiskit.circuit.library import TwoLocal from qiskit.quantum_info import Statevector from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.applications.estimation import EuropeanCallPricing from qiskit_finance.circuit.library import NormalDistribution # Set upper and lower data values bounds = np.array([0.0, 7.0]) # Set number of qubits used in the uncertainty model num_qubits = 3 # Load the trained circuit parameters g_params = [0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225] # Set an initial state for the generator circuit init_dist = NormalDistribution(num_qubits, mu=1.0, sigma=1.0, bounds=bounds) # construct the variational form var_form = TwoLocal(num_qubits, "ry", "cz", entanglement="circular", reps=1) # keep a list of the parameters so we can associate them to the list of numerical values # (otherwise we need a dictionary) theta = var_form.ordered_parameters # compose the generator circuit, this is the circuit loading the uncertainty model g_circuit = init_dist.compose(var_form) # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 2 # set the approximation scaling for the payoff function c_approx = 0.25 # Evaluate trained probability distribution values = [ bounds[0] + (bounds[1] - bounds[0]) * x / (2**num_qubits - 1) for x in range(2**num_qubits) ] uncertainty_model = g_circuit.assign_parameters(dict(zip(theta, g_params))) amplitudes = Statevector.from_instruction(uncertainty_model).data x = np.array(values) y = np.abs(amplitudes) ** 2 # Sample from target probability distribution N = 100000 log_normal = np.random.lognormal(mean=1, sigma=1, size=N) log_normal = np.round(log_normal) log_normal = log_normal[log_normal <= 7] log_normal_samples = [] for i in range(8): log_normal_samples += [np.sum(log_normal == i)] log_normal_samples = np.array(log_normal_samples / sum(log_normal_samples)) # Plot distributions plt.bar(x, y, width=0.2, label="trained distribution", color="royalblue") plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.grid() plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15) plt.ylabel("Probability ($\%$)", size=15) plt.plot( log_normal_samples, "-o", color="deepskyblue", label="target distribution", linewidth=4, markersize=12, ) plt.legend(loc="best") plt.show() # Evaluate payoff for different distributions payoff = np.array([0, 0, 0, 1, 2, 3, 4, 5]) ep = np.dot(log_normal_samples, payoff) print("Analytically calculated expected payoff w.r.t. the target distribution: %.4f" % ep) ep_trained = np.dot(y, payoff) print("Analytically calculated expected payoff w.r.t. the trained distribution: %.4f" % ep_trained) # Plot exact payoff function (evaluated on the grid of the trained uncertainty model) x = np.array(values) y_strike = np.maximum(0, x - strike_price) plt.plot(x, y_strike, "ro-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Spot Price", size=15) plt.ylabel("Payoff", size=15) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.show() # construct circuit for payoff function european_call_pricing = EuropeanCallPricing( num_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=bounds, uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % ep_trained) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/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/drithidavuluri/Implementation-of-Algorithm-using-Qiskit
drithidavuluri
import qiskit.quantum_info as qi #this is used to do calculations from qiskit.circuit.library import FourierChecking from qiskit.visualization import plot_histogram f=[1,-1,-1,-1] g=[1,1,-1,-1] circuit = FourierChecking(f=f,g=g) circuit.draw() zero = qi.Statevector.from_label('00') sv = zero.evolve(circuit) probs = sv.probabilities_dict() plot_histogram(probs) print(probs)
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# let's randomly pick a number between 0 and 9, and print its value if it is greater than 5 from random import randrange r = randrange(10) if r > 5: print(r) # when the condition (r > 5) is valid/true, the code (print(r)) will be executed # you may need to execute your code more than once to see an outcome # repeat the same task four times, and also print the value of iteration variable (i) for i in range(4): r = randrange(10) # this code belongs to for-loop, and so it is indented if r > 5: # this code also belongs to for-loop, and so it is indented as well print("i =",i,"r =",r) # this code belongs to if-statement, and so it is indented with respect to if-statement # if you are unlucky (with probabability less than 13/100), you may not see any outcome after a single run # do the same task 100 times, and find the percentage of successful iterations (attempts) # an iteration (attempt) is successful if the randomly picked number is greater than 5 # the expected percentage is 40, because, out of 10 numbers, there are 4 numbers greater than 5 # but the experimental results differ success = 0 for i in range(100): r = randrange(10) if r > 5: success = success + 1 print(success,"%") # each experiment most probably will give different percentage value # let's randomly pick a number between 0 and 9, and print whether it is less than 6 or not # we use two conditionals here r = randrange(10) print("the picked number is ",r) if r < 6: print("it is less than 6") if r >= 6: print("it is greater than or equal to 6") # let's write the same algorithm by using if-else structure r = randrange(10) print("the picked number is ",r) if r < 6: print("it is less than 6") else: # if the above condition (r<6) is False print("it is greater than or equal to 6") # # your solution is here # # # when there are many related conditionals, we can use if-elif-else structure # # let's randomly pick an even number between 1 and 99 # then determine whether it is less than 25, between 25 and 50, between 51 and 75, or greater than 75. r = randrange(2,100,2) # randonmly pick a number in range {2,4,6,...,98}, which satisfies our condition # let's print this range to verify our claim print(list(range(2,100,2))) print() # print an empty line print("the picked number is",r) if r < 25: print("it is less than 25") elif r<=50: # if the above condition is False and the condition here is True print("it is between 25 and 50") elif r<=75: # if both conditions above are False and the condition here is True print("it is between 51 and 75") else: # if none of the above conditions is True print("it is greater than 75") # # your solution is here # # let's determine whether a randomly picked number between -10 and 100 is prime or not. # this is a good example for using more than one conditional in different parts of the program # this is also an example for "break" command, which terminates any loop immediately r = randrange(-10,101) # pick a number between -10 and 100 print(r) # print is value if r < 2: print("it is NOT a prime number") # this is by definition elif r == 2: print("it is a PRIME number") # we already know this else: prime=True # we assume that r is prime, and try to falsify this assumption by looking for a divisor in the following loop for i in range(2,r): # check all integers between 2 and r-1 if r % i ==0: # if i divides r without any reminder (or reminder is zero), then r is not a prime number print("it is NOT a prime number") prime=False # our assumption is falsifed break # TERMINATE the iteration immediately # we are out of if-scope # we are out of for-loop-scope if prime == True: # if our assumption is still True (if it was not falsified inside for-loop) print("it is a PRIME number") # this is an example to write a function # our function will return a Boolean value True or False def prime(number): # our function takes one parameter (has one argument) if number < 2: return False # once return command is executed, we exit the function if number == 2: return True # because of return command, we can use "if" instead of "elif" if number % 2 == 0: return False # any even number greater than 2 is not prime, because it is divisible by 2 for i in range(3,number,2): # we can skip even integers if number % i == 0: return False # once we find a divisor of the number, we return False and exit the function return True # the number has passed all checks until now # by using "return" command appropriately, the programs can be shortened # remark that this might not be a good choice everytime for readibility of codes # let's test our program by printing all prime numbers between -10 and 30 for i in range(-10,30): # we pass i to the function prime if prime(i): # the function prime(i) returns True or False print(i) # this code will be executed if i is prime, i.e., prime(i) returns True
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) # You can reverse the order of the qubits. from qiskit.quantum_info import DensityMatrix qc = QuantumCircuit(2) qc.h([0, 1]) qc.t(1) qc.s(0) qc.cx(0,1) matrix = DensityMatrix(qc) plot_bloch_multivector(matrix, title='My Bloch Spheres', reverse_bits=True)
https://github.com/acfilok96/Quantum-Computation
acfilok96
from qiskit import * from qiskit.tools.visualization import plot_bloch_multivector circuit = QuantumCircuit(1,1) circuit.x(0) simulator = Aer.get_backend('statevector_simulator') result = execute(circuit, backend=simulator).result() statevector = result.get_statevector() print(statevector) %matplotlib inline circuit.draw(output='mpl') # bloch sphere plot_bloch_multivector(statevector) # measurement circuit.measure([0],[0]) backend = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=backend, shots=1024).result() counts = result.get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(counts) circuit = QuantumCircuit(1,1) circuit.x(0) simulator = Aer.get_backend('unitary_simulator') result = execute(circuit, backend=simulator).result() unitary = result.get_unitary() print(unitary) %matplotlib inline circuit.draw(output='mpl') # bloch sphere plot_bloch_multivector(unitary)
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
nahumsa
# initialization import numpy as np # importing Qiskit from qiskit import IBMQ, Aer from qiskit import QuantumCircuit, transpile # import basic plot tools from qiskit.visualization import plot_histogram # set the length of the n-bit input string. n = 3 # Constant Oracle const_oracle = QuantumCircuit(n+1) # Random output output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw() # Balanced Oracle balanced_oracle = QuantumCircuit(n+1) # Binary string length b_str = "101" # For each qubit in our circuit # we place an X-gate if the corresponding digit in b_str is 1 # or do nothing if the digit is 0 balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw() # Creating the controlled-NOT gates # using each input qubit as a control # and the output as a target balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Wrapping the controls in X-gates # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw() dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(balanced_oracle) # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) # Display circuit dj_circuit.draw() # Viewing the output # use local simulator aer_sim = Aer.get_backend('aer_simulator') results = aer_sim.run(dj_circuit).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/Interlin-q/diskit
Interlin-q
from qiskit import BasicAer from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms import Shor N = 15 shor = Shor(N) backend = BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1024) ret = shor.run(quantum_instance) print("The list of factors of {} as computed by the Shor's algorithm is {}.".format(N, ret['factors'][0]))
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2019, 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. """ CNOTDihedral operator class. """ from __future__ import annotations import itertools import numpy as np from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.base_operator import BaseOperator from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.symplectic.pauli import Pauli from qiskit.quantum_info.operators.scalar_op import ScalarOp from qiskit.quantum_info.operators.mixins import generate_apidocs, AdjointMixin from qiskit.circuit import QuantumCircuit, Instruction from .dihedral_circuits import _append_circuit from .polynomial import SpecialPolynomial class CNOTDihedral(BaseOperator, AdjointMixin): """An N-qubit operator from the CNOT-Dihedral group. The CNOT-Dihedral group is generated by the quantum gates, :class:`~qiskit.circuit.library.CXGate`, :class:`~qiskit.circuit.library.TGate`, and :class:`~qiskit.circuit.library.XGate`. **Representation** An :math:`N`-qubit CNOT-Dihedral operator is stored as an affine function and a phase polynomial, based on the convention in references [1, 2]. The affine function consists of an :math:`N \\times N` invertible binary matrix, and an :math:`N` binary vector. The phase polynomial is a polynomial of degree at most 3, in :math:`N` variables, whose coefficients are in the ring Z_8 with 8 elements. .. code-block:: from qiskit import QuantumCircuit from qiskit.quantum_info import CNOTDihedral circ = QuantumCircuit(3) circ.cx(0, 1) circ.x(2) circ.t(1) circ.t(1) circ.t(1) elem = CNOTDihedral(circ) # Print the CNOTDihedral element print(elem) .. parsed-literal:: phase polynomial = 0 + 3*x_0 + 3*x_1 + 2*x_0*x_1 affine function = (x_0,x_0 + x_1,x_2 + 1) **Circuit Conversion** CNOTDihedral operators can be initialized from circuits containing *only* the following gates: :class:`~qiskit.circuit.library.IGate`, :class:`~qiskit.circuit.library.XGate`, :class:`~qiskit.circuit.library.YGate`, :class:`~qiskit.circuit.library.ZGate`, :class:`~qiskit.circuit.library.TGate`, :class:`~qiskit.circuit.library.TdgGate` :class:`~qiskit.circuit.library.SGate`, :class:`~qiskit.circuit.library.SdgGate`, :class:`~qiskit.circuit.library.CXGate`, :class:`~qiskit.circuit.library.CZGate`, :class:`~qiskit.circuit.library.CSGate`, :class:`~qiskit.circuit.library.CSdgGate`, :class:`~qiskit.circuit.library.SwapGate`, :class:`~qiskit.circuit.library.CCZGate`. They can be converted back into a :class:`~qiskit.circuit.QuantumCircuit`, or :class:`~qiskit.circuit.Gate` object using the :meth:`~CNOTDihedral.to_circuit` or :meth:`~CNOTDihderal.to_instruction` methods respectively. Note that this decomposition is not necessarily optimal in terms of number of gates if the number of qubits is more than two. CNOTDihedral operators can also be converted to :class:`~qiskit.quantum_info.Operator` objects using the :meth:`to_operator` method. This is done via decomposing to a circuit, and then simulating the circuit as a unitary operator. References: 1. Shelly Garion and Andrew W. Cross, *Synthesis of CNOT-Dihedral circuits with optimal number of two qubit gates*, `Quantum 4(369), 2020 <https://quantum-journal.org/papers/q-2020-12-07-369/>`_ 2. Andrew W. Cross, Easwar Magesan, Lev S. Bishop, John A. Smolin and Jay M. Gambetta, *Scalable randomised benchmarking of non-Clifford gates*, npj Quantum Inf 2, 16012 (2016). """ def __init__( self, data: CNOTDihedral | QuantumCircuit | Instruction | None = None, num_qubits: int | None = None, validate: bool = True, ): """Initialize a CNOTDihedral operator object. Args: data (CNOTDihedral or QuantumCircuit or ~qiskit.circuit.Instruction): Optional, operator to initialize. num_qubits (int): Optional, initialize an empty CNOTDihedral operator. validate (bool): if True, validates the CNOTDihedral element. Raises: QiskitError: if the type is invalid. QiskitError: if validate=True and the CNOTDihedral element is invalid. """ if num_qubits: # initialize n-qubit identity self._num_qubits = num_qubits # phase polynomial self.poly = SpecialPolynomial(self._num_qubits) # n x n invertible matrix over Z_2 self.linear = np.eye(self._num_qubits, dtype=np.int8) # binary shift, n coefficients in Z_2 self.shift = np.zeros(self._num_qubits, dtype=np.int8) # Initialize from another CNOTDihedral by sharing the underlying # poly, linear and shift elif isinstance(data, CNOTDihedral): self.linear = data.linear self.shift = data.shift self.poly = data.poly # Initialize from ScalarOp as N-qubit identity discarding any global phase elif isinstance(data, ScalarOp): if not data.is_unitary() or set(data._input_dims) != {2} or data.num_qubits is None: raise QiskitError("Can only initialize from N-qubit identity ScalarOp.") self._num_qubits = data.num_qubits # phase polynomial self.poly = SpecialPolynomial(self._num_qubits) # n x n invertible matrix over Z_2 self.linear = np.eye(self._num_qubits, dtype=np.int8) # binary shift, n coefficients in Z_2 self.shift = np.zeros(self._num_qubits, dtype=np.int8) # Initialize from a QuantumCircuit or Instruction object elif isinstance(data, (QuantumCircuit, Instruction)): self._num_qubits = data.num_qubits elem = self._from_circuit(data) self.poly = elem.poly self.linear = elem.linear self.shift = elem.shift elif isinstance(data, Pauli): self._num_qubits = data.num_qubits elem = self._from_circuit(data.to_instruction()) self.poly = elem.poly self.linear = elem.linear self.shift = elem.shift else: raise QiskitError("Invalid input type for CNOTDihedral class.") # Initialize BaseOperator super().__init__(num_qubits=self._num_qubits) # Validate the CNOTDihedral element if validate and not self._is_valid(): raise QiskitError("Invalid CNOTDihedral element.") @property def name(self): """Unique string identifier for operation type.""" return "cnotdihedral" @property def num_clbits(self): """Number of classical bits.""" return 0 def _z2matmul(self, left, right): """Compute product of two n x n z2 matrices.""" prod = np.mod(np.dot(left, right), 2) return prod def _z2matvecmul(self, mat, vec): """Compute mat*vec of n x n z2 matrix and vector.""" prod = np.mod(np.dot(mat, vec), 2) return prod def _dot(self, other): """Left multiplication self * other.""" if self.num_qubits != other.num_qubits: raise QiskitError("Multiplication on different number of qubits.") result = CNOTDihedral(num_qubits=self.num_qubits) result.shift = [ (x[0] + x[1]) % 2 for x in zip(self._z2matvecmul(self.linear, other.shift), self.shift) ] result.linear = self._z2matmul(self.linear, other.linear) # Compute x' = B1*x + c1 using the p_j identity new_vars = [] for i in range(self.num_qubits): support = np.arange(self.num_qubits)[np.nonzero(other.linear[i])] poly = SpecialPolynomial(self.num_qubits) poly.set_pj(support) if other.shift[i] == 1: poly = -1 * poly poly.weight_0 = (poly.weight_0 + 1) % 8 new_vars.append(poly) # p' = p1 + p2(x') result.poly = other.poly + self.poly.evaluate(new_vars) return result def _compose(self, other): """Right multiplication other * self.""" if self.num_qubits != other.num_qubits: raise QiskitError("Multiplication on different number of qubits.") result = CNOTDihedral(num_qubits=self.num_qubits) result.shift = [ (x[0] + x[1]) % 2 for x in zip(self._z2matvecmul(other.linear, self.shift), other.shift) ] result.linear = self._z2matmul(other.linear, self.linear) # Compute x' = B1*x + c1 using the p_j identity new_vars = [] for i in range(self.num_qubits): support = np.arange(other.num_qubits)[np.nonzero(self.linear[i])] poly = SpecialPolynomial(self.num_qubits) poly.set_pj(support) if self.shift[i] == 1: poly = -1 * poly poly.weight_0 = (poly.weight_0 + 1) % 8 new_vars.append(poly) # p' = p1 + p2(x') result.poly = self.poly + other.poly.evaluate(new_vars) return result def __eq__(self, other): """Test equality.""" return ( isinstance(other, CNOTDihedral) and self.poly == other.poly and (self.linear == other.linear).all() and (self.shift == other.shift).all() ) def _append_cx(self, i, j): """Apply a CX gate to this element. Left multiply the element by CX(i, j). """ if not 0 <= i < self.num_qubits or not 0 <= j < self.num_qubits: raise QiskitError("CX qubits are out of bounds.") self.linear[j] = (self.linear[i] + self.linear[j]) % 2 self.shift[j] = (self.shift[i] + self.shift[j]) % 2 def _append_phase(self, k, i): """Apply an k-th power of T to this element. Left multiply the element by T_i^k. """ if not 0 <= i < self.num_qubits: raise QiskitError("phase qubit out of bounds.") # If the kth bit is flipped, conjugate this gate if self.shift[i] == 1: k = (7 * k) % 8 # Take all subsets \alpha of the support of row i # of weight up to 3 and add k*(-2)**(|\alpha| - 1) mod 8 # to the corresponding term. support = np.arange(self.num_qubits)[np.nonzero(self.linear[i])] subsets_2 = itertools.combinations(support, 2) subsets_3 = itertools.combinations(support, 3) for j in support: value = self.poly.get_term([j]) self.poly.set_term([j], (value + k) % 8) for j in subsets_2: value = self.poly.get_term(list(j)) self.poly.set_term(list(j), (value + -2 * k) % 8) for j in subsets_3: value = self.poly.get_term(list(j)) self.poly.set_term(list(j), (value + 4 * k) % 8) def _append_x(self, i): """Apply X to this element. Left multiply the element by X(i). """ if not 0 <= i < self.num_qubits: raise QiskitError("X qubit out of bounds.") self.shift[i] = (self.shift[i] + 1) % 2 def __str__(self): """Return formatted string representation.""" out = "phase polynomial = \n" out += str(self.poly) out += "\naffine function = \n" out += " (" for row in range(self.num_qubits): wrote = False for col in range(self.num_qubits): if self.linear[row][col] != 0: if wrote: out += " + x_" + str(col) else: out += "x_" + str(col) wrote = True if self.shift[row] != 0: out += " + 1" if row != self.num_qubits - 1: out += "," out += ")\n" return out def to_circuit(self): """Return a QuantumCircuit implementing the CNOT-Dihedral element. Return: QuantumCircuit: a circuit implementation of the CNOTDihedral object. References: 1. Shelly Garion and Andrew W. Cross, *Synthesis of CNOT-Dihedral circuits with optimal number of two qubit gates*, `Quantum 4(369), 2020 <https://quantum-journal.org/papers/q-2020-12-07-369/>`_ 2. Andrew W. Cross, Easwar Magesan, Lev S. Bishop, John A. Smolin and Jay M. Gambetta, *Scalable randomised benchmarking of non-Clifford gates*, npj Quantum Inf 2, 16012 (2016). """ from qiskit.synthesis.cnotdihedral import synth_cnotdihedral_full return synth_cnotdihedral_full(self) def to_instruction(self): """Return a Gate instruction implementing the CNOTDihedral object.""" return self.to_circuit().to_gate() def _from_circuit(self, circuit): """Initialize from a QuantumCircuit or Instruction. Args: circuit (QuantumCircuit or ~qiskit.circuit.Instruction): instruction to initialize. Returns: CNOTDihedral: the CNOTDihedral object for the circuit. Raises: QiskitError: if the input instruction is not CNOTDihedral or contains classical register instruction. """ if not isinstance(circuit, (QuantumCircuit, Instruction)): raise QiskitError("Input must be a QuantumCircuit or Instruction") # Initialize an identity CNOTDihedral object elem = CNOTDihedral(num_qubits=self._num_qubits) _append_circuit(elem, circuit) return elem def __array__(self, dtype=None): if dtype: return np.asarray(self.to_matrix(), dtype=dtype) return self.to_matrix() def to_matrix(self): """Convert operator to Numpy matrix.""" return self.to_operator().data def to_operator(self) -> Operator: """Convert to an Operator object.""" return Operator(self.to_instruction()) def compose( self, other: CNOTDihedral, qargs: list | None = None, front: bool = False ) -> CNOTDihedral: if qargs is not None: raise NotImplementedError("compose method does not support qargs.") if self.num_qubits != other.num_qubits: raise QiskitError("Incompatible dimension for composition") if front: other = self._dot(other) else: other = self._compose(other) other.poly.weight_0 = 0 # set global phase return other def _tensor(self, other, reverse=False): """Returns the tensor product operator.""" if not isinstance(other, CNOTDihedral): raise QiskitError("Tensored element is not a CNOTDihderal object.") if reverse: elem0 = self elem1 = other else: elem0 = other elem1 = self result = CNOTDihedral(num_qubits=elem0.num_qubits + elem1.num_qubits) linear = np.block( [ [elem0.linear, np.zeros((elem0.num_qubits, elem1.num_qubits), dtype=np.int8)], [np.zeros((elem1.num_qubits, elem0.num_qubits), dtype=np.int8), elem1.linear], ] ) result.linear = linear shift = np.block([elem0.shift, elem1.shift]) result.shift = shift for i in range(elem0.num_qubits): value = elem0.poly.get_term([i]) result.poly.set_term([i], value) for j in range(i): value = elem0.poly.get_term([j, i]) result.poly.set_term([j, i], value) for k in range(j): value = elem0.poly.get_term([k, j, i]) result.poly.set_term([k, j, i], value) for i in range(elem1.num_qubits): value = elem1.poly.get_term([i]) result.poly.set_term([i + elem0.num_qubits], value) for j in range(i): value = elem1.poly.get_term([j, i]) result.poly.set_term([j + elem0.num_qubits, i + elem0.num_qubits], value) for k in range(j): value = elem1.poly.get_term([k, j, i]) result.poly.set_term( [k + elem0.num_qubits, j + elem0.num_qubits, i + elem0.num_qubits], value ) return result def tensor(self, other: CNOTDihedral) -> CNOTDihedral: return self._tensor(other, reverse=True) def expand(self, other: CNOTDihedral) -> CNOTDihedral: return self._tensor(other, reverse=False) def adjoint(self): circ = self.to_instruction() result = self._from_circuit(circ.inverse()) return result def conjugate(self): circ = self.to_instruction() new_circ = QuantumCircuit(self.num_qubits) bit_indices = {bit: index for index, bit in enumerate(circ.definition.qubits)} for instruction in circ.definition: new_qubits = [bit_indices[tup] for tup in instruction.qubits] if instruction.operation.name == "p": params = 2 * np.pi - instruction.operation.params[0] instruction.operation.params[0] = params new_circ.append(instruction.operation, new_qubits) elif instruction.operation.name == "t": instruction.operation.name = "tdg" new_circ.append(instruction.operation, new_qubits) elif instruction.operation.name == "tdg": instruction.operation.name = "t" new_circ.append(instruction.operation, new_qubits) elif instruction.operation.name == "s": instruction.operation.name = "sdg" new_circ.append(instruction.operation, new_qubits) elif instruction.operation.name == "sdg": instruction.operation.name = "s" new_circ.append(instruction.operation, new_qubits) else: new_circ.append(instruction.operation, new_qubits) result = self._from_circuit(new_circ) return result def transpose(self): circ = self.to_instruction() result = self._from_circuit(circ.reverse_ops()) return result def _is_valid(self): """Return True if input is a CNOTDihedral element.""" if ( self.poly.weight_0 != 0 or len(self.poly.weight_1) != self.num_qubits or len(self.poly.weight_2) != int(self.num_qubits * (self.num_qubits - 1) / 2) or len(self.poly.weight_3) != int(self.num_qubits * (self.num_qubits - 1) * (self.num_qubits - 2) / 6) ): return False if ( (self.linear).shape != (self.num_qubits, self.num_qubits) or len(self.shift) != self.num_qubits or not np.allclose((np.linalg.det(self.linear) % 2), 1) ): return False if ( not (set(self.poly.weight_1.flatten())).issubset({0, 1, 2, 3, 4, 5, 6, 7}) or not (set(self.poly.weight_2.flatten())).issubset({0, 2, 4, 6}) or not (set(self.poly.weight_3.flatten())).issubset({0, 4}) ): return False if not (set(self.shift.flatten())).issubset({0, 1}) or not ( set(self.linear.flatten()) ).issubset({0, 1}): return False return True # Update docstrings for API docs generate_apidocs(CNOTDihedral)
https://github.com/scaleway/qiskit-scaleway
scaleway
# Copyright 2024 Scaleway # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import cirq import matplotlib.pyplot as plt from qiskit import QuantumCircuit from qiskit_scaleway import ScalewayProvider provider = ScalewayProvider( project_id="<your-scaleway-project-id>", secret_key="<your-scaleway-secret-key>", ) # Scaleway provides Qsim backend, whichs is compatible with Cirq SDK backend = provider.get_backend("qsim_simulation_l40s") # Define a quantum circuit that produces a 4-qubit GHZ state. qc = QuantumCircuit(4) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.measure_all() # Create a QPU's session with Qsim installed for a limited duration session_id = backend.start_session( deduplication_id="my-qsim-session-workshop", max_duration="2h" ) # Create and send a job to the target session qsim_job = backend.run(qc, shots=1000, session_id=session_id) # Wait and get the result # To retrieve the result as Cirq result, you need to have Cirq package installed cirq_result = qsim_job.result(format="cirq") # Display the Cirq Result cirq.plot_state_histogram(cirq_result, plt.subplot()) plt.show() # Revoke manually the QPU's session if needed # If not done, will be revoked automatically after 2 hours backend.stop_session(session_id)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
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, L_BFGS_B from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit.utils import algorithm_globals from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier, VQC from qiskit_machine_learning.algorithms.regressors import NeuralNetworkRegressor, VQR from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN algorithm_globals.random_seed = 42 num_inputs = 2 num_samples = 20 X = 2 * algorithm_globals.random.random([num_samples, num_inputs]) - 1 y01 = 1 * (np.sum(X, axis=1) >= 0) # in { 0, 1} y = 2 * y01 - 1 # in {-1, +1} y_one_hot = np.zeros((num_samples, 2)) for i in range(num_samples): y_one_hot[i, y01[i]] = 1 for x, y_target in zip(X, y): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() # construct QNN qc = QuantumCircuit(2) feature_map = ZZFeatureMap(2) ansatz = RealAmplitudes(2) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) qc.draw(output="mpl") estimator_qnn = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters ) # QNN maps inputs to [-1, +1] estimator_qnn.forward(X[0, :], algorithm_globals.random.random(estimator_qnn.num_weights)) # 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 neural network classifier estimator_classifier = NeuralNetworkClassifier( estimator_qnn, optimizer=COBYLA(maxiter=60), callback=callback_graph ) # create empty array for callback to store evaluations of the objective function 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) # evaluate data points y_predict = estimator_classifier.predict(X) # plot results # red == wrongly classified for x, y_target, y_p in zip(X, y, y_predict): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") if y_target != y_p: plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() estimator_classifier.weights # construct feature map feature_map = ZZFeatureMap(num_inputs) # construct ansatz ansatz = RealAmplitudes(num_inputs, reps=1) # construct quantum circuit qc = QuantumCircuit(num_inputs) qc.append(feature_map, range(num_inputs)) qc.append(ansatz, range(num_inputs)) qc.decompose().draw(output="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 sampler_qnn = SamplerQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=output_shape, ) # construct classifier sampler_classifier = NeuralNetworkClassifier( neural_network=sampler_qnn, optimizer=COBYLA(maxiter=30), callback=callback_graph ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data sampler_classifier.fit(X, y01) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier sampler_classifier.score(X, y01) # evaluate data points y_predict = sampler_classifier.predict(X) # plot results # red == wrongly classified for x, y_target, y_p in zip(X, y01, y_predict): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") if y_target != y_p: plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() sampler_classifier.weights # construct feature map, ansatz, and optimizer feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs, reps=1) # construct variational quantum classifier vqc = VQC( feature_map=feature_map, ansatz=ansatz, loss="cross_entropy", optimizer=COBYLA(maxiter=30), callback=callback_graph, ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data vqc.fit(X, y_one_hot) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier vqc.score(X, y_one_hot) # evaluate data points y_predict = vqc.predict(X) # plot results # red == wrongly classified for x, y_target, y_p in zip(X, y_one_hot, y_predict): if y_target[0] == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") if not np.all(y_target == y_p): plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() from sklearn.datasets import make_classification from sklearn.preprocessing import MinMaxScaler X, y = make_classification( n_samples=10, n_features=2, n_classes=3, n_redundant=0, n_clusters_per_class=1, class_sep=2.0, random_state=algorithm_globals.random_seed, ) X = MinMaxScaler().fit_transform(X) plt.scatter(X[:, 0], X[:, 1], c=y) y_cat = np.empty(y.shape, dtype=str) y_cat[y == 0] = "A" y_cat[y == 1] = "B" y_cat[y == 2] = "C" print(y_cat) vqc = VQC( num_qubits=2, optimizer=COBYLA(maxiter=30), callback=callback_graph, ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data vqc.fit(X, y_cat) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier vqc.score(X, y_cat) predict = vqc.predict(X) print(f"Predicted labels: {predict}") print(f"Ground truth: {y_cat}") num_samples = 20 eps = 0.2 lb, ub = -np.pi, np.pi X_ = np.linspace(lb, ub, num=50).reshape(50, 1) f = lambda x: np.sin(x) X = (ub - lb) * algorithm_globals.random.random([num_samples, 1]) + lb y = f(X[:, 0]) + eps * (2 * algorithm_globals.random.random(num_samples) - 1) plt.plot(X_, f(X_), "r--") plt.plot(X, y, "bo") plt.show() # construct simple feature map param_x = Parameter("x") feature_map = QuantumCircuit(1, name="fm") feature_map.ry(param_x, 0) # construct simple ansatz param_y = Parameter("y") ansatz = QuantumCircuit(1, name="vf") ansatz.ry(param_y, 0) # construct a circuit qc = QuantumCircuit(1) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) # construct QNN regression_estimator_qnn = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters ) # construct the regressor from the neural network regressor = NeuralNetworkRegressor( neural_network=regression_estimator_qnn, loss="squared_error", optimizer=L_BFGS_B(maxiter=5), callback=callback_graph, ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit to data regressor.fit(X, y) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score the result regressor.score(X, y) # plot target function plt.plot(X_, f(X_), "r--") # plot data plt.plot(X, y, "bo") # plot fitted line y_ = regressor.predict(X_) plt.plot(X_, y_, "g-") plt.show() regressor.weights vqr = VQR( feature_map=feature_map, ansatz=ansatz, optimizer=L_BFGS_B(maxiter=5), callback=callback_graph, ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit regressor vqr.fit(X, y) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score result vqr.score(X, y) # plot target function plt.plot(X_, f(X_), "r--") # plot data plt.plot(X, y, "bo") # plot fitted line y_ = vqr.predict(X_) plt.plot(X_, y_, "g-") plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import sys sys.path.insert(1, '..') # sets the path to the parent folder, where the notebook was originally executed import time import datetime import numpy as np from matplotlib import pyplot as plt import qiskit from qiskit import * from qiskit.opflow import X,Z,I from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA, SLSQP, SPSA from qiskit.opflow import CircuitSampler from qiskit.ignis.mitigation.measurement import CompleteMeasFitter # you will need to pip install qiskit-ignis from qiskit.ignis.mitigation.measurement import complete_meas_cal from scipy import sparse import scipy.sparse.linalg.eigen.arpack as arp from modules.utils import * anti = -1 L = 5 num_trash = 2 name = "ibmq_antiferro-1D-load_bogota-optimize" # remove test at the end when running on a real device filename = "data/noisy_VQE_maxiter-500_Ising_L5_anti_-1_20" #"data/noisy_VQE_maxiter-100_Ising_L5_anti_-1_20_recycle" print("filename: ", filename, "notebook name: ", name) # where to get the simulated thetas values from? needs to contain a thetas_mitigated array filename_simulated_thetas = 'data/ibmq_antiferro-1D-load_simu_thetas-loss-cost_run2.npz' load = False recompute = True # whether or not to recompute Magnetization, makes sense on device IBMQ.load_account() # this then automatically loads your saved account provider = IBMQ.get_provider(hub='ibm-q-research') device = provider.backend.ibmq_rome print(device) backend = device #backend = qiskit.providers.aer.AerSimulator.from_backend(device) coupling_map = device.configuration().coupling_map noise_model = qiskit.providers.aer.noise.NoiseModel.from_backend(device) basis_gates = noise_model.basis_gates #aqua_globals.random_seed = seed qi = qiskit.utils.QuantumInstance(backend=backend, # , seed_simulator=seed, seed_transpiler=seed coupling_map=coupling_map, #, noise_model=noise_model, measurement_error_mitigation_cls= CompleteMeasFitter, cals_matrix_refresh_period=30 #How often to refresh the calibration matrix in measurement mitigation. in minutes ) # Very important, at the moment poorly coded so it needs to come back to this instance all the time ansatz = qiskit.circuit.library.TwoLocal(L,rotation_blocks="ry", entanglement_blocks='cz', entanglement="sca", reps=1) #ansatz.draw("mpl") ansatz = qiskit.transpile(ansatz, backend) #ansatz.draw("mpl") L = 5 num_trash = 2 anti = -1 VQE_params = np.load(filename + ".npz", allow_pickle=True) pick = np.arange(0,len(VQE_params['gx_list']),3) gx_list = VQE_params['gx_list'][pick] gz_list = VQE_params['gz_list'][pick] opt_params = VQE_params['opt_params'][pick] Qmags = VQE_params["Qmag"][pick] Qen = VQE_params["Qen"][pick] Sen = VQE_params["Sen"][pick] Smags = VQE_params["Smag"][pick] gx_vals = np.unique(gx_list) gz_vals = np.unique(gz_list) if load: temp = np.load("data/" + name + "executed_mags-Es.npz",allow_pickle=True) Qmags = temp["Qmags"] Qen = temp["Qen"] Sen = temp["Sen"] Smags = temp["Smags"] verbose=1 if recompute: mag = QMag(L,anti) #magnetization operator (Qiskit) Smag = Mag(L,anti) #magnetization operator (numpy) Qen_executed=np.zeros(len(opt_params), dtype="complex") Qmags_executed=np.zeros(len(opt_params), dtype="complex") for j in range(len(opt_params)): t0 = datetime.datetime.now() gx = gx_list[j] gz = gz_list[j] H = QHIsing(L, anti, np.float32(gx), np.float32(gz)) # build Hamiltonian Op state = ansatz.assign_parameters(opt_params[j]) meas_outcome = ~StateFn(mag) @ StateFn(state) Qmags_executed[j] = CircuitSampler(qi).convert(meas_outcome).eval() #https://quantumcomputing.stackexchange.com/questions/12080/evaluating-expectation-values-of-operators-in-qiskit #e_outcome = ~StateFn(H) @ StateFn(state) #Qen_executed[j] = CircuitSampler(qi).convert(e_outcome).eval() init_state, E, ham = ising_groundstate(L, anti, np.float64(gx), np.float64(gz)) Sen[j] = E Smags[j] = init_state.T.conj()@Smag@init_state #Magnetization with Numpy results print(f"{j+1} / {len(opt_params)}, gx = {gx:.2f}, gz = {gz:.2f}, time : {(datetime.datetime.now() - t0)}") np.savez("data/" + name + "executed_mags-Es.npz",Qmags=Qmags_executed, Qen=Qen_executed, Sen=Sen, Smags=Smags) # for large parameter space takes quite a while because of the exact diagonalization temp = np.load("data/ibmq_antiferro-1D-load_bogota-optimize-20pointsexecuted_mags-Es.npz",allow_pickle=True) Qmags_executed_bogota = temp["Qmags"] fig, ax = plt.subplots(ncols=1, figsize=(6,5)) ax.plot(gx_list, Qmags,"x--", label="noisy rome simu") ax.plot(gx_list, Smags,"x--", label="ED") ax.plot(gx_list, Qmags_executed_bogota[::3],"x--", label="ibmq_bogota") if recompute: ax.plot(gx_list, Qmags_executed,"x--", label="ibmq_rome") ax.legend() ax.set_xscale("log") plt.tight_layout() plt.savefig("plots/temp_compare-bogota-rome_vqe-vals-from-noisy-rome-simulation.png") ############################################################################## ### II - Training ########################################################### ############################################################################## # linear entangler (as in scales linearly with trash qubits) def get_entangler_map(L, num_trash, i_permut=1, nums_trash=[1,2]): result = [] nums_compressed = list(range(L)) for trashqubit in nums_trash: nums_compressed.remove(trashqubit) if nums_trash == None: #old way nums_compressed = list(range(L))[:L-num_trash] nums_trash = list(range(L))[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly for i in range(L-num_trash): result.append((repeated[i_permut + i], nums_compressed[i])) return result def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz", nums_trash = [1,2]): entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)] if nums_trash == None: nums_trash = list(range(L))[-num_trash:] circ = qiskit.circuit.library.TwoLocal(L, parametrized_gate, entangling_gate, entanglement, reps=num_trash, insert_barriers=insert_barriers, skip_final_rotation_layer=True ).assign_parameters(thetas[:-num_trash]) if insert_barriers: circ.barrier() for i in nums_trash: circ.ry(thetas[i], i) #circ.ry(circuit.Parameter(f'θ{i}'), L-i-1) return circ def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(num_trash, 'c') circ = QuantumCircuit(qreg, creg) circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=False)#.assign_parameters(thetas) # difference to bind? if measurement: for i in range(num_trash): circ.measure(qreg[L-i-1], creg[i]) if init_state is not None: if vqe: circ = ansatz.assign_parameters(init_state) + circ # needs to have ansatz defined somewhere in the script else: circ.initialize(init_state, qreg) return circ def feature_encoding(thetas, x): """ thetas: parameters to be optimized, x: Ising model parameter (eg. field) """ new_thetas = [] thetas = thetas.reshape((-1,2)) for theta in thetas: new_thetas.append(theta[0] * x + theta[1]) return new_thetas def calibrate_circuit(L, num_trash,shots=1000): qreg = QuantumRegister(L, 'q') # obtain calibration matrix qubit_list = [L-i-1 for i in range(num_trash)] # only need to calibrate the trash qubits circlabel = f'mcal_{datetime.datetime.now()}' meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qreg, circlabel=circlabel) cal_job = backend.run(meas_calibs, shots=shots) #, noise_model=noise_model) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel=circlabel) print(circlabel, meas_fitter.cal_matrix) return meas_fitter def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100, meas_fitter = None): circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) tcirc = qiskit.transpile(circ, backend) # Execute the circuit job_sim = backend.run(tcirc, shots=shots) # , seed_simulator=123, seed_transpiler=234 fix seed to make it reproducible result = job_sim.result() # Results without mitigation counts = result.get_counts() if meas_fitter != None: # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(result) counts = mitigated_results.get_counts(0) return counts meas_fitter = calibrate_circuit(L, num_trash) phis = opt_params # translate to Rikes naming gxs = gx_list gzs = gz_list def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ if vqe: init_state = phis[p] else: J, gx, gz = p init_state, _ = ising_groundstate(L, J, gx, gz) if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots, meas_fitter=meas_fitter) cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0) return cost/shots def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ cost = 0. n_samples = len(ising_params) for i, p in enumerate(ising_params): if param_encoding: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i], meas_fitter=meas_fitter) else: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, meas_fitter=meas_fitter) return cost/n_samples def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None, meas_fitter=None): if thetas is None: n_params = (2*L+2)*2 if param_encoding else (2*L+2) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer if pick_optimizer == "cobyla": optimizer = COBYLA(maxiter=max_iter, tol=0.0001) if pick_optimizer == "adam" or pick_optimizer == "ADAM": optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) if pick_optimizer == "spsa" or pick_optimizer == None: optimizer = SPSA(maxiter=max_iter, #blocking=True, callback=store_intermediate_result, learning_rate=0.3, perturbation=0.1 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x, meas_fitter=meas_fitter)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted def run_inference(thetas, shots=1000, L=5, meas_fitter=None): points = 50 J = -1.0 x,y = np.meshgrid(gx_vals, gz_vals) cost = np.zeros((len(gx_vals) * len(gz_vals))) Smags = np.zeros((len(gx_vals) * len(gz_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) if not i%verbose: print(f"{i+1} / {len(opt_params)}, gx = {gx:.2f}, gz = {gz:.2f}, time : {verbose*(datetime.datetime.now() - t0)}") cost = cost.reshape((len(gx_vals), len(gz_vals))) return cost phys_params = [-1] thetas_guess = np.load(filename_simulated_thetas, allow_pickle=True)["thetas_mitigated"] # Training thetas_opt_mitigated, loss, accepted = optimize(phys_params, thetas = thetas_guess, max_iter=30, L=5,meas_fitter=meas_fitter) #, pick_optimizer="adam") plt.plot(loss) # Inference cost_mitigated = np.zeros((len(gx_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): t0 = datetime.datetime.now() cost_mitigated[i] = cost_function_single(thetas_opt_mitigated, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something if not i%verbose: print(f"{i+1} / {len(opt_params)}, gx = {p[0]:.2f}, gz = {p[1]:.2f}, time : {verbose*(datetime.datetime.now() - t0)}") "data/" + name + "_thetas-loss-cost_run2" np.savez("data/" + name + "_thetas-loss-cost_run2", cost_mitigated=cost_mitigated, thetas_mitigated=thetas_opt_mitigated, ) fig, ax = plt.subplots(ncols=1,figsize=(6,5)) ax.set_title("Mitigated results") cost = np.load("data/" + name + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,".:", label="raw output") ax.plot(gx_list, abs(Qmags),"x--", color="tab:orange", label="Qmag") ax.set_xscale("log") for p in phys_params: ax.plot(gx_list[p],cost[p],"o",alpha=0.3,color="magenta")
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. """ https://arxiv.org/abs/2108.10182 """ import qiskit from qclib.state_preparation.util.tree_utils import children def output(angle_tree, output_qubits): """Define output qubits""" if angle_tree: output_qubits.insert(0, angle_tree.qubit) # qiskit little-endian if angle_tree.left: output(angle_tree.left, output_qubits) else: output(angle_tree.right, output_qubits) def _add_register(angle_tree, qubits, start_level): if angle_tree: angle_tree.qubit = qubits.pop(0) if angle_tree.level < start_level: _add_register(angle_tree.left, qubits, start_level) _add_register(angle_tree.right, qubits, start_level) else: if angle_tree.left: _add_register(angle_tree.left, qubits, start_level) else: _add_register(angle_tree.right, qubits, start_level) def add_register(circuit, angle_tree, start_level): """ Organize qubit registers, grouping by "output" and "ancilla" types. """ level = 0 level_nodes = [] nodes = [angle_tree] while len(nodes) > 0: # count nodes per level level_nodes.append(len(nodes)) nodes = children(nodes) level += 1 noutput = level # one output qubits per level nqubits = sum(level_nodes[:start_level]) # bottom-up qubits # top-down qubits: (number of sub-states) * (number of qubits per sub-state) nqubits += level_nodes[start_level] * (noutput - start_level) nancilla = nqubits - noutput output_register = qiskit.QuantumRegister(noutput, name="output") circuit.add_register(output_register) qubits = [*output_register[::-1]] if nancilla > 0: ancilla_register = qiskit.QuantumRegister(nancilla, name="ancilla") circuit.add_register(ancilla_register) qubits.extend([*ancilla_register[::-1]]) _add_register(angle_tree, qubits, start_level)
https://github.com/urwin419/QiskitChecker
urwin419
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) 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": ### replaced x gate ### qc.z(qubit) if msg[0] == "1": ### replaced z gate ### qc.x(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) return qc
https://github.com/arnavdas88/QuGlassyIsing
arnavdas88
!pip install qiskit J = 4.0 B_x = 0.25 B_z = 1.5 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_CountsAF3.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/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
from random import randrange r = randrange(10,51) if r % 2 ==0: print(r,"is even") else: print(r,"is odd") from random import randrange for N in [100,1000,10000,100000]: first_half=second_half=0 for i in range(N): r = randrange(100) if r<50: first_half = first_half + 1 else: second_half=second_half + 1 print(N,"->",first_half/N,second_half/N)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018, 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. # pylint: disable=invalid-name """ Visualization function for DAG circuit representation. """ from rustworkx.visualization import graphviz_draw from qiskit.dagcircuit.dagnode import DAGOpNode, DAGInNode, DAGOutNode from qiskit.circuit import Qubit from qiskit.utils import optionals as _optionals from qiskit.exceptions import InvalidFileError from .exceptions import VisualizationError @_optionals.HAS_GRAPHVIZ.require_in_call def dag_drawer(dag, scale=0.7, filename=None, style="color"): """Plot the directed acyclic graph (dag) to represent operation dependencies in a quantum circuit. This function calls the :func:`~rustworkx.visualization.graphviz_draw` function from the ``rustworkx`` package to draw the DAG. Args: dag (DAGCircuit): The dag to draw. scale (float): scaling factor filename (str): file path to save image to (format inferred from name) style (str): 'plain': B&W graph 'color' (default): color input/output/op nodes Returns: PIL.Image: if in Jupyter notebook and not saving to file, otherwise None. Raises: VisualizationError: when style is not recognized. InvalidFileError: when filename provided is not valid Example: .. plot:: :include-source: 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) """ # NOTE: use type str checking to avoid potential cyclical import # the two tradeoffs ere that it will not handle subclasses and it is # slower (which doesn't matter for a visualization function) type_str = str(type(dag)) if "DAGDependency" in type_str: graph_attrs = {"dpi": str(100 * scale)} def node_attr_func(node): if style == "plain": return {} if style == "color": n = {} n["label"] = str(node.node_id) + ": " + str(node.name) if node.name == "measure": n["color"] = "blue" n["style"] = "filled" n["fillcolor"] = "lightblue" if node.name == "barrier": n["color"] = "black" n["style"] = "filled" n["fillcolor"] = "green" if getattr(node.op, "_directive", False): n["color"] = "black" n["style"] = "filled" n["fillcolor"] = "red" if getattr(node.op, "condition", None): n["label"] = str(node.node_id) + ": " + str(node.name) + " (conditional)" n["color"] = "black" n["style"] = "filled" n["fillcolor"] = "lightgreen" return n else: raise VisualizationError("Unrecognized style %s for the dag_drawer." % style) edge_attr_func = None else: register_bit_labels = { bit: f"{reg.name}[{idx}]" for reg in list(dag.qregs.values()) + list(dag.cregs.values()) for (idx, bit) in enumerate(reg) } graph_attrs = {"dpi": str(100 * scale)} def node_attr_func(node): if style == "plain": return {} if style == "color": n = {} if isinstance(node, DAGOpNode): n["label"] = node.name n["color"] = "blue" n["style"] = "filled" n["fillcolor"] = "lightblue" if isinstance(node, DAGInNode): if isinstance(node.wire, Qubit): label = register_bit_labels.get( node.wire, f"q_{dag.find_bit(node.wire).index}" ) else: label = register_bit_labels.get( node.wire, f"c_{dag.find_bit(node.wire).index}" ) n["label"] = label n["color"] = "black" n["style"] = "filled" n["fillcolor"] = "green" if isinstance(node, DAGOutNode): if isinstance(node.wire, Qubit): label = register_bit_labels.get( node.wire, f"q[{dag.find_bit(node.wire).index}]" ) else: label = register_bit_labels.get( node.wire, f"c[{dag.find_bit(node.wire).index}]" ) n["label"] = label n["color"] = "black" n["style"] = "filled" n["fillcolor"] = "red" return n else: raise VisualizationError("Invalid style %s" % style) def edge_attr_func(edge): e = {} if isinstance(edge, Qubit): label = register_bit_labels.get(edge, f"q_{dag.find_bit(edge).index}") else: label = register_bit_labels.get(edge, f"c_{dag.find_bit(edge).index}") e["label"] = label return e image_type = None if filename: if "." not in filename: raise InvalidFileError("Parameter 'filename' must be in format 'name.extension'") image_type = filename.split(".")[-1] return graphviz_draw( dag._multi_graph, node_attr_func, edge_attr_func, graph_attrs, filename, image_type, )
https://github.com/qiskit-community/qiskit-dell-runtime
qiskit-community
# This code is part of qiskit-runtime. # # (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. """The FeatureMap class.""" import json import numpy as np from qiskit import QuantumCircuit, QuantumRegister class FeatureMap: """Mapping data with the feature map.""" def __init__(self, feature_dimension, entangler_map=None): """ Args: feature_dimension (int): number of features (twice the number of qubits for this encoding) entangler_map (list[list]): connectivity of qubits with a list of [source, target], or None for full entanglement. Note that the order in the list is the order of applying the two-qubit gate. Raises: ValueError: If the value of ``feature_dimension`` is odd. """ if isinstance(feature_dimension, int): if feature_dimension % 2 == 0: self._feature_dimension = feature_dimension else: raise ValueError("Feature dimension must be an even integer.") else: raise ValueError("Feature dimension must be an even integer.") self._num_qubits = int(feature_dimension / 2) if entangler_map is None: self._entangler_map = [ [i, j] for i in range(self._num_qubits) for j in range(i + 1, self._num_qubits) ] else: self._entangler_map = entangler_map self._num_parameters = self._num_qubits def construct_circuit(self, x=None, parameters=None, q=None, inverse=False, name=None): """Construct the feature map circuit. Args: x (numpy.ndarray): data vector of size feature_dimension parameters (numpy.ndarray): optional parameters in feature map q (QauntumRegister): the QuantumRegister object for the circuit inverse (bool): whether or not to invert the circuit name (str): The name to use for the constructed ``QuantumCircuit`` object Returns: QuantumCircuit: a quantum circuit transforming data x Raises: ValueError: If the input parameters or vector are invalid """ if parameters is not None: if isinstance(parameters, (int, float)): raise ValueError("Parameters must be a list.") if len(parameters) == 1: parameters = parameters * np.ones(self._num_qubits) else: if len(parameters) != self._num_parameters: raise ValueError( "The number of feature map parameters must be {}.".format( self._num_parameters ) ) if len(x) != self._feature_dimension: raise ValueError( "The input vector must be of length {}.".format(self._feature_dimension) ) if q is None: q = QuantumRegister(self._num_qubits, name="q") circuit = QuantumCircuit(q, name=name) for i in range(self._num_qubits): circuit.ry(-parameters[i], q[i]) for source, target in self._entangler_map: circuit.cz(q[source], q[target]) for i in range(self._num_qubits): circuit.rz(-2 * x[2 * i + 1], q[i]) circuit.rx(-2 * x[2 * i], q[i]) if inverse: return circuit.inverse() else: return circuit def to_json(self): """Return JSON representation of this object. Returns: str: JSON string representing this object. """ return json.dumps( {"feature_dimension": self._feature_dimension, "entangler_map": self._entangler_map} ) @classmethod def from_json(cls, data): """Return an instance of this class from the JSON representation. Args: data (str): JSON string representing an object. Returns: FeatureMap: An instance of this class. """ return cls(**json.loads(data))
https://github.com/Brogis1/2020_SCS_Qiskit_Workshop
Brogis1
import numpy as np from qiskit import __qiskit_version__ from qiskit.chemistry.drivers import PySCFDriver, PyQuanteDriver, UnitsType from qiskit.chemistry import FermionicOperator from qiskit.aqua.algorithms import VQE, ExactEigensolver from qiskit.chemistry.components.variational_forms import UCCSD from qiskit.chemistry.components.initial_states import HartreeFock from qiskit.aqua.components.optimizers import COBYLA from qiskit.aqua import QuantumInstance from qiskit import Aer from qiskit.chemistry.algorithms.q_equation_of_motion.q_equation_of_motion import QEquationOfMotion from qiskit.visualization import plot_histogram from qiskit import IBMQ from qiskit.providers.aer import noise __qiskit_version__ driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.735', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() h1 = molecule.one_body_integrals h2 = molecule.two_body_integrals nuclear_repulsion_energy = molecule.nuclear_repulsion_energy num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 print("HF energy: {}".format(molecule.hf_energy - molecule.nuclear_repulsion_energy)) print("# of electrons: {}".format(num_particles)) print("# of spin orbitals: {}".format(num_spin_orbitals)) ferop = FermionicOperator(h1=h1, h2=h2) map_type = 'jordan_wigner' qubitop = ferop.mapping(map_type=map_type) print(qubitop.print_details()) exact_eigensolver = ExactEigensolver(qubitop, k=1<<qubitop.num_qubits) ret = exact_eigensolver.run() print('The ground state energy is: {:.12f}'.format(ret['eigvals'][0].real)) print('The ground state is:') for i in range(1<<qubitop.num_qubits): print(np.binary_repr(i, width=qubitop.num_qubits), ret['eigvecs'][0][i]) qubit_reduction = False HF_state = HartreeFock(qubitop.num_qubits, num_spin_orbitals, num_particles, map_type, qubit_reduction) var_form = UCCSD(qubitop.num_qubits, depth=1, num_orbitals=num_spin_orbitals, num_particles=num_particles, initial_state=HF_state, qubit_mapping=map_type, two_qubit_reduction=qubit_reduction) params = np.random.rand(var_form._num_parameters) circuit = var_form.construct_circuit(params) circuit.decompose().draw(output='mpl') backend = Aer.get_backend('statevector_simulator') import logging from qiskit.chemistry import set_qiskit_chemistry_logging set_qiskit_chemistry_logging(logging.INFO) # choose among DEBUG, INFO, WARNING, ERROR, CRITICAL and NOTSET max_eval = 200 cobyla = COBYLA(maxiter=max_eval) vqe = VQE(qubitop, var_form, cobyla) quantum_instance = QuantumInstance(backend=backend) results = vqe.run(quantum_instance) print('The computed ground state energy is: {:.12f}'.format(results['eigvals'][0])) print("Parameters: {}".format(results['opt_params'])) h1_nop = np.identity(qubitop.num_qubits) fermionic_nop = FermionicOperator(h1=h1_nop) qubit_nop = fermionic_nop.mapping(map_type=map_type) print(qubit_nop.print_details()) wavefn = var_form.construct_circuit(results['opt_params']) statevector_mode = True use_simulator_snapshot_mode = True circuits = qubit_nop.construct_evaluation_circuit(wavefn, statevector_mode, use_simulator_snapshot_mode=use_simulator_snapshot_mode) results_2 = quantum_instance.execute(circuits) avg, std = qubit_nop.evaluate_with_result(results_2, statevector_mode, use_simulator_snapshot_mode=use_simulator_snapshot_mode) print(round(np.real(avg),1)) eom = QEquationOfMotion(qubitop, qubitop.num_qubits, num_particles, qubit_mapping=map_type) gaps, _ = eom.calculate_excited_states(wavefn, quantum_instance = quantum_instance) exact_energies = [] for i in range(1<<qubitop.num_qubits): state = ret['eigvecs'][i] nop_exp = qubit_nop.evaluate_with_statevector(state) if round(np.real(nop_exp[0]),1) == 2: exact_energies.append(np.real(ret['eigvals'][i])) qeom_energies = [results['eigvals'][0]] for i in range(len(gaps)): qeom_energies.append(qeom_energies[0]+gaps[i]) print('The exact energies are {}'.format(exact_energies)) print('The qEOM energies are {}'.format(qeom_energies)) backend_2 = Aer.get_backend('qasm_simulator') shots = 1000 quantum_instance_2 = QuantumInstance(backend=backend_2, shots = shots) results_3 = vqe.run(quantum_instance_2) print('The computed ground state energy is: {:.12f}'.format(results_3['eigvals'][0])) print("Parameters: {}".format(results_3['opt_params'])) plot_histogram(results_3['eigvecs'][0], color='midnightblue', title="H2 ground state, 1000 shots") IBMQ.save_account('679268b65869103438b43782543ef1cb532068e8dbc53d8acc34f160430eeb37655fbaf0351df831623d8bd5cf7496f8e21bd266cab2a963342dd737775465db', overwrite=True) provider = IBMQ.load_account() print(provider.backends()) device = provider.get_backend('ibmqx2') properties = device.properties() coupling_map = device.configuration().coupling_map noise_model = noise.device.basic_device_noise_model(properties) basis_gates = noise_model.basis_gates quantum_instance_3 = QuantumInstance(backend_2, shots=shots, basis_gates=basis_gates, coupling_map=coupling_map, noise_model=noise_model) results_4 = vqe.run(quantum_instance_3) print('The computed ground state energy is: {:.12f}'.format(results_3['eigvals'][0])) print("Parameters: {}".format(results_3['opt_params'])) plot_histogram(results_4['eigvecs'][0], color='midnightblue', title="H2 ground state, 1000 shots")
https://github.com/harshagarine/QISKIT_INDIA_CHALLENGE
harshagarine
### WRITE YOUR CODE BETWEEN THESE LINES - START # import libraries that are used in the function below. from qiskit import QuantumCircuit import numpy as np from math import sqrt, pi ### WRITE YOUR CODE BETWEEN THESE LINES - END def build_state(): circuit = QuantumCircuit(1) initial_state = [0,1] circuit.initialize(initial_state, 0) circuit.ry(pi/3,0) ### WRITE YOUR CODE BETWEEN THESE LINES - END return circuit
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.x(0).c_if(cr, 0) qc.measure(0, 0) qc.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import NormalDistribution # can be used in case a principal component analysis has been done to derive the uncertainty model, ignored in this example. A = np.eye(2) b = np.zeros(2) # specify the number of qubits that are used to represent the different dimenions of the uncertainty model num_qubits = [2, 2] # specify the lower and upper bounds for the different dimension low = [0, 0] high = [0.12, 0.24] mu = [0.12, 0.24] sigma = 0.01 * np.eye(2) # construct corresponding distribution bounds = list(zip(low, high)) u = NormalDistribution(num_qubits, mu, sigma, bounds) # plot contour of probability density function x = np.linspace(low[0], high[0], 2 ** num_qubits[0]) y = np.linspace(low[1], high[1], 2 ** num_qubits[1]) z = u.probabilities.reshape(2 ** num_qubits[0], 2 ** num_qubits[1]) plt.contourf(x, y, z) plt.xticks(x, size=15) plt.yticks(y, size=15) plt.grid() plt.xlabel("$r_1$ (%)", size=15) plt.ylabel("$r_2$ (%)", size=15) plt.colorbar() plt.show() # specify cash flow cf = [1.0, 2.0] periods = range(1, len(cf) + 1) # plot cash flow plt.bar(periods, cf) plt.xticks(periods, size=15) plt.yticks(size=15) plt.grid() plt.xlabel("periods", size=15) plt.ylabel("cashflow ($)", size=15) plt.show() # estimate real value cnt = 0 exact_value = 0.0 for x1 in np.linspace(low[0], high[0], pow(2, num_qubits[0])): for x2 in np.linspace(low[1], high[1], pow(2, num_qubits[1])): prob = u.probabilities[cnt] for t in range(len(cf)): # evaluate linear approximation of real value w.r.t. interest rates exact_value += prob * ( cf[t] / pow(1 + b[t], t + 1) - (t + 1) * cf[t] * np.dot(A[:, t], np.asarray([x1, x2])) / pow(1 + b[t], t + 2) ) cnt += 1 print("Exact value: \t%.4f" % exact_value) # specify approximation factor c_approx = 0.125 # create fixed income pricing application from qiskit_finance.applications.estimation import FixedIncomePricing fixed_income = FixedIncomePricing( num_qubits=num_qubits, pca_matrix=A, initial_interests=b, cash_flow=cf, rescaling_factor=c_approx, bounds=bounds, uncertainty_model=u, ) fixed_income._objective.draw() fixed_income_circ = QuantumCircuit(fixed_income._objective.num_qubits) # load probability distribution fixed_income_circ.append(u, range(u.num_qubits)) # apply function fixed_income_circ.append(fixed_income._objective, range(fixed_income._objective.num_qubits)) fixed_income_circ.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 # construct amplitude estimation problem = fixed_income.to_estimation_problem() ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (fixed_income.interpret(result))) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
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. """Test Qiskit's inverse gate operation.""" import unittest import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, pulse from qiskit.circuit import Clbit from qiskit.circuit.library import RXGate, RYGate from qiskit.test import QiskitTestCase from qiskit.circuit.exceptions import CircuitError from qiskit.extensions.simulator import Snapshot class TestCircuitProperties(QiskitTestCase): """QuantumCircuit properties tests.""" def test_qarg_numpy_int(self): """Test castable to integer args for QuantumCircuit.""" n = np.int64(12) qc1 = QuantumCircuit(n) self.assertEqual(qc1.num_qubits, 12) self.assertEqual(type(qc1), QuantumCircuit) def test_carg_numpy_int(self): """Test castable to integer cargs for QuantumCircuit.""" n = np.int64(12) c1 = ClassicalRegister(n) qc1 = QuantumCircuit(c1) c_regs = qc1.cregs self.assertEqual(c_regs[0], c1) self.assertEqual(type(qc1), QuantumCircuit) def test_carg_numpy_int_2(self): """Test castable to integer cargs for QuantumCircuit.""" qc1 = QuantumCircuit(12, np.int64(12)) self.assertEqual(len(qc1.clbits), 12) self.assertTrue(all(isinstance(bit, Clbit) for bit in qc1.clbits)) self.assertEqual(type(qc1), QuantumCircuit) def test_qarg_numpy_int_exception(self): """Test attempt to pass non-castable arg to QuantumCircuit.""" self.assertRaises(CircuitError, QuantumCircuit, "string") def test_warning_on_noninteger_float(self): """Test warning when passing non-integer float to QuantumCircuit""" self.assertRaises(CircuitError, QuantumCircuit, 2.2) # but an integer float should pass qc = QuantumCircuit(2.0) self.assertEqual(qc.num_qubits, 2) def test_circuit_depth_empty(self): """Test depth of empty circuity""" q = QuantumRegister(5, "q") qc = QuantumCircuit(q) self.assertEqual(qc.depth(), 0) def test_circuit_depth_no_reg(self): """Test depth of no register circuits""" qc = QuantumCircuit() self.assertEqual(qc.depth(), 0) def test_circuit_depth_meas_only(self): """Test depth of measurement only""" q = QuantumRegister(1, "q") c = ClassicalRegister(1, "c") qc = QuantumCircuit(q, c) qc.measure(q, c) self.assertEqual(qc.depth(), 1) def test_circuit_depth_barrier(self): """Make sure barriers do not add to depth""" # ┌───┐ ░ ┌─┐ # q_0: ┤ H ├──■──────────────────░─┤M├──────────── # ├───┤┌─┴─┐ ░ └╥┘┌─┐ # q_1: ┤ H ├┤ X ├──■─────────────░──╫─┤M├───────── # ├───┤└───┘ │ ┌───┐ ░ ║ └╥┘┌─┐ # q_2: ┤ H ├───────┼──┤ X ├──■───░──╫──╫─┤M├────── # ├───┤ │ └─┬─┘┌─┴─┐ ░ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├───────┼────┼──┤ X ├─░──╫──╫──╫─┤M├─── # ├───┤ ┌─┴─┐ │ └───┘ ░ ║ ║ ║ └╥┘┌─┐ # q_4: ┤ H ├─────┤ X ├──■────────░──╫──╫──╫──╫─┤M├ # └───┘ └───┘ ░ ║ ║ ║ ║ └╥┘ # c: 5/═════════════════════════════╩══╩══╩══╩══╩═ # 0 1 2 3 4 q = QuantumRegister(5, "q") c = ClassicalRegister(5, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(q[4]) qc.cx(q[0], q[1]) qc.cx(q[1], q[4]) qc.cx(q[4], q[2]) qc.cx(q[2], q[3]) qc.barrier(q) qc.measure(q, c) self.assertEqual(qc.depth(), 6) def test_circuit_depth_simple(self): """Test depth for simple circuit""" # ┌───┐ # q_0: ┤ H ├──■──────────────────── # └───┘ │ ┌───┐┌─┐ # q_1: ───────┼────────────┤ X ├┤M├ # ┌───┐ │ ┌───┐┌───┐└─┬─┘└╥┘ # q_2: ┤ X ├──┼──┤ X ├┤ X ├──┼───╫─ # └───┘ │ └───┘└───┘ │ ║ # q_3: ───────┼──────────────┼───╫─ # ┌─┴─┐┌───┐ │ ║ # q_4: ─────┤ X ├┤ X ├───────■───╫─ # └───┘└───┘ ║ # c: 1/══════════════════════════╩═ # 0 q = QuantumRegister(5, "q") c = ClassicalRegister(1, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[4]) qc.x(q[2]) qc.x(q[2]) qc.x(q[2]) qc.x(q[4]) qc.cx(q[4], q[1]) qc.measure(q[1], c[0]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_multi_reg(self): """Test depth for multiple registers""" # ┌───┐ # q1_0: ┤ H ├──■───────────────── # ├───┤┌─┴─┐ # q1_1: ┤ H ├┤ X ├──■──────────── # ├───┤└───┘ │ ┌───┐ # q1_2: ┤ H ├───────┼──┤ X ├──■── # ├───┤ │ └─┬─┘┌─┴─┐ # q2_0: ┤ H ├───────┼────┼──┤ X ├ # ├───┤ ┌─┴─┐ │ └───┘ # q2_1: ┤ H ├─────┤ X ├──■─────── # └───┘ └───┘ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") c = ClassicalRegister(5, "c") qc = QuantumCircuit(q1, q2, c) qc.h(q1[0]) qc.h(q1[1]) qc.h(q1[2]) qc.h(q2[0]) qc.h(q2[1]) qc.cx(q1[0], q1[1]) qc.cx(q1[1], q2[1]) qc.cx(q2[1], q1[2]) qc.cx(q1[2], q2[0]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_3q_gate(self): """Test depth for 3q gate""" # ┌───┐ # q1_0: ┤ H ├──■────■───────────────── # ├───┤ │ ┌─┴─┐ # q1_1: ┤ H ├──┼──┤ X ├──■──────────── # ├───┤ │ └───┘ │ ┌───┐ # q1_2: ┤ H ├──┼─────────┼──┤ X ├──■── # ├───┤┌─┴─┐ │ └─┬─┘┌─┴─┐ # q2_0: ┤ H ├┤ X ├───────┼────┼──┤ X ├ # ├───┤└─┬─┘ ┌─┴─┐ │ └───┘ # q2_1: ┤ H ├──■───────┤ X ├──■─────── # └───┘ └───┘ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") c = ClassicalRegister(5, "c") qc = QuantumCircuit(q1, q2, c) qc.h(q1[0]) qc.h(q1[1]) qc.h(q1[2]) qc.h(q2[0]) qc.h(q2[1]) qc.ccx(q2[1], q1[0], q2[0]) qc.cx(q1[0], q1[1]) qc.cx(q1[1], q2[1]) qc.cx(q2[1], q1[2]) qc.cx(q1[2], q2[0]) self.assertEqual(qc.depth(), 6) def test_circuit_depth_conditionals1(self): """Test circuit depth for conditional gates #1.""" # ┌───┐ ┌─┐ # q_0: ┤ H ├──■──┤M├───────────────── # ├───┤┌─┴─┐└╥┘┌─┐ # q_1: ┤ H ├┤ X ├─╫─┤M├────────────── # ├───┤└───┘ ║ └╥┘ ┌───┐ # q_2: ┤ H ├──■───╫──╫──┤ H ├──────── # ├───┤┌─┴─┐ ║ ║ └─╥─┘ ┌───┐ # q_3: ┤ H ├┤ X ├─╫──╫────╫────┤ H ├─ # └───┘└───┘ ║ ║ ║ └─╥─┘ # ║ ║ ┌──╨──┐┌──╨──┐ # c: 4/═══════════╩══╩═╡ 0x2 ╞╡ 0x4 ╞ # 0 1 └─────┘└─────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.cx(q[0], q[1]) qc.cx(q[2], q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.h(q[2]).c_if(c, 2) qc.h(q[3]).c_if(c, 4) self.assertEqual(qc.depth(), 5) def test_circuit_depth_conditionals2(self): """Test circuit depth for conditional gates #2.""" # ┌───┐ ┌─┐┌─┐ # q_0: ┤ H ├──■──┤M├┤M├────────────── # ├───┤┌─┴─┐└╥┘└╥┘ # q_1: ┤ H ├┤ X ├─╫──╫─────────────── # ├───┤└───┘ ║ ║ ┌───┐ # q_2: ┤ H ├──■───╫──╫──┤ H ├──────── # ├───┤┌─┴─┐ ║ ║ └─╥─┘ ┌───┐ # q_3: ┤ H ├┤ X ├─╫──╫────╫────┤ H ├─ # └───┘└───┘ ║ ║ ║ └─╥─┘ # ║ ║ ┌──╨──┐┌──╨──┐ # c: 4/═══════════╩══╩═╡ 0x2 ╞╡ 0x4 ╞ # 0 0 └─────┘└─────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.cx(q[0], q[1]) qc.cx(q[2], q[3]) qc.measure(q[0], c[0]) qc.measure(q[0], c[0]) qc.h(q[2]).c_if(c, 2) qc.h(q[3]).c_if(c, 4) self.assertEqual(qc.depth(), 6) def test_circuit_depth_conditionals3(self): """Test circuit depth for conditional gates #3.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───■──────────── # ├───┤└╥┘ │ ┌─┐ # q_1: ┤ H ├─╫────┼───┤M├────── # ├───┤ ║ │ └╥┘┌─┐ # q_2: ┤ H ├─╫────┼────╫─┤M├─── # ├───┤ ║ ┌─┴─┐ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──┤ X ├──╫──╫─┤M├ # └───┘ ║ └─╥─┘ ║ ║ └╥┘ # ║ ┌──╨──┐ ║ ║ ║ # c: 4/══════╩═╡ 0x2 ╞═╩══╩══╩═ # 0 └─────┘ 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.cx(q[0], q[3]).c_if(c, 2) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.depth(), 4) def test_circuit_depth_bit_conditionals1(self): """Test circuit depth for single bit conditional gates #1.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────────────────────── # ├───┤└╥┘ ┌───┐ # q_1: ┤ H ├─╫───────┤ H ├────────────── # ├───┤ ║ ┌─┐ └─╥─┘ # q_2: ┤ H ├─╫─┤M├─────╫──────────────── # ├───┤ ║ └╥┘ ║ ┌───┐ # q_3: ┤ H ├─╫──╫──────╫────────┤ H ├─── # └───┘ ║ ║ ║ └─╥─┘ # ║ ║ ┌────╨────┐┌────╨────┐ # c: 4/══════╩══╩═╡ c_0=0x1 ╞╡ c_2=0x0 ╞ # 0 2 └─────────┘└─────────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[2], c[2]) qc.h(q[1]).c_if(c[0], True) qc.h(q[3]).c_if(c[2], False) self.assertEqual(qc.depth(), 3) def test_circuit_depth_bit_conditionals2(self): """Test circuit depth for single bit conditional gates #2.""" # ┌───┐┌─┐ » # q_0: ┤ H ├┤M├──────────────────────────────■─────────────────────■─────» # ├───┤└╥┘ ┌───┐ ┌─┴─┐ │ » # q_1: ┤ H ├─╫───────┤ H ├─────────────────┤ X ├───────────────────┼─────» # ├───┤ ║ ┌─┐ └─╥─┘ └─╥─┘ ┌─┴─┐ » # q_2: ┤ H ├─╫─┤M├─────╫─────────────────────╫──────────■────────┤ H ├───» # ├───┤ ║ └╥┘ ║ ┌───┐ ║ ┌─┴─┐ └─╥─┘ » # q_3: ┤ H ├─╫──╫──────╫────────┤ H ├────────╫────────┤ X ├────────╫─────» # └───┘ ║ ║ ║ └─╥─┘ ║ └─╥─┘ ║ » # ║ ║ ┌────╨────┐┌────╨────┐┌────╨────┐┌────╨────┐┌────╨────┐» # c: 4/══════╩══╩═╡ c_1=0x1 ╞╡ c_3=0x1 ╞╡ c_0=0x0 ╞╡ c_2=0x0 ╞╡ c_1=0x1 ╞» # 0 2 └─────────┘└─────────┘└─────────┘└─────────┘└─────────┘» # « # «q_0: ─────────── # « # «q_1: ─────■───── # « │ # «q_2: ─────┼───── # « ┌─┴─┐ # «q_3: ───┤ H ├─── # « └─╥─┘ # « ┌────╨────┐ # «c: 4/╡ c_3=0x1 ╞ # « └─────────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[2], c[2]) qc.h(q[1]).c_if(c[1], True) qc.h(q[3]).c_if(c[3], True) qc.cx(0, 1).c_if(c[0], False) qc.cx(2, 3).c_if(c[2], False) qc.ch(0, 2).c_if(c[1], True) qc.ch(1, 3).c_if(c[3], True) self.assertEqual(qc.depth(), 4) def test_circuit_depth_bit_conditionals3(self): """Test circuit depth for single bit conditional gates #3.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├────────────────────────────────────── # ├───┤└╥┘ ┌───┐ ┌─┐ # q_1: ┤ H ├─╫────┤ H ├─────────────────────┤M├────── # ├───┤ ║ └─╥─┘ ┌───┐ └╥┘┌─┐ # q_2: ┤ H ├─╫──────╫──────┤ H ├─────────────╫─┤M├─── # ├───┤ ║ ║ └─╥─┘ ┌───┐ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──────╫────────╫──────┤ H ├────╫──╫─┤M├ # └───┘ ║ ║ ║ └─╥─┘ ║ ║ └╥┘ # ║ ┌────╨────┐┌──╨──┐┌────╨────┐ ║ ║ ║ # c: 4/══════╩═╡ c_0=0x1 ╞╡ 0x2 ╞╡ c_3=0x1 ╞═╩══╩══╩═ # 0 └─────────┘└─────┘└─────────┘ 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.h(1).c_if(c[0], True) qc.h(q[2]).c_if(c, 2) qc.h(3).c_if(c[3], True) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.depth(), 6) def test_circuit_depth_measurements1(self): """Test circuit depth for measurements #1.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────── # ├───┤└╥┘┌─┐ # q_1: ┤ H ├─╫─┤M├────── # ├───┤ ║ └╥┘┌─┐ # q_2: ┤ H ├─╫──╫─┤M├─── # ├───┤ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──╫──╫─┤M├ # └───┘ ║ ║ ║ └╥┘ # c: 4/══════╩══╩══╩══╩═ # 0 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.depth(), 2) def test_circuit_depth_measurements2(self): """Test circuit depth for measurements #2.""" # ┌───┐┌─┐┌─┐┌─┐┌─┐ # q_0: ┤ H ├┤M├┤M├┤M├┤M├ # ├───┤└╥┘└╥┘└╥┘└╥┘ # q_1: ┤ H ├─╫──╫──╫──╫─ # ├───┤ ║ ║ ║ ║ # q_2: ┤ H ├─╫──╫──╫──╫─ # ├───┤ ║ ║ ║ ║ # q_3: ┤ H ├─╫──╫──╫──╫─ # └───┘ ║ ║ ║ ║ # c: 4/══════╩══╩══╩══╩═ # 0 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[0], c[1]) qc.measure(q[0], c[2]) qc.measure(q[0], c[3]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_measurements3(self): """Test circuit depth for measurements #3.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────── # ├───┤└╥┘┌─┐ # q_1: ┤ H ├─╫─┤M├────── # ├───┤ ║ └╥┘┌─┐ # q_2: ┤ H ├─╫──╫─┤M├─── # ├───┤ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──╫──╫─┤M├ # └───┘ ║ ║ ║ └╥┘ # c: 4/══════╩══╩══╩══╩═ # 0 0 0 0 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[0]) qc.measure(q[2], c[0]) qc.measure(q[3], c[0]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_barriers1(self): """Test circuit depth for barriers #1.""" # ┌───┐ ░ # q_0: ┤ H ├──■───░─────────── # └───┘┌─┴─┐ ░ # q_1: ─────┤ X ├─░─────────── # └───┘ ░ ┌───┐ # q_2: ───────────░─┤ H ├──■── # ░ └───┘┌─┴─┐ # q_3: ───────────░──────┤ X ├ # ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.cx(0, 1) circ.barrier(q) circ.h(2) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_barriers2(self): """Test circuit depth for barriers #2.""" # ┌───┐ ░ ░ ░ # q_0: ┤ H ├─░───■───░───────░────── # └───┘ ░ ┌─┴─┐ ░ ░ # q_1: ──────░─┤ X ├─░───────░────── # ░ └───┘ ░ ┌───┐ ░ # q_2: ──────░───────░─┤ H ├─░───■── # ░ ░ └───┘ ░ ┌─┴─┐ # q_3: ──────░───────░───────░─┤ X ├ # ░ ░ ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.barrier(q) circ.cx(0, 1) circ.barrier(q) circ.h(2) circ.barrier(q) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_barriers3(self): """Test circuit depth for barriers #3.""" # ┌───┐ ░ ░ ░ ░ ░ # q_0: ┤ H ├─░───■───░──░──░───────░────── # └───┘ ░ ┌─┴─┐ ░ ░ ░ ░ # q_1: ──────░─┤ X ├─░──░──░───────░────── # ░ └───┘ ░ ░ ░ ┌───┐ ░ # q_2: ──────░───────░──░──░─┤ H ├─░───■── # ░ ░ ░ ░ └───┘ ░ ┌─┴─┐ # q_3: ──────░───────░──░──░───────░─┤ X ├ # ░ ░ ░ ░ ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.barrier(q) circ.cx(0, 1) circ.barrier(q) circ.barrier(q) circ.barrier(q) circ.h(2) circ.barrier(q) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_snap1(self): """Test circuit depth for snapshots #1.""" # ┌───┐ ░ # q_0: ┤ H ├──■───░─────────── # └───┘┌─┴─┐ ░ # q_1: ─────┤ X ├─░─────────── # └───┘ ░ ┌───┐ # q_2: ───────────░─┤ H ├──■── # ░ └───┘┌─┴─┐ # q_3: ───────────░──────┤ X ├ # ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.cx(0, 1) circ.append(Snapshot("snap", num_qubits=4), [0, 1, 2, 3]) circ.h(2) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_snap2(self): """Test circuit depth for snapshots #2.""" # ┌───┐ ░ ░ ░ # q_0: ┤ H ├─░───■───░───────░────── # └───┘ ░ ┌─┴─┐ ░ ░ # q_1: ──────░─┤ X ├─░───────░────── # ░ └───┘ ░ ┌───┐ ░ # q_2: ──────░───────░─┤ H ├─░───■── # ░ ░ └───┘ ░ ┌─┴─┐ # q_3: ──────░───────░───────░─┤ X ├ # ░ ░ ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.append(Snapshot("snap0", num_qubits=4), [0, 1, 2, 3]) circ.cx(0, 1) circ.append(Snapshot("snap1", num_qubits=4), [0, 1, 2, 3]) circ.h(2) circ.append(Snapshot("snap2", num_qubits=4), [0, 1, 2, 3]) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_snap3(self): """Test circuit depth for snapshots #3.""" # ┌───┐ ░ ░ # q_0: ┤ H ├──■───░──░─────────── # └───┘┌─┴─┐ ░ ░ # q_1: ─────┤ X ├─░──░─────────── # └───┘ ░ ░ ┌───┐ # q_2: ───────────░──░─┤ H ├──■── # ░ ░ └───┘┌─┴─┐ # q_3: ───────────░──░──────┤ X ├ # ░ ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.cx(0, 1) circ.append(Snapshot("snap0", num_qubits=4), [0, 1, 2, 3]) circ.append(Snapshot("snap1", num_qubits=4), [0, 1, 2, 3]) circ.h(2) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_2qubit(self): """Test finding depth of two-qubit gates only.""" # ┌───┐ # q_0: ┤ H ├──■─────────────────── # └───┘┌─┴─┐┌─────────┐ ┌─┐ # q_1: ─────┤ X ├┤ Rz(0.1) ├─■─┤M├ # ┌───┐└───┘└─────────┘ │ └╥┘ # q_2: ┤ H ├──■──────────────┼──╫─ # └───┘┌─┴─┐ │ ║ # q_3: ─────┤ X ├────────────■──╫─ # └───┘ ║ # c: 1/═════════════════════════╩═ # 0 circ = QuantumCircuit(4, 1) circ.h(0) circ.cx(0, 1) circ.h(2) circ.cx(2, 3) circ.rz(0.1, 1) circ.cz(1, 3) circ.measure(1, 0) self.assertEqual(circ.depth(lambda x: x.operation.num_qubits == 2), 2) def test_circuit_depth_multiqubit_or_conditional(self): """Test finding depth of multi-qubit or conditional gates.""" # ┌───┐ ┌───┐ # q_0: ┤ H ├──■───────────────────────────┤ X ├─── # └───┘ │ ┌─────────┐ ┌─┐ └─╥─┘ # q_1: ───────■──┤ Rz(0.1) ├──────■─┤M├─────╫───── # ┌─┴─┐└──┬───┬──┘ │ └╥┘ ║ # q_2: ─────┤ X ├───┤ H ├─────■───┼──╫──────╫───── # └───┘ └───┘ ┌─┴─┐ │ ║ ║ # q_3: ─────────────────────┤ X ├─■──╫──────╫───── # └───┘ ║ ┌────╨────┐ # c: 1/══════════════════════════════╩═╡ c_0 = T ╞ # 0 └─────────┘ circ = QuantumCircuit(4, 1) circ.h(0) circ.ccx(0, 1, 2) circ.h(2) circ.cx(2, 3) circ.rz(0.1, 1) circ.cz(1, 3) circ.measure(1, 0) circ.x(0).c_if(0, 1) self.assertEqual( circ.depth(lambda x: x.operation.num_qubits >= 2 or x.operation.condition is not None), 4, ) def test_circuit_depth_first_qubit(self): """Test finding depth of gates touching q0 only.""" # ┌───┐ ┌───┐ # q_0: ┤ H ├──■─────┤ T ├───────── # └───┘┌─┴─┐┌──┴───┴──┐ ┌─┐ # q_1: ─────┤ X ├┤ Rz(0.1) ├─■─┤M├ # ┌───┐└───┘└─────────┘ │ └╥┘ # q_2: ┤ H ├──■──────────────┼──╫─ # └───┘┌─┴─┐ │ ║ # q_3: ─────┤ X ├────────────■──╫─ # └───┘ ║ # c: 1/═════════════════════════╩═ # 0 circ = QuantumCircuit(4, 1) circ.h(0) circ.cx(0, 1) circ.t(0) circ.h(2) circ.cx(2, 3) circ.rz(0.1, 1) circ.cz(1, 3) circ.measure(1, 0) self.assertEqual(circ.depth(lambda x: circ.qubits[0] in x.qubits), 3) def test_circuit_size_empty(self): """Circuit.size should return 0 for an empty circuit.""" size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) self.assertEqual(qc.size(), 0) def test_circuit_size_single_qubit_gates(self): """Circuit.size should increment for each added single qubit gate.""" size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) self.assertEqual(qc.size(), 1) qc.h(q[1]) self.assertEqual(qc.size(), 2) def test_circuit_size_2qubit(self): """Circuit.size of only 2-qubit gates.""" size = 3 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.cx(q[0], q[1]) qc.rz(0.1, q[1]) qc.rzz(0.1, q[1], q[2]) self.assertEqual(qc.size(lambda x: x.operation.num_qubits == 2), 2) def test_circuit_size_ignores_barriers_snapshots(self): """Circuit.size should not count barriers or snapshots.""" q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) self.assertEqual(qc.size(), 2) qc.barrier(q) self.assertEqual(qc.size(), 2) qc.append(Snapshot("snapshot_label", num_qubits=4), [0, 1, 2, 3]) self.assertEqual(qc.size(), 2) def test_circuit_count_ops(self): """Test circuit count ops.""" q = QuantumRegister(6, "q") qc = QuantumCircuit(q) qc.h(q) qc.x(q[1]) qc.y(q[2:4]) qc.z(q[3:]) result = qc.count_ops() expected = {"h": 6, "z": 3, "y": 2, "x": 1} self.assertIsInstance(result, dict) self.assertEqual(expected, result) def test_circuit_nonlocal_gates(self): """Test num_nonlocal_gates.""" # ┌───┐ ┌────────┐ # q_0: ┤ H ├───────────────────┤0 ├ # ├───┤ ┌───┐ │ │ # q_1: ┤ H ├───┤ X ├─────────■─┤ ├ # ├───┤ └───┘ │ │ │ # q_2: ┤ H ├─────■───────────X─┤ Iswap ├ # ├───┤ │ ┌───┐ │ │ │ # q_3: ┤ H ├─────┼─────┤ Z ├─X─┤ ├ # ├───┤┌────┴────┐├───┤ │ │ # q_4: ┤ H ├┤ Ry(0.1) ├┤ Z ├───┤1 ├ # ├───┤└──┬───┬──┘└───┘ └───╥────┘ # q_5: ┤ H ├───┤ Z ├───────────────╫───── # └───┘ └───┘ ┌──╨──┐ # c: 2/═════════════════════════╡ 0x2 ╞══ # └─────┘ q = QuantumRegister(6, "q") c = ClassicalRegister(2, "c") qc = QuantumCircuit(q, c) qc.h(q) qc.x(q[1]) qc.cry(0.1, q[2], q[4]) qc.z(q[3:]) qc.cswap(q[1], q[2], q[3]) qc.iswap(q[0], q[4]).c_if(c, 2) result = qc.num_nonlocal_gates() expected = 3 self.assertEqual(expected, result) def test_circuit_nonlocal_gates_no_instruction(self): """Verify num_nunlocal_gates does not include barriers.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/4500 n = 3 qc = QuantumCircuit(n) qc.h(range(n)) qc.barrier() self.assertEqual(qc.num_nonlocal_gates(), 0) def test_circuit_connected_components_empty(self): """Verify num_connected_components is width for empty""" q = QuantumRegister(7, "q") qc = QuantumCircuit(q) self.assertEqual(7, qc.num_connected_components()) def test_circuit_connected_components_multi_reg(self): """Test tensor factors works over multi registers""" # ┌───┐ # q1_0: ┤ H ├──■───────────────── # ├───┤┌─┴─┐ # q1_1: ┤ H ├┤ X ├──■──────────── # ├───┤└───┘ │ ┌───┐ # q1_2: ┤ H ├───────┼──┤ X ├──■── # ├───┤ │ └─┬─┘┌─┴─┐ # q2_0: ┤ H ├───────┼────┼──┤ X ├ # ├───┤ ┌─┴─┐ │ └───┘ # q2_1: ┤ H ├─────┤ X ├──■─────── # └───┘ └───┘ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2) qc.h(q1[0]) qc.h(q1[1]) qc.h(q1[2]) qc.h(q2[0]) qc.h(q2[1]) qc.cx(q1[0], q1[1]) qc.cx(q1[1], q2[1]) qc.cx(q2[1], q1[2]) qc.cx(q1[2], q2[0]) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_connected_components_multi_reg2(self): """Test tensor factors works over multi registers #2.""" # q1_0: ──■──────────── # │ # q1_1: ──┼─────────■── # │ ┌───┐ │ # q1_2: ──┼──┤ X ├──┼── # │ └─┬─┘┌─┴─┐ # q2_0: ──┼────■──┤ X ├ # ┌─┴─┐ └───┘ # q2_1: ┤ X ├────────── # └───┘ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2) qc.cx(q1[0], q2[1]) qc.cx(q2[0], q1[2]) qc.cx(q1[1], q2[0]) self.assertEqual(qc.num_connected_components(), 2) def test_circuit_connected_components_disconnected(self): """Test tensor factors works with 2q subspaces.""" # q1_0: ──■────────────────────── # │ # q1_1: ──┼────■───────────────── # │ │ # q1_2: ──┼────┼────■──────────── # │ │ │ # q1_3: ──┼────┼────┼────■─────── # │ │ │ │ # q1_4: ──┼────┼────┼────┼────■── # │ │ │ │ ┌─┴─┐ # q2_0: ──┼────┼────┼────┼──┤ X ├ # │ │ │ ┌─┴─┐└───┘ # q2_1: ──┼────┼────┼──┤ X ├───── # │ │ ┌─┴─┐└───┘ # q2_2: ──┼────┼──┤ X ├────────── # │ ┌─┴─┐└───┘ # q2_3: ──┼──┤ X ├─────────────── # ┌─┴─┐└───┘ # q2_4: ┤ X ├──────────────────── # └───┘ q1 = QuantumRegister(5, "q1") q2 = QuantumRegister(5, "q2") qc = QuantumCircuit(q1, q2) qc.cx(q1[0], q2[4]) qc.cx(q1[1], q2[3]) qc.cx(q1[2], q2[2]) qc.cx(q1[3], q2[1]) qc.cx(q1[4], q2[0]) self.assertEqual(qc.num_connected_components(), 5) def test_circuit_connected_components_with_clbits(self): """Test tensor components with classical register.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────── # ├───┤└╥┘┌─┐ # q_1: ┤ H ├─╫─┤M├────── # ├───┤ ║ └╥┘┌─┐ # q_2: ┤ H ├─╫──╫─┤M├─── # ├───┤ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──╫──╫─┤M├ # └───┘ ║ ║ ║ └╥┘ # c: 4/══════╩══╩══╩══╩═ # 0 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_connected_components(), 4) def test_circuit_connected_components_with_cond(self): """Test tensor components with one conditional gate.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───■──────────── # ├───┤└╥┘ │ ┌─┐ # q_1: ┤ H ├─╫────┼───┤M├────── # ├───┤ ║ │ └╥┘┌─┐ # q_2: ┤ H ├─╫────┼────╫─┤M├─── # ├───┤ ║ ┌─┴─┐ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──┤ X ├──╫──╫─┤M├ # └───┘ ║ └─╥─┘ ║ ║ └╥┘ # ║ ┌──╨──┐ ║ ║ ║ # c: 4/══════╩═╡ 0x2 ╞═╩══╩══╩═ # 0 └─────┘ 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.cx(q[0], q[3]).c_if(c, 2) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_connected_components_with_cond2(self): """Test tensor components with two conditional gates.""" # ┌───┐ ┌───┐ # q_0: ┤ H ├─┤ H ├──────── # ├───┤ └─╥─┘ # q_1: ┤ H ├───╫──────■─── # ├───┤ ║ ┌─┴─┐ # q_2: ┤ H ├───╫────┤ X ├─ # ├───┤ ║ └─╥─┘ # q_3: ┤ H ├───╫──────╫─── # └───┘┌──╨──┐┌──╨──┐ # c: 8/═════╡ 0x0 ╞╡ 0x4 ╞ # └─────┘└─────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(2 * size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(0).c_if(c, 0) qc.cx(1, 2).c_if(c, 4) self.assertEqual(qc.num_connected_components(), 2) def test_circuit_connected_components_with_cond3(self): """Test tensor components with three conditional gates and measurements.""" # ┌───┐┌─┐ ┌───┐ # q0_0: ┤ H ├┤M├─┤ H ├────────────────── # ├───┤└╥┘ └─╥─┘ # q0_1: ┤ H ├─╫────╫──────■───────────── # ├───┤ ║ ║ ┌─┴─┐ ┌─┐ # q0_2: ┤ H ├─╫────╫────┤ X ├─┤M├─────── # ├───┤ ║ ║ └─╥─┘ └╥┘ ┌───┐ # q0_3: ┤ H ├─╫────╫──────╫────╫──┤ X ├─ # └───┘ ║ ║ ║ ║ └─╥─┘ # ║ ┌──╨──┐┌──╨──┐ ║ ┌──╨──┐ # c0: 4/══════╩═╡ 0x0 ╞╡ 0x1 ╞═╩═╡ 0x2 ╞ # 0 └─────┘└─────┘ 2 └─────┘ size = 4 q = QuantumRegister(size) c = ClassicalRegister(size) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.h(q[0]).c_if(c, 0) qc.cx(q[1], q[2]).c_if(c, 1) qc.measure(q[2], c[2]) qc.x(q[3]).c_if(c, 2) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_connected_components_with_bit_cond(self): """Test tensor components with one single bit conditional gate.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────────■──────── # ├───┤└╥┘┌─┐ │ # q_1: ┤ H ├─╫─┤M├────────┼──────── # ├───┤ ║ └╥┘┌─┐ │ # q_2: ┤ H ├─╫──╫─┤M├─────┼──────── # ├───┤ ║ ║ └╥┘ ┌─┴─┐ ┌─┐ # q_3: ┤ H ├─╫──╫──╫────┤ X ├───┤M├ # └───┘ ║ ║ ║ └─╥─┘ └╥┘ # ║ ║ ║ ┌────╨────┐ ║ # c: 4/══════╩══╩══╩═╡ c_0=0x1 ╞═╩═ # 0 1 2 └─────────┘ 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.cx(q[0], q[3]).c_if(c[0], True) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_connected_components(), 3) def test_circuit_connected_components_with_bit_cond2(self): """Test tensor components with two bit conditional gates.""" # ┌───┐ ┌───┐ ┌───┐ # q_0: ┤ H ├───┤ H ├─────────────────┤ X ├─── # ├───┤ └─╥─┘ └─┬─┘ # q_1: ┤ H ├─────╫─────────────────────■───── # ├───┤ ║ ║ # q_2: ┤ H ├─────╫──────────■──────────╫───── # ├───┤ ║ │ ║ # q_3: ┤ H ├─────╫──────────■──────────╫───── # └───┘┌────╨────┐┌────╨────┐┌────╨────┐ # c: 6/═════╡ c_1=0x1 ╞╡ c_0=0x1 ╞╡ c_4=0x0 ╞ # └─────────┘└─────────┘└─────────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size + 2, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(0).c_if(c[1], True) qc.cx(1, 0).c_if(c[4], False) qc.cz(2, 3).c_if(c[0], True) self.assertEqual(qc.num_connected_components(), 5) def test_circuit_connected_components_with_bit_cond3(self): """Test tensor components with register and bit conditional gates.""" # ┌───┐ ┌───┐ # q0_0: ┤ H ├───┤ H ├─────────────────────── # ├───┤ └─╥─┘ # q0_1: ┤ H ├─────╫─────────■─────────────── # ├───┤ ║ ┌─┴─┐ # q0_2: ┤ H ├─────╫───────┤ X ├───────────── # ├───┤ ║ └─╥─┘ ┌───┐ # q0_3: ┤ H ├─────╫─────────╫──────┤ X ├──── # └───┘ ║ ║ └─╥─┘ # ┌────╨─────┐┌──╨──┐┌────╨─────┐ # c0: 4/═════╡ c0_0=0x1 ╞╡ 0x1 ╞╡ c0_2=0x1 ╞ # └──────────┘└─────┘└──────────┘ size = 4 q = QuantumRegister(size) c = ClassicalRegister(size) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(q[0]).c_if(c[0], True) qc.cx(q[1], q[2]).c_if(c, 1) qc.x(q[3]).c_if(c[2], True) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_unitary_factors1(self): """Test unitary factors empty circuit.""" size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) self.assertEqual(qc.num_unitary_factors(), 4) def test_circuit_unitary_factors2(self): """Test unitary factors multi qregs""" q1 = QuantumRegister(2, "q1") q2 = QuantumRegister(2, "q2") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q1, q2, c) self.assertEqual(qc.num_unitary_factors(), 4) def test_circuit_unitary_factors3(self): """Test unitary factors measurements and conditionals.""" # ┌───┐ ┌─┐ # q_0: ┤ H ├────────■──────────■────■──────────■──┤M├─── # ├───┤ │ │ │ ┌─┐ │ └╥┘ # q_1: ┤ H ├──■─────┼─────■────┼────┼──┤M├─────┼───╫──── # ├───┤┌─┴─┐ │ ┌─┴─┐ │ │ └╥┘┌─┐ │ ║ # q_2: ┤ H ├┤ X ├───┼───┤ X ├──┼────┼───╫─┤M├──┼───╫──── # ├───┤└───┘ ┌─┴─┐ └───┘┌─┴─┐┌─┴─┐ ║ └╥┘┌─┴─┐ ║ ┌─┐ # q_3: ┤ H ├──────┤ X ├──────┤ X ├┤ X ├─╫──╫─┤ X ├─╫─┤M├ # └───┘ └─╥─┘ └───┘└───┘ ║ ║ └───┘ ║ └╥┘ # ┌──╨──┐ ║ ║ ║ ║ # c: 4/══════════╡ 0x2 ╞════════════════╩══╩═══════╩══╩═ # └─────┘ 1 2 0 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.cx(q[1], q[2]) qc.cx(q[1], q[2]) qc.cx(q[0], q[3]).c_if(c, 2) qc.cx(q[0], q[3]) qc.cx(q[0], q[3]) qc.cx(q[0], q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_unitary_factors(), 2) def test_circuit_unitary_factors4(self): """Test unitary factors measurements go to same cbit.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────── # ├───┤└╥┘┌─┐ # q_1: ┤ H ├─╫─┤M├────── # ├───┤ ║ └╥┘┌─┐ # q_2: ┤ H ├─╫──╫─┤M├─── # ├───┤ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──╫──╫─┤M├ # └───┘ ║ ║ ║ └╥┘ # q_4: ──────╫──╫──╫──╫─ # ║ ║ ║ ║ # c: 5/══════╩══╩══╩══╩═ # 0 0 0 0 size = 5 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[0]) qc.measure(q[2], c[0]) qc.measure(q[3], c[0]) self.assertEqual(qc.num_unitary_factors(), 5) def test_num_qubits_qubitless_circuit(self): """Check output in absence of qubits.""" c_reg = ClassicalRegister(3) circ = QuantumCircuit(c_reg) self.assertEqual(circ.num_qubits, 0) def test_num_qubits_qubitfull_circuit(self): """Check output in presence of qubits""" q_reg = QuantumRegister(4) c_reg = ClassicalRegister(3) circ = QuantumCircuit(q_reg, c_reg) self.assertEqual(circ.num_qubits, 4) def test_num_qubits_registerless_circuit(self): """Check output for circuits with direct argument for qubits.""" circ = QuantumCircuit(5) self.assertEqual(circ.num_qubits, 5) def test_num_qubits_multiple_register_circuit(self): """Check output for circuits with multiple quantum registers.""" q_reg1 = QuantumRegister(5) q_reg2 = QuantumRegister(6) q_reg3 = QuantumRegister(7) circ = QuantumCircuit(q_reg1, q_reg2, q_reg3) self.assertEqual(circ.num_qubits, 18) def test_calibrations_basis_gates(self): """Check if the calibrations for basis gates provided are added correctly.""" circ = QuantumCircuit(2) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) with pulse.build() as q1_y90: pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), pulse.DriveChannel(1)) # Add calibration circ.add_calibration(RXGate(3.14), [0], q0_x180) circ.add_calibration(RYGate(1.57), [1], q1_y90) self.assertEqual(set(circ.calibrations.keys()), {"rx", "ry"}) self.assertEqual(set(circ.calibrations["rx"].keys()), {((0,), (3.14,))}) self.assertEqual(set(circ.calibrations["ry"].keys()), {((1,), (1.57,))}) self.assertEqual( circ.calibrations["rx"][((0,), (3.14,))].instructions, q0_x180.instructions ) self.assertEqual(circ.calibrations["ry"][((1,), (1.57,))].instructions, q1_y90.instructions) def test_calibrations_custom_gates(self): """Check if the calibrations for custom gates with params provided are added correctly.""" circ = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) # Add calibrations with a custom gate 'rxt' circ.add_calibration("rxt", [0], q0_x180, params=[1.57, 3.14, 4.71]) self.assertEqual(set(circ.calibrations.keys()), {"rxt"}) self.assertEqual(set(circ.calibrations["rxt"].keys()), {((0,), (1.57, 3.14, 4.71))}) self.assertEqual( circ.calibrations["rxt"][((0,), (1.57, 3.14, 4.71))].instructions, q0_x180.instructions ) def test_calibrations_no_params(self): """Check calibrations if the no params is provided with just gate name.""" circ = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) circ.add_calibration("h", [0], q0_x180) self.assertEqual(set(circ.calibrations.keys()), {"h"}) self.assertEqual(set(circ.calibrations["h"].keys()), {((0,), ())}) self.assertEqual(circ.calibrations["h"][((0,), ())].instructions, q0_x180.instructions) def test_has_calibration_for(self): """Test that `has_calibration_for` returns a correct answer.""" qc = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) qc.add_calibration("h", [0], q0_x180) qc.h(0) qc.h(1) self.assertTrue(qc.has_calibration_for(qc.data[0])) self.assertFalse(qc.has_calibration_for(qc.data[1])) def test_has_calibration_for_legacy(self): """Test that `has_calibration_for` returns a correct answer when presented with a legacy 3 tuple.""" qc = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) qc.add_calibration("h", [0], q0_x180) qc.h(0) qc.h(1) self.assertTrue( qc.has_calibration_for( (qc.data[0].operation, list(qc.data[0].qubits), list(qc.data[0].clbits)) ) ) self.assertFalse( qc.has_calibration_for( (qc.data[1].operation, list(qc.data[1].qubits), list(qc.data[1].clbits)) ) ) def test_metadata_copy_does_not_share_state(self): """Verify mutating the metadata of a circuit copy does not impact original.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/6057 qc1 = QuantumCircuit(1) qc1.metadata = {"a": 0} qc2 = qc1.copy() qc2.metadata["a"] = 1000 self.assertEqual(qc1.metadata["a"], 0) def test_metadata_is_dict(self): """Verify setting metadata to None in the constructor results in an empty dict.""" qc = QuantumCircuit(1) metadata1 = qc.metadata self.assertEqual(metadata1, {}) def test_metadata_raises(self): """Test that we must set metadata to a dict.""" qc = QuantumCircuit(1) with self.assertRaises(TypeError): qc.metadata = 1 def test_metdata_deprectation(self): """Test that setting metadata to None emits a deprecation warning.""" qc = QuantumCircuit(1) with self.assertWarns(DeprecationWarning): qc.metadata = None self.assertEqual(qc.metadata, {}) def test_scheduling(self): """Test cannot return schedule information without scheduling.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) with self.assertRaises(AttributeError): # pylint: disable=pointless-statement qc.op_start_times if __name__ == "__main__": unittest.main()
https://github.com/BoxiLi/qiskit-CR-calibration
BoxiLi
""" Generation of echoed and direct CNOT gate based on calibrated CR pulse data. """ from copy import deepcopy import numpy as np from numpy import pi from scipy.signal import find_peaks import matplotlib.pyplot as plt from scipy.optimize import curve_fit import qiskit from qiskit import pulse, circuit, schedule, transpile from qiskit.circuit import Gate, QuantumCircuit from qiskit.transpiler import InstructionProperties from .job_util import ( load_job_data, save_job_data, read_calibration_data, save_calibration_data, omega_GHz_to_amp, ) from .cr_pulse import ( process_zx_tomo_data, get_cr_schedule, _get_normalized_cr_tomography_data, ) # Logger setup after importing logging import logging logger = logging.getLogger(__name__) # %% Esitmate the gate time for a CNOT gate def fit_function( func, xdata, ydata, init_params, show_plot=False, ): """ Fit a given function using ``scipy.optimize.curve_fit``. Args: func (Callable): The function to fit the data. The first arguments is the input x data. xdata (ArrayLike): X axis. ydata (ArrayLike): Y axis. init_params (ArrayLike): Initial parameter for x data show_plot (bool, optional): If True, plot the fitted function and the given data. Defaults to False. Returns: list: The fitted parameters. """ xdata = np.array(xdata) ydata = np.array(ydata) if func is None: func = lambda x, A, B, f, phi: (A * np.cos(2 * pi * f * x - phi) + B) try: fitparams, conv = curve_fit( func, xdata, ydata, p0=init_params, ) except RuntimeError as e: logger.warn("RuntimeError in the optimization") fitparams = init_params xline = np.linspace(xdata[0], xdata[-1], 100) yline = func(xline, *fitparams) diff = np.sum(np.abs(ydata - func(xdata, *fitparams))) / len(ydata) if diff > 0.1: logger.warning( "The fitting error is too large. The calibrated value could be wrong. Please double check the calibration data." ) if show_plot: fig = plt.figure() plt.plot(xdata, ydata, "x", c="k") plt.plot(xline, yline) plt.ylabel("Signal [a.u.]") plt.ylim([-1.1, 1.1]) return fitparams def _find_peak_index(ydata, xdata, height, positive=False): """Find the index of the first (close to time 0) peak in the given data. Args: ydata (np.ndarray): The y-values of the data. xdata (np.ndarray): The x-values of the data. height (float): The minimum height of peaks to be detected. positive (bool, optional): If True, find positive peaks; otherwise, find negative peaks. Defaults to False. Returns: int: The index of the estimated peak. Raises: Warning: If no peaks are found in the data. It returns then the maximal index. """ extreme_indices = find_peaks(ydata, height=height)[0] if positive: # Positive maximum extreme_indices = np.array([i for i in extreme_indices if xdata[i] > 0]) if extreme_indices.size > 0: # Closest one to 0. estimated_index = extreme_indices[ np.argmax(-np.abs(xdata[extreme_indices] - 0.0)) ] else: logger.warning("Peak not found! Consider increase the drive strength.") estimated_index = np.argmax(ydata) return estimated_index def _find_closest_extreme_point(f, phi, estimated_x_value): """Find the closest extreme point to the estimated maximum or minimum. Args: f (float): Frequency of the sinusoidal function. phi (float): Phase of the sinusoidal function. estimated_x_value (float): The estimated x-value of the maximum or minimum. Returns: float: The phase of the closest extreme point. """ extreme_points = (phi + np.array([-np.pi, 0.0, np.pi])) / f / 2 / pi _diff_estimation = -np.abs(extreme_points - estimated_x_value) return extreme_points[np.argmax(_diff_estimation)] def estimate_cr_width(job_id, angle="90"): """ Estimate the duration of the CR pulse from the calibrated tomography experiment data. This function takes the job ID of a tomography experiment for a calibrated CR pulse. It computes the duration of the CR pulse based on the observed signal. The function returns the estimated duration of the CR pulse as an integer that satisfies the qiskit-pulse requirement. Args: job_id (str): The ID of the calibrated tomography experiment job. angle (str, optional): The angle of the CR gate, either "90" or "45". Defaults to "90". Returns: int: The estimated duration of the CR pulse. Note: Due to the truncation of the pulse time to a mulitple of 16, there is additional esitmation error introduced. This could be compensated for by adjusting the pulse amplitude. Here we omit this as the error is small. """ def _helper(cr_times, signal_z): # Rough estimation of the first positive maximum estimated_index = _find_peak_index( -signal_z, cr_times, height=0.75, positive=True ) # Curve fit A, B, f, phi = fit_function( lambda x, A, B, f, phi: (A * np.cos(2 * pi * f * x - phi) + B), cr_times, signal_z, init_params=[-1, 0, 1 / 2 / (cr_times[estimated_index]), 0.0], show_plot=False, ) fitted_first_min = _find_closest_extreme_point( f, phi, cr_times[estimated_index] ) period = 1 / f if angle == "90": estimated_result = fitted_first_min - period / 4 elif angle == "45": estimated_result = fitted_first_min - period / 8 * 3 else: raise ValueError("Unknown angle") return estimated_result cr_times, splitted_data, dt = _get_normalized_cr_tomography_data(job_id) signal_z0 = splitted_data[4] signal_z1 = splitted_data[5] est1 = _helper(cr_times, signal_z0) est2 = _helper(cr_times, signal_z1) if np.abs(est2 - est1) > 100: logger.warning( "The estimated CR pulse time is different for control qubit in state 0 and 1. This indicate that the ZX interaction strength is not well calibrated." ) estimated_result = (est1 + est2) / 2 estimated_result = _helper(cr_times, signal_z1) estimated_result = (estimated_result + 8) // 16 * 16 return int(estimated_result) # %% ################# Calibrate a CNOT gate def _get_ZX_sign(job_id): coupling_strength = process_zx_tomo_data(job_id, show_plot=False) return np.sign(coupling_strength["ZX"]) def create_cr45_pairs( backend, qubits, cr_params, ix_params, ZX_sign, cr45_duration, frequency_offset=0.0 ): """ Generate CR pulse schedule for a 45 degree ZX rotation. Args: backend (Backend): The quantum backend. qubits (Tuple): Tuple of qubits (control, target). cr_params (dict): Dictionary containing the base CR pulse parameters. ix_params (dict): Dictionary containing the IX pulse parameters. ZX_sign (int): Sign of the ZX interaction (1 or -1). cr45_duration (int): Duration of the CR pulses for a 45 degree rotation. frequency_offset (float, optional): Frequency offset. Defaults to 0.0. Returns: list: Pulse schedule for a CR45m and CR45p pulse schedule. """ cr_params = deepcopy(cr_params) ix_params = deepcopy(ix_params) cr_params["duration"] = cr45_duration ix_params["duration"] = cr45_duration cr_sched1 = get_cr_schedule( qubits, backend, cr_params=cr_params, ix_params=ix_params, frequency_offset=frequency_offset, ) cr_params["angle"] += pi ix_params["angle"] += pi cr_sched2 = get_cr_schedule( qubits, backend, cr_params=cr_params, ix_params=ix_params, frequency_offset=frequency_offset, ) if ZX_sign == 1: return cr_sched2, cr_sched1 else: return cr_sched1, cr_sched2 def create_echoed_cnot_schedule( backend, qubits, calibration_data, reverse_direction=False ): """ Generate a schedule for a echod CNOT gate based on CR pulse. Args: backend (Backend): The quantum backend. qubits (Tuple): Tuple of qubits (control, target). cr_params (dict): Dictionary containing the base CR pulse parameters. ix_params (dict): Dictionary containing the IX pulse parameters. ZX_sign (int): Sign of the ZX interaction (1 or -1). cr45_duration (int): Duration of the CR pulses for a 45 degree rotation. cr90_duration (int): Duration of the CR pulses for a 90 degree rotation. idle_duration (int): Duration of the idle time between the CR pulses. frequency_offset (float, optional): Frequency offset. Defaults to 0.0. Returns: qsikit.pulse.Schedule: A pulse schedule for a CNOT gate with echo. """ cr_params = calibration_data["cr_params"] ix_params = calibration_data["ix_params"] calibrated_cr_tomo_id = calibration_data["calibration_job_id"] duration = estimate_cr_width(calibrated_cr_tomo_id, angle="45") frequency_offset = calibration_data["frequency_offset"] ZX_sign = _get_ZX_sign(calibrated_cr_tomo_id) cr45m_sched, cr45p_sched = create_cr45_pairs( backend, qubits, cr_params, ix_params, ZX_sign, duration, frequency_offset=frequency_offset, ) CR45p = Gate("CR45p", 2, []) CR45m = Gate("CR45m", 2, []) backend = deepcopy(backend) backend.target.add_instruction( CR45m, {qubits: InstructionProperties(calibration=cr45m_sched)}, name="CR45m", ) backend.target.add_instruction( CR45p, {qubits: InstructionProperties(calibration=cr45p_sched)}, name="CR45p", ) circ = QuantumCircuit(2, 2) if reverse_direction: circ.h(0) circ.h(1) circ.sx(1) circ.x(0) circ.append(CR45p, [0, 1]) circ.x(0) circ.append(CR45m, [0, 1]) circ.rz(np.pi / 2, 0) if reverse_direction: circ.h(0) circ.h(1) try: basis_gates = backend.configuration().basis_gates except AttributeError: basis_gates = ["measure", "sx", "x", "rz"] transpile_options = { "basis_gates": basis_gates + ["CR45p", "CR45m"], "initial_layout": qubits, "optimization_level": 1, } transpiled_circ = transpile(circ, backend=backend, **transpile_options) # Transfer Schedule to ScheduleBlock using pulse builder. Otherwise qiskit_ibm_provider rejects it. cnot_sched = pulse.Schedule() cnot_sched.append(schedule(transpiled_circ, backend=backend), inplace=True) return cnot_sched def create_cr90m( backend, qubits, cr_params, ix_params, ZX_sign, cr90_duration, x_gate_ix_params, frequency_offset=0.0, ): """ Generate CR pulse schedule for a 90 degree -ZX rotation. Args: backend (Backend): The quantum backend. qubits (Tuple): Tuple of qubits (control, target). cr_params (dict): Dictionary containing the base CR pulse parameters. ix_params (dict): Dictionary containing the IX pulse parameters. ZX_sign (int): Sign of the ZX interaction (1 or -1). cr90_duration (int): Duration of the CR pulse for a 90 degree rotation. frequency_offset (float, optional): Frequency offset. Defaults to 0.0. Returns: qiskit.pulse.Schedule: A pulse schedule for a CR90m pulse. """ cr_params = deepcopy(cr_params) ix_params = deepcopy(ix_params) if ZX_sign == 1: cr_params["angle"] += pi ix_params["angle"] += pi cr_params["duration"] = cr90_duration ix_params["duration"] = cr90_duration if x_gate_ix_params is not None: x_gate_ix_params["duration"] = cr90_duration if ZX_sign == 1: x_gate_ix_params["angle"] += pi return get_cr_schedule( qubits, backend, cr_params=cr_params, ix_params=ix_params, x_gate_ix_params=x_gate_ix_params, frequency_offset=frequency_offset, ) def create_direct_cnot_schedule( backend, qubits, calibration_data, with_separate_x=False, reverse_direction=False ): """ Generate a schedule for a direct CNOT pulse. Args: backend (Backend): The quantum backend. qubits (Tuple): Tuple of qubits (control, target). calibration_data (dict): Dictionary containing calibration data. with_separate_x (bool, optional): If True, includes a separate X gate before the CR90m. Defaults to False. Returns: qiskit.pulse.Schedule: A pulse schedule for a direct CNOT pulse. """ cr_params = calibration_data["cr_params"] ix_params = calibration_data["ix_params"] if with_separate_x: x_gate_ix_params = None else: x_gate_ix_params = deepcopy(calibration_data["x_gate_ix_params"]) calibrated_cr_tomo_id = calibration_data["calibration_job_id"] rz0_correction = calibration_data.get("rz0_correction", 0.0) frequency_offset = calibration_data.get("x_gate_frequency_offset", 0.0) ZX_sign = _get_ZX_sign(calibrated_cr_tomo_id) duration = estimate_cr_width(calibrated_cr_tomo_id, angle="90") cr90m_sched = create_cr90m( backend, qubits, cr_params, ix_params, ZX_sign, duration, x_gate_ix_params=x_gate_ix_params, frequency_offset=frequency_offset, ) CR90m = Gate("CR90m", 2, []) backend = deepcopy(backend) backend.target.add_instruction( CR90m, {qubits: InstructionProperties(calibration=cr90m_sched)}, name="CR90m", ) circ = QuantumCircuit(2) if reverse_direction: circ.h(0) circ.h(1) if with_separate_x: circ.rx(pi / 2, 1) circ.append(CR90m, [0, 1]) circ.rz(pi / 2, 0) circ.rz(rz0_correction, 0) if reverse_direction: circ.h(0) circ.h(1) try: basis_gates = backend.configuration().basis_gates except AttributeError: basis_gates = ["measure", "sx", "x", "rz"] transpile_options = { "basis_gates": basis_gates + ["CR90m"], "initial_layout": qubits, "optimization_level": 1, } transpiled_circ = transpile(circ, backend=backend, **transpile_options) # Transfer Schedule to ScheduleBlock using pulse builder. Otherwise qiskit_ibm_provider rejects it. cnot_sched = pulse.Schedule() cnot_sched.append(schedule(transpiled_circ, backend=backend), inplace=True) return cnot_sched # %% Calibration of the RZ0 phase correction def get_rz0_amplification_circuits(num_gates_list, phase_list): """ Generate a list of circuits for calibrating RZ0 phase correction by amplifying the effect. Args: num_gates_list (list): List of integers specifying the number of CNOT gates in each circuit. phase_list (list): List of phase values for the RZ gate. Returns: list: List of circuits with varied numbers of CNOT gates and RZ phases. """ circ_list = [] phase = circuit.Parameter("phase") custom_cnot = Gate("custom_cnot", 2, []) for n in num_gates_list: circ = QuantumCircuit(2, 2) circ.h(0) circ.barrier() for _ in range(n): circ.append(custom_cnot, [0, 1]) circ.rz(phase, 0) circ.barrier() circ.h(0) circ.measure(0, 0) circ.measure(1, 1) circ_list += [circ.assign_parameters({phase: p}) for p in phase_list] return circ_list def get_rz0_pi_calibration_circuits(phase_list): """ Generate a list of circuits for calibrating RZ0 phase correction with pi rotations. One measures 00 if CX has correct ZI phase, if the phase is pi, one measures 11. Args: phase_list (list): List of phase values for the RZ gate. Returns: list: List of circuits for differnet phase. """ phase = circuit.Parameter("phase") custom_cnot = Gate("custom_cnot", 2, []) circ = QuantumCircuit(2, 2) circ.h(0) # CX with a phase need to be calibrated circ.barrier() circ.append(custom_cnot, [0, 1]) circ.rz(phase, 0) circ.barrier() circ.rx(pi / 2, 0) # CX with a phase need to be calibrated circ.barrier() circ.append(custom_cnot, [0, 1]) circ.rz(phase, 0) circ.barrier() circ.rx(-pi / 2, 1) circ.h(0) circ.measure(0, 0) circ.measure(1, 1) return [circ.assign_parameters({phase: p}) for p in phase_list] def send_rz0_calibration_job(backend, qubits, phase_list, circ_list, session): """ Send a job for calibrating RZ0 phase correction. Args: backend (Backend): The quantum backend. qubits (Tuple): Tuple of qubits (control, target). phase_list (list): List of phase values for the RZ gate. circ_list (list): List of QuantumCircuit objects to be executed session: A Qiskit runtime Session. Returns: str: Job ID of the calibration job. """ try: basis_gates = backend.configuration().basis_gates except AttributeError: basis_gates = ["measure", "sx", "x", "rz"] transpiled_circ_list = transpile( circ_list, backend=backend, basis_gates=basis_gates + ["custom_cnot"], initial_layout=qubits, optimization_level=1, ) shots = 1024 if session is not None: job = session.run( "circuit-runner", inputs={ "circuits": transpiled_circ_list, "skip_transpilation": True, "shots": shots, }, ) else: job = backend.run(transpiled_circ_list, shots=shots) parameters = { "name": "rz0 calibration", "backend": backend.name, "qubits": qubits, "phase_list": phase_list, "shots": shots, } logger.info( "ZI calibration ID: " + job.job_id() + "\n" + "\n".join([f"{key}: {val}" for key, val in parameters.items()]) + "\n" ) save_job_data(job, backend=backend, parameters=parameters) return job.job_id() def rough_rz0_correction_calibration(backend, qubits, gate_name, session): """ Perform a rough calibration of the RZ0 phase phase correction on the control qubit. Args: backend (Backend): The quantum backend. qubits (Tuple): Tuple of qubits (control, target). gate_name (str): Name of the gate for calibration. session: A Qiskit runtime Session. """ logger.info("Rough calibration of the RZ0 phase correction.") calibration_data = read_calibration_data(backend, gate_name, qubits) calibration_data = deepcopy(calibration_data) calibration_data["rz0_correction"] = 0.0 custom_cnot_schedule = create_direct_cnot_schedule( backend, qubits, calibration_data, with_separate_x=False ) phase_list = np.linspace(-pi, pi, 50) max_num_gates = 8 num_gates_list = range(2, max_num_gates + 1, 2) circ_list = get_rz0_amplification_circuits( num_gates_list, phase_list ) + get_rz0_pi_calibration_circuits(phase_list) backend = deepcopy(backend) backend.target.add_instruction( Gate("custom_cnot", 2, []), {qubits: InstructionProperties(calibration=custom_cnot_schedule)}, name="custom_cnot", ) job_id = send_rz0_calibration_job(backend, qubits, phase_list, circ_list, session) logger.info("Job complete. Analyzing data...") data = load_job_data(job_id) result = data["result"] shots = data["parameters"]["shots"] prob_list = np.array( [result.get_counts(i).get("00", 0) / shots for i in range(len(result.results))] ) prob_list = prob_list.reshape(len(result.results) // 50, 50) fig, ax = plt.subplots(1) im = ax.imshow(prob_list, vmin=0, vmax=1, aspect=3, cmap="PuBu") ax.set_xticklabels([0] + [round(p, 2) for p in phase_list[::10]]) ax.set_yticks([0, 1, 2, 3, 4], [2, 4, 6, 8, "parity"]) ax.set_ylabel("Number of CNOT") cbar = fig.colorbar(im, spacing="proportional", shrink=0.4) cbar.set_label(r"Probability of $|00\rangle$") estimated_rz0_correction = phase_list[np.argmax(np.sum(prob_list, axis=0))] calibration_data["rz0_correction"] = estimated_rz0_correction logger.info(f"Estimated RZ0 correction: {estimated_rz0_correction}\n") save_calibration_data(backend, gate_name, qubits, calibration_data) def fine_rz0_correction_calibration( backend, qubits, gate_name, session, num_repeat_cnot=2 ): """ Perform a fine-tuning calibration of the phase correction on the control qubit. Args: backend (Backend): The quantum backend. qubits (Tuple): Tuple of qubits (control, target). gate_name (str): Name of the gate for calibration. session: A Qiskit Quantum Session. """ logger.info("Fine calibration of the RZ0 phase correction.") calibration_data = read_calibration_data(backend, gate_name, qubits) rz0_correction = calibration_data["rz0_correction"] calibration_data = deepcopy(calibration_data) calibration_data["rz0_correction"] = 0.0 custom_cnot_schedule = create_direct_cnot_schedule( backend, qubits, calibration_data, with_separate_x=False ) narrow_phase_list = rz0_correction + np.linspace(-pi / 10, pi / 10, 50) circ_list = get_rz0_amplification_circuits((num_repeat_cnot,), narrow_phase_list) backend = deepcopy(backend) backend.target.add_instruction( Gate("custom_cnot", 2, []), {qubits: InstructionProperties(calibration=custom_cnot_schedule)}, name="custom_cnot", ) job_id = send_rz0_calibration_job( backend, qubits, narrow_phase_list, circ_list, session ) data = load_job_data(job_id) result = data["result"] shots = data["parameters"]["shots"] def _find_closest_extreme_point(f, phi, estimated_x_value): """ Find the extreme point that is closed to the estimated maximum/minimum. """ extreme_points = (phi + np.linspace(-10 * pi, 10 * pi, 21)) / f / 2 / pi _diff_estimation = -np.abs(extreme_points - estimated_x_value) return extreme_points[np.argmax(_diff_estimation)] prob_list = np.array( [result.get_counts(i).get("00", 0) / shots for i in range(len(result.results))] ) data_to_fit = -prob_list rought_estimated_min_point = narrow_phase_list[np.argmin(data_to_fit)] A, B, f, phi = fit_function( lambda x, A, B, f, phi: (A * np.cos(2 * pi * f * x - phi) + B), narrow_phase_list, data_to_fit, init_params=[-1.0, 0, 1.0, rought_estimated_min_point], show_plot=True, ) rz0_correction = _find_closest_extreme_point(f, phi, rought_estimated_min_point) calibration_data["rz0_correction"] = rz0_correction logger.info(f"Fine-tuning RZ0 correction: {rz0_correction}") save_calibration_data(backend, gate_name, qubits, calibration_data) # %% Fine-tuning the ZX and IX strength def _CR_angle_error_amplification(backend, qubits, gate_name, session, max_num_gate): custom_cnot = Gate("custom_cnot", 2, []) circ_list = [] for initial_state in [0, 1]: for num_gate in range(max_num_gate): circ = QuantumCircuit(2, 1) if initial_state == 1: circ.x(0) circ.rx(pi / 2, 1) for _ in range(num_gate): circ.barrier() circ.append(custom_cnot, [0, 1], []) circ.measure(1, 0) circ_list.append(circ) calibration_data = read_calibration_data(backend, gate_name, qubits) modified_calibration_data = deepcopy(calibration_data) custom_cnot_sched = create_direct_cnot_schedule( backend, qubits, modified_calibration_data, with_separate_x=False ) backend_tmp = deepcopy(backend) backend_tmp.target.add_instruction( custom_cnot, {qubits: InstructionProperties(calibration=custom_cnot_sched)}, name="custom_cnot", ) transpiled_circ_list = transpile( circ_list, backend=backend_tmp, basis_gates=backend_tmp.configuration().basis_gates + ["custom_cnot"], initial_layout=qubits, optimization_level=1, ) shots = 1024 job = session.run( "circuit-runner", inputs={ "circuits": transpiled_circ_list, "skip_transpilation": True, "shots": shots, }, ) parameters = { "name": "Fine CR amplitude calibration", "backend": backend_tmp.name, "qubits": qubits, "gate_name": gate_name, "phase_list": max_num_gate, "shots": shots, "calibration": calibration_data, } logger.info( "ZI calibration ID: " + job.job_id() + "\n" + "\n".join([f"{key}: {val}" for key, val in parameters.items()]) + "\n" ) save_job_data(job, backend=backend_tmp, parameters=parameters) logger.info("CR angle fine-tuning job complete.") result = load_job_data(job)["result"] return job.job_id() def _analyize_CR_angle_data( job_id, ): data = load_job_data(job_id) result = data["result"] shots = data["parameters"]["shots"] qubits = data["parameters"]["qubits"] prob_list = np.array( [result.get_counts(i).get("0", 0) / shots for i in range(len(result.results))] ) plt.plot(prob_list[: len(prob_list) // 2], "o-", label="control 0") plt.plot(prob_list[len(prob_list) // 2 :], "o-", label="control 1") plt.legend() control0_data = prob_list[: len(prob_list) // 2] control1_data = prob_list[len(prob_list) // 2 :] import warnings def _func1(x, epsZX, epsIX, B): with warnings.catch_warnings(): # Ignore the Runtime warning when x is not an integer. # This happens because in `fit_function` we plot func as a function of x. # It will gives nan, automatically ignore in the plot, so we just hide the warning here. # One needs to plot the fitted points manually. warnings.simplefilter("ignore") result = ( 1 * (-1) ** x * (np.cos(pi / 2 + pi / 4 * x * (-epsZX - epsIX))) + 0.5 ) return result def _func0(x, epsZX, epsIX, B): with warnings.catch_warnings(): warnings.simplefilter("ignore") result = 1 * (np.cos(pi / 2 + pi / 4 * x * (epsZX - epsIX))) + 0.5 return result def _fun(x, epsZX, epsIX, B): result1 = _func1(x, epsZX, epsIX, B) result0 = _func0(x, epsZX, epsIX, B) return np.concatenate([result0, result1]) data_to_fit = np.concatenate([control0_data, control1_data]) iteration_number = len(control0_data) with warnings.catch_warnings(): # Ignore OptimizeWarning of SciPy because the Covariance cannot be calculated. warnings.simplefilter("ignore") params = fit_function( _fun, list(range(iteration_number)), data_to_fit, init_params=[ 0.0, 0.0, 0, ], show_plot=False, ) xline = np.array(list(range(iteration_number))) plt.plot(xline, _func0(xline, *params), "x") plt.plot(xline, _func1(xline, *params), "x") plt.show() epsZX, epsIX, _ = params logger.info(f"ZX error {round(epsZX*100, 2)}%, IX error {round(epsIX*100, 2)}%") return epsZX, epsIX def CR_angle_fine_tuning(backend, qubits, gate_name, session, max_num_gate=10): job_id = _CR_angle_error_amplification( backend, qubits, gate_name, max_num_gate=max_num_gate, session=session ) epsZX, epsIX = _analyize_CR_angle_data(job_id) if np.abs(epsZX) + np.abs(epsZX) <= 0.01: logger.info("No need for amplitude calibration.\n") return old_calibration_data = read_calibration_data(backend, gate_name, qubits) modified_calibration_data = deepcopy(old_calibration_data) modified_calibration_data["cr_params"]["amp"] *= 1 + epsZX # Divided by 2 IX_amp_correction = omega_GHz_to_amp( backend, qubits[1], modified_calibration_data["x_gate_coeffs"]["IX"] / 2 * epsIX / 1000, ) modified_calibration_data["x_gate_ix_params"]["amp"] += IX_amp_correction save_calibration_data(backend, gate_name, qubits, modified_calibration_data) job_id2 = _CR_angle_error_amplification( backend, qubits, gate_name, max_num_gate=max_num_gate, session=session ) epsZX_new, epsIX_new = _analyize_CR_angle_data(job_id2) if (epsZX_new**2 + epsIX_new**2) < (epsZX**2 + epsZX**2): save_calibration_data(backend, gate_name, qubits, modified_calibration_data) logger.info("CR drive ampliutude updated.\n") else: save_calibration_data(backend, gate_name, qubits, old_calibration_data) logger.info("Calibration brings no improvement.\n")
https://github.com/mattalcasabas/quantum-shors-algorithm
mattalcasabas
import matplotlib.pyplot as plt import numpy as np from qiskit import QuantumCircuit, Aer, execute from math import gcd import pandas as pd from qiskit.visualization import plot_histogram
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) ### added y gate ### qc.cx(0, 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) ### added h gate ### qc.h(0) return qc
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# External imports from pylab import cm from sklearn import metrics import numpy as np import matplotlib.pyplot as plt # Qiskit imports from qiskit import QuantumCircuit from qiskit.circuit import ParameterVector from qiskit.visualization import circuit_drawer from qiskit.algorithms.optimizers import SPSA from qiskit.circuit.library import ZZFeatureMap from qiskit_machine_learning.kernels import TrainableFidelityQuantumKernel from qiskit_machine_learning.kernels.algorithms import QuantumKernelTrainer from qiskit_machine_learning.algorithms import QSVC from qiskit_machine_learning.datasets import ad_hoc_data class QKTCallback: """Callback wrapper class.""" def __init__(self) -> None: self._data = [[] for i in range(5)] def callback(self, x0, x1=None, x2=None, x3=None, x4=None): """ Args: x0: number of function evaluations x1: the parameters x2: the function value x3: the stepsize x4: whether the step was accepted """ self._data[0].append(x0) self._data[1].append(x1) self._data[2].append(x2) self._data[3].append(x3) self._data[4].append(x4) def get_callback_data(self): return self._data def clear_callback_data(self): self._data = [[] for i in range(5)] adhoc_dimension = 2 X_train, y_train, X_test, y_test, adhoc_total = ad_hoc_data( training_size=20, test_size=5, n=adhoc_dimension, gap=0.3, plot_data=False, one_hot=False, include_sample_total=True, ) plt.figure(figsize=(5, 5)) plt.ylim(0, 2 * np.pi) plt.xlim(0, 2 * np.pi) plt.imshow( np.asmatrix(adhoc_total).T, interpolation="nearest", origin="lower", cmap="RdBu", extent=[0, 2 * np.pi, 0, 2 * np.pi], ) plt.scatter( X_train[np.where(y_train[:] == 0), 0], X_train[np.where(y_train[:] == 0), 1], marker="s", facecolors="w", edgecolors="b", label="A train", ) plt.scatter( X_train[np.where(y_train[:] == 1), 0], X_train[np.where(y_train[:] == 1), 1], marker="o", facecolors="w", edgecolors="r", label="B train", ) plt.scatter( X_test[np.where(y_test[:] == 0), 0], X_test[np.where(y_test[:] == 0), 1], marker="s", facecolors="b", edgecolors="w", label="A test", ) plt.scatter( X_test[np.where(y_test[:] == 1), 0], X_test[np.where(y_test[:] == 1), 1], marker="o", facecolors="r", edgecolors="w", label="B test", ) plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0) plt.title("Ad hoc dataset for classification") plt.show() # Create a rotational layer to train. We will rotate each qubit the same amount. training_params = ParameterVector("θ", 1) fm0 = QuantumCircuit(2) fm0.ry(training_params[0], 0) fm0.ry(training_params[0], 1) # Use ZZFeatureMap to represent input data fm1 = ZZFeatureMap(2) # Create the feature map, composed of our two circuits fm = fm0.compose(fm1) print(circuit_drawer(fm)) print(f"Trainable parameters: {training_params}") # Instantiate quantum kernel quant_kernel = TrainableFidelityQuantumKernel(feature_map=fm, training_parameters=training_params) # Set up the optimizer cb_qkt = QKTCallback() spsa_opt = SPSA(maxiter=10, callback=cb_qkt.callback, learning_rate=0.05, perturbation=0.05) # Instantiate a quantum kernel trainer. qkt = QuantumKernelTrainer( quantum_kernel=quant_kernel, loss="svc_loss", optimizer=spsa_opt, initial_point=[np.pi / 2] ) # Train the kernel using QKT directly qka_results = qkt.fit(X_train, y_train) optimized_kernel = qka_results.quantum_kernel print(qka_results) # Use QSVC for classification qsvc = QSVC(quantum_kernel=optimized_kernel) # Fit the QSVC qsvc.fit(X_train, y_train) # Predict the labels labels_test = qsvc.predict(X_test) # Evalaute the test accuracy accuracy_test = metrics.balanced_accuracy_score(y_true=y_test, y_pred=labels_test) print(f"accuracy test: {accuracy_test}") plot_data = cb_qkt.get_callback_data() # callback data K = optimized_kernel.evaluate(X_train) # kernel matrix evaluated on the training samples plt.rcParams["font.size"] = 20 fig, ax = plt.subplots(1, 2, figsize=(14, 5)) ax[0].plot([i + 1 for i in range(len(plot_data[0]))], np.array(plot_data[2]), c="k", marker="o") ax[0].set_xlabel("Iterations") ax[0].set_ylabel("Loss") ax[1].imshow(K, cmap=cm.get_cmap("bwr", 20)) fig.tight_layout() plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import execute, pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(100, 1.0), d0) pulse_prog.draw()
https://github.com/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 # 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 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) # 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), ")") t3_st_qcs = transpile(t3_st_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_st_qcs), ")") t3_st_qcs[-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-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 8192 reps = 8 jobs = [] for _ in range(reps): # execute job = execute(t3_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=initial_layout) print('Job ID', cal_job.job_id()) 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/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. """Tests LogicNetwork.Tweedledum2Qiskit converter.""" import unittest from qiskit.utils.optionals import HAS_TWEEDLEDUM from qiskit.test import QiskitTestCase from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import XGate if HAS_TWEEDLEDUM: # pylint: disable=import-error from qiskit.circuit.classicalfunction.utils import tweedledum2qiskit from tweedledum.ir import Circuit from tweedledum.operators import X @unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.") class TestTweedledum2Qiskit(QiskitTestCase): """Tests qiskit.transpiler.classicalfunction.utils.tweedledum2qiskit function.""" def test_x(self): """Single uncontrolled X""" tweedledum_circuit = Circuit() tweedledum_circuit.apply_operator(X(), [tweedledum_circuit.create_qubit()]) circuit = tweedledum2qiskit(tweedledum_circuit) expected = QuantumCircuit(1) expected.x(0) self.assertEqual(circuit, expected) def test_cx_0_1(self): """CX(0, 1)""" tweedledum_circuit = Circuit() qubits = [] qubits.append(tweedledum_circuit.create_qubit()) qubits.append(tweedledum_circuit.create_qubit()) tweedledum_circuit.apply_operator(X(), [qubits[0], qubits[1]]) circuit = tweedledum2qiskit(tweedledum_circuit) expected = QuantumCircuit(2) expected.append(XGate().control(1, ctrl_state="1"), [0, 1]) self.assertEqual(circuit, expected) def test_cx_1_0(self): """CX(1, 0)""" tweedledum_circuit = Circuit() qubits = [] qubits.append(tweedledum_circuit.create_qubit()) qubits.append(tweedledum_circuit.create_qubit()) tweedledum_circuit.apply_operator(X(), [qubits[1], qubits[0]]) circuit = tweedledum2qiskit(tweedledum_circuit) expected = QuantumCircuit(2) expected.append(XGate().control(1, ctrl_state="1"), [1, 0]) self.assertEqual(expected, circuit) def test_cx_qreg(self): """CX(0, 1) with qregs parameter""" tweedledum_circuit = Circuit() qubits = [] qubits.append(tweedledum_circuit.create_qubit()) qubits.append(tweedledum_circuit.create_qubit()) tweedledum_circuit.apply_operator(X(), [qubits[1], qubits[0]]) qr = QuantumRegister(2, "qr") circuit = tweedledum2qiskit(tweedledum_circuit, qregs=[qr]) expected = QuantumCircuit(qr) expected.append(XGate().control(1, ctrl_state="1"), [qr[1], qr[0]]) self.assertEqual(expected, circuit)
https://github.com/abbarreto/qiskit3
abbarreto
https://github.com/DRA-chaos/Quantum-Classical-Hyrid-Neural-Network-for-binary-image-classification-using-PyTorch-Qiskit-pipeline
DRA-chaos
!pip install qiskit # check if CUDA is available import torch train_on_gpu = torch.cuda.is_available() if not train_on_gpu: print('CUDA is not available. Training on CPU ...') else: print('CUDA is available! Training on GPU ...') import numpy as np import matplotlib.pyplot as plt import torch from torch.autograd import Function from torchvision import datasets, transforms import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import qiskit from qiskit import transpile, assemble from qiskit.visualization import * import numpy as np import torch from torch.autograd import Function import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import torchvision from torchvision import datasets, transforms from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, execute from qiskit.circuit import Parameter from qiskit import Aer from tqdm import tqdm from matplotlib import pyplot as plt %matplotlib inline def to_numbers(tensor_list): num_list = [] for tensor in tensor_list: num_list += [tensor.item()] return num_list class QuantumCircuit: """ This class provides a simple interface for interaction with the quantum circuit """ def __init__(self, n_qubits, backend, shots): # --- Circuit definition --- self._circuit = qiskit.QuantumCircuit(n_qubits) all_qubits = [i for i in range(n_qubits)] self.theta = qiskit.circuit.Parameter('theta') self._circuit.h(all_qubits) self._circuit.barrier() self._circuit.ry(self.theta, all_qubits) self._circuit.measure_all() # --------------------------- self.backend = backend self.shots = shots def run(self, thetas): t_qc = transpile(self._circuit, self.backend) qobj = assemble(t_qc, shots=self.shots, parameter_binds = [{self.theta: theta} for theta in thetas]) job = self.backend.run(qobj) result = job.result().get_counts() counts = np.array(list(result.values())) states = np.array(list(result.keys())).astype(float) # Compute probabilities for each state probabilities = counts / self.shots # Get state expectation expectation = np.sum(states * probabilities) return np.array([expectation]) class HybridFunction(Function): """ Hybrid quantum - classical function definition """ @staticmethod def forward(ctx, input, quantum_circuit, shift): """ Forward pass computation """ ctx.shift = shift ctx.quantum_circuit = quantum_circuit expectation_z = ctx.quantum_circuit.run(input[0].tolist()) result = torch.tensor([expectation_z]) ctx.save_for_backward(input, result) return result @staticmethod def backward(ctx, grad_output): """ Backward pass computation """ input, expectation_z = ctx.saved_tensors input_list = np.array(input.tolist()) shift_right = input_list + np.ones(input_list.shape) * ctx.shift shift_left = input_list - np.ones(input_list.shape) * ctx.shift gradients = [] for i in range(len(input_list)): expectation_right = ctx.quantum_circuit.run(shift_right[i]) expectation_left = ctx.quantum_circuit.run(shift_left[i]) gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left]) gradients.append(gradient) gradients = np.array([gradients]).T return torch.tensor([gradients]).float() * grad_output.float(), None, None class Hybrid(nn.Module): """ Hybrid quantum - classical layer definition """ def __init__(self, backend, shots, shift): super(Hybrid, self).__init__() self.quantum_circuit = QuantumCircuit(1, backend, shots) self.shift = shift def forward(self, input): return HybridFunction.apply(input, self.quantum_circuit, self.shift) import torchvision transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform) len(cifar_trainset) from torch.utils.data import DataLoader, random_split #cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform) labels = cifar_trainset.targets # get the labels for the data labels = np.array(labels) idx1 = np.where(labels == 0) # filter on aeroplanes idx2 = np.where(labels == 1) # filter on automobiles # Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set) n=100 # concatenate the data indices idx = np.concatenate((idx1[0][0:n],idx2[0][0:n])) # create the filtered dataset for our training set cifar_trainset.targets = labels[idx] cifar_trainset.data = cifar_trainset.data[idx] cifar_trainset, valid = random_split(cifar_trainset,[150,50]) train_loader = torch.utils.data.DataLoader(cifar_trainset, batch_size=1, shuffle=True) valid_loader = torch.utils.data.DataLoader(valid, batch_size=1, shuffle=True) @torch.no_grad() def get_all_preds(model, test_loader): all_preds = torch.tensor([]) for batch in train_loader: images, labels = batch preds = model(images) all_preds = torch.cat( (all_preds, preds) ,dim=0 ) return all_preds import numpy as np import matplotlib.pyplot as plt n_samples_show = 6 data_iter = iter(train_loader) fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 2)) while n_samples_show > 0: images, targets = data_iter.__next__() images=images.squeeze() axes[n_samples_show - 1].imshow(images[0].numpy(), cmap='gray') axes[n_samples_show - 1].set_xticks([]) axes[n_samples_show - 1].set_yticks([]) axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item())) n_samples_show -= 1 import torchvision transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors cifar_testset = datasets.CIFAR10(root='./data1', train=False, download=True, transform=transform) labels = cifar_testset.targets # get the labels for the data labels = np.array(labels) idx1 = np.where(labels == 0) # filter on aeroplanes idx2 = np.where(labels == 1) # filter on automobiles # Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set) n=100 # concatenate the data indices idx = np.concatenate((idx1[0][0:n],idx2[0][0:n])) # create the filtered dataset for our training set cifar_testset.targets = labels[idx] cifar_testset.data = cifar_testset.data[idx] test_loader = torch.utils.data.DataLoader(cifar_testset, batch_size=1, shuffle=False) len(cifar_testset) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.dropout = nn.Dropout2d() self.fc1 = nn.Linear(500, 500) self.fc2 = nn.Linear(500, 1) self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2) 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(1, -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.hybrid(x) return torch.cat((x, 1 - x), -1) %matplotlib inline import matplotlib.pyplot as plt model = Net() valid_loss_min = np.Inf # track change in validation loss optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 5 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() model.load_state_dict(torch.load('model_cifar.pt')) total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) %matplotlib inline import matplotlib.pyplot as plt model = Net() valid_loss_min = np.Inf # track change in validation loss optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 3 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) if (validation_loss)<=(valid_loss_min): print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format( valid_loss_min, validation_loss)) torch.save(model.state_dict(), 'model_cifar.pt') valid_loss_min = validation_loss #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) %matplotlib inline import matplotlib.pyplot as plt model = Net() valid_loss_min = np.Inf # track change in validation loss optimizer = optim.Adam(model.parameters(), lr=0.0008) loss_func = nn.NLLLoss() epochs = 5 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch+1, loss_list[epoch], loss_list_V[-1])) if (validation_loss)<=(valid_loss_min): print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format( valid_loss_min, validation_loss)) torch.save(model.state_dict(), 'model_cifar.pt') valid_loss_min = validation_loss #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) %matplotlib inline import matplotlib.pyplot as plt model = Net() valid_loss_min = np.Inf # track change in validation loss optimizer = optim.Adam(model.parameters(), lr=0.0008) loss_func = nn.NLLLoss() epochs = 10 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch+1, loss_list[epoch], loss_list_V[-1])) if (validation_loss)<=(valid_loss_min): print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format( valid_loss_min, validation_loss)) torch.save(model.state_dict(), 'model_cifar.pt') valid_loss_min = validation_loss #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) %matplotlib inline import matplotlib.pyplot as plt model = Net() valid_loss_min = np.Inf # track change in validation loss optimizer = optim.Adam(model.parameters(), lr=0.0008) loss_func = nn.NLLLoss() epochs = 25 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) if (validation_loss)<=(valid_loss_min): print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format( valid_loss_min, validation_loss)) torch.save(model.state_dict(), 'model_cifar.pt') valid_loss_min = validation_loss #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 5 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 10 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[epoch], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) n_samples_show = 6 count = 0 fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) model.eval() with torch.no_grad(): for batch_idx, (data, target) in enumerate(test_loader): if count == n_samples_show: break output = model(data) pred = output.argmax(dim=1, keepdim=True) data=data.squeeze() axes[count].imshow(data[0].numpy().squeeze(), cmap='gray') axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title('Predicted {}'.format(pred.item())) count += 1 model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 7 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 8 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 9 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 6 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0004) loss_func = nn.NLLLoss() epochs = 6 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0003) loss_func = nn.NLLLoss() epochs = 5 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0008) loss_func = nn.NLLLoss() epochs = 7 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.SGD(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 10 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 15 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.01) loss_func = nn.NLLLoss() epochs = 15 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 15 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 10 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 3 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 7 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0008) loss_func = nn.NLLLoss() epochs = 10 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0008) loss_func = nn.NLLLoss() epochs = 15 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0008) loss_func = nn.NLLLoss() epochs = 5 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0008) loss_func = nn.NLLLoss() epochs = 3 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) %matplotlib inline import matplotlib.pyplot as plt model = Net() valid_loss_min = np.Inf # track change in validation loss optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 5 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model early_stopping = EarlyStopping(patience=patience, verbose=True) model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch+1, loss_list[-1], loss_list_V[-1])) early_stopping(valid_loss, model) if early_stopping.early_stop: print("Early stopping") break #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() %matplotlib inline import matplotlib.pyplot as plt model = Net() valid_loss_min = np.Inf # track change in validation loss optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 5 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Validation [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch+1, loss_list[epoch], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) %matplotlib inline import matplotlib.pyplot as plt model = Net() valid_loss_min = np.Inf # track change in validation loss optimizer = optim.Adam(model.parameters(), lr=0.0008) loss_func = nn.NLLLoss() epochs = 8 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) if (validation_loss)<=(valid_loss_min): print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format( valid_loss_min, validation_loss)) torch.save(model.state_dict(), 'model_cifar.pt') valid_loss_min = validation_loss #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() %matplotlib inline import matplotlib.pyplot as plt model = Net() valid_loss_min = np.Inf # track change in validation loss optimizer = optim.Adam(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 10 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) if (validation_loss)<=(valid_loss_min): print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format( valid_loss_min, validation_loss)) torch.save(model.state_dict(), 'model_cifar.pt') valid_loss_min = validation_loss #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) %matplotlib inline import matplotlib.pyplot as plt model = Net() valid_loss_min = np.Inf # track change in validation loss optimizer = optim.Adam(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 15 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) %matplotlib inline import matplotlib.pyplot as plt model = Net() valid_loss_min = np.Inf # track change in validation loss optimizer = optim.Adam(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 20 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) %matplotlib inline import matplotlib.pyplot as plt model = Net() valid_loss_min = np.Inf # track change in validation loss optimizer = optim.Adam(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 3 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() #print('validation [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) %matplotlib inline import matplotlib.pyplot as plt model = Net() valid_loss_min = np.Inf # track change in validation loss optimizer = optim.Adam(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 15 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[epoch], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) %matplotlib inline import matplotlib.pyplot as plt model = Net() valid_loss_min = np.Inf # track change in validation loss optimizer = optim.Adam(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 15 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[epoch], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) %matplotlib inline import matplotlib.pyplot as plt model = Net() valid_loss_min = np.Inf # track change in validation loss optimizer = optim.Adam(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 5 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[epoch], loss_list_V[-1])) if (validation_loss)<=(valid_loss_min): print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format( valid_loss_min, validation_loss)) torch.save(model.state_dict(), 'model_cifar.pt') valid_loss_min = validation_loss #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) %matplotlib inline import matplotlib.pyplot as plt model = Net() valid_loss_min = np.Inf # track change in validation loss optimizer = optim.Adam(model.parameters(), lr=0.0001) loss_func = nn.CrossEntropyLoss() epochs = 10 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch+1, loss_list[epoch], loss_list_V[-1])) if (validation_loss)<=(valid_loss_min): print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format( valid_loss_min, validation_loss)) torch.save(model.state_dict(), 'model_cifar.pt') valid_loss_min = validation_loss #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) %matplotlib inline import matplotlib.pyplot as plt model = Net() valid_loss_min = np.Inf # track change in validation loss optimizer = optim.Adam(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 15 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch+1, loss_list[epoch], loss_list_V[-1])) if (validation_loss)<=(valid_loss_min): print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format( valid_loss_min, validation_loss)) torch.save(model.state_dict(), 'model_cifar.pt') valid_loss_min = validation_loss #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) )
https://github.com/luis6156/Shor-s-Quantum-Algorithm
luis6156
from qiskit import QuantumCircuit, Aer, execute, IBMQ from qiskit.utils import QuantumInstance import numpy as np from qiskit.algorithms import Shor IBMQ.enable_account('ENTER API TOKEN HERE') # Enter your API token here provider = IBMQ.get_provider(hub='ibm-q') backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1000) my_shor = Shor(quantum_instance) result_dict = my_shor.factor(15) print(result_dict)
https://github.com/arian-code/nptel_quantum_assignments
arian-code
from sympy import * from sympy.physics.quantum.state import Ket, Bra from sympy.physics.quantum import TensorProduct import numpy as np init_printing(use_unicode=True) #One Q bit gates H=Matrix([[1/sqrt(2), 1/sqrt(2)],[1/sqrt(2), -1/sqrt(2)]]) S=Matrix([[0, 1],[1, I]]) X=Matrix([[0, 1],[1, 0]]) Y=Matrix([[0, -I],[I, 0]]) Z=Matrix([[1, 0],[0, -1]]) Identity=Matrix([[1, 0],[0, 1]]) H, S, X, Y, Z, Identity #Two Q bit gates CNOT=Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]) CNOT HI=TensorProduct(H, Identity) #Example only CNOT, HI circuit=TensorProduct(X, Identity)*CNOT*TensorProduct(X, Identity) circuit #option A in_1=Matrix([[1],[0],[0],[0]]) lhs=circuit*in_1 rhs=Matrix([[0],[1],[0],[0]]) print (lhs) print (rhs) if (lhs==rhs): print ("It is true") else: print ("It is false") #option B in_1=Matrix([[0],[1],[0],[0]]) lhs=circuit*in_1 rhs=Matrix([[0],[1],[0],[0]]) print (lhs) print (rhs) if (lhs==rhs): print ("It is true") else: print ("It is false") #option C in_1=Matrix([[0],[0],[1],[0]]) lhs=circuit*in_1 rhs=Matrix([[0],[0],[1],[0]]) print (lhs) print (rhs) if (lhs==rhs): print ("It is true") else: print ("It is false") #option D in_1=Matrix([[0],[0],[1],[0]]) lhs=circuit*in_1 rhs=Matrix([[0],[0],[0],[1]]) print (lhs) print (rhs) if (lhs==rhs): print ("It is true") else: print ("It is false")
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# import the drawing methods from matplotlib.pyplot import plot, figure, show # draw a figure figure(figsize=(6,6), dpi=80) # include our predefined functions %run qlatvia.py # draw the axes draw_axes() # draw the origin plot(0,0,'ro') # a point in red color # draw these quantum states as points (in blue, green, yellow, and cyan colors) plot(1,0,'bo') plot(0,1,'go') plot(-1,0,'yo') plot(0,-1,'co') show() # import the drawing methods from matplotlib.pyplot import figure, arrow, show # draw a figure figure(figsize=(6,6), dpi=80) # include our predefined functions %run qlatvia.py # draw the axes draw_axes() # draw the quantum states as vectors (in red, blue, green, and yellow colors) arrow(0,0,0.92,0,head_width=0.04, head_length=0.08, color="r") arrow(0,0,0,0.92,head_width=0.04, head_length=0.08, color="b") arrow(0,0,-0.92,0,head_width=0.04, head_length=0.08, color="g") arrow(0,0,0,-0.92,head_width=0.04, head_length=0.08, color="y") show() # import the drawing methods from matplotlib.pyplot import plot, figure # draw a figure figure(figsize=(6,6), dpi=60) # draw the origin plot(0,0,'ro') from random import randrange colors = ['ro','bo','go','yo','co','mo','ko'] # # your solution is here # # randomly creating a 2-dimensional quantum state from random import randrange def random_quantum_state(): first_entry = randrange(-100,101) second_entry = randrange(-100,101) length_square = first_entry**2+second_entry**2 while length_square == 0: first_entry = randrange(-100,101) second_entry = randrange(-100,101) length_square = first_entry**2+second_entry**2 first_entry = first_entry / length_square**0.5 second_entry = second_entry / length_square**0.5 return [first_entry,second_entry] # import the drawing methods from matplotlib.pyplot import plot, figure, show # draw a figure figure(figsize=(6,6), dpi=60) # draw the origin plot(0,0,'ro') from random import randrange colors = ['ro','bo','go','yo','co','mo','ko'] for i in range(500): # create a random quantum state quantum_state = random_quantum_state(); # draw a blue point for the random quantum state x = quantum_state[0]; y = quantum_state[1]; plot(x,y,colors[randrange(len(colors))]) show() # import the drawing methods from matplotlib.pyplot import plot, figure, arrow # draw a figure figure(figsize=(6,6), dpi=60) # include our predefined functions %run qlatvia.py # draw the axes draw_axes() # draw the origin plot(0,0,'ro') from random import randrange colors = ['r','b','g','y','b','c','m'] # # your solution is here # # randomly creating a 2-dimensional quantum state from random import randrange def random_quantum_state(): first_entry = randrange(-100,101) second_entry = randrange(-100,101) length_square = first_entry**2+second_entry**2 while length_square == 0: first_entry = randrange(-100,101) second_entry = randrange(-100,101) length_square = first_entry**2+second_entry**2 first_entry = first_entry / length_square**0.5 second_entry = second_entry / length_square**0.5 return [first_entry,second_entry] # import the drawing methods from matplotlib.pyplot import plot, figure, arrow, show %run qlatvia.py # draw a figure figure(figsize=(6,6), dpi=60) draw_axes(); # draw the origin plot(0,0,'ro') from random import randrange colors = ['r','b','g','y','b','c','m'] for i in range(500): # create a random quantum state quantum_state = random_quantum_state(); # draw a blue vector for the random quantum state x = quantum_state[0]; y = quantum_state[1]; # shorten the line length to 0.92 # line_length + head_length (0.08) should be 1 x = 0.92 * x y = 0.92 * y arrow(0,0,x,y,head_width=0.04,head_length=0.08,color=colors[randrange(len(colors))]) show() # import the drawing methods from matplotlib.pyplot import figure figure(figsize=(6,6), dpi=80) # size of the figure # include our predefined functions %run qlatvia.py # draw axes draw_axes() # draw the unit circle draw_unit_circle() %run qlatvia.py draw_qubit() draw_quantum_state(3/5,4/5,"|v>") %run qlatvia.py draw_qubit() draw_quantum_state(3/5,4/5,"|v>") from matplotlib.pyplot import arrow, text, gca # the projection on |0>-axis arrow(0,0,3/5,0,color="blue",linewidth=1.5) arrow(0,4/5,3/5,0,color="blue",linestyle='dotted') text(0.1,-0.1,"cos(a)=3/5") # the projection on |1>-axis arrow(0,0,0,4/5,color="blue",linewidth=1.5) arrow(3/5,0,0,4/5,color="blue",linestyle='dotted') text(-0.1,0.55,"sin(a)=4/5",rotation="90") # drawing the angle with |0>-axis from matplotlib.patches import Arc gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=0,theta2=53) ) text(0.08,0.05,'.',fontsize=30) text(0.21,0.09,'a') # set the angle from random import randrange myangle = randrange(361) ################################################ from matplotlib.pyplot import figure,gca from matplotlib.patches import Arc from math import sin,cos,pi # draw a figure figure(figsize=(6,6), dpi=60) %run qlatvia.py draw_axes() print("the selected angle is",myangle,"degrees") ratio_of_arc = ((1000*myangle/360)//1)/1000 print("it is",ratio_of_arc,"of a full circle") print("its length is",ratio_of_arc,"x 2\u03C0","=",ratio_of_arc*2*pi) myangle_in_radian = 2*pi*(myangle/360) print("its radian value is",myangle_in_radian) gca().add_patch( Arc((0,0),0.2,0.2,angle=0,theta1=0,theta2=myangle,color="red",linewidth=2) ) gca().add_patch( Arc((0,0),2,2,angle=0,theta1=0,theta2=myangle,color="brown",linewidth=2) ) x = cos(myangle_in_radian) y = sin(myangle_in_radian) draw_quantum_state(x,y,"|v>") # the projection on |0>-axis arrow(0,0,x,0,color="blue",linewidth=1) arrow(0,y,x,0,color="blue",linestyle='dashed') # the projection on |1>-axis arrow(0,0,0,y,color="blue",linewidth=1) arrow(x,0,0,y,color="blue",linestyle='dashed') print() print("the amplitude of state |0> is",x) print("the amplitude of state |1> is",y) print() print("the probability of observing state |0> is",x*x) print("the probability of observing state |1> is",y*y) print("the total probability is",round(x*x+y*y,6)) # %%writefile FILENAME.py # your function is here from math import cos, sin, pi from random import randrange def random_quantum_state2(): angle_degree = randrange(360) angle_radian = 2*pi*angle_degree/360 return [cos(angle_radian),sin(angle_radian)] # include our predefined functions %run qlatvia.py # draw the axes draw_qubit() for i in range(6): [x,y]=random_quantum_state2() draw_quantum_state(x,y,"|v"+str(i)+">") # include our predefined functions %run qlatvia.py # draw the axes draw_qubit() for i in range(100): [x,y]=random_quantum_state2() draw_quantum_state(x,y,"")
https://github.com/neelkamath/quantum-experiments
neelkamath
from qiskit import * from qiskit.tools.visualization import plot_histogram %matplotlib inline secretnumber = '11100011' circuit = QuantumCircuit(len(secretnumber)+1,len(secretnumber)) circuit.h(range(len(secretnumber))) circuit.x(len(secretnumber)) circuit.h(len(secretnumber)) circuit.barrier() for ii, yesno in enumerate(reversed(secretnumber)): if yesno == '1': circuit.cx(ii,len(secretnumber)) circuit.barrier() circuit.h(range(len(secretnumber))) circuit.barrier() circuit.measure(range(len(secretnumber)),range(len(secretnumber))) circuit.draw(output = 'mpl')
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Qiskit's gates in QASM2.""" import unittest from math import pi import re from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.circuit import Parameter, Qubit, Clbit, Gate from qiskit.circuit.library import C3SXGate, CCZGate, CSGate, CSdgGate, PermutationGate from qiskit.qasm.exceptions import QasmError # Regex pattern to match valid OpenQASM identifiers VALID_QASM2_IDENTIFIER = re.compile("[a-z][a-zA-Z_0-9]*") class TestCircuitQasm(QiskitTestCase): """QuantumCircuit QASM2 tests.""" def test_circuit_qasm(self): """Test circuit qasm() method.""" qr1 = QuantumRegister(1, "qr1") qr2 = QuantumRegister(2, "qr2") cr = ClassicalRegister(3, "cr") qc = QuantumCircuit(qr1, qr2, cr) qc.p(0.3, qr1[0]) qc.u(0.3, 0.2, 0.1, qr2[1]) qc.s(qr2[1]) qc.sdg(qr2[1]) qc.cx(qr1[0], qr2[1]) qc.barrier(qr2) qc.cx(qr2[1], qr1[0]) qc.h(qr2[1]) qc.x(qr2[1]).c_if(cr, 0) qc.y(qr1[0]).c_if(cr, 1) qc.z(qr1[0]).c_if(cr, 2) qc.barrier(qr1, qr2) qc.measure(qr1[0], cr[0]) qc.measure(qr2[0], cr[1]) qc.measure(qr2[1], cr[2]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg qr1[1]; qreg qr2[2]; creg cr[3]; p(0.3) qr1[0]; u(0.3,0.2,0.1) qr2[1]; s qr2[1]; sdg qr2[1]; cx qr1[0],qr2[1]; barrier qr2[0],qr2[1]; cx qr2[1],qr1[0]; h qr2[1]; if(cr==0) x qr2[1]; if(cr==1) y qr1[0]; if(cr==2) z qr1[0]; barrier qr1[0],qr2[0],qr2[1]; measure qr1[0] -> cr[0]; measure qr2[0] -> cr[1]; measure qr2[1] -> cr[2];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_composite_circuit(self): """Test circuit qasm() method when a composite circuit instruction is included within circuit. """ composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_instruction() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate composite_circ q0,q1 { h q0; x q1; cx q0,q1; } qreg qr[2]; creg cr[2]; h qr[0]; cx qr[0],qr[1]; barrier qr[0],qr[1]; composite_circ qr[0],qr[1]; measure qr[0] -> cr[0]; measure qr[1] -> cr[1];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_multiple_same_composite_circuits(self): """Test circuit qasm() method when a composite circuit is added to the circuit multiple times """ composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_instruction() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate composite_circ q0,q1 { h q0; x q1; cx q0,q1; } qreg qr[2]; creg cr[2]; h qr[0]; cx qr[0],qr[1]; barrier qr[0],qr[1]; composite_circ qr[0],qr[1]; composite_circ qr[0],qr[1]; measure qr[0] -> cr[0]; measure qr[1] -> cr[1];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_multiple_composite_circuits_with_same_name(self): """Test circuit qasm() method when multiple composite circuit instructions with the same circuit name are added to the circuit """ my_gate = QuantumCircuit(1, name="my_gate") my_gate.h(0) my_gate_inst1 = my_gate.to_instruction() my_gate = QuantumCircuit(1, name="my_gate") my_gate.x(0) my_gate_inst2 = my_gate.to_instruction() my_gate = QuantumCircuit(1, name="my_gate") my_gate.x(0) my_gate_inst3 = my_gate.to_instruction() qr = QuantumRegister(1, name="qr") circuit = QuantumCircuit(qr, name="circuit") circuit.append(my_gate_inst1, [qr[0]]) circuit.append(my_gate_inst2, [qr[0]]) my_gate_inst2_id = id(circuit.data[-1].operation) circuit.append(my_gate_inst3, [qr[0]]) my_gate_inst3_id = id(circuit.data[-1].operation) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate my_gate q0 {{ h q0; }} gate my_gate_{1} q0 {{ x q0; }} gate my_gate_{0} q0 {{ x q0; }} qreg qr[1]; my_gate qr[0]; my_gate_{1} qr[0]; my_gate_{0} qr[0];\n""".format( my_gate_inst3_id, my_gate_inst2_id ) self.assertEqual(circuit.qasm(), expected_qasm) def test_circuit_qasm_with_composite_circuit_with_children_composite_circuit(self): """Test circuit qasm() method when composite circuits with children composite circuits in the definitions are added to the circuit""" child_circ = QuantumCircuit(2, name="child_circ") child_circ.h(0) child_circ.cx(0, 1) parent_circ = QuantumCircuit(3, name="parent_circ") parent_circ.append(child_circ, range(2)) parent_circ.h(2) grandparent_circ = QuantumCircuit(4, name="grandparent_circ") grandparent_circ.append(parent_circ, range(3)) grandparent_circ.x(3) qc = QuantumCircuit(4) qc.append(grandparent_circ, range(4)) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate child_circ q0,q1 { h q0; cx q0,q1; } gate parent_circ q0,q1,q2 { child_circ q0,q1; h q2; } gate grandparent_circ q0,q1,q2,q3 { parent_circ q0,q1,q2; x q3; } qreg q[4]; grandparent_circ q[0],q[1],q[2],q[3];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_pi(self): """Test circuit qasm() method with pi params.""" circuit = QuantumCircuit(2) circuit.cz(0, 1) circuit.u(2 * pi, 3 * pi, -5 * pi, 0) qasm_str = circuit.qasm() circuit2 = QuantumCircuit.from_qasm_str(qasm_str) self.assertEqual(circuit, circuit2) def test_circuit_qasm_with_composite_circuit_with_one_param(self): """Test circuit qasm() method when a composite circuit instruction has one param """ original_str = """OPENQASM 2.0; include "qelib1.inc"; gate nG0(param0) q0 { h q0; } qreg q[3]; creg c[3]; nG0(pi) q[0];\n""" qc = QuantumCircuit.from_qasm_str(original_str) self.assertEqual(original_str, qc.qasm()) def test_circuit_qasm_with_composite_circuit_with_many_params_and_qubits(self): """Test circuit qasm() method when a composite circuit instruction has many params and qubits """ original_str = """OPENQASM 2.0; include "qelib1.inc"; gate nG0(param0,param1) q0,q1 { h q0; h q1; } qreg q[3]; qreg r[3]; creg c[3]; creg d[3]; nG0(pi,pi/2) q[0],r[0];\n""" qc = QuantumCircuit.from_qasm_str(original_str) self.assertEqual(original_str, qc.qasm()) def test_c3sxgate_roundtrips(self): """Test that C3SXGate correctly round trips. Qiskit gives this gate a different name ('c3sx') to the name in Qiskit's version of qelib1.inc ('c3sqrtx') gate, which can lead to resolution issues.""" qc = QuantumCircuit(4) qc.append(C3SXGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; qreg q[4]; c3sqrtx q[0],q[1],q[2],q[3]; """ self.assertEqual(qasm, expected) parsed = QuantumCircuit.from_qasm_str(qasm) self.assertIsInstance(parsed.data[0].operation, C3SXGate) def test_c3sxgate_qasm_deprecation_warning(self): """Test deprecation warning for C3SXGate.""" with self.assertWarnsRegex(DeprecationWarning, r"Correct exporting to OpenQASM 2"): C3SXGate().qasm() def test_cczgate_qasm(self): """Test that CCZ dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(3) qc.append(CCZGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate ccz q0,q1,q2 { h q2; ccx q0,q1,q2; h q2; } qreg q[3]; ccz q[0],q[1],q[2]; """ self.assertEqual(qasm, expected) def test_csgate_qasm(self): """Test that CS dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.append(CSGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate cs q0,q1 { p(pi/4) q0; cx q0,q1; p(-pi/4) q1; cx q0,q1; p(pi/4) q1; } qreg q[2]; cs q[0],q[1]; """ self.assertEqual(qasm, expected) def test_csdggate_qasm(self): """Test that CSdg dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.append(CSdgGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate csdg q0,q1 { p(-pi/4) q0; cx q0,q1; p(pi/4) q1; cx q0,q1; p(-pi/4) q1; } qreg q[2]; csdg q[0],q[1]; """ self.assertEqual(qasm, expected) def test_rzxgate_qasm(self): """Test that RZX dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.rzx(0, 0, 1) qc.rzx(pi / 2, 1, 0) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate rzx(param0) q0,q1 { h q1; cx q0,q1; rz(param0) q1; cx q0,q1; h q1; } qreg q[2]; rzx(0) q[0],q[1]; rzx(pi/2) q[1],q[0]; """ self.assertEqual(qasm, expected) def test_ecrgate_qasm(self): """Test that ECR dumps its definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.ecr(0, 1) qc.ecr(1, 0) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate rzx(param0) q0,q1 { h q1; cx q0,q1; rz(param0) q1; cx q0,q1; h q1; } gate ecr q0,q1 { rzx(pi/4) q0,q1; x q0; rzx(-pi/4) q0,q1; } qreg q[2]; ecr q[0],q[1]; ecr q[1],q[0]; """ self.assertEqual(qasm, expected) def test_unitary_qasm(self): """Test that UnitaryGate can be dumped to OQ2 correctly.""" qc = QuantumCircuit(1) qc.unitary([[1, 0], [0, 1]], 0) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate unitary q0 { u(0,0,0) q0; } qreg q[1]; unitary q[0]; """ self.assertEqual(qasm, expected) def test_multiple_unitary_qasm(self): """Test that multiple UnitaryGate instances can all dump successfully.""" custom = QuantumCircuit(1, name="custom") custom.unitary([[1, 0], [0, -1]], 0) qc = QuantumCircuit(2) qc.unitary([[1, 0], [0, 1]], 0) qc.unitary([[0, 1], [1, 0]], 1) qc.append(custom.to_gate(), [0], []) qasm = qc.qasm() expected = re.compile( r"""OPENQASM 2.0; include "qelib1.inc"; gate unitary q0 { u\(0,0,0\) q0; } gate (?P<u1>unitary_[0-9]*) q0 { u\(pi,-pi/2,pi/2\) q0; } gate (?P<u2>unitary_[0-9]*) q0 { u\(0,pi/2,pi/2\) q0; } gate custom q0 { (?P=u2) q0; } qreg q\[2\]; unitary q\[0\]; (?P=u1) q\[1\]; custom q\[0\]; """, re.MULTILINE, ) self.assertRegex(qasm, expected) def test_unbound_circuit_raises(self): """Test circuits with unbound parameters raises.""" qc = QuantumCircuit(1) theta = Parameter("θ") qc.rz(theta, 0) with self.assertRaises(QasmError): qc.qasm() def test_gate_qasm_with_ctrl_state(self): """Test gate qasm() with controlled gate that has ctrl_state setting.""" from qiskit.quantum_info import Operator qc = QuantumCircuit(2) qc.ch(0, 1, ctrl_state=0) qasm_str = qc.qasm() self.assertEqual(Operator(qc), Operator(QuantumCircuit.from_qasm_str(qasm_str))) def test_circuit_qasm_with_mcx_gate(self): """Test circuit qasm() method with MCXGate See https://github.com/Qiskit/qiskit-terra/issues/4943 """ qc = QuantumCircuit(4) qc.mcx([0, 1, 2], 3) # qasm output doesn't support parameterized gate yet. # param0 for "gate mcuq(param0) is not used inside the definition expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate mcx q0,q1,q2,q3 { h q3; p(pi/8) q0; p(pi/8) q1; p(pi/8) q2; p(pi/8) q3; cx q0,q1; p(-pi/8) q1; cx q0,q1; cx q1,q2; p(-pi/8) q2; cx q0,q2; p(pi/8) q2; cx q1,q2; p(-pi/8) q2; cx q0,q2; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; h q3; } qreg q[4]; mcx q[0],q[1],q[2],q[3];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_mcx_gate_variants(self): """Test circuit qasm() method with MCXGrayCode, MCXRecursive, MCXVChain""" import qiskit.circuit.library as cl n = 5 qc = QuantumCircuit(2 * n - 1) qc.append(cl.MCXGrayCode(n), range(n + 1)) qc.append(cl.MCXRecursive(n), range(n + 2)) qc.append(cl.MCXVChain(n), range(2 * n - 1)) # qasm output doesn't support parameterized gate yet. # param0 for "gate mcuq(param0) is not used inside the definition expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate mcu1(param0) q0,q1,q2,q3,q4,q5 { cu1(pi/16) q4,q5; cx q4,q3; cu1(-pi/16) q3,q5; cx q4,q3; cu1(pi/16) q3,q5; cx q3,q2; cu1(-pi/16) q2,q5; cx q4,q2; cu1(pi/16) q2,q5; cx q3,q2; cu1(-pi/16) q2,q5; cx q4,q2; cu1(pi/16) q2,q5; cx q2,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q3,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q2,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q3,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q1,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q2,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q1,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q2,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; } gate mcx_gray q0,q1,q2,q3,q4,q5 { h q5; mcu1(pi) q0,q1,q2,q3,q4,q5; h q5; } gate mcx q0,q1,q2,q3 { h q3; p(pi/8) q0; p(pi/8) q1; p(pi/8) q2; p(pi/8) q3; cx q0,q1; p(-pi/8) q1; cx q0,q1; cx q1,q2; p(-pi/8) q2; cx q0,q2; p(pi/8) q2; cx q1,q2; p(-pi/8) q2; cx q0,q2; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; h q3; } gate mcx_recursive q0,q1,q2,q3,q4,q5,q6 { mcx q0,q1,q2,q6; mcx q3,q4,q6,q5; mcx q0,q1,q2,q6; mcx q3,q4,q6,q5; } gate mcx_vchain q0,q1,q2,q3,q4,q5,q6,q7,q8 { rccx q0,q1,q6; rccx q2,q6,q7; rccx q3,q7,q8; ccx q4,q8,q5; rccx q3,q7,q8; rccx q2,q6,q7; rccx q0,q1,q6; } qreg q[9]; mcx_gray q[0],q[1],q[2],q[3],q[4],q[5]; mcx_recursive q[0],q[1],q[2],q[3],q[4],q[5],q[6]; mcx_vchain q[0],q[1],q[2],q[3],q[4],q[5],q[6],q[7],q[8];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_registerless_bits(self): """Test that registerless bits do not have naming collisions in their registers.""" initial_registers = [QuantumRegister(2), ClassicalRegister(2)] qc = QuantumCircuit(*initial_registers, [Qubit(), Clbit()]) # Match a 'qreg identifier[3];'-like QASM register declaration. register_regex = re.compile(r"\s*[cq]reg\s+(\w+)\s*\[\d+\]\s*", re.M) qasm_register_names = set() for statement in qc.qasm().split(";"): match = register_regex.match(statement) if match: qasm_register_names.add(match.group(1)) self.assertEqual(len(qasm_register_names), 4) # Check that no additional registers were added to the circuit. self.assertEqual(len(qc.qregs), 1) self.assertEqual(len(qc.cregs), 1) # Check that the registerless-register names are recalculated after adding more registers, # to avoid naming clashes in this case. generated_names = qasm_register_names - {register.name for register in initial_registers} for generated_name in generated_names: qc.add_register(QuantumRegister(1, name=generated_name)) qasm_register_names = set() for statement in qc.qasm().split(";"): match = register_regex.match(statement) if match: qasm_register_names.add(match.group(1)) self.assertEqual(len(qasm_register_names), 6) def test_circuit_qasm_with_repeated_instruction_names(self): """Test that qasm() doesn't change the name of the instructions that live in circuit.data, but a copy of them when there are repeated names.""" qc = QuantumCircuit(2) qc.h(0) qc.x(1) # Create some random custom gate and name it "custom" custom = QuantumCircuit(1) custom.h(0) custom.y(0) gate = custom.to_gate() gate.name = "custom" # Another random custom gate named "custom" as well custom2 = QuantumCircuit(2) custom2.x(0) custom2.z(1) gate2 = custom2.to_gate() gate2.name = "custom" # Append custom gates with same name to original circuit qc.append(gate, [0]) qc.append(gate2, [1, 0]) # Expected qasm string will append the id to the second gate with repeated name expected_qasm = f"""OPENQASM 2.0; include "qelib1.inc"; gate custom q0 {{ h q0; y q0; }} gate custom_{id(gate2)} q0,q1 {{ x q0; z q1; }} qreg q[2]; h q[0]; x q[1]; custom q[0]; custom_{id(gate2)} q[1],q[0];\n""" # Check qasm() produced the correct string self.assertEqual(expected_qasm, qc.qasm()) # Check instruction names were not changed by qasm() names = ["h", "x", "custom", "custom"] for idx, instruction in enumerate(qc._data): self.assertEqual(instruction.operation.name, names[idx]) def test_circuit_qasm_with_invalid_identifiers(self): """Test that qasm() detects and corrects invalid OpenQASM gate identifiers, while not changing the instructions on the original circuit""" qc = QuantumCircuit(2) # Create some gate and give it an invalid name custom = QuantumCircuit(1) custom.x(0) custom.u(0, 0, pi, 0) gate = custom.to_gate() gate.name = "A[$]" # Another gate also with invalid name custom2 = QuantumCircuit(2) custom2.x(0) custom2.append(gate, [1]) gate2 = custom2.to_gate() gate2.name = "invalid[name]" # Append gates qc.append(gate, [0]) qc.append(gate2, [1, 0]) # Expected qasm with valid identifiers expected_qasm = "\n".join( [ "OPENQASM 2.0;", 'include "qelib1.inc";', "gate gate_A___ q0 { x q0; u(0,0,pi) q0; }", "gate invalid_name_ q0,q1 { x q0; gate_A___ q1; }", "qreg q[2];", "gate_A___ q[0];", "invalid_name_ q[1],q[0];", "", ] ) # Check qasm() produces the correct string self.assertEqual(expected_qasm, qc.qasm()) # Check instruction names were not changed by qasm() names = ["A[$]", "invalid[name]"] for idx, instruction in enumerate(qc._data): self.assertEqual(instruction.operation.name, names[idx]) def test_circuit_qasm_with_duplicate_invalid_identifiers(self): """Test that qasm() corrects invalid identifiers and the de-duplication code runs correctly, without altering original instructions""" base = QuantumCircuit(1) # First gate with invalid name, escapes to "invalid__" clash1 = QuantumCircuit(1, name="invalid??") clash1.x(0) base.append(clash1, [0]) # Second gate with invalid name that also escapes to "invalid__" clash2 = QuantumCircuit(1, name="invalid[]") clash2.z(0) base.append(clash2, [0]) # Check qasm is correctly produced names = set() for match in re.findall(r"gate (\S+)", base.qasm()): self.assertTrue(VALID_QASM2_IDENTIFIER.fullmatch(match)) names.add(match) self.assertEqual(len(names), 2) # Check instruction names were not changed by qasm() names = ["invalid??", "invalid[]"] for idx, instruction in enumerate(base._data): self.assertEqual(instruction.operation.name, names[idx]) def test_circuit_qasm_escapes_register_names(self): """Test that registers that have invalid OpenQASM 2 names get correctly escaped, even when they would escape to the same value.""" qc = QuantumCircuit(QuantumRegister(2, "?invalid"), QuantumRegister(2, "!invalid")) qc.cx(0, 1) qc.cx(2, 3) qasm = qc.qasm() match = re.fullmatch( rf"""OPENQASM 2.0; include "qelib1.inc"; qreg ({VALID_QASM2_IDENTIFIER.pattern})\[2\]; qreg ({VALID_QASM2_IDENTIFIER.pattern})\[2\]; cx \1\[0\],\1\[1\]; cx \2\[0\],\2\[1\]; """, qasm, ) self.assertTrue(match) self.assertNotEqual(match.group(1), match.group(2)) def test_circuit_qasm_escapes_reserved(self): """Test that the OpenQASM 2 exporter won't export reserved names.""" qc = QuantumCircuit(QuantumRegister(1, "qreg")) gate = Gate("gate", 1, []) gate.definition = QuantumCircuit(1) qc.append(gate, [qc.qubits[0]]) qasm = qc.qasm() match = re.fullmatch( rf"""OPENQASM 2.0; include "qelib1.inc"; gate ({VALID_QASM2_IDENTIFIER.pattern}) q0 {{ }} qreg ({VALID_QASM2_IDENTIFIER.pattern})\[1\]; \1 \2\[0\]; """, qasm, ) self.assertTrue(match) self.assertNotEqual(match.group(1), "gate") self.assertNotEqual(match.group(1), "qreg") def test_circuit_qasm_with_double_precision_rotation_angle(self): """Test that qasm() emits high precision rotation angles per default.""" from qiskit.circuit.tools.pi_check import MAX_FRAC qc = QuantumCircuit(1) qc.p(0.123456789, 0) qc.p(pi * pi, 0) qc.p(MAX_FRAC * pi + 1, 0) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; p(0.123456789) q[0]; p(9.869604401089358) q[0]; p(51.26548245743669) q[0];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_rotation_angles_close_to_pi(self): """Test that qasm() properly rounds values closer than 1e-12 to pi.""" qc = QuantumCircuit(1) qc.p(pi + 1e-11, 0) qc.p(pi + 1e-12, 0) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; p(3.141592653599793) q[0]; p(pi) q[0];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_raises_on_single_bit_condition(self): """OpenQASM 2 can't represent single-bit conditions, so test that a suitable error is printed if this is attempted.""" qc = QuantumCircuit(1, 1) qc.x(0).c_if(0, True) with self.assertRaisesRegex(QasmError, "OpenQASM 2 can only condition on registers"): qc.qasm() def test_circuit_raises_invalid_custom_gate_no_qubits(self): """OpenQASM 2 exporter of custom gates with no qubits. See: https://github.com/Qiskit/qiskit-terra/issues/10435""" legit_circuit = QuantumCircuit(5, name="legit_circuit") empty_circuit = QuantumCircuit(name="empty_circuit") legit_circuit.append(empty_circuit) with self.assertRaisesRegex(QasmError, "acts on zero qubits"): legit_circuit.qasm() def test_circuit_raises_invalid_custom_gate_clbits(self): """OpenQASM 2 exporter of custom instruction. See: https://github.com/Qiskit/qiskit-terra/issues/7351""" instruction = QuantumCircuit(2, 2, name="inst") instruction.cx(0, 1) instruction.measure([0, 1], [0, 1]) custom_instruction = instruction.to_instruction() qc = QuantumCircuit(2, 2) qc.append(custom_instruction, [0, 1], [0, 1]) with self.assertRaisesRegex(QasmError, "acts on 2 classical bits"): qc.qasm() def test_circuit_qasm_with_permutations(self): """Test circuit qasm() method with Permutation gates.""" qc = QuantumCircuit(4) qc.append(PermutationGate([2, 1, 0]), [0, 1, 2]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate permutation__2_1_0_ q0,q1,q2 { swap q0,q2; } qreg q[4]; permutation__2_1_0_ q[0],q[1],q[2];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_multiple_permutation(self): """Test that multiple PermutationGates can be added to a circuit.""" custom = QuantumCircuit(3, name="custom") custom.append(PermutationGate([2, 1, 0]), [0, 1, 2]) custom.append(PermutationGate([0, 1, 2]), [0, 1, 2]) qc = QuantumCircuit(4) qc.append(PermutationGate([2, 1, 0]), [0, 1, 2], []) qc.append(PermutationGate([1, 2, 0]), [0, 1, 2], []) qc.append(custom.to_gate(), [1, 3, 2], []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate permutation__2_1_0_ q0,q1,q2 { swap q0,q2; } gate permutation__1_2_0_ q0,q1,q2 { swap q1,q2; swap q0,q2; } gate permutation__0_1_2_ q0,q1,q2 { } gate custom q0,q1,q2 { permutation__2_1_0_ q0,q1,q2; permutation__0_1_2_ q0,q1,q2; } qreg q[4]; permutation__2_1_0_ q[0],q[1],q[2]; permutation__1_2_0_ q[0],q[1],q[2]; custom q[1],q[3],q[2]; """ self.assertEqual(qasm, expected) def test_circuit_qasm_with_reset(self): """Test circuit qasm() method with Reset.""" qc = QuantumCircuit(2) qc.reset([0, 1]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; reset q[0]; reset q[1];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_nested_gate_naming_clashes(self): """Test that gates that have naming clashes but only appear in the body of another gate still get exported correctly.""" # pylint: disable=missing-class-docstring class Inner(Gate): def __init__(self, param): super().__init__("inner", 1, [param]) def _define(self): self._definition = QuantumCircuit(1) self._definition.rx(self.params[0], 0) class Outer(Gate): def __init__(self, param): super().__init__("outer", 1, [param]) def _define(self): self._definition = QuantumCircuit(1) self._definition.append(Inner(self.params[0]), [0], []) qc = QuantumCircuit(1) qc.append(Outer(1.0), [0], []) qc.append(Outer(2.0), [0], []) qasm = qc.qasm() expected = re.compile( r"""OPENQASM 2\.0; include "qelib1\.inc"; gate inner\(param0\) q0 { rx\(1\.0\) q0; } gate outer\(param0\) q0 { inner\(1\.0\) q0; } gate (?P<inner1>inner_[0-9]*)\(param0\) q0 { rx\(2\.0\) q0; } gate (?P<outer1>outer_[0-9]*)\(param0\) q0 { (?P=inner1)\(2\.0\) q0; } qreg q\[1\]; outer\(1\.0\) q\[0\]; (?P=outer1)\(2\.0\) q\[0\]; """, re.MULTILINE, ) self.assertRegex(qasm, expected) def test_opaque_output(self): """Test that gates with no definition are exported as `opaque`.""" custom = QuantumCircuit(1, name="custom") custom.append(Gate("my_c", 1, []), [0]) qc = QuantumCircuit(2) qc.append(Gate("my_a", 1, []), [0]) qc.append(Gate("my_a", 1, []), [1]) qc.append(Gate("my_b", 2, [1.0]), [1, 0]) qc.append(custom.to_gate(), [0], []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; opaque my_a q0; opaque my_b(param0) q0,q1; opaque my_c q0; gate custom q0 { my_c q0; } qreg q[2]; my_a q[0]; my_a q[1]; my_b(1.0) q[1],q[0]; custom q[0]; """ self.assertEqual(qasm, expected) def test_sequencial_inner_gates_with_same_name(self): """Test if inner gates sequentially added with the same name result in the correct qasm""" qubits_range = range(3) gate_a = QuantumCircuit(3, name="a") gate_a.h(qubits_range) gate_a = gate_a.to_instruction() gate_b = QuantumCircuit(3, name="a") gate_b.append(gate_a, qubits_range) gate_b.x(qubits_range) gate_b = gate_b.to_instruction() qc = QuantumCircuit(3) qc.append(gate_b, qubits_range) qc.z(qubits_range) gate_a_id = id(qc.data[0].operation) expected_output = f"""OPENQASM 2.0; include "qelib1.inc"; gate a q0,q1,q2 {{ h q0; h q1; h q2; }} gate a_{gate_a_id} q0,q1,q2 {{ a q0,q1,q2; x q0; x q1; x q2; }} qreg q[3]; a_{gate_a_id} q[0],q[1],q[2]; z q[0]; z q[1]; z q[2]; """ self.assertEqual(qc.qasm(), expected_output) def test_empty_barrier(self): """Test that a blank barrier statement in _Qiskit_ acts over all qubits, while an explicitly no-op barrier (assuming Qiskit continues to allow this) is not output to OQ2 at all, since the statement requires an argument in the spec.""" qc = QuantumCircuit(QuantumRegister(2, "qr1"), QuantumRegister(3, "qr2")) qc.barrier() # In Qiskit land, this affects _all_ qubits. qc.barrier([]) # This explicitly affects _no_ qubits (so is totally meaningless). expected = """\ OPENQASM 2.0; include "qelib1.inc"; qreg qr1[2]; qreg qr2[3]; barrier qr1[0],qr1[1],qr2[0],qr2[1],qr2[2]; """ self.assertEqual(qc.qasm(), expected) def test_small_angle_valid(self): """Test that small angles do not get converted to invalid OQ2 floating-point values.""" # OQ2 _technically_ requires a decimal point in all floating-point values, even ones that # are followed by an exponent. qc = QuantumCircuit(1) qc.rx(0.000001, 0) expected = """\ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; rx(1.e-06) q[0]; """ self.assertEqual(qc.qasm(), expected) if __name__ == "__main__": unittest.main()
https://github.com/abbarreto/qiskit4
abbarreto
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import * from qiskit.visualization import plot_histogram # quantum circuit to make a Bell state bell = QuantumCircuit(2, 2) bell.h(0) bell.cx(0, 1) meas = QuantumCircuit(2, 2) meas.measure([0,1], [0,1]) # execute the quantum circuit backend = BasicAer.get_backend('qasm_simulator') # the device to run on circ = bell.compose(meas) result = backend.run(transpile(circ, backend), shots=1000).result() counts = result.get_counts(circ) print(counts) plot_histogram(counts) # Execute 2-qubit Bell state again second_result = backend.run(transpile(circ, backend), shots=1000).result() second_counts = second_result.get_counts(circ) # Plot results with legend legend = ['First execution', 'Second execution'] plot_histogram([counts, second_counts], legend=legend) plot_histogram([counts, second_counts], legend=legend, sort='desc', figsize=(15,12), color=['orange', 'black'], bar_labels=False) from qiskit.visualization import plot_state_city, plot_bloch_multivector from qiskit.visualization import plot_state_paulivec, plot_state_hinton from qiskit.visualization import plot_state_qsphere # execute the quantum circuit backend = BasicAer.get_backend('statevector_simulator') # the device to run on result = backend.run(transpile(bell, backend)).result() psi = result.get_statevector(bell) plot_state_city(psi) plot_state_hinton(psi) plot_state_qsphere(psi) plot_state_paulivec(psi) plot_bloch_multivector(psi) plot_state_city(psi, title="My City", color=['black', 'orange']) plot_state_hinton(psi, title="My Hinton") plot_state_paulivec(psi, title="My Paulivec", color=['purple', 'orange', 'green']) plot_bloch_multivector(psi, title="My Bloch Spheres") from qiskit.visualization import plot_bloch_vector plot_bloch_vector([0,1,0]) plot_bloch_vector([0,1,0], title='My Bloch Sphere') import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeManilaV2 from qiskit import transpile from qiskit.tools.visualization import plot_histogram # Get a fake backend from the fake provider backend = FakeManilaV2() # Create a simple circuit circuit = QuantumCircuit(3) circuit.h(0) circuit.cx(0,1) circuit.cx(0,2) circuit.measure_all() circuit.draw('mpl') # Transpile the ideal circuit to a circuit that can be directly executed by the backend transpiled_circuit = transpile(circuit, backend) transpiled_circuit.draw('mpl') # Run the transpiled circuit using the simulated fake backend job = backend.run(transpiled_circuit) counts = job.result().get_counts() plot_histogram(counts)
https://github.com/nickk124/quantumsearch
nickk124
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jun 27 12:07:22 2020 @author: ericyelton """ #Imports import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit,execute, Aer # gates/operators from qiskit.quantum_info.operators import Operator from qiskit.quantum_info import random_unitary #visualization from qiskit.visualization import plot_histogram import matplotlib.pyplot as plt import matplotlib.patches as patch from matplotlib.path import Path from matplotlib.animation import FuncAnimation #in this algorithm we have a dimension of n for the state space #then we have log2(n) states in the coin space #defining the dimensions of the quantum circuit class QRWreg: """ QRWreg initializes a Quantum Random Walk registry it inputs the variable dim which is the number of qubits in the state space """ #dim is the number of qubits #c is the number of coin qubits def __init__(self,dim): c = (np.log2(dim)) if c.is_integer() != 1: raise TypeError("The number of qubits n must have log2(n) be an integer") self.c = int(c) self.dim = dim n = int(dim+c) #the total number of qubits used will be given by self.n = n qr = QuantumRegister(n,'q') cl = ClassicalRegister(n,"c") self.qr = qr self.cl = cl circ = QuantumCircuit(qr, cl) self.circuit = circ #defining the QRW search algorithm as a subclass of the QRW registry class QRWsearch(QRWreg): """ QRWsearch is an implimentation of the quantum random walk search algorithm based on the paper titled "Quantum random-walk search algorithm" from N. Shenvi et al this class ineherits the QRWreg class dim - number of qubits in the state space state_search - the state that the algorithm searches for """ def __init__(self,dim,state_search): QRWreg.__init__(self,dim) self.circuit = QRWreg(dim).circuit quan_reg = QRWreg(dim).qr clas_reg = QRWreg(dim).cl self.search = state_search circ = self.circuit #hadamards on all of the states circ.h(quan_reg[0:self.n]) #operating U prime pi/2 sqrt(2) times times = np.ceil(0.5*np.pi*np.sqrt(2**(self.dim))) for i in range(int(times)): circ.unitary(self.Uprime(),quan_reg,label="U'") #measure the registry onto the classical bits circ.measure(quan_reg,clas_reg) #defining all of the operators for the QRW search def S(self, display_matrix=False): coin = self.c num_dir = int(2 ** coin) state = self.dim S = np.zeros((2**(coin+state),2**(coin+state))) for i in range(num_dir): for j in range(2**state): #performing the bit flip using an XOR j_bin = int(j) e_i = int(i+1) xor = j_bin ^ e_i row = xor+(i*(2**state)) S[row][j+(i*(2**state))] =1 if display_matrix: print('Matrix for the shift operator:') print(S) return Operator(S) def C(self, display_matrix=False): #definition of the C operator is an outer product in the coin space #tensor product with the identity in state spac coin = self.c num_dir = int(2 ** coin) state = self.dim num_state = int(2**state) #defining the operator in just the coin space s_c = np.zeros((2**(coin),2**(coin))) I_c = np.zeros((2**(coin),2**(coin))) for i in range(num_dir): I_c[i][i] = 1 for j in range(num_dir): s_c[i][j] =num_dir**-1 s_c = 2*s_c s_c = Operator(s_c) I_c = Operator(I_c) G = s_c-I_c #defining the identity in the state space I_s = np.zeros((2**(state),2**(state))) for i in range(num_state): I_s[i][i] = 1 I = Operator(I_s) C = G.tensor(I) if display_matrix: print('Matrix for the quantum coin operator:') print(np.real(C.data)) return C def U(self, display_matrix=False): S_= self.S() C_ = self.C() U = C_.compose(S_) if display_matrix: print('Matrix for U:') print(np.real(U.data)) return U def Uprime(self, display_matrix=False): #state_search is the state we are searching for #we will focus on the second term #Note that state search must be in decimal if self.search >= 2**self.dim: raise TypeError("Search State parameter is outside of state space values") elif self.search < 0: raise TypeError("Search State parameter is outside of state space values") else: #focusings on the second term of Uprime coin = self.c num_dir = int(2**coin) state = self.dim num_state = int(2**state) search_array = np.zeros((num_state,num_state)) search_array[self.search][self.search] = 1 search = Operator(search_array) s_c = np.zeros((2**(coin),2**(coin))) for i in range(num_dir): for j in range(num_dir): s_c[i][j] = num_dir**-1 coin_ = Operator(s_c) search_op = coin_.tensor(search) S_ = self.S() term2 = search_op.compose(S_) U_ = self.U() Uprime = U_-(2*term2) if display_matrix: print("Matrix for U':") print(np.real(Uprime.data)) return Uprime #Visualization def draw_circuit(self): return self.circuit.draw(output='mpl') def plot_states_hist(self): # plots by actually measuring the circuit #self.circuit.measure_all() backend = Aer.get_backend('qasm_simulator') shots = 1024 # number of times circuit is run, for sampling results = execute(self.circuit, backend=backend, shots=shots).result() answer = results.get_counts() return plot_histogram(answer, figsize=(5,5)) #defining the QRW algorithm as a subclass of the QRW registry class QRW(QRWreg): """ The QRW Class is an arbitrary implementation of a QRW dim - number of qubits in the state space c_label = is a string that determines what coin operator to use on the coin space - Hadamard = Hadamard operator tensor product with the Identity -Random = Is a random unitary operator step - is the number of 'steps' the QRW completes it is the number of times the operator U is called """ def __init__(self,dim,c_label,step): QRWreg.__init__(self,dim) self.circuit = QRWreg(dim).circuit quan_reg = QRWreg(dim).qr clas_reg = QRWreg(dim).cl circ = self.circuit #hadamards on all of the states circ.h(quan_reg[0:self.n]) for i in range(int(step)): circ.unitary(self.U(c_label),quan_reg,label="Step") #measure the registry onto the classical bits circ.measure(quan_reg,clas_reg) #defining all of the operators for the QRW search def S(self): coin = self.c num_dir = int(2 ** coin) state = self.dim S = np.zeros((2**(coin+state),2**(coin+state))) for i in range(num_dir): for j in range(2**state): #performing the bit flip using an XOR j_bin = int(j) e_i = int(i+1) xor = j_bin ^ e_i row = xor+(i*(2**state)) S[row][j+(i*(2**state))] =1 return Operator(S) def C(self,c_label): coin = self.c state = self.dim #creating the identity in the S space I = np.zeros((2**state,2**state)) for i in range(2**state): I[i][i] = 1 I = Operator(I) if c_label == "Hadamard": result= np.zeros((2**coin,2**coin)) for i in range(2**coin): for j in range(2**coin): #bin_i = bin(i) #bin_j = bin(j) if i >= 2 and j >= 2: result[i][j] = -1*(-1)**(i * j)*(2**(-1*(0.5*coin))) else: result[i][j] = (-1)**(i * j)*(2**(-1*(0.5*coin))) res_op = (Operator(result)) C_final = res_op.tensor(I) return C_final elif c_label == "Random": dim = [] for i in range(coin): dim.append(2) res_op = random_unitary(tuple(dim)) C_final = res_op.tensor(I) return C_final else: raise TypeError("Label string for C is not a valid input") def U(self,c_label): S_= self.S() C_ = self.C(c_label) U = C_.compose(S_) return U #Visualization def draw_circuit(self): return self.circuit.draw() def plot_states_hist(self): # plots by actually measuring the circuit backend = Aer.get_backend('qasm_simulator') print(backend) shots = 1024 # number of times circuit is run, for sampling results = execute(self.circuit, backend=backend, shots=shots).result() print(results.get_counts()) answer = results.get_counts() return plot_histogram(answer, figsize=(15,5)) #controlling the circuit def execute(self): backend = Aer.get_backend('qasm_simulator') results = execute(self.circuit, backend=backend,shots = 1).result() answer = results.get_counts() #one execution means there will be one state in the answer dict state = list(answer.keys()) return state[0] #animating the 2D 'mapping' for the QRW it inherits the QRW class class QRW_Automata(QRW): """ QRW_Automata is a class that inherits the QRW class it animates multiple executions of the QRW algorithm into a cellular automata board Note this algorithm has only been defined for the cases of 2 and 4 state qubits! dim - number of qubits in the state space c_label = is a string that determines what coin operator to use on the coin space - Hadamard = Hadamard operator tensor product with the Identity -Random = Is a random unitary operator step - is the number of 'steps' the QRW completes it is the number of times the operator U is called iters - number of times the circuit is executed (also determines the number of frames in the animation) """ def __init__(self,dim,c_label,step,iters): QRW.__init__(self,dim,c_label,step) self.n = QRW(dim,c_label,step).n self.c = QRW(dim,c_label,step).c self.circ = QRW(dim,c_label,step).circuit state = [] for i in range(iters): state.append(QRW(dim,c_label,step).execute()) self.state = state print("state") print(state) c_state = [] s_state = [] for i in state: c_state.append(i[0:self.c]) s_state.append(i[self.c:]) self.c_state = c_state self.s_state = s_state if (dim/2).is_integer() != True: raise ValueError("The one-half of the number of qubits in the state space must be an integer") #dividing up the board according to number of bits #n is the number of rows and columns #we are just doing the case for n = 4 if int(self.dim) !=4 and int(self.dim) !=2: raise ValueError("Grid is implemented for only for the cases where n=2 and n=4 in the state space") figure,axes = plt.subplots(nrows = 2,ncols = 1) plt.title("QRW Automata {step}".format(step=c_label)) axes[0].set_facecolor((0,0,0)) axes[0].get_xaxis().set_ticks([]) axes[0].get_yaxis().set_ticks([]) axes[1].get_xaxis().set_ticks([]) axes[1].get_yaxis().set_ticks([]) self.fig = figure self.ax = axes self.circuit.draw('mpl',scale = 0.9,ax=axes[1]) n_v = (2*self.dim) if self.c % 2 !=0: n_h = self.dim else: n_h = n_v v_lines = np.arange(0,1,1/n_v) h_lines = np.arange(0,1,1/n_h) #drawing the frames for the board for i in v_lines: axes[0].axvline(x=i,ymin=0,ymax=1,color='r') for i in h_lines: axes[0].axhline(y=i,xmin=0,xmax=1,color='r') anim = FuncAnimation(self.fig,self.animate, frames =int(len(state)), interval = 200) anim.save("QRW_{n}qubits_{op}_{st}steps.mp4".format(n = self.dim,op = c_label,st = step),) def animate(self,i): #ploting the state space : if self.dim ==2: c_ = self.c_state[i] s_ = self.s_state[i] n_v = (2*self.dim) n_h = self.dim verts = [ (0.+int(s_[-1])*(1/n_v)+0.5*int(c_), 1.-int(s_[0])*(1/n_h)-(1/n_h)), # left, bottom (0.+int(s_[-1])*(1/n_v)+0.5*int(c_), 1.-int(s_[0])*(1/n_h)), # left, top ((1/n_v)+int(s_[-1])*(1/n_v)+0.5*int(c_), 1.-int(s_[0])*(1/n_h)), # right, top ((1/n_v)+int(s_[-1])*(1/n_v)+0.5*int(c_), 1.-int(s_[0])*(1/n_h)-(1/n_h)), # right, bottom (0.+int(s_[-1])*(1/n_v)+0.5*int(c_), 1.-int(s_[0])*(1/n_h)-(1/n_h)), # ignored ] codes = [ Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY, ] path = Path(verts,codes) cell = patch.PathPatch(path,facecolor = 'w') self.ax[0].set_xlabel("Measured state:{state_}".format(state_=self.state[i])) self.ax[0].add_patch(cell) return patch elif self.dim ==4: c_ = self.c_state[i] s_ = self.s_state[i] n_v = (2*self.dim) n_h = (2*self.dim) verts = [ (0.+int(s_[-1])*(1/n_v)+int(s_[-2])*(2/n_v)+0.5*int(c_[1]), 1.-int(s_[0])*2*(1/n_h)-int(s_[1])*(1/n_h)-(1/n_h)-0.5*int(c_[0])), # left, bottom (0.+int(s_[-1])*(1/n_v)+int(s_[-2])*(2/n_v)+0.5*int(c_[1]), 1.-int(s_[0])*2*(1/n_h)-int(s_[1])*(1/n_h)-0.5*int(c_[0])), # left, top ((1/n_v)+int(s_[-1])*(1/n_v)+int(s_[-2])*(2/n_v)+0.5*int(c_[1]), 1.-int(s_[0])*2*(1/n_h)-int(s_[1])*(1/n_h)-0.5*int(c_[0])), # right, top ((1/n_v)+int(s_[-1])*(1/n_v)+int(s_[-2])*(2/n_v)+0.5*int(c_[1]), 1.-int(s_[0])*2*(1/n_h)-int(s_[1])*(1/n_h)-(1/n_h)-0.5*int(c_[0])), # right, bottom (0.+int(s_[-1])*(1/n_v)+int(s_[-2])*(2/n_v)+0.5*int(c_[1]), 1.-int(s_[0])*2*(1/n_h)-int(s_[1])*(1/n_h)-(1/n_h)-0.5*int(c_[0])), # ignored ] codes = [ Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY, ] path = Path(verts,codes) cell = patch.PathPatch(path,facecolor = 'w') self.ax[0].set_xlabel("Measured state:{state_}".format(state_=self.state[i])) self.ax[0].add_patch(cell) return patch if __name__=='main': QRW_Automata(4,"Hadamard",4,15)
https://github.com/qiskit-community/prototype-zne
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2022-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. from test import NO_INTS, NO_REAL, TYPES from unittest.mock import Mock, patch from numpy.random import Generator, default_rng from pytest import fixture, mark, raises, warns from qiskit import QuantumCircuit from zne.noise_amplification.folding_amplifier.global_folding_amplifier import ( GlobalFoldingAmplifier, ) from zne.noise_amplification.folding_amplifier.local_folding_amplifier import ( LocalFoldingAmplifier, ) MOCK_TARGET_PATH = "zne.noise_amplification.folding_amplifier.folding_amplifier.FoldingAmplifier" @fixture(scope="module") def patch_amplifier_with_multiple_mocks(): def factory_method(**kwargs): return patch.multiple(MOCK_TARGET_PATH, **kwargs) return factory_method @mark.parametrize( "NoiseAmplifier", (GlobalFoldingAmplifier, LocalFoldingAmplifier), ids=("GlobalFoldingAmplifier", "LocalFoldingAmplifier"), ) class TestFoldingAmplifier: @fixture(scope="function") def setter_mocks(self): mocks = { "_set_sub_folding_option": Mock(), "_set_barriers": Mock(), "_prepare_rng": Mock(), "_set_noise_factor_relative_tolerance": Mock(), } return mocks ################################################################################ ## INIT TESTS ################################################################################ def test_init_default_kwargs( self, NoiseAmplifier, patch_amplifier_with_multiple_mocks, setter_mocks ): with patch_amplifier_with_multiple_mocks(**setter_mocks): NoiseAmplifier() setter_mocks["_set_sub_folding_option"].assert_called_once_with("from_first") setter_mocks["_set_barriers"].assert_called_once_with(True) setter_mocks["_prepare_rng"].assert_called_once_with(None) setter_mocks["_set_noise_factor_relative_tolerance"].assert_called_once_with(1e-2) def test_init_custom_kwargs( self, NoiseAmplifier, patch_amplifier_with_multiple_mocks, setter_mocks ): with patch_amplifier_with_multiple_mocks(**setter_mocks): NoiseAmplifier( sub_folding_option="random", barriers=False, random_seed=1, noise_factor_relative_tolerance=1e-1, ) setter_mocks["_set_sub_folding_option"].assert_called_once_with("random") setter_mocks["_set_barriers"].assert_called_once_with(False) setter_mocks["_prepare_rng"].assert_called_once_with(1) setter_mocks["_set_noise_factor_relative_tolerance"].assert_called_once_with(1e-1) ################################################################################ ## PROPERTIES and SETTER TESTS ################################################################################ @mark.parametrize( "sub_folding_option", cases := ["from_last", "from_first", "random"], ids=[f"{c}" for c in cases], ) def test_set_sub_folding_option(self, NoiseAmplifier, sub_folding_option): noise_amplifier = NoiseAmplifier() noise_amplifier._set_sub_folding_option(sub_folding_option) assert noise_amplifier.sub_folding_option == sub_folding_option @mark.parametrize( "sub_folding_option", [(t,) for t in TYPES], ids=[str(type(i).__name__) for i in TYPES] ) def test_set_sub_folding_option_value_error(self, NoiseAmplifier, sub_folding_option): with raises(ValueError): NoiseAmplifier()._set_sub_folding_option(sub_folding_option) @mark.parametrize( "random_seed", cases := [1, 2], ids=[f"{c}" for c in cases], ) def test_prepare_rng(self, NoiseAmplifier, random_seed): noise_amplifier = NoiseAmplifier() noise_amplifier._prepare_rng(random_seed) assert isinstance(noise_amplifier._rng, Generator) rng = default_rng(random_seed) assert noise_amplifier._rng.bit_generator.state == rng.bit_generator.state @mark.parametrize( "random_seed", [(t,) for t in NO_INTS], ids=[str(type(i).__name__) for i in NO_INTS] ) def test_prepare_rng_type_error(self, NoiseAmplifier, random_seed): with raises(TypeError): NoiseAmplifier()._prepare_rng(random_seed) @mark.parametrize( "tolerance", cases := [0.1, 0.01], ids=[f"{c}" for c in cases], ) def test_set_noise_factor_relative_tolerance(self, NoiseAmplifier, tolerance): noise_amplifier = NoiseAmplifier() noise_amplifier._set_noise_factor_relative_tolerance(tolerance) assert noise_amplifier._noise_factor_relative_tolerance == tolerance @mark.parametrize( "tolerance", [(t,) for t in NO_REAL], ids=[str(type(i).__name__) for i in NO_REAL] ) def test_set_noise_factor_relative_tolerance_type_error(self, NoiseAmplifier, tolerance): with raises(TypeError): NoiseAmplifier()._set_noise_factor_relative_tolerance(tolerance) @mark.parametrize("warn_user", cases := [True, False], ids=[f"{c}" for c in cases]) def test_set_warn_user(self, NoiseAmplifier, warn_user): noise_amplifier = NoiseAmplifier() noise_amplifier.warn_user = warn_user assert noise_amplifier.warn_user == warn_user @mark.parametrize( "warn_user", cases := [t for t in TYPES if not isinstance(t, bool)], ids=[str(type(c).__name__) for c in cases], ) def test_set_warn_user_type_error(self, NoiseAmplifier, warn_user): noise_amplifier = NoiseAmplifier() with raises(TypeError): noise_amplifier.warn_user = warn_user @mark.parametrize( "barriers", cases := [True, False, 1, 0, "", "|"], ids=[f"{c}" for c in cases] ) def test_set_barriers(self, NoiseAmplifier, barriers): noise_amplifier = NoiseAmplifier() noise_amplifier._set_barriers(barriers) assert noise_amplifier.barriers is bool(barriers) ################################################################################ ## TESTS ################################################################################ @mark.parametrize( "noise_factor", cases := [1, 1.2, 2, 3.5], ids=[f"{c}" for c in cases], ) def test_validate_noise_factor(self, NoiseAmplifier, noise_factor): NoiseAmplifier()._validate_noise_factor(noise_factor) @mark.parametrize( "noise_factor", cases := [0, 0.5, -1, -2.5], ids=[f"{c}" for c in cases], ) def test_validate_noise_factor_value_error(self, NoiseAmplifier, noise_factor): with raises(ValueError): NoiseAmplifier()._validate_noise_factor(noise_factor) @mark.parametrize( "folding, expected", cases := tuple( zip( [0, 1, 2], [1, 3, 5], ) ), ids=[f"{f}-{e}" for f, e in cases], ) def test_folding_to_noise_factor(self, NoiseAmplifier, folding, expected): assert NoiseAmplifier().folding_to_noise_factor(folding) == expected def test_warn_user_true(self, NoiseAmplifier): with warns(UserWarning): NoiseAmplifier().warn("warning") def test_warn_user_false(self, NoiseAmplifier): NoiseAmplifier(warn_user=False).warn("no warning") @mark.parametrize( "num_instructions, noise_factor, expected", cases := [ (9, 1.2, (0, 1)), (9, 2, (0, 4)), (9, 3.6, (1, 3)), (9, 4, (1, 5)), (9, 17 / 3.0, (2, 3)), (9, 100, (49, 5)), (17, 1.2, (0, 2)), (17, 2, (0, 8)), (17, 3.6, (1, 5)), (17, 4, (1, 9)), (17, 100, (49, 9)), ], ids=[f"{ni}-{nf}-{cd}" for ni, nf, cd in cases], ) @mark.filterwarnings("ignore::UserWarning") def test_compute_folding_nums(self, NoiseAmplifier, num_instructions, noise_factor, expected): assert NoiseAmplifier()._compute_folding_nums(noise_factor, num_instructions) == expected @mark.parametrize( "noise_factor", cases := [1.5, 3.05], ids=[f"{c}" for c in cases], ) def test_compute_folding_nums_warning(self, NoiseAmplifier, noise_factor): with warns(UserWarning): assert NoiseAmplifier()._compute_folding_nums(noise_factor, 3) def test_compute_folding_no_foldings(self, NoiseAmplifier): with warns(UserWarning): assert NoiseAmplifier()._compute_folding_nums(3, 0) == (0, 0) @mark.parametrize("registers", [(), (0,), (1,), (0, 1)]) def test_apply_barrier_true(self, NoiseAmplifier, registers): circuit = QuantumCircuit(2) original = circuit.copy() noise_amplifier = NoiseAmplifier(barriers=True) circuit = noise_amplifier._apply_barrier(circuit, *registers) last_instruction = circuit.data.pop() assert last_instruction.operation.name == "barrier" registers = [circuit.qubits[r] for r in registers] or circuit.qubits assert last_instruction.qubits == tuple(registers) assert circuit == original @mark.parametrize("registers", [(), (0,), (1,), (0, 1)]) def test_apply_barrier_false(self, NoiseAmplifier, registers): circuit = QuantumCircuit(2) original = circuit.copy() noise_amplifier = NoiseAmplifier(barriers=False) circuit = noise_amplifier._apply_barrier(circuit, *registers) assert circuit == original
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.circuit.library import UCCSD ansatz = UCCSD() ansatz.num_spin_orbitals = 10 from qiskit_nature.second_q.circuit.library import UCCSD ansatz = UCCSD() ansatz.num_spatial_orbitals = 5 from qiskit_nature.circuit.library import UCC, UVCC ucc = UCC(qubit_converter=None, num_particles=None, num_spin_orbitals=None, excitations=None) uvcc = UVCC(qubit_converter=None, num_modals=None, excitations=None) from qiskit_nature.second_q.circuit.library import UCC, UVCC ucc = UCC(num_spatial_orbitals=None, num_particles=None, excitations=None, qubit_converter=None) uvcc = UVCC(num_modals=None, excitations=None, qubit_converter=None) from qiskit_nature.circuit.library import HartreeFock, VSCF from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import DirectMapper, JordanWignerMapper hf = HartreeFock( num_spin_orbitals=4, num_particles=(1, 1), qubit_converter=QubitConverter(JordanWignerMapper()) ) vscf = VSCF(num_modals=[2, 2]) from qiskit_nature.second_q.circuit.library import HartreeFock, VSCF from qiskit_nature.second_q.mappers import DirectMapper, JordanWignerMapper, QubitConverter hf = HartreeFock() hf.num_spatial_orbitals = 2 hf.num_particles = (1, 1) hf.qubit_converter = QubitConverter(JordanWignerMapper()) vscf = VSCF() vscf.num_modals = [2, 2] from qiskit.providers.basicaer import BasicAer from qiskit.utils import QuantumInstance from qiskit_nature.algorithms.ground_state_solvers import VQEUCCFactory quantum_instance = QuantumInstance(BasicAer.get_backend("statevector_simulator")) vqe_factory = VQEUCCFactory(quantum_instance=quantum_instance) from qiskit.algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit_nature.second_q.circuit.library import UCCSD from qiskit_nature.second_q.algorithms.ground_state_solvers import VQEUCCFactory estimator = Estimator() ansatz = UCCSD() optimizer = SLSQP() vqe_factory = VQEUCCFactory(estimator, ansatz, optimizer) from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver, VQEUCCFactory from qiskit_nature.algorithms.excited_states_solvers import QEOM from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import JordanWignerMapper vqe_factory = VQEUCCFactory() converter = QubitConverter(JordanWignerMapper()) ground_state_solver = GroundStateEigensolver(converter, vqe_factory) qeom = QEOM(ground_state_solver) from qiskit.algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit_nature.second_q.circuit.library import UCCSD from qiskit_nature.second_q.algorithms.ground_state_solvers import ( GroundStateEigensolver, VQEUCCFactory, ) from qiskit_nature.second_q.algorithms.excited_states_solvers import QEOM from qiskit_nature.second_q.mappers import JordanWignerMapper, QubitConverter estimator = Estimator() ansatz = UCCSD() optimizer = SLSQP() vqe_factory = VQEUCCFactory(estimator, ansatz, optimizer) converter = QubitConverter(JordanWignerMapper()) ground_state_solver = GroundStateEigensolver(converter, vqe_factory) qeom = QEOM(ground_state_solver, estimator) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/martynscn/Masters-Thesis-on-Quantum-Cryptography
martynscn
# This code has been adapted and modified from IBM Qiskit 2021 and also from https://github.com/ttlion/ShorAlgQiskit. # It uses the implementation as contained in the work of Stephane Beauregard (https://arxiv.org/abs/quant-ph/0205095) # Many thanks to IBM Qiskit team, Tiago Miguel (ttlion), Qubit by Qubit, Peter Shor and Stephane Beauregard. from typing import Optional, Union, Tuple, List import math import array import fractions import logging import numpy as np from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, execute, IBMQ, transpile,BasicAer, Aer, assemble from qiskit.circuit import Gate, Instruction, ParameterVector from qiskit.circuit.library import QFT from qiskit.providers import BaseBackend, Backend from qiskit.quantum_info import partial_trace from qiskit.utils import summarize_circuits from qiskit.utils.arithmetic import is_power from qiskit.utils.validation import validate_min from qiskit.utils.quantum_instance import QuantumInstance import qiskit.visualization from qiskit.providers.aer import QasmSimulator from datetime import datetime import csv # provider = IBMQ.enable_account("PUT TOKEN HERE") backend = QasmSimulator() from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" #"last_expr" or "all" def get_angles(a: int, n) -> np.ndarray: # """Calculates the array of angles to be used in the addition in Fourier Space.""" s = bin(int(a))[2:].zfill(n + 1) angles = np.zeros([n + 1]) for i in range(0, n + 1): for j in range(i, n + 1): if s[j] == '1': angles[n - i] += math.pow(2, -(j - i)) angles[n - i] *= np.pi return angles[::-1] # This returns the angles in the opposite order def my_create_QFT(qft_num_qubits,approximation_degree: int = 0,do_swaps: bool = False,insert_barriers: bool = True, name: str = 'qft'): # up_reg = QuantumRegister(size = qft_num_qubits, name="aux") circuit_qft = QuantumCircuit(qft_num_qubits) i=qft_num_qubits-1 while i>=0: # circuit_qft.h(up_reg[i]) circuit_qft.h(i) j=i-1 while j>=0: if (np.pi)/(pow(2,(i-j))) > approximation_degree: # circuit_qft.cu1( (np.pi)/(pow(2,(i-j))) , up_reg[i] , up_reg[j] ) circuit_qft.cu1( (np.pi)/(pow(2,(i-j))) , i , j ) j=j-1 if insert_barriers: circuit_qft.barrier() i=i-1 """ If specified, apply the Swaps at the end """ if do_swaps: i=0 while i < ((qft_num_qubits-1)/2): # circuit_qft.swap(up_reg[i], up_reg[qft_num_qubits-1-i]) circuit_qft.swap(i, qft_num_qubits-1-i) i=i+1 circuit_qft.name = "QFT" return circuit_qft def my_create_inverse_QFT(qft_num_qubits,approximation_degree: int = 0,do_swaps: bool = False,insert_barriers: bool = True, name: str = 'iqft'): my_create_QFT_circuit = my_create_QFT(qft_num_qubits,approximation_degree,do_swaps,insert_barriers, name) my_create_inverse_QFT_circuit = my_create_QFT_circuit.inverse() my_create_inverse_QFT_circuit.name = "QFT†" return my_create_inverse_QFT_circuit def phi_add_gate(size: int, angles: Union[np.ndarray, ParameterVector]) -> Gate: # """Gate that performs addition by a in Fourier Space.""" circuit = QuantumCircuit(size, name="phi_add") for i, angle in enumerate(angles): circuit.p(angle, i) return circuit.to_gate() def double_controlled_phi_add_mod_N(num_qubits: int, angles: Union[np.ndarray, ParameterVector],reg_size, a, N, n) -> QuantumCircuit: # """Creates a circuit which implements double-controlled modular addition by a.""" circuit = QuantumCircuit(num_qubits, name="ccphi_add_mod_N") ctl_up = 0 ctl_down = 1 ctl_aux = 2 # get qubits from aux register, omitting the control qubit qubits = range(3, num_qubits) # store the gates representing addition/subtraction by a in Fourier Space phi_add_a = phi_add_gate(len(qubits), angles) iphi_add_a = phi_add_a.inverse() phi_add_N = phi_add_gate(reg_size - 1, get_angles(N, n)) iphi_add_N = phi_add_N.inverse() circuit.append(phi_add_a.control(2), [ctl_up, ctl_down, *qubits]) circuit.append(iphi_add_N, qubits) qft = QFT(n + 1).to_instruction() # qft = my_create_QFT(n + 1).to_instruction() iqft = QFT(n + 1).inverse().to_instruction() # iqft = my_create_inverse_QFT(n + 1).to_instruction() circuit.append(iqft, qubits) circuit.cx(qubits[0], ctl_aux) circuit.append(qft, qubits) circuit.append(phi_add_N, qubits) circuit.append(iphi_add_a.control(2), [ctl_up, ctl_down, *qubits]) circuit.append(iqft, qubits) circuit.x(qubits[0]) circuit.cx(qubits[0], ctl_aux) circuit.x(qubits[0]) circuit.append(qft, qubits) circuit.append(phi_add_a.control(2), [ctl_up, ctl_down, *qubits]) return circuit # """Circuit that implements single controlled modular multiplication by a""" def controlled_multiple_mod_N(num_qubits: int, N: int, a: int, n, aux_reg_size): # """Implements modular multiplication by a as an instruction.""" circuit = QuantumCircuit( num_qubits, # name="multiply_by_{}_mod_{}".format(a % N, N), name=r"${0}^{{{1}^{{{2}}}}} mod{3}$".format(2,2,int(math.log(math.log(a,2),2)), N) ) # label = r"${0}^{{{1}^{{{2}}}}} mod{3}$".format("†","y") down = circuit.qubits[1: n + 1] aux = circuit.qubits[n + 1:] qubits = [aux[i] for i in reversed(range(n + 1))] ctl_up = 0 ctl_aux = aux[-1] angle_params = ParameterVector("angles", length=len(aux) - 1) double_controlled_phi_add = double_controlled_phi_add_mod_N( len(aux) + 2, angle_params, aux_reg_size, a, N, n ) idouble_controlled_phi_add = double_controlled_phi_add.inverse() qft_circuit = QFT(n + 1).to_instruction() # qft_circuit = my_create_QFT(n + 1).to_instruction() iqft_circuit = QFT(n + 1).inverse().to_instruction() # iqft_circuit = my_create_inverse_QFT(n + 1).to_instruction() circuit.append(qft_circuit, qubits) # perform controlled addition by a on the aux register in Fourier space for i, ctl_down in enumerate(down): a_exp = (2 ** i) * a % N angles = get_angles(a_exp, n) bound = double_controlled_phi_add.assign_parameters({angle_params: angles}) circuit.append(bound, [ctl_up, ctl_down, ctl_aux, *qubits]) circuit.append(iqft_circuit, qubits) # perform controlled subtraction by a in Fourier space on both the aux and down register for j in range(n): circuit.cswap(ctl_up, down[j], aux[j]) circuit.append(qft_circuit, qubits) a_inv = modinv(a, N) for i in reversed(range(len(down))): a_exp = (2 ** i) * a_inv % N angles = get_angles(a_exp, n) bound = idouble_controlled_phi_add.assign_parameters({angle_params: angles}) circuit.append(bound, [ctl_up, down[i], ctl_aux, *qubits]) circuit.append(iqft_circuit, qubits) return circuit def modinv(a: int, m: int) -> int: # """Returns the modular multiplicative inverse of a with respect to the modulus m.""" def egcd(a: int, b: int) -> Tuple[int, int, int]: if a == 0: return b, 0, 1 else: g, y, x = egcd(b % a, a) return g, x - (b // a) * y, y g, x, _ = egcd(a, m) if g != 1: raise ValueError("The greatest common divisor of {} and {} is {}, so the " "modular inverse does not exist.".format(a, m, g)) return x % m def get_factors(N: int, a: int, measurement: str) -> Optional[List[int]]: # """Apply the continued fractions to find r and the gcd to find the desired factors.""" x_final = int(measurement, 2) #print('In decimal, x_final value for this result is: {}.'.format(x_final)) if x_final <= 0: fail_reason = 'x_final value is <= 0, there are no continued fractions.' else: fail_reason = None #print('Running continued fractions for this case.') # Calculate T and x/T T_upper = len(measurement) T = pow(2, T_upper) x_over_T = x_final / T ## this is our theta # Cycle in which each iteration corresponds to putting one more term in the # calculation of the Continued Fraction (CF) of x/T # Initialize the first values according to CF rule i = 0 b = array.array('i') t = array.array('f') b.append(math.floor(x_over_T)) t.append(x_over_T - b[i]) exponential = 0.0 while i < N and fail_reason is None: # From the 2nd iteration onwards, calculate the new terms of the CF based on the previous terms as the rule suggests if i > 0: try: b_temp = math.floor(1 / t[i - 1]) except ZeroDivisionError as err: b_temp = 0 b.append(b_temp) try: t_temp = (1 / t[i - 1]) - b[i] except ZeroDivisionError as err: t_temp = 0 t.append(t_temp) # type: ignore # Calculate the denominator of the CF using the known terms denominator = calculate_continued_fraction(b) # Increment i for next iteration i += 1 if denominator % 2 == 1: #print('Odd denominator, will try next iteration of continued fractions.') continue # Denominator is even, try to get factors of N. Get the exponential a^(r/2) if denominator < 1000: try: exponential = pow(a, denominator / 2) except OverflowError as err: exponential = 999999999 # Check if the value is too big or not if exponential > 1000000: if exponential == 999999999: fail_reason = 'OverflowError' else: fail_reason = 'denominator of continued fraction is too big (> 10^9).' else: # The value is not too big, get the right values and do the proper gcd() putting_plus = int(exponential + 1) putting_minus = int(exponential - 1) one_factor = math.gcd(putting_plus, N) other_factor = math.gcd(putting_minus, N) # Check if the factors found are trivial factors or are the desired factors if any(factor in {1, N} for factor in (one_factor, other_factor)): #print('Found just trivial factors, not good enough.') # Check if the number has already been found, (use i - 1 because i was already incremented) if t[i - 1] == 0: fail_reason = 'the continued fractions found exactly x_final/(2^(2n)).' else: return sorted((one_factor, other_factor)) # Search for factors failed, write the reason for failure to the debug logs #print('Cannot find factors from measurement {0} because {1}'.format(measurement, fail_reason or 'it took too many attempts.')) return None def calculate_continued_fraction(b: array.array) -> int: # """Calculate the continued fraction of x/T from the current terms of expansion b.""" x_over_T = 0 for i in reversed(range(len(b) - 1)): x_over_T = 1 / (b[i + 1] + x_over_T) x_over_T += b[0] frac = fractions.Fraction(x_over_T).limit_denominator() #print('Approximation number %s of continued fractions:'.format(len(b))) #print("Numerator:{0} \t\t Denominator: {1}.".format(frac.numerator, frac.denominator)) return frac.denominator def process_results(sim_result, circuit, shots, N, a, n): counts_result = sim_result.get_counts(circuit) total_counts = len(counts_result) counts_result_sorted = sorted(counts_result.items(), key=lambda x: x[1], reverse=True) # """ Print info to user from the simulation results """ # print('Printing the various results followed by how many times they happened (out of the {} cases):\n'.format(shots)) counts_result_keys = list(counts_result.keys()) counts_result_values = list(counts_result.values()) #i=0 #while i < len(counts_result): #print('Result \"{0}\" happened {1} times out of {2}\n'.format(list(sim_result.get_counts().keys())[i],list(sim_result.get_counts().values())[i],shots)) #print('Result \"{0}\" happened {1} times out of {2}\n'.format(counts_result_keys[i],counts_result_values[i],shots)) #i=i+1 prob_success=0 prob_failure=0 result_successful_counts = 0 result_failure_counts = 0 # len(counts_result_sorted) # For each simulation result, print proper info to user and try to calculate the factors of N #for measurement in counts_result_keys: for measurement, frequency in counts_result_sorted: # Get the x_final value from the final state qubits x_value = int(measurement, 2) #prob_this_result = 100 * ( int(counts_result[measurement] ) ) / (shots) prob_this_result = 100 * frequency/shots # print("------> Analyzing result {0}. This result happened in {1:.4f} % of all cases\nIn decimal, x_final value for this result is: {2}".format(measurement,prob_this_result,x_value)) factors = get_factors(N, a, measurement) if factors: prob_success = prob_success + prob_this_result # print('Found factors {0} from measurement {1} which is {2} in decimal.\n'.format(factors, measurement, x_value)) result_successful_counts = result_successful_counts + 1 if factors not in result_factors: result_factors.append(factors) elif not factors: prob_failure = prob_failure + prob_this_result result_failure_counts = result_failure_counts + 1 return [result_factors, prob_success, prob_failure, total_counts, result_successful_counts,result_failure_counts] def my_shor(a,N,shots): start_time_number = datetime.now() start_time = start_time_number.strftime("%H:%M:%S") summary_result = dict() validate_min('N', N, 3) validate_min('a', a, 2) if N < 1 or N % 2 == 0: raise ValueError('The input needs to be an odd integer greater than 1.') if a >= N or math.gcd(a, N) != 1: raise ValueError('The integer a needs to satisfy a < N and gcd(a, N) = 1.') n = math.ceil(math.log(N,2)) global result_factors result_factors = [] tf, b, p = is_power(N, return_decomposition=True) if tf: print('The input integer is a power: {0}={1}^{2}.'.format(N, b, p)) result_factors.append(b) # """auxilliary quantum register used in addition and multiplication""" aux_reg = QuantumRegister(size = n+2, name="aux_reg") up_reg = QuantumRegister(2*n, name = "up_reg") # """quantum register where the multiplications are made""" down_reg = QuantumRegister(n, name = "down_reg") # """classical register where the measured values of the QFT are stored""" up_classic = ClassicalRegister(2*n, name="up_classic") # """ Create Quantum Circuit """ circuit = QuantumCircuit(up_reg ,down_reg ,aux_reg, up_classic, name="Shor circuit(N={}, a={})".format(N, a)) # phi_add_N_gate = phiADD(circuit,q,a,N,inv) phi_add_N_gate = phi_add_gate(aux_reg.size - 1, get_angles(N,n)) iphi_add_N_gate = phi_add_N_gate.inverse() # """ Initialize down register to 1 and create maximal superposition in top register """ circuit.h(up_reg) circuit.x(down_reg[0]) # circuit.draw(filename = "shor_standard_QFT") # """ Apply the multiplication gates as showed in the report in order to create the exponentiation """ for i, ctl_up in enumerate(up_reg): # type: ignore a_aux = int(pow(a, pow(2, i))) controlled_multiple_mod_N_circuit = controlled_multiple_mod_N( len(down_reg) + len(aux_reg) + 1, N, a_aux,n,aux_reg.size ) controlled_multiple_mod_N_result = controlled_multiple_mod_N_circuit.to_instruction() circuit.append( controlled_multiple_mod_N_result, [ctl_up, *down_reg, *aux_reg] ) # circuit.draw() iqft = QFT(len(up_reg)).inverse().to_instruction() # iqft = my_create_inverse_QFT(len(up_reg)).to_instruction() # iqft = my_create_inverse_QFT(len(up_reg), insert_barriers = False).to_gate(label = r"$QFT^{{{0}}}$".format("†")) circuit.append(iqft, up_reg) circuit.measure(up_reg, up_classic) # circuit.draw(filename = "shor_standard_QFT_final_circuit",fold = -1 ) # print(summarize_circuits(circuit)) # circuit.draw() print('Running with N={0} and a={1} with number of qubits n={2}'.format(N, a, 4*n + 2)) qc_compiled = transpile(circuit, backend, optimization_level = 3) job_sim_1 = backend.run(qc_compiled, shots=shots) sim_result=job_sim_1.result() # counts_result = sim_result.get_counts(circuit) # len(counts_result) # measurement_plot = qiskit.visualization.plot_histogram(counts_result,figsize=(20, 12) ,number_to_keep = 30,bar_labels=True, title = "Measurement results from shor_standard_QFT circuit variant" ) # measurement_plot.savefig("shor_standard_QFT_measurement") # measurement_plot processed_result = process_results(sim_result, circuit, shots, N, a, n) end_time_number = datetime.now() end_time = end_time_number.strftime("%H:%M:%S") duration = end_time_number - start_time_number print("Current Start Time =", start_time) print(processed_result) print("Current End Time =", end_time) circuit_count_ops = circuit.count_ops() circuit_decomposed = circuit.decompose() circuit_decomposed_count_ops = circuit_decomposed.count_ops() qc_compiled_count_ops = qc_compiled.count_ops() summary_result["num_qubits"] = n summary_result["Number(N)"] = N summary_result["a"] = a summary_result["start_time"] = start_time summary_result["end_time"] = end_time summary_result["duration"] = duration summary_result["result_factors"] = processed_result[0] summary_result["prob_success"] = processed_result[1] summary_result["prob_failure"] = processed_result[2] summary_result["total_counts"] = processed_result[3] summary_result["result_successful_counts"] = processed_result[4] summary_result["result_failure_counts"] = processed_result[5] summary_result["circuit_width"] = circuit.width() summary_result["circuit_depth"] = circuit.depth() summary_result["circuit_size"] = circuit.size() summary_result["circuit_num_nonlocal_gates"] = circuit.num_nonlocal_gates() summary_result["circuit_num_ancillas"] = circuit.num_ancillas summary_result["circuit_num_clbits"] = circuit.num_clbits summary_result["circuit_num_qubits"] = circuit.num_qubits summary_result["circuit_num_ancillas"] = circuit.num_ancillas summary_result["circuit_num_of_count_ops"] = len(circuit_count_ops) summary_result["circuit_num_of_x"] = circuit_count_ops.get('x') summary_result["circuit_num_of_measure"] = circuit_count_ops.get('measure') summary_result["circuit_num_of_h"] = circuit_count_ops.get('h') summary_result["circuit_num_of_cswap"] = circuit_count_ops.get('cswap') summary_result["circuit_num_of_swap"] = circuit_count_ops.get('swap') summary_result["circuit_num_of_cx"] = circuit_count_ops.get('cx') summary_result["circuit_num_of_toffoli"] = circuit_count_ops.get('toffoli') summary_result["circuit_num_of_p"] = circuit_count_ops.get('p') summary_result["circuit_num_of_t"] = circuit_count_ops.get('t') summary_result["circuit_decomposed_width"] = circuit_decomposed.width() summary_result["circuit_decomposed_depth"] = circuit_decomposed.depth() summary_result["circuit_decomposed_size"] = circuit_decomposed.size() summary_result["circuit_decomposed_num_nonlocal_gates"] = circuit_decomposed.num_nonlocal_gates() summary_result["circuit_decomposed_num_ancillas"] = circuit_decomposed.num_ancillas summary_result["circuit_decomposed_num_clbits"] = circuit_decomposed.num_clbits summary_result["circuit_decomposed_num_qubits"] = circuit_decomposed.num_qubits summary_result["circuit_decomposed_num_ancillas"] = circuit_decomposed.num_ancillas summary_result["circuit_decomposed_num_of_count_ops"] = len(circuit_decomposed_count_ops) summary_result["circuit_decomposed_num_of_x"] = circuit_decomposed_count_ops.get('x') summary_result["circuit_decomposed_num_of_measure"] = circuit_decomposed_count_ops.get('measure') summary_result["circuit_decomposed_num_of_h"] = circuit_decomposed_count_ops.get('h') summary_result["circuit_decomposed_num_of_cswap"] = circuit_decomposed_count_ops.get('cswap') summary_result["circuit_decomposed_num_of_swap"] = circuit_decomposed_count_ops.get('swap') summary_result["circuit_decomposed_num_of_cx"] = circuit_decomposed_count_ops.get('cx') summary_result["circuit_decomposed_num_of_toffoli"] = circuit_decomposed_count_ops.get('toffoli') summary_result["circuit_decomposed_num_of_p"] = circuit_decomposed_count_ops.get('p') summary_result["circuit_decomposed_num_of_t"] = circuit_decomposed_count_ops.get('t') summary_result["qc_compiled_width"] = qc_compiled.width() summary_result["qc_compiled_depth"] = qc_compiled.depth() summary_result["qc_compiled_size"] = qc_compiled.size() summary_result["qc_compiled_num_nonlocal_gates"] = qc_compiled.num_nonlocal_gates() summary_result["qc_compiled_num_ancillas"] = qc_compiled.num_ancillas summary_result["qc_compiled_num_clbits"] = qc_compiled.num_clbits summary_result["qc_compiled_num_qubits"] = qc_compiled.num_qubits summary_result["qc_compiled_num_ancillas"] = qc_compiled.num_ancillas summary_result["qc_compiled_num_of_count_ops"] = len(qc_compiled_count_ops) summary_result["qc_compiled_num_of_x"] = qc_compiled_count_ops.get('x') summary_result["qc_compiled_num_of_measure"] = qc_compiled_count_ops.get('measure') summary_result["qc_compiled_num_of_h"] = qc_compiled_count_ops.get('h') summary_result["qc_compiled_num_of_cswap"] = qc_compiled_count_ops.get('cswap') summary_result["qc_compiled_num_of_swap"] = qc_compiled_count_ops.get('swap') summary_result["qc_compiled_num_of_cx"] = qc_compiled_count_ops.get('cx') summary_result["qc_compiled_num_of_toffoli"] = qc_compiled_count_ops.get('toffoli') summary_result["qc_compiled_num_of_p"] = qc_compiled_count_ops.get('p') summary_result["qc_compiled_num_of_t"] = qc_compiled_count_ops.get('t') return summary_result # Run for just a single number N %%time N = 33 shots = 1024 global result_factors all_summary_result_temp = [] for random_a in range(16, 17): if math.gcd(random_a,N) > 1: continue a = random_a summary_result = my_shor(a,N,shots) print("Finished running for a = {} and N = {}\n".format(a, N)) all_summary_result_temp.append(summary_result) summary_result_list = [] for key, value in summary_result.items(): summary_result_list.append([key,value]) summary_result_list with open("a({0})_N({1})_standard.csv".format(a, N), 'a') as myfile: write = csv.writer(myfile) #write.writerow(fields) write.writerows(summary_result_list) all_summary_result_temp # Run for many numbers N. %%time shots = 1024 global result_factors all_summary_result = [] for N in [15, 21, 33, 35, 39, 51, 55, 57]: for a in range(2, N): if math.gcd(a,N) > 1: continue print("Beginning running for a = {} and N = {}".format(a, N)) summary_result = my_shor(a,N,shots) print("Finished running for a = {} and N = {}\n\n".format(a, N)) all_summary_result.append(summary_result) all_summary_result %qiskit_copyright
https://github.com/usamisaori/Grover
usamisaori
import qiskit from qiskit import QuantumCircuit from qiskit.visualization import plot_histogram from qiskit.quantum_info import Operator import numpy as np from qiskit import execute, Aer simulator = Aer.get_backend('qasm_simulator') import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') def createYouneInitCircuit(): circuit = QuantumCircuit(3, 2) circuit.h(0) circuit.h(1) circuit.barrier() return circuit youneInitCircuit = createYouneInitCircuit() youneInitCircuit.draw(output='mpl') def createYouneOracle(): circuit = QuantumCircuit(3, 2) circuit.x(0) circuit.x(1) circuit.ccx(0, 1, 2) circuit.x(0) circuit.x(1) circuit.barrier() circuit.x(0) circuit.ccx(0, 1, 2) circuit.x(0) circuit.barrier() return circuit youneOracle = createYouneOracle() youneOracle.draw(output='mpl') def createYouneDiffuser(): circuit = QuantumCircuit(3, 2) circuit.h(0) circuit.h(1) circuit.barrier(2) circuit.x(2) circuit.x(0) circuit.x(1) circuit.h(2) circuit.ccx(0, 1, 2) circuit.barrier(0) circuit.barrier(1) circuit.h(2) circuit.x(2) circuit.x(0) circuit.x(1) circuit.h(0) circuit.h(1) # circuit.h(2) circuit.barrier() return circuit youneDiffuser = createYouneDiffuser() youneDiffuser.draw(output='mpl') youneGroverIteration = createYouneOracle().compose(createYouneDiffuser()) grover_youne = createYouneInitCircuit().compose(youneGroverIteration.copy()) grover_youne.draw(output='mpl') grover_youne.measure([0, 1], [0, 1]) job = execute(grover_youne, simulator, shots = 10000) results = job.result() counts = results.get_counts(grover_youne) print(counts) plot_histogram(counts, figsize=(4, 5), color="#0099CC", title="youne grover - find evens") def createYouneOracle2(): circuit = QuantumCircuit(3, 2) circuit.x(0) circuit.cx(0, 2) circuit.x(0) circuit.barrier() return circuit youneOracle2 = createYouneOracle2() youneOracle2.draw(output='mpl') # 0 => 4 2 => 6 Operator(youneOracle2).data youneGroverIteration2 = createYouneOracle2().compose(createYouneDiffuser()) grover_youne2 = createYouneInitCircuit().compose(youneGroverIteration2.copy()) grover_youne2.draw(output='mpl') grover_youne2.measure([0, 1], [0, 1]) job = execute(grover_youne2, simulator, shots = 10000) results = job.result() counts = results.get_counts(grover_youne2) print(counts) plot_histogram(counts, figsize=(4, 5), color="#66CCFF", title="youne grover(using another Oracle) - find evens")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit # Create a circuit with a register of three qubits circ = QuantumCircuit(3) # H gate on qubit 0, putting this qubit in a superposition of |0> + |1>. circ.h(0) # A CX (CNOT) gate on control qubit 0 and target qubit 1 generating a Bell state. circ.cx(0, 1) # CX (CNOT) gate on control qubit 0 and target qubit 2 resulting in a GHZ state. circ.cx(0, 2) # Draw the circuit circ.draw('mpl')
https://github.com/IvanIsCoding/Quantum
IvanIsCoding
%matplotlib inline from qiskit import * from qiskit.visualization import plot_histogram circuit = QuantumCircuit(2) circuit.x(0) circuit.z(1) circuit.draw(output="mpl") unitary_simulator = Aer.get_backend("unitary_simulator") unitary = execute(circuit, backend=unitary_simulator).result().get_unitary() print(unitary) circuit = QuantumCircuit(2) circuit.h(0) circuit.x(1) circuit.cx(0, 1) circuit.draw(output="mpl") state_simulator = Aer.get_backend("statevector_simulator") state_vector = execute(circuit, backend=state_simulator).result().get_statevector() print(state_vector) circuit = QuantumCircuit(2) circuit.h(0) circuit.h(1) circuit.cz(0, 1) circuit.draw(output="mpl") state_vector = execute(circuit, backend=state_simulator).result().get_statevector() print(state_vector) circuit = QuantumCircuit(3, 3) circuit.h([0, 1]) circuit.ccx(0, 1, 2) circuit.measure([0, 1, 2], [0, 1, 2]) circuit.draw(output="mpl") simulator = Aer.get_backend("qasm_simulator") counts = execute(circuit, backend=simulator, shots=2**16).result().get_counts() plot_histogram(counts) circuit = QuantumCircuit(3, 3) circuit.x(0) circuit.cx(0, 1) circuit.ccx(0, 1, 2) circuit.ccx(0, 1, 2) circuit.cx(0, 1) circuit.x(0) circuit.measure([0, 1, 2], [0, 1, 2]) circuit.draw(output="mpl") counts = execute(circuit, backend=simulator, shots=2**16).result().get_counts() plot_histogram(counts)
https://github.com/chunfuchen/qiskit-chemistry
chunfuchen
# -*- 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 logging import numpy as np from qiskit import QuantumRegister, QuantumCircuit from qiskit.aqua.components.initial_states import InitialState logger = logging.getLogger(__name__) class HartreeFock(InitialState): """A Hartree-Fock initial state.""" CONFIGURATION = { 'name': 'HartreeFock', 'description': 'Hartree-Fock initial state', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'hf_state_schema', 'type': 'object', 'properties': { 'num_orbitals': { 'type': 'integer', 'default': 4, 'minimum': 1 }, 'num_particles': { 'type': 'integer', 'default': 2, 'minimum': 1 }, 'qubit_mapping': { 'type': 'string', 'default': 'parity', 'oneOf': [ {'enum': ['jordan_wigner', 'parity', 'bravyi_kitaev']} ] }, 'two_qubit_reduction': { 'type': 'boolean', 'default': True } }, 'additionalProperties': False } } def __init__(self, num_qubits, num_orbitals, num_particles, qubit_mapping='parity', two_qubit_reduction=True, sq_list=None): """Constructor. Args: num_qubits (int): number of qubits num_orbitals (int): number of spin orbitals qubit_mapping (str): mapping type for qubit operator two_qubit_reduction (bool): flag indicating whether or not two qubit is reduced num_particles (int): number of particles sq_list ([int]): position of the single-qubit operators that anticommute with the cliffords Raises: ValueError: wrong setting in num_particles and num_orbitals. ValueError: wrong setting for computed num_qubits and supplied num_qubits. """ self.validate(locals()) super().__init__() self._sq_list = sq_list self._qubit_tapering = False if self._sq_list is None else True self._qubit_mapping = qubit_mapping.lower() self._two_qubit_reduction = two_qubit_reduction if self._qubit_mapping != 'parity': if self._two_qubit_reduction: logger.warning("two_qubit_reduction only works with parity qubit mapping " "but you have {}. We switch two_qubit_reduction " "to False.".format(self._qubit_mapping)) self._two_qubit_reduction = False self._num_orbitals = num_orbitals self._num_particles = num_particles if self._num_particles > self._num_orbitals: raise ValueError("# of particles must be less than or equal to # of orbitals.") self._num_qubits = num_orbitals - 2 if self._two_qubit_reduction else self._num_orbitals self._num_qubits = self._num_qubits \ if not self._qubit_tapering else self._num_qubits - len(sq_list) if self._num_qubits != num_qubits: raise ValueError("Computed num qubits {} does not match " "actual {}".format(self._num_qubits, num_qubits)) self._bitstr = None def _build_bitstr(self): half_orbitals = self._num_orbitals // 2 bitstr = np.zeros(self._num_orbitals, np.bool) bitstr[-int(np.ceil(self._num_particles / 2)):] = True bitstr[-(half_orbitals + int(np.floor(self._num_particles / 2))):-half_orbitals] = True if self._qubit_mapping == 'parity': new_bitstr = bitstr.copy() t = np.triu(np.ones((self._num_orbitals, self._num_orbitals))) new_bitstr = t.dot(new_bitstr.astype(np.int)) % 2 bitstr = np.append(new_bitstr[1:half_orbitals], new_bitstr[half_orbitals + 1:]) \ if self._two_qubit_reduction else new_bitstr elif self._qubit_mapping == 'bravyi_kitaev': binary_superset_size = int(np.ceil(np.log2(self._num_orbitals))) beta = 1 basis = np.asarray([[1, 0], [0, 1]]) for i in range(binary_superset_size): beta = np.kron(basis, beta) beta[0, :] = 1 beta = beta[:self._num_orbitals, :self._num_orbitals] new_bitstr = beta.dot(bitstr.astype(int)) % 2 bitstr = new_bitstr.astype(np.bool) if self._qubit_tapering: sq_list = (len(bitstr) - 1) - np.asarray(self._sq_list) bitstr = np.delete(bitstr, sq_list) self._bitstr = bitstr.astype(np.bool) def construct_circuit(self, mode, register=None): """ Construct the statevector of desired initial state. Args: mode (string): `vector` or `circuit`. The `vector` mode produces the vector. While the `circuit` constructs the quantum circuit corresponding that vector. register (QuantumRegister): register for circuit construction. Returns: QuantumCircuit or numpy.ndarray: statevector. Raises: ValueError: when mode is not 'vector' or 'circuit'. """ if self._bitstr is None: self._build_bitstr() if mode == 'vector': state = 1.0 one = np.asarray([0.0, 1.0]) zero = np.asarray([1.0, 0.0]) for k in self._bitstr[::-1]: state = np.kron(one if k else zero, state) return state elif mode == 'circuit': if register is None: register = QuantumRegister(self._num_qubits, name='q') quantum_circuit = QuantumCircuit(register) for qubit_idx, bit in enumerate(self._bitstr[::-1]): if bit: quantum_circuit.u3(np.pi, 0.0, np.pi, register[qubit_idx]) return quantum_circuit else: raise ValueError('Mode should be either "vector" or "circuit"') @property def bitstr(self): """Getter of the bit string represented the statevector.""" if self._bitstr is None: self._build_bitstr() return self._bitstr
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
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, L_BFGS_B from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit.utils import algorithm_globals from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier, VQC from qiskit_machine_learning.algorithms.regressors import NeuralNetworkRegressor, VQR from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN algorithm_globals.random_seed = 42 num_inputs = 2 num_samples = 20 X = 2 * algorithm_globals.random.random([num_samples, num_inputs]) - 1 y01 = 1 * (np.sum(X, axis=1) >= 0) # in { 0, 1} y = 2 * y01 - 1 # in {-1, +1} y_one_hot = np.zeros((num_samples, 2)) for i in range(num_samples): y_one_hot[i, y01[i]] = 1 for x, y_target in zip(X, y): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() # construct QNN qc = QuantumCircuit(2) feature_map = ZZFeatureMap(2) ansatz = RealAmplitudes(2) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) qc.draw(output="mpl") estimator_qnn = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters ) # QNN maps inputs to [-1, +1] estimator_qnn.forward(X[0, :], algorithm_globals.random.random(estimator_qnn.num_weights)) # 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 neural network classifier estimator_classifier = NeuralNetworkClassifier( estimator_qnn, optimizer=COBYLA(maxiter=60), callback=callback_graph ) # create empty array for callback to store evaluations of the objective function 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) # evaluate data points y_predict = estimator_classifier.predict(X) # plot results # red == wrongly classified for x, y_target, y_p in zip(X, y, y_predict): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") if y_target != y_p: plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() estimator_classifier.weights # construct feature map feature_map = ZZFeatureMap(num_inputs) # construct ansatz ansatz = RealAmplitudes(num_inputs, reps=1) # construct quantum circuit qc = QuantumCircuit(num_inputs) qc.append(feature_map, range(num_inputs)) qc.append(ansatz, range(num_inputs)) qc.decompose().draw(output="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 sampler_qnn = SamplerQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=output_shape, ) # construct classifier sampler_classifier = NeuralNetworkClassifier( neural_network=sampler_qnn, optimizer=COBYLA(maxiter=30), callback=callback_graph ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data sampler_classifier.fit(X, y01) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier sampler_classifier.score(X, y01) # evaluate data points y_predict = sampler_classifier.predict(X) # plot results # red == wrongly classified for x, y_target, y_p in zip(X, y01, y_predict): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") if y_target != y_p: plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() sampler_classifier.weights # construct feature map, ansatz, and optimizer feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs, reps=1) # construct variational quantum classifier vqc = VQC( feature_map=feature_map, ansatz=ansatz, loss="cross_entropy", optimizer=COBYLA(maxiter=30), callback=callback_graph, ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data vqc.fit(X, y_one_hot) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier vqc.score(X, y_one_hot) # evaluate data points y_predict = vqc.predict(X) # plot results # red == wrongly classified for x, y_target, y_p in zip(X, y_one_hot, y_predict): if y_target[0] == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") if not np.all(y_target == y_p): plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() from sklearn.datasets import make_classification from sklearn.preprocessing import MinMaxScaler X, y = make_classification( n_samples=10, n_features=2, n_classes=3, n_redundant=0, n_clusters_per_class=1, class_sep=2.0, random_state=algorithm_globals.random_seed, ) X = MinMaxScaler().fit_transform(X) plt.scatter(X[:, 0], X[:, 1], c=y) y_cat = np.empty(y.shape, dtype=str) y_cat[y == 0] = "A" y_cat[y == 1] = "B" y_cat[y == 2] = "C" print(y_cat) vqc = VQC( num_qubits=2, optimizer=COBYLA(maxiter=30), callback=callback_graph, ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data vqc.fit(X, y_cat) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier vqc.score(X, y_cat) predict = vqc.predict(X) print(f"Predicted labels: {predict}") print(f"Ground truth: {y_cat}") num_samples = 20 eps = 0.2 lb, ub = -np.pi, np.pi X_ = np.linspace(lb, ub, num=50).reshape(50, 1) f = lambda x: np.sin(x) X = (ub - lb) * algorithm_globals.random.random([num_samples, 1]) + lb y = f(X[:, 0]) + eps * (2 * algorithm_globals.random.random(num_samples) - 1) plt.plot(X_, f(X_), "r--") plt.plot(X, y, "bo") plt.show() # construct simple feature map param_x = Parameter("x") feature_map = QuantumCircuit(1, name="fm") feature_map.ry(param_x, 0) # construct simple ansatz param_y = Parameter("y") ansatz = QuantumCircuit(1, name="vf") ansatz.ry(param_y, 0) # construct a circuit qc = QuantumCircuit(1) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) # construct QNN regression_estimator_qnn = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters ) # construct the regressor from the neural network regressor = NeuralNetworkRegressor( neural_network=regression_estimator_qnn, loss="squared_error", optimizer=L_BFGS_B(maxiter=5), callback=callback_graph, ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit to data regressor.fit(X, y) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score the result regressor.score(X, y) # plot target function plt.plot(X_, f(X_), "r--") # plot data plt.plot(X, y, "bo") # plot fitted line y_ = regressor.predict(X_) plt.plot(X_, y_, "g-") plt.show() regressor.weights vqr = VQR( feature_map=feature_map, ansatz=ansatz, optimizer=L_BFGS_B(maxiter=5), callback=callback_graph, ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit regressor vqr.fit(X, y) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score result vqr.score(X, y) # plot target function plt.plot(X_, f(X_), "r--") # plot data plt.plot(X, y, "bo") # plot fitted line y_ = vqr.predict(X_) plt.plot(X_, y_, "g-") plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/ColibrITD-SAS/mpqp
ColibrITD-SAS
from mpqp import QCircuit from mpqp.gates import H, CNOT circuit = QCircuit([H(0), CNOT(0,1)], label="Bell state") print(circuit) from mpqp.execution import run, ATOSDevice result = run(circuit, ATOSDevice.MYQLM_PYLINALG) print(result) print(result.amplitudes) print(result.probabilities) from mpqp.measures import BasisMeasure circuit.add(BasisMeasure([0,1], shots=0)) result = run(circuit, ATOSDevice.MYQLM_PYLINALG) print(result) circuit = circuit.without_measurements() circuit.add(BasisMeasure([0,1], shots=1024)) result = run(circuit, ATOSDevice.MYQLM_PYLINALG) print(result) print(result.samples) print(result.counts) print(result.probabilities) from mpqp.execution import IBMDevice, AWSDevice, GOOGLEDevice results = run(circuit, [ATOSDevice.MYQLM_PYLINALG, IBMDevice.AER_SIMULATOR, AWSDevice.BRAKET_LOCAL_SIMULATOR, GOOGLEDevice.CIRQ_LOCAL_SIMULATOR]) print(results) print('---------') print(results[0]) result = run(circuit, IBMDevice.IBMQ_QASM_SIMULATOR) print(result) from mpqp.execution import submit job_id, job = submit(circuit, IBMDevice.IBMQ_QASM_SIMULATOR) print(job_id) from mpqp.execution import get_remote_result result = get_remote_result(job_id, IBMDevice.IBMQ_QASM_SIMULATOR) print(result)
https://github.com/kosakhro/QAOA-for-exact-cover
kosakhro
from qiskit import * from qiskit.visualization import plot_bloch_multivector from qiskit.visualization import plot_histogram import numpy as np import matplotlib.pyplot as plt import seaborn as sns IBMQ.load_account() matplotlib inline my_provider = IBMQ.get_provider() my_provider.backends() simulator = my_provider.get_backend('ibmq_5_yorktown') # Making the quantum circuit def circuitI(gamma, beta, J, h1, h2): qc = QuantumCircuit(2, 2) qc.h([0, 1]) qc.h(1) qc.cz(0,1) qc.rx(2*gamma*J, 1) qc.cz(0,1) qc.h(1) qc.i(0) qc.rz(2*gamma*h1, 0) qc.rz(2*gamma*h2, 1) qc.rx(2*beta, 0) qc.rx(2*beta, 1) qc.measure([0,1], [0,1]) return qc # Initializing the variables for D. J = 1 h1 = 0 h2 = 0 #Setting the dimesions of the pasephase. The amount of simulated points = n**2 n = 61 p = np.pi/(n-1) res = np.zeros([n, n, 4]) # Running a simulation for each point for i in range(n): qc_list = [] gamma = i*p for j in range(n): beta = j*p qc = circuitI(gamma, beta, J, h1, h2) qc_list.append(qc) transpiled_circs = transpile(qc_list, backend=simulator) job = execute(transpiled_circs, backend = simulator, shots=1000 ) for circ_index in range(len(transpiled_circs)): counts = job.result().get_counts(qc_list[circ_index]) res[i][circ_index][:] = np.array([int(counts.get('00', 0)), int(counts.get('01', 0)), int(counts.get('10', 0)), int(counts.get('11', 0))]) print(res) #Draw the current circuit qc.draw(output='mpl') transpiled_circs[0].draw(output='mpl') # Making a heatmap plot sns.heatmap(res[:, :, 1]+res[:, :, 2])
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.mappers.second_quantization import LogarithmicMapper mapper = LogarithmicMapper(2) from qiskit_nature.second_q.mappers import LogarithmicMapper mapper = LogarithmicMapper(2) from qiskit_nature.second_q.mappers import LogarithmicMapper mapper = LogarithmicMapper(padding=2) from qiskit_nature.circuit.library import HartreeFock from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import JordanWignerMapper converter = QubitConverter(JordanWignerMapper()) init_state = HartreeFock(num_spin_orbitals=6, num_particles=(2, 1), qubit_converter=converter) print(init_state.draw()) from qiskit_nature.second_q.circuit.library import HartreeFock from qiskit_nature.second_q.mappers import JordanWignerMapper, QubitConverter converter = QubitConverter(JordanWignerMapper()) init_state = HartreeFock(num_spatial_orbitals=3, num_particles=(2, 1), qubit_converter=converter) print(init_state.draw()) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/abbarreto/qiskit4
abbarreto
from qiskit import QuantumCircuit, Aer, execute, IBMQ from qiskit.utils import QuantumInstance import numpy as np from qiskit.algorithms import Shor IBMQ.enable_account('ENTER API TOKEN HERE') # Enter your API token here provider = IBMQ.get_provider(hub='ibm-q') backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1000) my_shor = Shor(quantum_instance) result_dict = my_shor.factor(15) print(result_dict)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from IPython.display import HTML HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document ).ready(code_toggle); </script> <form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code for QISKit exercises."></form>''') # QISKIT: QFT code # calculate qft of two qubit as the example above from initialize import * def qft(circ, q, n): """n-qubit QFT on q in circ.""" for j in range(n): for k in range(j): circ.cu1(3.14/float(2**(j-k)), q[j], q[k]) circ.h(q[j]) #initialize quantum program my_alg = initialize(circuit_name = 'fourier', qubit_number=2, bit_number=2, backend = 'local_qasm_simulator', shots = 1024) #add gates to the circuit qft(my_alg.q_circuit, my_alg.q_reg, 2) # qft of input state my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures first qubit my_alg.q_circuit.measure(my_alg.q_reg[1], my_alg.c_reg[1]) # measures second qubit # print list of gates in the circuit print('List of gates:') for circuit in my_alg.q_circuit: print(circuit.name) #Execute the quantum algorithm result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots) #Show the results obtained from the quantum algorithm counts = result.get_counts(my_alg.circ_name) print('\nThe measured outcomes of the circuits are:',counts) # credits to: https://github.com/QISKit/qiskit-tutorial
https://github.com/nagarx/Quantum-KNN-Classifier-using-Qiskit
nagarx
from qiskit import QuantumCircuit, QuantumRegister def swap_test(N): ''' `N`: Number of qubits of the quantum registers. ''' a = QuantumRegister(N, 'a') b = QuantumRegister(N, 'b') d = QuantumRegister(1, 'd') # Quantum Circuit qc_swap = QuantumCircuit(name = ' SWAP \nTest') qc_swap.add_register(a) qc_swap.add_register(b) qc_swap.add_register(d) qc_swap.h(d) for i in range(N): qc_swap.cswap(d, a[i], b[i]) qc_swap.h(d) return qc_swap
https://github.com/kaelynj/Qiskit-HubbardModel
kaelynj
#Jupyter notebook to check if imports work correctly %matplotlib inline import sys sys.path.append('./src') import HubbardEvolutionChain as hc import ClassicalHubbardEvolutionChain as chc import FullClassicalHubbardEvolutionChain as fhc from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer, QuantumRegister, ClassicalRegister from qiskit.compiler import transpile, assemble from qiskit.quantum_info import Operator from qiskit.tools.monitor import job_monitor from qiskit.tools.jupyter import * import qiskit.visualization as qvis import random as rand import scipy.linalg as la provider = IBMQ.load_account() import matplotlib.pyplot as plt import matplotlib.colors as mcolors import numpy as np from matplotlib import rcParams rcParams['text.usetex'] = True def get_bin(x, n=0): """ Get the binary representation of x. Parameters: x (int), n (int, number of digits)""" binry = format(x, 'b').zfill(n) sup = list( reversed( binry[0:int(len(binry)/2)] ) ) sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) ) return format(x, 'b').zfill(n) #==========Set Parameters of the System=============# dt = 0.25 #Delta t T = 5. time_steps = int(T/dt) t = 1.0 #Hopping parameter #t = [1.0, 2.] U = 2. #On-Site repulsion #time_steps = 10 nsites = 3 trotter_slices = 10 initial_state = np.array([1, 4]) #Run simulation run_results1 = hc.sys_evolve(nsites, initial_state, T, dt, t, U, 10) run_results2 = hc.sys_evolve(nsites, initial_state, T, dt, t, U, 40) run_results3, eng3 = hc.sys_evolve_eng(nsites, initial_state, T, dt, t, U, 60) run_results4 = hc.sys_evolve(nsites, initial_state, T, dt, t, U, 90) #print(True if np.isscalar(initial_state) else False) ''' #Fidelity measurements #run_results1, engs1 = hc.sys_evolve_eng(nsites, initial_state, T, dt, t, U, 10) run_results2 = hc.sys_evolve_den(nsites, initial_state, T, dt, t, U, 40) #run_results3, engs3 = hc.sys_evolve_eng(nsites, initial_state, T, dt, t, U, 100) #run_results4, engs4 = hc.sys_evolve_eng(nsites, initial_state, T, dt, t, U, 150) #Collect data on how Trotter steps change energy range trotter_range = [10, 20, 30, 40, 50, 60, 70, 80] eng_range = [] #engs = [] #runs = [] for trot_step in trotter_range: run_results3, eng3 = hc.sys_evolve_eng(nsites, initial_state, T, dt, t, U, trot_step) runs.append(run_results3[:,-1]) eng_range.append(np.ptp(eng3)) engs.append(eng3) ''' #sample_run = run_results3[:,-1] #print(sample_run) #print(run_results3[:,-1],' ',len(run_results3[:,-1])) #print(tp_run[-1],' ',len(tp_run[-1])) #Plot the raw data as a colormap #xticks = np.arange(2**(nsites*2)) xlabels=[] print("Time Steps: ",time_steps, " Step Size: ",dt) for i in range(2**(nsites*2)): xlabels.append(hc.get_bin(i,6)) fig, ax = plt.subplots(figsize=(10,20)) c = ax.pcolor(np.transpose(runs), cmap='binary') ax.set_title('Basis State Amplitude', fontsize=22) plt.yticks(np.arange(2**(nsites*2)), xlabels, size=18) plt.xticks(np.arange(0,13), trotter_range, size=18) ax.set_xlabel('No. of Trotter Steps', fontsize=22) ax.set_ylabel('State', fontsize=26) plt.show() #plt.plot(trotter_range, eng_range) #plt.xlabel('No. of Trotter Steps', fontsize=18) #plt.ylabel('Energy Range', fontsize=18) proc_data = np.zeros([2*nsites, len(trotter_range)]) runs_array = np.array(runs) for step in range(0,len(trotter_range)): for i in range(0,2**(2*nsites)): num = ''.join( list( reversed(hc.get_bin(i,2*nsites)) ) ) #print('i: ', i,' step: ',step) for mode in range(len(num)): if num[mode]=='1': proc_data[mode, step] += runs_array[step, i] norm = 0. for mode in range(len(num)): norm += proc_data[mode, step] proc_data[:,step] = proc_data[:,step] / norm print(proc_data[0,:]) #============ Run Classical Evolution ==============# #Define our basis states #States for 3 electrons with net spin up ''' states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]], [[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]], [[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ] ''' #States for 2 electrons in singlet state states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]], [[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]], [[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ] #''' #States for a single electron #states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ] #Possible initial wavefunctions #wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.] #Half-filling initial state (101010) wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state (010010) #wfk = [0., 0., 0., 0., 0., 1., 0., 0., 0.] #2 electron initial state (010001) #wfk = [0., -1., 0.] #1 electron initial state #System parameters t = 1.0 U = 2. classical_time_step = 0.01 classical_total_time = 500*0.01 times = np.arange(0., classical_total_time, classical_time_step) states = fhc.get_states(numsites) evolution, engs = chc.sys_evolve(states, wfk, t, U, classical_total_time, classical_time_step) print(evolution[-25]) #System parameters t = 1.0 U = 2. classical_time_step = 0.01 classical_total_time = 500*0.01 times = np.arange(0., classical_total_time, classical_time_step) states = fhc.get_states(nsites) #print(states) #print(states[64]) wfk_full = np.zeros(len(states), dtype=np.complex_) target_state = [[0,1], [0,0]] target_index = 0 for l in range(len(states)): if len(target_state) == sum([1 for i, j in zip(target_state, states[l]) if i == j]): print('Target state found at: ',l) target_index = l wfk_full[18] = 1. #010010 #wfk_full[21] = 1. #010101 #wfk_full[42] = 1. #101010 #wfk_full[2] = 1. #000010 #wfk_full[target_index] = 1. #wfk_full[2] = 0.5 - 0.5*1j #wfk_full[0] = 1/np.sqrt(2) print(wfk_full) evolution, engs, wfks = fhc.sys_evolve(states, wfk_full, t, U, classical_total_time, classical_time_step) #print(wfks[-26]) #print(run_results1[-1]) tst = np.outer(np.conj(wfks[-25]),wfks[-25]) #print(times[-25]) #print(np.shape(tst)) def fidelity(numerical_density, quantum_density): sqrt_quantum = la.sqrtm(quantum_density) fidelity_matrix = np.matmul(sqrt_quantum, np.matmul(numerical_density,sqrt_quantum)) fidelity_matrix = la.sqrtm(fidelity_matrix) trace = np.trace(fidelity_matrix) trace2 = np.conj(trace)*trace #Try tr(rho*sigma)+sqrt(det(rho)*det(sigma)) fidelity = np.trace(np.matmul(numerical_density, quantum_density)) + np.sqrt(np.linalg.det(numerical_density)*np.linalg.det(quantum_density)) return fidelity print("Fidelity") print( fidelity( run_results2[-1], tst) ) print('============================') print('Trace') print('Numerical: ',np.trace(tst)) print('Quantum: ',np.trace(run_results2[-1])) print('============================') print('Square Trace') print('Numerical: ',np.trace(np.matmul(tst, tst))) print('Quantum: ',np.trace(np.matmul(run_results2[-1], run_results2[-1]))) print('============================') fidelities = [] fidelities.append(fidelity(tst, run_results1[-1])) fidelities.append(fidelity(tst, run_results2[-1])) fidelities.append(fidelity(tst, run_results3[-1])) fidelities.append(fidelity(tst, run_results4[-1])) trotters = [10, 40, 100, 150] plt.plot(trotters, fidelities) #Calculate RootMeanSquare rms = np.zeros(len(trotter_range)) for trotter_index in range(len(trotter_range)): sq_diff = 0. for mode in range(2*nsites): sq_diff += (evolution[-25, mode] - proc_data[mode, trotter_index])**2 rms[trotter_index] = np.sqrt(sq_diff / 2*nsites) plt.plot(trotter_range, rms) plt.xlabel('Trotter Steps', fontsize=14) plt.ylabel('RMS',fontsize=14) plt.title('RMS for 1 Electrons 010000', fontsize=14) #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) for i in range(nsites): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(trotter_range, proc_data[i,:], marker="^", color=str(colors[i]), label=strup) ax2.plot(trotter_range, proc_data[i+nsites,:], marker="v", linestyle='--', color=str(colors[i]), label=strdwn) ax2.plot(trotter_range, np.full(len(trotter_range), evolution[-1, i]), linestyle='-', color=str(colors[i]),label=strup) ax2.plot(trotter_range, np.full(len(trotter_range), evolution[-1, i+nsites]), linestyle='-', color=str(colors[i]),label=strdwn) #ax2.set_ylim(0, 0.55) #ax2.set_xlim(0, time_steps*dt+dt/2.) #ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2)) #ax2.set_yticks(np.arange(0,0.55, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Probability Convergence for 3 electrons', fontsize=22) ax2.set_xlabel('Number of Trotter Steps', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20) processed_data3 = hc.process_run(nsites, time_steps, dt, run_results3) tdat = np.arange(0.,T, dt) norm_dat = [np.sum(x) for x in np.transpose(processed_data3)] print(norm_dat) print(eng3) #plt.plot(norm_dat) plt.plot(tdat, eng3, label='80 Steps') plt.plot(times, engs, label='Numerical') plt.xlabel('Time', fontsize=18) plt.ylabel('Energy',fontsize=18) plt.ylim(-1e-5, 1e-5) plt.legend() print(np.ptp(eng3)) ## ============ Run Classical Evolution ============== #Define our basis states #States for 3 electrons with net spin up ''' states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]], [[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]], [[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ] ''' #States for 2 electrons in singlet state states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]], [[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]], [[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ] #''' #States for a single electron #states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ] #Possible initial wavefunctions #wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.] #Half-filling initial state wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state #wfk = [0., 1., 0.] #1 electron initial state #System parameters for evolving system numerically t = 1.0 U = 2. classical_time_step = 0.01 classical_total_time = 500*0.01 times = np.arange(0., classical_total_time, classical_time_step) evolution, engs = chc.sys_evolve(states, wfk, t, U, classical_total_time, classical_time_step) #Get norms and energies as a function of time. Round to 10^-12 norms = np.array([np.sum(x) for x in evolution]) norms = np.around(norms, 12) engs = np.around(engs, 12) #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) fig3, ax3 = plt.subplots(1, 2, figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) cos = np.cos(np.sqrt(2)*times)**2 sit1 = "Site "+str(1)+r'$\uparrow$' sit2 = "Site "+str(2)+r'$\uparrow$' sit3 = "Site "+str(3)+r'$\uparrow$' #ax2.plot(times, evolve[:,0], marker='.', color='k', linewidth=2, label=sit1) #ax2.plot(times, evolve[:,1], marker='.', color=str(colors[0]), linewidth=2, label=sit2) #ax2.plot(times, evolve[:,2], marker='.', color=str(colors[1]), linewidth=1.5, label=sit3) #ax2.plot(times, cos, label='cosdat') #ax2.plot(times, np.zeros(len(times))) for i in range(3): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(times, evolution[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) ax2.plot(times, evolution[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) #ax2.set_ylim(0, 1.) ax2.set_xlim(0, classical_total_time) #ax2.set_xlim(0, 1.) ax2.set_xticks(np.arange(0,classical_total_time, 0.2)) #ax2.set_yticks(np.arange(0,1.1, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20) #Plot energy and normalization ax3[0].plot(times, engs, color='b') ax3[1].plot(times, norms, color='r') ax3[0].set_xlabel('Time', fontsize=24) ax3[0].set_ylabel('Energy [t]', fontsize=24) ax3[1].set_xlabel('Time', fontsize=24) ax3[1].set_ylabel('Normalization', fontsize=24) print(evolution) #processed_data1 = hc.process_run(nsites, time_steps, dt, run_results1) #processed_data2 = hc.process_run(nsites, time_steps, dt, run_results2) processed_data3 = hc.process_run(nsites, time_steps, dt, run_results3) #processed_data4 = hc.process_run(nsites, time_steps, dt, run_results4) timesq = np.arange(0, time_steps*dt, dt) #Create plots of the processed data #fig0, ax0 = plt.subplots(figsize=(20,10)) fig1, ax1 = plt.subplots(figsize=(20,10)) fig2, ax2 = plt.subplots(figsize=(20,10)) fig3, ax3 = plt.subplots(figsize=(20,10)) fig4, ax4 = plt.subplots(figsize=(20,10)) fig5, ax5 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) ''' #Plot energies ax0.plot(timesq, eng1, color=str(colors[0]), label='10 Steps') ax0.plot(timesq, eng2, color=str(colors[1]), label='20 Steps') ax0.plot(timesq, eng3, color=str(colors[2]), label='40 Steps') ax0.plot(timesq, eng4, color=str(colors[3]), label='60 Steps') ax0.legend(fontsize=20) ax0.set_xlabel("Time", fontsize=24) ax0.set_ylabel("Total Energy", fontsize=24) ax0.tick_params(labelsize=16) ''' #Site 1 strup = "10 Steps"+r'$\uparrow$' strdwn = "10 Steps"+r'$\downarrow$' #ax1.plot(timesq, processed_data1[0,:], marker="^", color=str(colors[0]), label=strup) #ax1.plot(timesq, processed_data1[0+nsites,:], linestyle='--', marker="v", color=str(colors[0]), label=strdwn) strup = "40 Steps"+r'$\uparrow$' strdwn = "40 Steps"+r'$\downarrow$' #ax1.plot(timesq, processed_data2[0,:], marker="^", color=str(colors[1]), label=strup) #ax1.plot(timesq, processed_data2[0+nsites,:], linestyle='--', marker="v", color=str(colors[1]), label=strdwn) strup = "60 Steps"+r'$\uparrow$' strdwn = "60 Steps"+r'$\downarrow$' ax1.plot(timesq, processed_data3[0,:], marker="^", color=str(colors[2]), label=strup) ax1.plot(timesq, processed_data3[0+nsites,:],linestyle='--', marker="v", color=str(colors[2]), label=strdwn) strup = "100 Steps"+r'$\uparrow$' strdwn = "100 Steps"+r'$\downarrow$' #ax1.plot(timesq, processed_data3[0,:], marker="^", color=str(colors[3]), label=strup) #ax1.plot(timesq, processed_data3[0+nsites,:], linestyle='--', marker="v", color=str(colors[3]), label=strdwn) strup = "Exact"+r'$\uparrow$' strdwn = "Exact"+r'$\downarrow$' #1e numerical evolution ax1.plot(times, evolution[:,0], linestyle='-', color='k', linewidth=2, label=strup) ax1.plot(times, evolution[:,0+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #2e+ numerical evolution #ax1.plot(times, mode_evolve[:,0], linestyle='-', color='k', linewidth=2, label=strup) #ax1.plot(times, mode_evolve[:,0+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #Site 2 strup = "10 Steps"+r'$\uparrow$' strdwn = "10 Steps"+r'$\downarrow$' #ax2.plot(timesq, processed_data1[1,:], marker="^", color=str(colors[0]), label=strup) #ax2.plot(timesq, processed_data1[1+nsites,:], marker="v", linestyle='--',color=str(colors[0]), label=strdwn) strup = "40 Steps"+r'$\uparrow$' strdwn = "40 Steps"+r'$\downarrow$' #ax2.plot(timesq, processed_data2[1,:], marker="^", color=str(colors[1]), label=strup) #ax2.plot(timesq, processed_data2[1+nsites,:], marker="v", linestyle='--',color=str(colors[1]), label=strdwn) strup = "60 Steps"+r'$\uparrow$' strdwn = "60 Steps"+r'$\downarrow$' ax2.plot(timesq, processed_data3[1,:], marker="^", color=str(colors[2]), label=strup) ax2.plot(timesq, processed_data3[1+nsites,:], marker="v", linestyle='--', color=str(colors[2]), label=strdwn) strup = "100 Steps"+r'$\uparrow$' strdwn = "100 Steps"+r'$\downarrow$' #ax2.plot(timesq, processed_data4[1,:], marker="^", color=str(colors[3]), label=strup) #ax2.plot(timesq, processed_data4[1+nsites,:], marker="v", linestyle='--', color=str(colors[3]), label=strdwn) #1e numerical evolution strup = "Exact"+r'$\uparrow$' strdwn = "Exact"+r'$\downarrow$' ax2.plot(times, evolution[:,1], linestyle='-', color='k', linewidth=2, label=strup) ax2.plot(times, evolution[:,1+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #2e+ numerical evolution #ax2.plot(times, mode_evolve[:,1], linestyle='-', color='k', linewidth=2, label=strup) #ax2.plot(times, mode_evolve[:,1+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #Site 3 strup = "10 Steps"+r'$\uparrow$' strdwn = "10 Steps"+r'$\downarrow$' #ax3.plot(timesq, processed_data1[2,:], marker="^", color=str(colors[0]), label=strup) #ax3.plot(timesq, processed_data1[2+nsites,:], marker="v", linestyle='--', color=str(colors[0]), label=strdwn) strup = "40 Steps"+r'$\uparrow$' strdwn = "40 Steps"+r'$\downarrow$' #ax3.plot(timesq, processed_data2[2,:], marker="^", color=str(colors[1]), label=strup) #ax3.plot(timesq, processed_data2[2+nsites,:], marker="v", linestyle='--', color=str(colors[1]), label=strdwn) strup = "60 Steps"+r'$\uparrow$' strdwn = "60 Steps"+r'$\downarrow$' ax3.plot(timesq, processed_data3[2,:], marker="^", color=str(colors[2]), label=strup) ax3.plot(timesq, processed_data3[2+nsites,:], marker="v", linestyle='--', color=str(colors[2]), label=strdwn) strup = "100 Steps"+r'$\uparrow$' strdwn = "100 Steps"+r'$\downarrow$' #ax3.plot(timesq, processed_data4[2,:], marker="^", color=str(colors[3]), label=strup) #ax3.plot(timesq, processed_data4[2+nsites,:], marker="v", linestyle='--', color=str(colors[3]), label=strdwn) #1e numerical evolution strup = "Exact"+r'$\uparrow$' strdwn = "Exact"+r'$\downarrow$' ax3.plot(times, evolution[:,2], linestyle='-', color='k', linewidth=2, label=strup) ax3.plot(times, evolution[:,2+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #2e+ numerical evolution #ax3.plot(times, mode_evolve[:,2], linestyle='-', color='k', linewidth=2, label=strup) #ax3.plot(times, mode_evolve[:,2+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #Site 4 r''' strup = "10 Steps"+r'$\uparrow$' strdwn = "10 Steps"+r'$\downarrow$' #ax4.plot(timesq, processed_data1[3,:], marker="^", color=str(colors[0]), label=strup) #ax4.plot(timesq, processed_data1[3+nsites,:], marker="v", linestyle='--', color=str(colors[0]), label=strdwn) strup = "40 Steps"+r'$\uparrow$' strdwn = "40 Steps"+r'$\downarrow$' #ax4.plot(timesq, processed_data2[3,:], marker="^", color=str(colors[1]), label=strup) #ax4.plot(timesq, processed_data2[3+nsites,:], marker="v", linestyle='--', color=str(colors[1]), label=strdwn) strup = "150 Steps"+r'$\uparrow$' strdwn = "150 Steps"+r'$\downarrow$' ax4.plot(timesq, processed_data3[3,:], marker="^", color=str(colors[2]), label=strup) ax4.plot(timesq, processed_data3[3+nsites,:], marker="v", linestyle='--', color=str(colors[2]), label=strdwn) strup = "100 Steps"+r'$\uparrow$' strdwn = "100 Steps"+r'$\downarrow$' #ax4.plot(timesq, processed_data4[3,:], marker="^", color=str(colors[3]), label=strup) #ax4.plot(timesq, processed_data4[3+nsites,:], marker="v", linestyle='--', color=str(colors[3]), label=strdwn) #1e numerical evolution strup = "Exact"+r'$\uparrow$' strdwn = "Exact"+r'$\downarrow$' ax4.plot(times, evolution[:,3], linestyle='-', color='k', linewidth=2, label=strup) ax4.plot(times, evolution[:,3+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #2e+ numerical evolution #ax3.plot(times, mode_evolve[:,2], linestyle='-', color='k', linewidth=2, label=strup) #ax3.plot(times, mode_evolve[:,2+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #Site 5 strup = "10 Steps"+r'$\uparrow$' strdwn = "10 Steps"+r'$\downarrow$' ax5.plot(timesq, processed_data1[4,:], marker="^", color=str(colors[0]), label=strup) ax5.plot(timesq, processed_data1[4+nsites,:], marker="v", linestyle='--', color=str(colors[0]), label=strdwn) strup = "40 Steps"+r'$\uparrow$' strdwn = "40 Steps"+r'$\downarrow$' #ax5.plot(timesq, processed_data2[4,:], marker="^", color=str(colors[1]), label=strup) #ax5.plot(timesq, processed_data2[4+nsites,:], marker="v", linestyle='--', color=str(colors[1]), label=strdwn) strup = "150 Steps"+r'$\uparrow$' strdwn = "150 Steps"+r'$\downarrow$' ax5.plot(timesq, processed_data3[4,:], marker="^", color=str(colors[2]), label=strup) ax5.plot(timesq, processed_data3[4+nsites,:], marker="v", linestyle='--', color=str(colors[2]), label=strdwn) strup = "100 Steps"+r'$\uparrow$' strdwn = "100 Steps"+r'$\downarrow$' #ax5.plot(timesq, processed_data4[4,:], marker="^", color=str(colors[3]), label=strup) #ax5.plot(timesq, processed_data4[4+nsites,:], marker="v", linestyle='--', color=str(colors[3]), label=strdwn) #1e numerical evolution strup = "Exact"+r'$\uparrow$' strdwn = "Exact"+r'$\downarrow$' ax5.plot(times, evolution[:,4], linestyle='-', color='k', linewidth=2, label=strup) ax5.plot(times, evolution[:,4+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #2e+ numerical evolution #ax3.plot(times, mode_evolve[:,2], linestyle='-', color='k', linewidth=2, label=strup) #ax3.plot(times, mode_evolve[:,2+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) r''' #ax2.set_ylim(0, 0.55) #ax2.set_xlim(0, time_steps*dt+dt/2.) #ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2)) #ax2.set_yticks(np.arange(0,0.55, 0.05)) ax1.tick_params(labelsize=16) ax2.tick_params(labelsize=16) ax3.tick_params(labelsize=16) ax4.tick_params(labelsize=16) ax5.tick_params(labelsize=16) ax1.set_title(r"Time Evolution of Site 1: 1/sqrt(2)*000000 + (0.5-0.5i)*0100000", fontsize=22) ax2.set_title(r"Time Evolution of Site 2: 1/sqrt(2)*000000 + (0.5-0.5i)*0100000", fontsize=22) ax3.set_title(r"Time Evolution of Site 3: 1/sqrt(2)*000000 + (0.5-0.5i)*0100000", fontsize=22) ax4.set_title(r"Time Evolution of Site 4: 1/sqrt(2)*000000 + (0.5-0.5i)*0100000", fontsize=22) ax5.set_title(r"Time Evolution of Site 5: 1/sqrt(2)*000000 + (0.5-0.5i)*0100000", fontsize=22) ax1.set_xlabel('Time', fontsize=24) ax2.set_xlabel('Time', fontsize=24) ax3.set_xlabel('Time', fontsize=24) ax4.set_xlabel('Time', fontsize=24) ax5.set_xlabel('Time', fontsize=24) ax1.set_ylabel('Probability', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax3.set_ylabel('Probability', fontsize=24) ax4.set_ylabel('Probability', fontsize=24) ax5.set_ylabel('Probability', fontsize=24) ax1.legend(fontsize=20) ax2.legend(fontsize=20) ax3.legend(fontsize=20) ax4.legend(fontsize=20) ax5.legend(fontsize=20) #==== Cell to Implement Energy Measurement Functions ====# def sys_evolve(nsites, excitations, total_time, dt, hop, U, trotter_steps): #Check for correct data types of input if not isinstance(nsites, int): raise TypeError("Number of sites should be int") if np.isscalar(excitations): raise TypeError("Initial state should be list or numpy array") if not np.isscalar(total_time): raise TypeError("Evolution time should be scalar") if not np.isscalar(dt): raise TypeError("Time step should be scalar") if not isinstance(trotter_steps, int): raise TypeError("Number of trotter slices should be int") numq = 2*nsites num_steps = int(total_time/dt) print('Num Steps: ',num_steps) print('Total Time: ', total_time) data = np.zeros((2**numq, num_steps)) energies = np.zeros(num_steps) for t_step in range(0, num_steps): #Create circuit with t_step number of steps q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #=========USE THIS REGION TO SET YOUR INITIAL STATE============== #Loop over each excitation for flip in excitations: qcirc.x(flip) #=============================================================== qcirc.barrier() #Append circuit with Trotter steps needed hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps) #Measure the circuit for i in range(numq): qcirc.measure(i, i) #Choose provider and backend provider = IBMQ.get_provider() #backend = Aer.get_backend('statevector_simulator') backend = Aer.get_backend('qasm_simulator') #backend = provider.get_backend('ibmq_qasm_simulator') #backend = provider.get_backend('ibmqx4') #backend = provider.get_backend('ibmqx2') #backend = provider.get_backend('ibmq_16_melbourne') shots = 8192 max_credits = 10 #Max number of credits to spend on execution job_exp = execute(qcirc, backend=backend, shots=shots, max_credits=max_credits) #job_monitor(job_exp) result = job_exp.result() counts = result.get_counts(qcirc) #print(result.get_counts(qcirc)) print("Job: ",t_step+1, " of ", num_steps," computing energy...") #Store results in data array and normalize them for i in range(2**numq): if counts.get(get_bin(i,numq)) is None: dat = 0 else: dat = counts.get(get_bin(i,numq)) data[i,t_step] = dat/shots #======================================================= #Compute energy of system #Compute repulsion energies repulsion_energy = measure_repulsion(U, nsites, counts, shots) #Compute hopping energies #Get list of hopping pairs even_pairs = [] for i in range(0,nsites-1,2): #up_pair = [i, i+1] #dwn_pair = [i+nsites, i+nsites+1] even_pairs.append([i, i+1]) even_pairs.append([i+nsites, i+nsites+1]) odd_pairs = [] for i in range(1,nsites-1,2): odd_pairs.append([i, i+1]) odd_pairs.append([i+nsites, i+nsites+1]) #Start with even hoppings, initialize circuit and find hopping pairs q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #Loop over each excitation for flip in excitations: qcirc.x(flip) qcirc.barrier() #Append circuit with Trotter steps needed hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps) even_hopping = measure_hopping(hop, even_pairs, qcirc, numq) #=============================================================== #Now do the same for the odd hoppings #Start with even hoppings, initialize circuit and find hopping pairs q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #Loop over each excitation for flip in excitations: qcirc.x(flip) qcirc.barrier() #Append circuit with Trotter steps needed hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps) odd_hopping = measure_hopping(hop, odd_pairs, qcirc, numq) total_energy = repulsion_energy + even_hopping + odd_hopping energies[t_step] = total_energy print("Total Energy is: ", total_energy) print("Job: ",t_step+1, " of ", num_steps," complete") return data, energies #Measure the total repulsion from circuit run def measure_repulsion(U, num_sites, results, shots): repulsion = 0. #Figure out how to include different hoppings later for state in results: for i in range( int( len(state)/2 ) ): if state[i]=='1': if state[i+num_sites]=='1': repulsion += U*results.get(state)/shots return repulsion def measure_hopping(hopping, pairs, circuit, num_qubits): #Add diagonalizing circuit for pair in pairs: circuit.cnot(pair[0],pair[1]) circuit.ch(pair[1],pair[0]) circuit.cnot(pair[0],pair[1]) #circuit.measure(pair[0],pair[0]) #circuit.measure(pair[1],pair[1]) circuit.measure_all() #Run circuit backend = Aer.get_backend('qasm_simulator') shots = 8192 max_credits = 10 #Max number of credits to spend on execution #print("Computing Hopping") hop_exp = execute(circuit, backend=backend, shots=shots, max_credits=max_credits) job_monitor(hop_exp) result = hop_exp.result() counts = result.get_counts(circuit) #print(counts) #Compute energy #print(pairs) for pair in pairs: hop_eng = 0. #print('Pair is: ',pair) for state in counts: #print('State is: ',state,' Index at pair[0]: ',num_qubits-1-pair[0],' Val: ',state[num_qubits-pair[0]]) if state[num_qubits-1-pair[0]]=='1': prob_01 = counts.get(state)/shots #print('Check state is: ',state) for comp_state in counts: #print('Comp State is: ',state,' Index at pair[0]: ',num_qubits-1-pair[1],' Val: ',comp_state[num_qubits-pair[0]]) if comp_state[num_qubits-1-pair[1]]=='1': #print('Comp state is: ',comp_state) hop_eng += -hopping*(prob_01 - counts.get(comp_state)/shots) return hop_eng #Try by constructing the matrix and finding the eigenvalues N = 3 Nup = 2 Ndwn = N - Nup t = 1.0 U = 2. #Check if two states are different by a single hop def hop(psii, psij): #Check spin down hopp = 0 if psii[0]==psij[0]: #Create array of indices with nonzero values indi = np.nonzero(psii[1])[0] indj = np.nonzero(psij[1])[0] for i in range(len(indi)): if abs(indi[i]-indj[i])==1: hopp = -t return hopp #Check spin up if psii[1]==psij[1]: indi = np.nonzero(psii[0])[0] indj = np.nonzero(psij[0])[0] for i in range(len(indi)): if abs(indi[i]-indj[i])==1: hopp = -t return hopp return hopp #On-site terms def repel(l,state): if state[0][l]==1 and state[1][l]==1: return state else: return [] #States for 3 electrons with net spin up ''' states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]], [[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]], [[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ] ''' #States for 2 electrons in singlet state states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]], [[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]], [[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ] #''' #States for a single electron states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ] #''' H = np.zeros((len(states),len(states)) ) #Construct Hamiltonian matrix for i in range(len(states)): psi_i = states[i] for j in range(len(states)): psi_j = states[j] if j==i: for l in range(0,len(states[0][0])): if psi_i == repel(l,psi_j): H[i,j] = U break else: H[i,j] = hop(psi_i, psi_j) print(H) results = la.eig(H) print() for i in range(len(results[0])): print('Eigenvalue: ',results[0][i]) print('Eigenvector: \n',results[1][i]) print() dens_ops = [] eigs = [] for vec in results[1]: dens_ops.append(np.outer(results[1][i],results[1][i])) eigs.append(results[0][i]) print(dens_ops) #Loop/function to flip through states mode_list = [] num_sites = 3 print(len(states[0][0])) for i in range(0,2*num_sites): index_list = [] for state_index in range(0,len(states)): state = states[state_index] #print(state[0]) #print(state[1]) #Check spin-up modes if i < num_sites: if state[0][i]==1: index_list.append(state_index) #Check spin-down modes else: if state[1][i-num_sites]==1: index_list.append(state_index) if index_list: mode_list.append(index_list) print(mode_list) wfk0 = 1/np.sqrt(2)*results[1][0] - 1/np.sqrt(2)*results[1][2] print(np.dot(np.conj(wfk0), np.dot(H, wfk0))) dtc = 0.01 tsteps = 500 times = np.arange(0., tsteps*dtc, dtc) t_op = la.expm(-1j*H*dtc) #print(np.subtract(np.identity(len(H)), dt*H*1j)) #print(t_op) #wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.] #Half-filling initial state #wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state wfk = [0., 1., 0.] #1 electron initial state evolve = np.zeros([tsteps, len(wfk)]) energies = np.zeros(tsteps) mode_evolve = np.zeros([tsteps, 6]) mode_evolve = np.zeros([tsteps, len(mode_list)]) evolve[0] = wfk energies[0] = np.dot(np.conj(wfk), np.dot(H, wfk)) print(energies[0]) excitations = 3. #Loop to find occupation of each mode for i in range(0,len(mode_list)): wfk_sum = 0. for j in mode_list[i]: wfk_sum += evolve[0][j] mode_evolve[0][i] = wfk_sum / excitations print(mode_evolve) print('========================================================') #Figure out how to generalize this later ''' mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]) /2. mode_evolve[0][1] = (evolve[0][3]+evolve[0][4]+evolve[0][5]) /2. mode_evolve[0][2] = (evolve[0][6]+evolve[0][7]+evolve[0][8]) /2. mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /2. mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /2. mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /2. ''' ''' mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][3]+evolve[0][4]+evolve[0][5]) /3. mode_evolve[0][1] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3. mode_evolve[0][2] = (evolve[0][3]+evolve[0][4]+evolve[0][5]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3. mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /3. mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /3. mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /3. #''' #print(mode_evolve[0]) #Define density matrices print(mode_evolve) print() print() for t in range(1, tsteps): #t_op = la.expm(-1j*H*t*dtc) wfk = np.dot(t_op, wfk) evolve[t] = np.multiply(np.conj(wfk), wfk) energies[t] = np.dot(np.conj(wfk), np.dot(H, wfk)) norm = np.sum(evolve[t]) #print(evolve[t]) #Store data in modes rather than basis defined in 'states' variable ''' #Procedure for two electrons mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]) / (2) mode_evolve[t][1] = (evolve[t][3]+evolve[t][4]+evolve[t][5]) / (2) mode_evolve[t][2] = (evolve[t][6]+evolve[t][7]+evolve[t][8]) / (2) mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) / (2) mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) / (2) mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) / (2) #Procedure for half-filling mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][3]+evolve[t][4]+evolve[t][5]) /3. mode_evolve[t][1] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3. mode_evolve[t][2] = (evolve[t][3]+evolve[t][4]+evolve[t][5]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3. mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) /3. mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) /3. mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) /3. #''' #print(mode_evolve[t]) #print(np.linalg.norm(evolve[t])) #print(len(evolve[:,0]) ) #print(len(times)) #print(evolve[:,0]) #print(min(evolve[:,0])) print(energies) timesq = np.arange(0, time_steps*dt, dt) for i in range(nsites): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(timesq, processed_data[i,:], marker="^", color=str(colors[i]), label=strup) ax2.plot(timesq, processed_data[i+nsites,:], marker="v", color=str(colors[i]), label=strdwn) #ax2.set_ylim(0, 0.55) ax2.set_xlim(0, time_steps*dt+dt/2.) #ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2)) #ax2.set_yticks(np.arange(0,0.55, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20) #Process and plot data '''The procedure here is, for each fermionic mode, add the probability of every state containing that mode (at a given time step), and renormalize the data based on the total occupation of each mode. Afterwards, plot the data as a function of time step for each mode.''' def process_run(num_sites, time_steps, results): proc_data = np.zeros((2*num_sites, time_steps)) timesq = np.arange(0.,time_steps*dt, dt) #Sum over time steps for t in range(time_steps): #Sum over all possible states of computer for i in range(2**(2*num_sites)): #num = get_bin(i, 2*nsite) num = ''.join( list( reversed(hc.get_bin(i,2*nsites)) ) ) #For each state, check which mode(s) it contains and add them for mode in range(len(num)): if num[mode]=='1': proc_data[mode,t] += results[i,t] #Renormalize these sums so that the total occupation of the modes is 1 norm = 0.0 for mode in range(len(num)): norm += proc_data[mode,t] proc_data[:,t] = proc_data[:,t] / norm return proc_data ''' At this point, proc_data is a 2d array containing the occupation of each mode, for every time step ''' processed_data = process_run(nsites, time_steps, run_results) #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) for i in range(nsites): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(timesq, processed_data[i,:], marker="^", color=str(colors[i]), label=strup) ax2.plot(timesq, processed_data[i+nsites,:], marker="v", color=str(colors[i]), label=strdwn) #ax2.set_ylim(0, 0.55) ax2.set_xlim(0, time_steps*dt+dt/2.) #ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2)) #ax2.set_yticks(np.arange(0,0.55, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20)
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
from qiskit import * from qiskit.visualization import plot_histogram import numpy as np def NOT(inp): """An NOT gate. Parameters: inp (str): Input, encoded in qubit 0. Returns: QuantumCircuit: Output NOT circuit. str: Output value measured from qubit 0. """ qc = QuantumCircuit(1, 1) # A quantum circuit with a single qubit and a single classical bit qc.reset(0) # We encode '0' as the qubit state |0⟩, and '1' as |1⟩ # Since the qubit is initially |0⟩, we don't need to do anything for an input of '0' # For an input of '1', we do an x to rotate the |0⟩ to |1⟩ if inp=='1': qc.x(0) # barrier between input state and gate operation qc.barrier() # Now we've encoded the input, we can do a NOT on it using x qc.x(0) #barrier between gate operation and measurement qc.barrier() # Finally, we extract the |0⟩/|1⟩ output of the qubit and encode it in the bit c[0] qc.measure(0,0) qc.draw() # We'll run the program on a simulator backend = Aer.get_backend('qasm_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = backend.run(qc, shots=1, memory=True) output = job.result().get_memory()[0] return qc, output ## Test the function for inp in ['0', '1']: qc, out = NOT(inp) print('NOT with input',inp,'gives output',out) display(qc.draw()) print('\n') def XOR(inp1,inp2): """An XOR gate. Parameters: inpt1 (str): Input 1, encoded in qubit 0. inpt2 (str): Input 2, encoded in qubit 1. Returns: QuantumCircuit: Output XOR circuit. str: Output value measured from qubit 1. """ qc = QuantumCircuit(2, 1) qc.reset(range(2)) if inp1=='1': qc.x(0) if inp2=='1': qc.x(1) # barrier between input state and gate operation qc.barrier() # this is where your program for quantum XOR gate goes qc.cx(0, 1) # barrier between input state and gate operation qc.barrier() qc.measure(1,0) # output from qubit 1 is measured #We'll run the program on a simulator backend = Aer.get_backend('qasm_simulator') #Since the output will be deterministic, we can use just a single shot to get it job = backend.run(qc, shots=1, memory=True) output = job.result().get_memory()[0] return qc, output ## Test the function for inp1 in ['0', '1']: for inp2 in ['0', '1']: qc, output = XOR(inp1, inp2) print('XOR with inputs',inp1,inp2,'gives output',output) display(qc.draw()) print('\n') def AND(inp1,inp2): """An AND gate. Parameters: inpt1 (str): Input 1, encoded in qubit 0. inpt2 (str): Input 2, encoded in qubit 1. Returns: QuantumCircuit: Output XOR circuit. str: Output value measured from qubit 2. """ qc = QuantumCircuit(3, 1) qc.reset(range(2)) if inp1=='1': qc.x(0) if inp2=='1': qc.x(1) qc.barrier() # this is where your program for quantum AND gate goes qc.ccx(0,1,2) qc.barrier() qc.measure(2, 0) # output from qubit 2 is measured # We'll run the program on a simulator backend = Aer.get_backend('qasm_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = backend.run(qc, shots=1, memory=True) output = job.result().get_memory()[0] return qc, output ## Test the function for inp1 in ['0', '1']: for inp2 in ['0', '1']: qc, output = AND(inp1, inp2) print('AND with inputs',inp1,inp2,'gives output',output) display(qc.draw()) print('\n') def NAND(inp1,inp2): """An NAND gate. Parameters: inpt1 (str): Input 1, encoded in qubit 0. inpt2 (str): Input 2, encoded in qubit 1. Returns: QuantumCircuit: Output NAND circuit. str: Output value measured from qubit 2. """ qc = QuantumCircuit(3, 1) qc.reset(range(3)) if inp1=='1': qc.x(0) if inp2=='1': qc.x(1) qc.barrier() # this is where your program for quantum NAND gate goes qc.ccx(0,1,2) if inp=='1': qc.x(2) qc.barrier() qc.measure(2, 0) # output from qubit 2 is measured # We'll run the program on a simulator backend = Aer.get_backend('aer_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = backend.run(qc,shots=1,memory=True) output = job.result().get_memory()[0] return qc, output ## Test the function for inp1 in ['0', '1']: for inp2 in ['0', '1']: qc, output = NAND(inp1, inp2) print('NAND with inputs',inp1,inp2,'gives output',output) display(qc.draw()) print('\n') def OR(inp1,inp2): """An OR gate. Parameters: inpt1 (str): Input 1, encoded in qubit 0. inpt2 (str): Input 2, encoded in qubit 1. Returns: QuantumCircuit: Output XOR circuit. str: Output value measured from qubit 2. """ qc = QuantumCircuit(3, 1) qc.reset(range(3)) if inp1=='1': qc.x(0) if inp2=='1': qc.x(1) qc.barrier() # this is where your program for quantum OR gate goes qc.cx(0, 2) qc.cx(1, 2) qc.barrier() qc.measure(2, 0) # output from qubit 2 is measured # We'll run the program on a simulator backend = Aer.get_backend('aer_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = backend.run(qc,shots=1,memory=True) output = job.result().get_memory()[0] return qc, output ## Test the function for inp1 in ['0', '1']: for inp2 in ['0', '1']: qc, output = OR(inp1, inp2) print('OR with inputs',inp1,inp2,'gives output',output) display(qc.draw()) print('\n') from qiskit import IBMQ #IBMQ.save_account("a68a35747d4eccd1d58f275e637909987c789ce5c0edd8a4f43014672bf0301b54b28b1b5f44ba8ff87500777429e1e4ceb79621a6ba248d6cca6bca0e233d23", overwrite=True) IBMQ.load_account() IBMQ.providers() provider = IBMQ.get_provider('ibm-q') provider.backends() import qiskit.tools.jupyter # run this cell backend = provider.get_backend('ibmq_quito') qc_and = QuantumCircuit(3) qc_and.ccx(0,1,2) print('AND gate') display(qc_and.draw()) print('\n\nTranspiled AND gate with all the required connectivity') qc_and.decompose().draw() from qiskit.tools.monitor import job_monitor # run the cell to define AND gate for real quantum system def AND(inp1, inp2, backend, layout): qc = QuantumCircuit(3, 1) qc.reset(range(3)) if inp1=='1': qc.x(0) if inp2=='1': qc.x(1) qc.barrier() qc.ccx(0, 1, 2) qc.barrier() qc.measure(2, 0) qc_trans = transpile(qc, backend, initial_layout=layout, optimization_level=3) job = backend.run(qc_trans, shots=8192) print(job.job_id()) job_monitor(job) output = job.result().get_counts() return qc_trans, output backend layout = [0, 1, 2] output_all = [] qc_trans_all = [] prob_all = [] worst = 1 best = 0 for input1 in ['0','1']: for input2 in ['0','1']: qc_trans, output = AND(input1, input2, backend, layout) output_all.append(output) qc_trans_all.append(qc_trans) prob = output[str(int( input1=='1' and input2=='1' ))]/8192 prob_all.append(prob) print('\nProbability of correct answer for inputs',input1,input2) print('{:.2f}'.format(prob) ) print('---------------------------------') worst = min(worst,prob) best = max(best, prob) print('') print('\nThe highest of these probabilities was {:.2f}'.format(best)) print('The lowest of these probabilities was {:.2f}'.format(worst)) print('Transpiled AND gate circuit for ibmq_vigo with input 0 0') print('\nThe circuit depth : {}'.format (qc_trans_all[0].depth())) print('# of nonlocal gates : {}'.format (qc_trans_all[0].num_nonlocal_gates())) print('Probability of correct answer : {:.2f}'.format(prob_all[0]) ) qc_trans_all[0].draw() print('Transpiled AND gate circuit for ibmq_vigo with input 0 1') print('\nThe circuit depth : {}'.format (qc_trans_all[1].depth())) print('# of nonlocal gates : {}'.format (qc_trans_all[1].num_nonlocal_gates())) print('Probability of correct answer : {:.2f}'.format(prob_all[1]) ) qc_trans_all[1].draw() print('Transpiled AND gate circuit for ibmq_vigo with input 1 0') print('\nThe circuit depth : {}'.format (qc_trans_all[2].depth())) print('# of nonlocal gates : {}'.format (qc_trans_all[2].num_nonlocal_gates())) print('Probability of correct answer : {:.2f}'.format(prob_all[2]) ) qc_trans_all[2].draw() print('Transpiled AND gate circuit for ibmq_vigo with input 1 1') print('\nThe circuit depth : {}'.format (qc_trans_all[3].depth())) print('# of nonlocal gates : {}'.format (qc_trans_all[3].num_nonlocal_gates())) print('Probability of correct answer : {:.2f}'.format(prob_all[3]) ) qc_trans_all[3].draw()
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. """Test the LookaheadSwap pass""" import unittest from numpy import pi from qiskit.dagcircuit import DAGCircuit from qiskit.transpiler.passes import LookaheadSwap from qiskit.transpiler import CouplingMap, Target from qiskit.converters import circuit_to_dag from qiskit.circuit.library import CXGate from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeMelbourne class TestLookaheadSwap(QiskitTestCase): """Tests the LookaheadSwap pass.""" def test_lookahead_swap_doesnt_modify_mapped_circuit(self): """Test that lookahead swap is idempotent. It should not modify a circuit which is already compatible with the coupling map, and can be applied repeatedly without modifying the circuit. """ qr = QuantumRegister(3, name="q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[2]) circuit.cx(qr[0], qr[1]) original_dag = circuit_to_dag(circuit) # Create coupling map which contains all two-qubit gates in the circuit. coupling_map = CouplingMap([[0, 1], [0, 2]]) mapped_dag = LookaheadSwap(coupling_map).run(original_dag) self.assertEqual(original_dag, mapped_dag) remapped_dag = LookaheadSwap(coupling_map).run(mapped_dag) self.assertEqual(mapped_dag, remapped_dag) def test_lookahead_swap_should_add_a_single_swap(self): """Test that LookaheadSwap will insert a SWAP to match layout. For a single cx gate which is not available in the current layout, test that the mapper inserts a single swap to enable the gate. """ qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[2]) dag_circuit = circuit_to_dag(circuit) coupling_map = CouplingMap([[0, 1], [1, 2]]) mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit) self.assertEqual( mapped_dag.count_ops().get("swap", 0), dag_circuit.count_ops().get("swap", 0) + 1 ) def test_lookahead_swap_finds_minimal_swap_solution(self): """Of many valid SWAPs, test that LookaheadSwap finds the cheapest path. For a two CNOT circuit: cx q[0],q[2]; cx q[0],q[1] on the initial layout: qN -> qN (At least) two solutions exist: - SWAP q[0],[1], cx q[0],q[2], cx q[0],q[1] - SWAP q[1],[2], cx q[0],q[2], SWAP q[1],q[2], cx q[0],q[1] Verify that we find the first solution, as it requires fewer SWAPs. """ qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[2]) circuit.cx(qr[0], qr[1]) dag_circuit = circuit_to_dag(circuit) coupling_map = CouplingMap([[0, 1], [1, 2]]) mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit) self.assertEqual( mapped_dag.count_ops().get("swap", 0), dag_circuit.count_ops().get("swap", 0) + 1 ) def test_lookahead_swap_maps_measurements(self): """Verify measurement nodes are updated to map correct cregs to re-mapped qregs. Create a circuit with measures on q0 and q2, following a swap between q0 and q2. Since that swap is not in the coupling, one of the two will be required to move. Verify that the mapped measure corresponds to one of the two possible layouts following the swap. """ qr = QuantumRegister(3, "q") cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.cx(qr[0], qr[2]) circuit.measure(qr[0], cr[0]) circuit.measure(qr[2], cr[1]) dag_circuit = circuit_to_dag(circuit) coupling_map = CouplingMap([[0, 1], [1, 2]]) mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit) mapped_measure_qargs = {op.qargs[0] for op in mapped_dag.named_nodes("measure")} self.assertIn(mapped_measure_qargs, [{qr[0], qr[1]}, {qr[1], qr[2]}]) def test_lookahead_swap_maps_measurements_with_target(self): """Verify measurement nodes are updated to map correct cregs to re-mapped qregs. Create a circuit with measures on q0 and q2, following a swap between q0 and q2. Since that swap is not in the coupling, one of the two will be required to move. Verify that the mapped measure corresponds to one of the two possible layouts following the swap. """ qr = QuantumRegister(3, "q") cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.cx(qr[0], qr[2]) circuit.measure(qr[0], cr[0]) circuit.measure(qr[2], cr[1]) dag_circuit = circuit_to_dag(circuit) target = Target() target.add_instruction(CXGate(), {(0, 1): None, (1, 2): None}) mapped_dag = LookaheadSwap(target).run(dag_circuit) mapped_measure_qargs = {op.qargs[0] for op in mapped_dag.named_nodes("measure")} self.assertIn(mapped_measure_qargs, [{qr[0], qr[1]}, {qr[1], qr[2]}]) def test_lookahead_swap_maps_barriers(self): """Verify barrier nodes are updated to re-mapped qregs. Create a circuit with a barrier on q0 and q2, following a swap between q0 and q2. Since that swap is not in the coupling, one of the two will be required to move. Verify that the mapped barrier corresponds to one of the two possible layouts following the swap. """ qr = QuantumRegister(3, "q") cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.cx(qr[0], qr[2]) circuit.barrier(qr[0], qr[2]) dag_circuit = circuit_to_dag(circuit) coupling_map = CouplingMap([[0, 1], [1, 2]]) mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit) mapped_barrier_qargs = [set(op.qargs) for op in mapped_dag.named_nodes("barrier")][0] self.assertIn(mapped_barrier_qargs, [{qr[0], qr[1]}, {qr[1], qr[2]}]) def test_lookahead_swap_higher_depth_width_is_better(self): """Test that lookahead swap finds better circuit with increasing search space. Increasing the tree width and depth is expected to yield a better (or same) quality circuit, in the form of fewer SWAPs. """ # q_0: ──■───────────────────■───────────────────────────────────────────────» # ┌─┴─┐ │ ┌───┐ » # q_1: ┤ X ├──■──────────────┼─────────────────┤ X ├─────────────────────────» # └───┘┌─┴─┐ │ └─┬─┘┌───┐ ┌───┐ » # q_2: ─────┤ X ├──■─────────┼───────────────────┼──┤ X ├──────────┤ X ├──■──» # └───┘┌─┴─┐ ┌─┴─┐ │ └─┬─┘ ┌───┐└─┬─┘ │ » # q_3: ──────────┤ X ├──■──┤ X ├─────────────────┼────┼────■──┤ X ├──┼────┼──» # └───┘┌─┴─┐└───┘ ┌───┐ │ │ │ └─┬─┘ │ │ » # q_4: ───────────────┤ X ├──■────────────┤ X ├──┼────■────┼────┼────┼────┼──» # └───┘┌─┴─┐ └─┬─┘ │ │ │ │ │ » # q_5: ────────────────────┤ X ├──■─────────┼────┼─────────┼────■────┼────┼──» # └───┘┌─┴─┐ │ │ │ │ │ » # q_6: ─────────────────────────┤ X ├──■────■────┼─────────┼─────────■────┼──» # └───┘┌─┴─┐ │ ┌─┴─┐ ┌─┴─┐» # q_7: ──────────────────────────────┤ X ├───────■───────┤ X ├──────────┤ X ├» # └───┘ └───┘ └───┘» # «q_0: ──■─────── # « │ # «q_1: ──┼─────── # « │ # «q_2: ──┼─────── # « │ # «q_3: ──┼─────── # « │ # «q_4: ──┼─────── # « │ # «q_5: ──┼────■── # « ┌─┴─┐ │ # «q_6: ┤ X ├──┼── # « └───┘┌─┴─┐ # «q_7: ─────┤ X ├ # « └───┘ qr = QuantumRegister(8, name="q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[4], qr[5]) circuit.cx(qr[5], qr[6]) circuit.cx(qr[6], qr[7]) circuit.cx(qr[0], qr[3]) circuit.cx(qr[6], qr[4]) circuit.cx(qr[7], qr[1]) circuit.cx(qr[4], qr[2]) circuit.cx(qr[3], qr[7]) circuit.cx(qr[5], qr[3]) circuit.cx(qr[6], qr[2]) circuit.cx(qr[2], qr[7]) circuit.cx(qr[0], qr[6]) circuit.cx(qr[5], qr[7]) original_dag = circuit_to_dag(circuit) # Create a ring of 8 connected qubits coupling_map = CouplingMap.from_grid(num_rows=2, num_columns=4) mapped_dag_1 = LookaheadSwap(coupling_map, search_depth=3, search_width=3).run(original_dag) mapped_dag_2 = LookaheadSwap(coupling_map, search_depth=5, search_width=5).run(original_dag) num_swaps_1 = mapped_dag_1.count_ops().get("swap", 0) num_swaps_2 = mapped_dag_2.count_ops().get("swap", 0) self.assertLessEqual(num_swaps_2, num_swaps_1) def test_lookahead_swap_hang_in_min_case(self): """Verify LookaheadSwap does not stall in minimal case.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2171 qr = QuantumRegister(14, "q") qc = QuantumCircuit(qr) qc.cx(qr[0], qr[13]) qc.cx(qr[1], qr[13]) qc.cx(qr[1], qr[0]) qc.cx(qr[13], qr[1]) dag = circuit_to_dag(qc) cmap = CouplingMap(FakeMelbourne().configuration().coupling_map) out = LookaheadSwap(cmap, search_depth=4, search_width=4).run(dag) self.assertIsInstance(out, DAGCircuit) def test_lookahead_swap_hang_full_case(self): """Verify LookaheadSwap does not stall in reported case.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2171 qr = QuantumRegister(14, "q") qc = QuantumCircuit(qr) qc.cx(qr[0], qr[13]) qc.cx(qr[1], qr[13]) qc.cx(qr[1], qr[0]) qc.cx(qr[13], qr[1]) qc.cx(qr[6], qr[7]) qc.cx(qr[8], qr[7]) qc.cx(qr[8], qr[6]) qc.cx(qr[7], qr[8]) qc.cx(qr[0], qr[13]) qc.cx(qr[1], qr[0]) qc.cx(qr[13], qr[1]) qc.cx(qr[0], qr[1]) dag = circuit_to_dag(qc) cmap = CouplingMap(FakeMelbourne().configuration().coupling_map) out = LookaheadSwap(cmap, search_depth=4, search_width=4).run(dag) self.assertIsInstance(out, DAGCircuit) def test_global_phase_preservation(self): """Test that LookaheadSwap preserves global phase""" qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.global_phase = pi / 3 circuit.cx(qr[0], qr[2]) dag_circuit = circuit_to_dag(circuit) coupling_map = CouplingMap([[0, 1], [1, 2]]) mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit) self.assertEqual(mapped_dag.global_phase, circuit.global_phase) self.assertEqual( mapped_dag.count_ops().get("swap", 0), dag_circuit.count_ops().get("swap", 0) + 1 ) if __name__ == "__main__": unittest.main()
https://github.com/lvillasen/Introduccion-a-la-Computacion-Cuantica
lvillasen
!pip install numpy import numpy as np print(np.round(np.pi,4)) lista = [0,1,2,3,4,5] print(lista[1]) print(lista[0:-1]) for i in range(5): print("Hola mundo i=%d" %i) lista = [i for i in range(10)] lista import matplotlib.pyplot as plt plt.plot(lista) plt.draw() i = 10 while (i < 15): print(i,end=",") i = i + 1 def f(x): return 2*x f(3) a = np.array([1,3,5.31,2,-10.3]) print("El mínimo es %2.3f y el mínimo %2.3e" %(a.min(),a.max())) b=np.where(a<3) # da los índices donde se cumple la condición print(b) a = [1,3,5,2,0] for i in a: if i < 3 : print(i, " es < que 3") else: print(i, " es >= que 3") !pip install qiskit[machine-learning] !pip install pylatexenc # instalamos la librería *pylatexenc* para dibujar circuitos con matplotlib import qiskit qiskit.__qiskit_version__ from qiskit import QuantumCircuit, Aer import numpy as np import qiskit.quantum_info as qi qc = QuantumCircuit(4,4) # Ponemos 4 qubits y 4 bits # Aplicamos algunas compuertas qc.h(0) qc.y(1) qc.z(2) qc.h(3) stv = qi.Statevector.from_instruction(qc) # Ahora hacemos mediciones de cada qubit qc.measure(0,0) qc.measure(1,1) qc.measure(2,2) qc.measure(3,3) qc.draw(output='mpl') from qiskit import QuantumCircuit, Aer import numpy as np import qiskit.quantum_info as qi qc = QuantumCircuit(4,4) # Ponemos 4 qubits y 4 bits # Aplicamos algunas compuertas qc.h(0) qc.y(1) qc.z(2) qc.h(3) stv = qi.Statevector.from_instruction(qc) # Ahora hacemos mediciones de cada qubit qc.measure(0,0) qc.measure(1,1) qc.measure(2,2) qc.measure(3,3) style = {'backgroundcolor': 'lightgreen'} qc.draw(output='mpl', style=style) stv.draw('latex', prefix="|\\psi\\rangle =") from qiskit.visualization import plot_histogram backend = Aer.get_backend('qasm_simulator') job = backend.run(qc, shots=1000) print(job.result().get_counts()) plot_histogram(job.result().get_counts()) from qiskit import QuantumCircuit import qiskit.quantum_info as qi qc = QuantumCircuit(3,3) for qubit in range(3): qc.h(qubit) stv = qi.Statevector.from_instruction(qc) for qubit in range(3): qc.measure(qubit,qubit) qc.draw("mpl") stv.draw('latex', prefix="|\\psi\\rangle =") from qiskit.visualization import plot_histogram backend = Aer.get_backend('qasm_simulator') job = backend.run(qc, shots=1000) print(job.result().get_counts()) plot_histogram(job.result().get_counts()) from qiskit import QuantumCircuit, Aer import qiskit.quantum_info as qi qc = QuantumCircuit(1,1) qc.measure(0,0) qc.draw("mpl") from qiskit.visualization import plot_histogram backend = Aer.get_backend('qasm_simulator') job = backend.run(qc, shots=1000) print(job.result().get_counts()) plot_histogram(job.result().get_counts()) from qiskit import QuantumCircuit import qiskit.quantum_info as qi import numpy as np qc = QuantumCircuit(1,1) qc.ry(-np.pi/2,0) stv = qi.Statevector.from_instruction(qc) qc.measure(0,0) qc.draw("mpl") stv.draw('latex', prefix="|\\psi\\rangle =") from qiskit.visualization import plot_histogram backend = Aer.get_backend('qasm_simulator') job = backend.run(qc, shots=1000) print(job.result().get_counts()) plot_histogram(job.result().get_counts()) from qiskit import QuantumCircuit import qiskit.quantum_info as qi qc = QuantumCircuit(1,1) qc.ry(np.pi/2,0) stv = qi.Statevector.from_instruction(qc) qc.measure(0,0) qc.draw("mpl") stv.draw('latex', prefix="|\\psi\\rangle =") from qiskit.visualization import plot_bloch_multivector plot_bloch_multivector(stv) from qiskit.visualization import plot_histogram backend = Aer.get_backend('qasm_simulator') job = backend.run(qc, shots=471) print(job.result().get_counts()) plot_histogram(job.result().get_counts()) from qiskit import IBMQ #IBMQ.save_account('CLAVE', overwrite=True) from qiskit import IBMQ IBMQ.load_account() # Load account from disk print(IBMQ.providers()) # List all available providers provider = IBMQ.get_provider(hub='ibm-q') provider.backends() from qiskit import QuantumCircuit from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I import numpy as np psi = 1 / np.sqrt(2) * ((One ^ One^ One) + (Zero ^ Zero^ Zero)) qc=QuantumCircuit(3) qc.x(0) qc.x(1) qc.x(2) op=CircuitOp(qc) from IPython.display import display, Latex,Math display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|0>|0>+|1>|1>|1>)')) display(Latex(f'$<\psi|X\otimes X\otimes X|\psi>$')) print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1)) from qiskit import QuantumCircuit from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I import numpy as np psi = 1 / np.sqrt(2) * ((One ^ One^ One) + (Zero ^ Zero^ Zero)) op = X^X^X from IPython.display import display, Latex,Math display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|0>|0>+|1>|1>|1>)')) display(Latex(f'$<\psi|Op|\psi>$')) print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1)) from qiskit import QuantumCircuit from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I import numpy as np psi = Zero from IPython.display import display, Latex,Math display(Math('|\psi> = |0>')) display(Latex(f'$<\psi|XX|\psi>$')) print("=",np.round(psi.adjoint().compose(X).compose(X).compose(psi).eval().real,1)) display(Latex(f'$<\psi|YY|\psi>$')) print("=",np.round(psi.adjoint().compose(Y).compose(Y).compose(psi).eval().real,1)) display(Latex(f'$<\psi|YY|\psi>$')) print("=",np.round(psi.adjoint().compose(Z).compose(Z).compose(psi).eval().real,1)) from qiskit import QuantumCircuit from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I import numpy as np psi = One from IPython.display import display, Latex,Math display(Math('|\psi> = |1>')) display(Latex(f'$<\psi|XX|\psi>$')) print("=",np.round(psi.adjoint().compose(X).compose(X).compose(psi).eval().real,1)) display(Latex(f'$<\psi|YY|\psi>$')) print("=",np.round(psi.adjoint().compose(Y).compose(Y).compose(psi).eval().real,1)) display(Latex(f'$<\psi|YY|\psi>$')) print("=",np.round(psi.adjoint().compose(Z).compose(Z).compose(psi).eval().real,1)) from qiskit import QuantumCircuit from qiskit.quantum_info import SparsePauliOp from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I import numpy as np psi = 1 / np.sqrt(2) * ((One ^One ^ Zero^ Zero) - (Zero ^Zero ^ One^ One)) op1 = -0.8105479805373275 * I^I^I^I + 0.1721839326191556 * I^I^I^Z - 0.2257534922240239 * I^I^Z^I \ + 0.17218393261915554 * I^Z^I^I - 0.2257534922240239 * Z^I^I^I # Step 1: Define operator op = SparsePauliOp.from_list( [ ("IIII", -0.8105479805373275), ("IIIZ", + 0.1721839326191556), ("IIZI", - 0.2257534922240239), ("IZII", + 0.17218393261915554), ("ZIII", - 0.2257534922240239), ("IIZZ", + 0.12091263261776629), ("IZIZ", + 0.16892753870087907), ("YYYY", + 0.04523279994605784), ("XXYY", + 0.04523279994605784), ("YYXX", + 0.04523279994605784), ("XXXX", + 0.04523279994605784), ("ZIIZ", + 0.16614543256382414), ("IZZI", +0.16614543256382414), ("ZIZI", + 0.17464343068300445), ("ZIZI", + 0.12091263261776629), ] ) # Step 2: Define quantum state state = QuantumCircuit(4) state.h(0) state.h(1) state.x(2) from qiskit.primitives import Estimator estimator = Estimator() expectation_value = estimator.run(state, op).result().values # for shot-based simulation: expectation_value = estimator.run(state, op, shots=1000).result().values print("expectation: ", expectation_value) print("=",np.round(psi.adjoint().compose(op1).compose(psi).eval().real,16)) from qiskit import QuantumCircuit, Aer,execute import qiskit.quantum_info as qi qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits # Aplicamos algunas compuertas qc.h(0) # Hadamard gate qc.cx(0,1) # CNOT gate stv = qi.Statevector.from_instruction(qc) for qubit in range(2): qc.measure(qubit,qubit) qc.draw("mpl") stv.draw('latex', prefix="|\\psi\\rangle =") from qiskit.visualization import plot_histogram backend = Aer.get_backend('qasm_simulator') job = backend.run(qc, shots=1000) print(job.result().get_counts()) plot_histogram(job.result().get_counts()) from qiskit import QuantumCircuit, Aer,execute import qiskit.quantum_info as qi qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits qc.h(0) # Hadamard gate qc.cx(0,1) # CNOT gate qc.z(1) # NOT gate stv = qi.Statevector.from_instruction(qc) for qubit in range(2): qc.measure(qubit,qubit) qc.draw("mpl") stv.draw('latex', prefix="|\\psi\\rangle =") from qiskit.visualization import plot_histogram backend = Aer.get_backend('qasm_simulator') job = backend.run(qc, shots=1000) print(job.result().get_counts()) plot_histogram(job.result().get_counts()) from qiskit import QuantumCircuit, Aer,execute import qiskit.quantum_info as qi qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits qc.h(0) # Hadamard gate qc.cx(0,1) # CNOT gate qc.x(1) # NOT gate stv = qi.Statevector.from_instruction(qc) for qubit in range(2): qc.measure(qubit,qubit) qc.draw("mpl") stv.draw('latex', prefix="|\\psi\\rangle =") from qiskit.visualization import plot_histogram backend = Aer.get_backend('qasm_simulator') job = backend.run(qc, shots=1000) print(job.result().get_counts()) plot_histogram(job.result().get_counts()) from qiskit import QuantumCircuit, Aer,execute import qiskit.quantum_info as qi qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits qc.h(0) # Hadamard gate qc.cx(0,1) # CNOT gate qc.x(1) # NOT gate qc.z(1) # Z gate qc.barrier() stv = qi.Statevector.from_instruction(qc) for qubit in range(2): qc.measure(qubit,qubit) qc.draw("mpl") stv.draw('latex', prefix="|\\psi\\rangle =") from qiskit.visualization import plot_histogram backend = Aer.get_backend('qasm_simulator') job = backend.run(qc, shots=1000) print(job.result().get_counts()) plot_histogram(job.result().get_counts()) from qiskit import QuantumCircuit from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I import numpy as np from IPython.display import display, Latex,Math Op1 = X^X Op2 = Y^Y Op3 = Z^Z for j in range(4): if j == 0: psi = 1 / np.sqrt(2) * ((Zero^ Zero) + (One^ One)) display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|0>+|1>|1>)')) if j == 1: psi = 1 / np.sqrt(2) * ((Zero^ Zero) - (One^ One)) display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|0>-|1>|1>)')) if j == 2: psi = 1 / np.sqrt(2) * ((Zero^ One) + (One^ Zero)) display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|1>+|1>|0>)')) if j == 3: psi = 1 / np.sqrt(2) * ((Zero^ One) - (One^ Zero)) display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|1>-|1>|0>)')) display(Latex(f'$<\psi|2(X\otimes X+Y\otimes Y+Z\otimes Z)|\psi>$')) print("=",2*(np.round(psi.adjoint().compose(Op1).compose(psi).eval().real,1) +np.round(psi.adjoint().compose(Op2).compose(psi).eval().real,1)+ np.round(psi.adjoint().compose(Op3).compose(psi).eval().real,1)),"\n") from qiskit import QuantumCircuit, Aer,transpile import qiskit.quantum_info as qi qc = QuantumCircuit(3,3) # Ponemos 3 qubits y 3 bits # Aplicamos algunas compuertas qc.h(0) # Hadamard gate qc.cx(0,1) # CNOT gate qc.cx(1,2) # CNOT gate stv = qi.Statevector.from_instruction(qc) for qubit in range(3): qc.measure(qubit,qubit) qc.draw("mpl") stv.draw('latex', prefix="|\\psi\\rangle =") from qiskit.visualization import plot_histogram backend = Aer.get_backend('qasm_simulator') job = backend.run(qc, shots=1000) print(job.result().get_counts()) plot_histogram(job.result().get_counts()) from qiskit import IBMQ, transpile from qiskit import QuantumCircuit from qiskit_aer import AerSimulator from qiskit.tools.visualization import plot_histogram from qiskit.providers.ibmq import least_busy from qiskit import IBMQ, Aer from qiskit_aer.noise import NoiseModel #IBMQ.save_account('CLAVE', overwrite=True) provider = IBMQ.load_account() backend = provider.get_backend('ibmq_manila') noise_model = NoiseModel.from_backend(backend) print("----------Noise Model for",backend,"--------------\n",noise_model) backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) noise_model = NoiseModel.from_backend(backend) print("----------Noise Model for",backend,"--------------\n",noise_model) sim_backend = AerSimulator.from_backend(backend) print("least busy backend: ", sim_backend) # Transpile the circuit for the noisy basis gates tqc = transpile(qc, sim_backend,optimization_level=3) # Execute noisy simulation and get counts job = sim_backend.run(tqc,shots=1000) print("Counts for 3-qubit GHZ state with simulated noise model for", backend) plot_histogram(job.result().get_counts()) tqc.draw("mpl") from qiskit import QuantumCircuit, Aer,transpile import qiskit.quantum_info as qi qc = QuantumCircuit(3,3) # Ponemos 3 qubits y 3 bits # Aplicamos algunas compuertas qc.h(0) # Hadamard gate qc.cx(0,1) # CNOT gate qc.cx(1,2) # CNOT gate stv = qi.Statevector.from_instruction(qc) for qubit in range(3): qc.measure(qubit,qubit) qc.draw("mpl") from qiskit import IBMQ from qiskit.providers.ibmq import least_busy # Load local account information IBMQ.load_account() # Get the least busy backend provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit tqc = transpile(qc, backend, optimization_level=3) job = backend.run(tqc,shots = 100) from qiskit.providers.jobstatus import JobStatus print(job.status(),job.queue_position()) print("Counts for 3-qubit GHZ state with real computer", backend) plot_histogram(job.result().get_counts()) import numpy as np from qiskit.visualization import array_to_latex from qiskit.quantum_info import random_statevector psi = random_statevector(2) display(array_to_latex(psi, prefix="|\\psi\\rangle =")) from qiskit.visualization import plot_bloch_multivector plot_bloch_multivector(psi) from qiskit import QuantumCircuit, assemble, Aer import qiskit.quantum_info as qi import numpy as np import qiskit.quantum_info as qi qc = QuantumCircuit(3,2) qc.initialize(psi, 0) stv0 = qi.Statevector.from_instruction(qc) qc.barrier() qc.h(1) # Hadamard qc.cx(1,2) # CNOT qc.barrier() qc.cx(0,1) qc.h(0) qc.barrier() stv = qi.Statevector.from_instruction(qc) qc.measure(0,0) qc.measure(1,1) qc.draw("mpl") from qiskit.visualization import plot_bloch_multivector plot_bloch_multivector(stv0) stv.draw('latex', prefix='Estado \quad del \quad sistema \quad de \quad 3 \quad qubits \quad = \quad') from qiskit import QuantumCircuit, Aer,execute from qiskit.visualization import plot_histogram backend = Aer.get_backend('qasm_simulator') job = backend.run(qc, shots=1) print(job.result().get_counts(qc)) plot_histogram(job.result().get_counts()) import qiskit.quantum_info as qi import numpy as np qc1 = QuantumCircuit(3,2) print(job.result().get_counts()) for key in job.result().data()["counts"]: if int(key,0) == 0 : print("El resultado es 00") q2_state = [np.round(stv[0],3),np.round(stv[4],3)] qc1.initialize(0, 0) qc1.initialize(0, 1) elif int(key,0) == 1 : print("El resultado es 01") q2_state = [np.round(stv[1],3),np.round(stv[5],3)] qc1.initialize(1, 0) qc1.initialize(0, 1) elif int(key,0) == 2 : print("El resultado es 10") q2_state = [np.round(stv[2],3),np.round(stv[6],3)] qc1.initialize(0, 0) qc1.initialize(1, 1) elif int(key,0) == 3 : print("El resultado es 11") q2_state = [np.round(stv[3],3),np.round(stv[7],3)] qc1.initialize(1, 0) qc1.initialize(1, 1) q2_normalizado = q2_state/np.linalg.norm(q2_state) qc1.barrier() qc1.initialize(q2_normalizado, 2) for key in job.result().data()["counts"]: if int(key,0) == 1 : qc1.z(2) if int(key,0) == 2 : qc1.x(2) if int(key,0) == 3 : qc1.x(2) qc1.z(2) stv1 = qi.Statevector.from_instruction(qc1) stv1.draw('latex', prefix='Estado \quad del \quad qubit \quad 2 = ') from qiskit.visualization import plot_bloch_multivector plot_bloch_multivector(stv1) import qiskit.quantum_info as qi import numpy as np qc2 = QuantumCircuit(3,2) for key in job.result().data(qc)["counts"]: if int(key,0) != 0 : qc2.initialize(psi, 2) qcc = qc.compose(qc1) qc3 = qcc.compose(qc2) qc3.draw("mpl") from qiskit import QuantumCircuit, assemble, Aer from qiskit import IBMQ, transpile from qiskit.providers.ibmq import least_busy from qiskit.tools.visualization import plot_histogram import qiskit.quantum_info as qi import numpy as np import qiskit.quantum_info as qi theta=np.pi*np.random.rand() phi = 2*np.pi*np.random.rand() print("theta =",np.round(theta,2),"rad, theta =",np.round(180*theta/np.pi,2),"grados") print("phi=",np.round(phi,2),"rad, phi =",np.round(180*phi/np.pi,2),"grados") qc = QuantumCircuit(3,3) qc.ry(theta,0) qc.rz(phi,0) stv0 = qi.Statevector.from_instruction(qc) qc.barrier() qc.h(1) # Hadamard qc.cx(1,2) # CNOT qc.barrier() qc.cx(0,1) qc.h(0) qc.barrier() qc.rz(-phi,2) qc.ry(-theta,2) qc.measure(0,0) qc.measure(1,1) qc.measure(2,2) style = {'backgroundcolor': 'lightgreen'} qc.draw(output='mpl', style=style) from qiskit.visualization import plot_bloch_multivector plot_bloch_multivector(stv0) backend = Aer.get_backend('qasm_simulator') job = backend.run(qc, shots=1000) #print(job.result().get_counts(qc)) try : n_error = job.result().get_counts(qc)['100'] except: n_error = 0 import matplotlib.pyplot as plt fig = plt.figure(figsize=(10,6)) states = ['000', '100'] counts = [job.result().get_counts(qc)['000'],n_error] plt.rcParams.update({'font.size': 20}) plt.bar(states,counts,width=0.4, bottom=None,align='center', data=None) for index, value in enumerate(counts): plt.text(index, value, str(value),fontsize=20) plt.xlabel('States',fontsize=20) plt.ylabel('Counts',fontsize=20) plt.show() #plot_histogram(job.result().get_counts()) from qiskit_aer import AerSimulator IBMQ.load_account() # Get the least busy backend provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) sim_backend = AerSimulator.from_backend(backend) print("least busy backend: ", sim_backend,"\n\n") # Transpile the circuit for the noisy basis gates tqc = transpile(qc, sim_backend,optimization_level=3) # Execute noisy simulation and get counts job = sim_backend.run(tqc,shots=1000) try : n_error = job.result().get_counts(qc)['100'] except: n_error = 0 import matplotlib.pyplot as plt try : n_error = job.result().get_counts(qc)['100'] except: n_error = 0 import matplotlib.pyplot as plt fig = plt.figure(figsize=(10,6)) states = ['000', '100'] counts = [job.result().get_counts(qc)['000'],n_error] plt.rcParams.update({'font.size': 20}) plt.bar(states,counts,width=0.4, bottom=None,align='center', data=None) for index, value in enumerate(counts): plt.text(index, value, str(value),fontsize=20) plt.xlabel('States',fontsize=20) plt.ylabel('Counts',fontsize=20) plt.show() tqc.draw("mpl") from qiskit import QuantumCircuit, Aer,execute from qiskit.visualization import plot_histogram IBMQ.load_account() # Get the least busy backend provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) tqc = transpile(qc, backend, optimization_level=3) job_teleportation = backend.run(tqc,shots = 1000) print(job_teleportation.status(),job_teleportation.queue_position()) print(job_teleportation.result().get_counts(),"\n\n") import matplotlib.pyplot as plt fig = plt.figure(figsize=(10,8)) states = ['000', '100'] counts = [job.result().get_counts(qc)['000'],n_error] plt.rcParams.update({'font.size': 20}) plt.bar(states,counts,width=0.4, bottom=None,align='center', data=None) for index, value in enumerate(counts): plt.text(index, value, str(value),fontsize=20) plt.xlabel('States',fontsize=20) plt.ylabel('Counts',fontsize=20) plt.show() from qiskit import QuantumCircuit, Aer,execute import qiskit.quantum_info as qi import numpy as np qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits qc.h(0) qc.cx(0,1) qc.x(1) qc.z(1) qc.barrier() stv = qi.Statevector.from_instruction(qc) qc.draw("mpl") stv.draw('latex', prefix="|\\psi\\rangle =") backend = Aer.get_backend('qasm_simulator') N_corr = 0 N_anticorr = 0 qc3 = QuantumCircuit(2, 2) qc3.measure(0,0) qc3.measure(1,1) print(" Experimento A1B1") qc11=qc print(qc11) qc11=qc.compose(qc3) job11 = execute(qc11,backend, shots=1000) result = job11.result() print("Resultados :",result.get_counts(qc11)) if job11.result().get_counts().get('11') is not None: N_corr += job11.result().get_counts()['11'] if job11.result().get_counts().get('00') is not None: N_corr += job11.result().get_counts()['00'] N_anticorr += job11.result().get_counts()['01']+job11.result().get_counts()['10'] print() print(" Experimento A1B2") qc12 = QuantumCircuit(2, 2) qc12.rz(0,1) qc12.ry(-2*np.pi/3,1) qc12.barrier() qc12=qc.compose(qc12) qc12=qc12.compose(qc3) print(qc12) job12 = execute(qc12,backend, shots=1000) result = job12.result() print("Resultados :",result.get_counts(qc12)) N_corr += job12.result().get_counts()['11']+job12.result().get_counts()['00'] N_anticorr += job12.result().get_counts()['01']+job12.result().get_counts()['10'] print() print(" Experimento A1B3") qc13 = QuantumCircuit(2, 2) qc13.rz(-np.pi,1) qc13.ry(-2*np.pi/3,1) qc13.barrier() qc13=qc.compose(qc13) qc13=qc13.compose(qc3) print(qc13) job13 = execute(qc13,backend, shots=1000) result = job13.result() print("Resultados :",result.get_counts(qc13)) N_corr += job13.result().get_counts()['11']+job13.result().get_counts()['00'] N_anticorr += job13.result().get_counts()['01']+job13.result().get_counts()['10'] print() print(" Experimento A2B1") qc21 = QuantumCircuit(2, 2) qc21.rz(0,0) qc21.ry(-2*np.pi/3,0) qc21.barrier() qc21=qc.compose(qc21) qc21=qc21.compose(qc3) print(qc21) job21 = execute(qc21,backend, shots=1000) result = job21.result() print("Resultados :",result.get_counts(qc21)) N_corr += job21.result().get_counts()['11']+job21.result().get_counts()['00'] N_anticorr += job21.result().get_counts()['01']+job21.result().get_counts()['10'] print() print(" Experimento A2B2") qc22 = QuantumCircuit(2, 2) qc22.rz(0,0) qc22.ry(-2*np.pi/3,0) qc22.rz(0,1) qc22.ry(-2*np.pi/3,1) qc22.barrier() qc22=qc.compose(qc22) qc22=qc22.compose(qc3) print(qc22) job22 = execute(qc22,backend, shots=1000) result = job22.result() print("Resultados :",result.get_counts(qc22)) if job22.result().get_counts().get('11') is not None: N_corr += job22.result().get_counts()['11'] if job22.result().get_counts().get('00') is not None: N_corr += job22.result().get_counts()['00'] N_anticorr += job22.result().get_counts()['01']+job22.result().get_counts()['10'] print() print(" Experimento A2B3") qc23 = QuantumCircuit(2, 2) qc23.rz(0,0) qc23.ry(-2*np.pi/3,0) qc23.rz(-np.pi,1) qc23.ry(-2*np.pi/3,1) qc23.barrier() qc23=qc.compose(qc23) qc23=qc23.compose(qc3) print(qc23) job23 = execute(qc23,backend, shots=1000) result = job23.result() print("Resultados :",result.get_counts(qc23)) N_corr += job23.result().get_counts()['11']+job23.result().get_counts()['00'] N_anticorr += job23.result().get_counts()['01']+job23.result().get_counts()['10'] print() print(" Experimento A3B1") qc31 = QuantumCircuit(2, 2) qc31.rz(-np.pi,0) qc31.ry(-2*np.pi/3,0) qc31.barrier() qc31=qc.compose(qc31) qc31=qc31.compose(qc3) print(qc31) job31 = execute(qc31,backend, shots=1000) result = job31.result() print("Resultados :",result.get_counts(qc31)) N_corr += job31.result().get_counts()['11']+job31.result().get_counts()['00'] N_anticorr += job31.result().get_counts()['01']+job31.result().get_counts()['10'] print() print(" Experimento A3B2") qc32 = QuantumCircuit(2, 2) qc32.rz(-np.pi,0) qc32.ry(-2*np.pi/3,0) qc32.rz(0,1) qc32.ry(-2*np.pi/3,1) qc32.barrier() qc32=qc.compose(qc32) qc32=qc32.compose(qc3) print(qc32) job32 = execute(qc32,backend, shots=1000) result = job31.result() print("Resultados :",result.get_counts(qc32)) N_corr += job32.result().get_counts()['11']+job32.result().get_counts()['00'] N_anticorr += job32.result().get_counts()['01']+job32.result().get_counts()['10'] print() print(" Experimento A3B3") qc33 = QuantumCircuit(2, 2) qc33.rz(-np.pi,0) qc33.ry(-2*np.pi/3,0) qc33.rz(-np.pi,1) qc33.ry(-2*np.pi/3,1) qc33.barrier() qc33=qc.compose(qc33) qc33=qc33.compose(qc3) print(qc33) job33 = execute(qc33,backend, shots=1000) result = job33.result() print("Resultados :",result.get_counts(qc33)) if job33.result().get_counts().get('11') is not None: N_corr += job33.result().get_counts()['11'] if job33.result().get_counts().get('00') is not None: N_corr += job33.result().get_counts()['00'] N_anticorr += job33.result().get_counts()['01']+job33.result().get_counts()['10'] print("Total correlated:", N_corr, " Total anti-correlated:", N_anticorr) from qiskit import IBMQ, Aer from qiskit_aer.noise import NoiseModel IBMQ.save_account('your-IBMQ-password', overwrite=True) provider = IBMQ.load_account() backend = provider.get_backend('ibmq_manila') noise_model = NoiseModel.from_backend(backend) print("----------Noise Model for",backend,"--------------\n",noise_model) from qiskit import QuantumCircuit, Aer,execute from qiskit.visualization import plot_histogram IBMQ.load_account() # Get the least busy backend provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) print("----------Noise Model for",backend,"--------------\n",noise_model) from qiskit import QuantumCircuit, Aer import qiskit.quantum_info as qi import numpy as np qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits qc.h(0) qc.cx(0,1) qc.x(1) qc.z(1) qc.barrier() stv = qi.Statevector.from_instruction(qc) qc.draw("mpl") stv.draw('latex', prefix="|\\psi\\rangle =") backend = AerSimulator.from_backend(backend) shots = 1000 N_corr = 0 N_anticorr = 0 qc3 = QuantumCircuit(2, 2) qc3.measure(0,0) qc3.measure(1,1) print(" Experiment A1B1") qc11=qc qc11=qc.compose(qc3) print(qc11) tqc11 = transpile(qc11, backend, optimization_level=3) job11 = backend.run(tqc11,shots =shots) print("Results :",job11.result().get_counts()) if job11.result().get_counts().get('11') is not None: N_corr += job11.result().get_counts()['11'] if job11.result().get_counts().get('00') is not None: N_corr += job11.result().get_counts()['00'] N_anticorr += job11.result().get_counts()['01']+job11.result().get_counts()['10'] print("\n Experiment A1B2") qc12 = QuantumCircuit(2, 2) qc12.rz(0,1) qc12.ry(-2*np.pi/3,1) qc12.barrier() qc12=qc.compose(qc12) qc12=qc12.compose(qc3) print(qc12) tqc12 = transpile(qc12, backend, optimization_level=3) job12 = backend.run(tqc12,shots =shots) print("Results :",job12.result().get_counts()) N_corr += job12.result().get_counts()['11']+job12.result().get_counts()['00'] N_anticorr += job12.result().get_counts()['01']+job12.result().get_counts()['10'] print("\n Experiment A1B3") qc13 = QuantumCircuit(2, 2) qc13.rz(-np.pi,1) qc13.ry(-2*np.pi/3,1) qc13.barrier() qc13=qc.compose(qc13) qc13=qc13.compose(qc3) print(qc13) tqc13 = transpile(qc13, backend, optimization_level=3) job13 = backend.run(tqc13,shots =shots) print("Results :",job13.result().get_counts()) N_corr += job13.result().get_counts()['11']+job13.result().get_counts()['00'] N_anticorr += job13.result().get_counts()['01']+job13.result().get_counts()['10'] print("\n Experiment A2B1") qc21 = QuantumCircuit(2, 2) qc21.rz(0,0) qc21.ry(-2*np.pi/3,0) qc21.barrier() qc21=qc.compose(qc21) qc21=qc21.compose(qc3) print(qc21) tqc21 = transpile(qc21, backend, optimization_level=3) job21 = backend.run(tqc21,shots =shots) print("Results :",job21.result().get_counts()) N_corr += job21.result().get_counts()['11']+job21.result().get_counts()['00'] N_anticorr += job21.result().get_counts()['01']+job21.result().get_counts()['10'] print("\n Experiment A2B2") qc22 = QuantumCircuit(2, 2) qc22.rz(0,0) qc22.ry(-2*np.pi/3,0) qc22.rz(0,1) qc22.ry(-2*np.pi/3,1) qc22.barrier() qc22=qc.compose(qc22) qc22=qc22.compose(qc3) print(qc22) tqc22 = transpile(qc22, backend, optimization_level=3) job22 = backend.run(tqc22,shots =shots) print("Results :",job22.result().get_counts()) if job22.result().get_counts().get('11') is not None: N_corr += job22.result().get_counts()['11'] if job22.result().get_counts().get('00') is not None: N_corr += job22.result().get_counts()['00'] N_anticorr += job22.result().get_counts()['01']+job22.result().get_counts()['10'] print("\n Experiment A2B3") qc23 = QuantumCircuit(2, 2) qc23.rz(0,0) qc23.ry(-2*np.pi/3,0) qc23.rz(-np.pi,1) qc23.ry(-2*np.pi/3,1) qc23.barrier() qc23=qc.compose(qc23) qc23=qc23.compose(qc3) print(qc23) tqc23 = transpile(qc23, backend, optimization_level=3) job23 = backend.run(tqc23,shots =shots) print("Results :",job23.result().get_counts()) N_corr += job23.result().get_counts()['11']+job23.result().get_counts()['00'] N_anticorr += job23.result().get_counts()['01']+job23.result().get_counts()['10'] print("\n Experiment A3B1") qc31 = QuantumCircuit(2, 2) qc31.rz(-np.pi,0) qc31.ry(-2*np.pi/3,0) qc31.barrier() qc31=qc.compose(qc31) qc31=qc31.compose(qc3) print(qc31) tqc31 = transpile(qc31, backend, optimization_level=3) job31 = backend.run(tqc31,shots =shots) print("Results :",job31.result().get_counts()) N_corr += job31.result().get_counts()['11']+job31.result().get_counts()['00'] N_anticorr += job31.result().get_counts()['01']+job31.result().get_counts()['10'] print("\n Experiment A3B2") qc32 = QuantumCircuit(2, 2) qc32.rz(-np.pi,0) qc32.ry(-2*np.pi/3,0) qc32.rz(0,1) qc32.ry(-2*np.pi/3,1) qc32.barrier() qc32=qc.compose(qc32) qc32=qc32.compose(qc3) print(qc32) tqc32 = transpile(qc32, backend, optimization_level=3) job32 = backend.run(tqc32,shots =shots) print("Results :",job32.result().get_counts(qc32)) N_corr += job32.result().get_counts()['11']+job32.result().get_counts()['00'] N_anticorr += job32.result().get_counts()['01']+job32.result().get_counts()['10'] print("\n Experiment A3B3") qc33 = QuantumCircuit(2, 2) qc33.rz(-np.pi,0) qc33.ry(-2*np.pi/3,0) qc33.rz(-np.pi,1) qc33.ry(-2*np.pi/3,1) qc33.barrier() qc33=qc.compose(qc33) qc33=qc33.compose(qc3) print(qc33) tqc33 = transpile(qc33, backend, optimization_level=3) job33 = backend.run(tqc33,shots =shots) print("Results :",job33.result().get_counts(qc33)) if job33.result().get_counts().get('11') is not None: N_corr += job33.result().get_counts()['11'] if job33.result().get_counts().get('00') is not None: N_corr += job33.result().get_counts()['00'] N_anticorr += job33.result().get_counts()['01']+job33.result().get_counts()['10'] print("\nOut of a total of",9*shots,"measurements, we obtained") print("Total correlated measurements:", N_corr) print("Total anti-correlated measurements:", N_anticorr," corresponding to ",np.round(100*N_anticorr/(9*shots),2),"%") from qiskit import IBMQ, Aer from qiskit_aer.noise import NoiseModel IBMQ.save_account('your-IBMQ-password', overwrite=True) provider = IBMQ.load_account() backend = provider.get_backend('ibmq_manila') noise_model = NoiseModel.from_backend(backend) print("----------Noise Model for",backend,"--------------\n",noise_model) from qiskit import QuantumCircuit, Aer,execute from qiskit.visualization import plot_histogram IBMQ.load_account() # Get the least busy backend provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) print("----------Noise Model for",backend,"--------------\n",noise_model) from qiskit import QuantumCircuit, Aer import qiskit.quantum_info as qi import numpy as np qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits qc.h(0) qc.cx(0,1) qc.x(1) qc.z(1) qc.barrier() stv = qi.Statevector.from_instruction(qc) qc.draw("mpl") stv.draw('latex', prefix="|\\psi\\rangle =") shots = 1000 N_corr = 0 N_anticorr = 0 qc3 = QuantumCircuit(2, 2) qc3.measure(0,0) qc3.measure(1,1) print(" Experiment A1B1") qc11=qc qc11=qc.compose(qc3) print(qc11) tqc11 = transpile(qc11, backend, optimization_level=3) job11 = backend.run(tqc11,shots =shots) print("\n Experiment A1B2") qc12 = QuantumCircuit(2, 2) qc12.rz(0,1) qc12.ry(-2*np.pi/3,1) qc12.barrier() qc12=qc.compose(qc12) qc12=qc12.compose(qc3) print(qc12) tqc12 = transpile(qc12, backend, optimization_level=3) job12 = backend.run(tqc12,shots =shots) print("\n Experiment A1B3") qc13 = QuantumCircuit(2, 2) qc13.rz(-np.pi,1) qc13.ry(-2*np.pi/3,1) qc13.barrier() qc13=qc.compose(qc13) qc13=qc13.compose(qc3) print(qc13) tqc13 = transpile(qc13, backend, optimization_level=3) job13 = backend.run(tqc13,shots =shots) print("\n Experiment A2B1") qc21 = QuantumCircuit(2, 2) qc21.rz(0,0) qc21.ry(-2*np.pi/3,0) qc21.barrier() qc21=qc.compose(qc21) qc21=qc21.compose(qc3) print(qc21) tqc21 = transpile(qc21, backend, optimization_level=3) job21 = backend.run(tqc21,shots =shots) print("\n Experiment A2B2") qc22 = QuantumCircuit(2, 2) qc22.rz(0,0) qc22.ry(-2*np.pi/3,0) qc22.rz(0,1) qc22.ry(-2*np.pi/3,1) qc22.barrier() qc22=qc.compose(qc22) qc22=qc22.compose(qc3) print(qc22) tqc22 = transpile(qc22, backend, optimization_level=3) job22 = backend.run(tqc22,shots =shots) from qiskit.providers.jobstatus import JobStatus print(job11.status(),job11.queue_position()) print(job12.status(),job12.queue_position()) print(job13.status(),job13.queue_position()) print(job21.status(),job21.queue_position()) print(job22.status(),job22.queue_position()) print("\n Experiment A2B3") qc23 = QuantumCircuit(2, 2) qc23.rz(0,0) qc23.ry(-2*np.pi/3,0) qc23.rz(-np.pi,1) qc23.ry(-2*np.pi/3,1) qc23.barrier() qc23=qc.compose(qc23) qc23=qc23.compose(qc3) print(qc23) tqc23 = transpile(qc23, backend, optimization_level=3) job23 = backend.run(tqc23,shots =shots) print("\n Experiment A3B1") qc31 = QuantumCircuit(2, 2) qc31.rz(-np.pi,0) qc31.ry(-2*np.pi/3,0) qc31.barrier() qc31=qc.compose(qc31) qc31=qc31.compose(qc3) print(qc31) tqc31 = transpile(qc31, backend, optimization_level=3) job31 = backend.run(tqc31,shots =shots) print("\n Experiment A3B2") qc32 = QuantumCircuit(2, 2) qc32.rz(-np.pi,0) qc32.ry(-2*np.pi/3,0) qc32.rz(0,1) qc32.ry(-2*np.pi/3,1) qc32.barrier() qc32=qc.compose(qc32) qc32=qc32.compose(qc3) print(qc32) tqc32 = transpile(qc32, backend, optimization_level=3) job32 = backend.run(tqc32,shots =shots) print("\n Experiment A3B3") qc33 = QuantumCircuit(2, 2) qc33.rz(-np.pi,0) qc33.ry(-2*np.pi/3,0) qc33.rz(-np.pi,1) qc33.ry(-2*np.pi/3,1) qc33.barrier() qc33=qc.compose(qc33) qc33=qc33.compose(qc3) print(qc33) tqc33 = transpile(qc33, backend, optimization_level=3) job33 = backend.run(tqc33,shots =shots) print(job23.status(),job23.queue_position()) print(job31.status(),job31.queue_position()) print(job32.status(),job32.queue_position()) print(job33.status(),job33.queue_position()) N_corr = 0 N_anticorr = 0 print(" Experiment A1B1") print("Results :",job11.result().get_counts()) if job11.result().get_counts().get('11') is not None: N_corr += job11.result().get_counts()['11'] if job11.result().get_counts().get('00') is not None: N_corr += job11.result().get_counts()['00'] N_anticorr += job11.result().get_counts()['01']+job11.result().get_counts()['10'] print(" Experiment A1B2") print("Results :",job12.result().get_counts()) N_corr += job12.result().get_counts()['11'] N_corr += job12.result().get_counts()['00'] N_anticorr += job12.result().get_counts()['01']+job12.result().get_counts()['10'] print(" Experiment A1B3") print("Results :",job13.result().get_counts()) N_corr += job13.result().get_counts()['11'] N_corr += job13.result().get_counts()['00'] N_anticorr += job13.result().get_counts()['01']+job13.result().get_counts()['10'] print(" Experiment A2B1") print("Results :",job21.result().get_counts()) N_corr += job21.result().get_counts()['11'] N_corr += job21.result().get_counts()['00'] N_anticorr += job21.result().get_counts()['01']+job21.result().get_counts()['10'] print(" Experiment A2B2") print("Results :",job22.result().get_counts()) if job22.result().get_counts().get('11') is not None: N_corr += job22.result().get_counts()['11'] if job22.result().get_counts().get('00') is not None: N_corr += job22.result().get_counts()['00'] N_anticorr += job22.result().get_counts()['01']+job22.result().get_counts()['10'] print(" Experiment A2B3") print("Results :",job23.result().get_counts()) N_corr += job23.result().get_counts()['11'] N_corr += job23.result().get_counts()['00'] N_anticorr += job23.result().get_counts()['01']+job23.result().get_counts()['10'] print(" Experiment A3B1") print("Results :",job31.result().get_counts()) N_corr += job31.result().get_counts()['11'] N_corr += job31.result().get_counts()['00'] N_anticorr += job31.result().get_counts()['01']+job31.result().get_counts()['10'] print(" Experiment A3B2") print("Results :",job32.result().get_counts()) N_corr += job32.result().get_counts()['11'] N_corr += job32.result().get_counts()['00'] N_anticorr += job32.result().get_counts()['01']+job32.result().get_counts()['10'] print(" Experiment A3B3") print("Results :",job33.result().get_counts()) if job33.result().get_counts().get('11') is not None: N_corr += job33.result().get_counts()['11'] if job33.result().get_counts().get('00') is not None: N_corr += job33.result().get_counts()['00'] N_anticorr += job33.result().get_counts()['01']+job33.result().get_counts()['10'] print("\nOut of a total of",9*shots,"measurements, we obtained") print("Total correlated measurements:", N_corr) print("Total anti-correlated measurements:", N_anticorr," corresponding to ",np.round(100*N_anticorr/(9*shots),2),"%") from qiskit.visualization import plot_histogram backend = Aer.get_backend('qasm_simulator') job = execute(qc,backend, shots=1000) result = job.result() print(result.get_counts(qc)) plot_histogram(result.get_counts(qc)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright from qiskit import QuantumCircuit, Aer,execute import numpy as np import qiskit.quantum_info as qi qc = QuantumCircuit(1,1) # Ponemos 1 qubit y 1 bit psi = [np.cos(2*np.pi/3/2),np.sin(2*np.pi/3/2)] qc.initialize(psi, 0) stv = qi.Statevector.from_instruction(qc) stv.draw('latex', prefix="|\\psi\\rangle =") qc.measure(0,0) qc.draw(output='mpl') from qiskit.visualization import plot_bloch_multivector plot_bloch_multivector(psi) from qiskit.visualization import plot_histogram backend = Aer.get_backend('qasm_simulator') n_shots = 1000 job = execute(qc,backend, shots=n_shots, memory=True) result = job.result() print(result.get_counts(qc)) plot_histogram(result.get_counts(qc)) Data =result.get_memory() np.array(list(map(int, Data))) print(np.array(list(map(int, Data)))) print("Suma de 1s =",sum(np.array(list(map(int, Data)))),"Suma de 0s =",n_shots-sum(np.array(list(map(int, Data))))) from qiskit import QuantumCircuit, Aer,execute import qiskit.quantum_info as qi qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits # Aplicamos algunas compuertas qc.h(0) # Hadamard gate qc.cx(0,1) # CNOT gate stv = qi.Statevector.from_instruction(qc) for qubit in range(2): qc.measure(qubit,qubit) qc.draw("mpl") from qiskit import QuantumCircuit, Aer,execute import qiskit.quantum_info as qi qc = QuantumCircuit(3,3) # Ponemos 3 qubits y 3 bits # Aplicamos algunas compuertas qc.h(0) # Hadamard gate qc.cx(0,1) # CNOT gate qc.cx(1,2) # CNOT gate stv = qi.Statevector.from_instruction(qc) for qubit in range(3): qc.measure(qubit,qubit) qc.draw("mpl") from qiskit import QuantumCircuit from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I import numpy as np psi = 1 / np.sqrt(2) * ((One ^ One^ One) + (Zero ^ Zero^ Zero)) op = X^Y^Y +X^X^X from IPython.display import display, Latex,Math display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|0>|0>+|1>|1>|1>)')) display(Latex(f'$<\psi|Op|\psi>$')) print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1)) import numpy as np from qiskit.opflow import Z, X,Y,I, Zero, One #operator = (X+X)** +(Y+Y)**2 +(Z+Z)**2 operator = X psi = 1 / np.sqrt(2) * ((Zero + One)) expectation_value = (~psi @ operator @ psi).eval() print(expectation_value.real) psi = 1 / np.sqrt(2) * ((Zero - One)) expectation_value = (psi.adjoint() @ operator @ psi).eval() print(expectation_value.real) # Para más detalles ver https://arxiv.org/pdf/2206.14584.pdf import numpy as np from qiskit.opflow import Z, X,Y,I, Zero, One operator = np.sin(2*np.pi/3)*X^Z+np.cos(2*np.pi/3)*Z^Z psi = 1 / np.sqrt(2) * ((Zero ^ One) - (One ^ Zero)) expectation_value = (psi.adjoint() @ operator @ psi).eval() print(expectation_value.real) # Para más detalles ver https://arxiv.org/pdf/2206.14584.pdf from qiskit import QuantumCircuit, assemble, Aer import qiskit.quantum_info as qi import numpy as np import qiskit.quantum_info as qi qc = QuantumCircuit(3,2) qc.initialize([1/np.sqrt(2),1/np.sqrt(2)], 0) stv0 = qi.Statevector.from_instruction(qc) qc.barrier() qc.h(1) # Hadamard qc.cx(1,2) # CNOT qc.barrier() qc.cx(0,1) qc.h(0) qc.barrier() stv = qi.Statevector.from_instruction(qc) qc.measure(0,0) qc.measure(1,1) qc.draw("mpl") from qiskit import QuantumCircuit, Aer,execute from qiskit.visualization import plot_histogram backend = Aer.get_backend('qasm_simulator') job = execute(qc,backend, shots=1) result = job.result() print(result.get_counts(qc)) plot_histogram(result.get_counts(qc)) from qiskit.opflow import CircuitStateFn import qiskit.quantum_info as qi import numpy as np psi=QuantumCircuit(3) psi.h(0) # Hadamard gate psi.cx(0,1) # CNOT gate psi.cx(1,2) # CNOT gate stv0 = qi.Statevector.from_instruction(psi) psi=CircuitStateFn(psi) stv0.draw('latex', prefix="|\\psi\\rangle =") from qiskit import QuantumCircuit from qiskit.opflow import CircuitOp qc=QuantumCircuit(3) qc.x(0) qc.x(1) qc.x(2) op=CircuitOp(qc) from IPython.display import display, Latex display(Latex(f'$<\psi|X\otimes X\otimes X|\psi>$')) print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1)) from qiskit import QuantumCircuit from qiskit.opflow import CircuitOp qc=QuantumCircuit(3) qc.x(0) qc.x(1) qc.x(2) op=CircuitOp(qc) from IPython.display import display, Latex display(Latex(f'$<\psi|X\otimes X\otimes X|\psi>$')) print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1)) from qiskit import QuantumCircuit from qiskit.opflow import CircuitOp qc=QuantumCircuit(3) qc.y(0) qc.y(1) qc.x(2) op=CircuitOp(qc) from IPython.display import display, Latex display(Latex(f'$<\psi|X\otimes Y\otimes Y|\psi>$')) print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1)) from qiskit import QuantumCircuit from qiskit.opflow import CircuitOp qc=QuantumCircuit(3) qc.y(0) qc.x(1) qc.y(2) op=CircuitOp(qc) from IPython.display import display, Latex display(Latex(f'$<\psi|Y\otimes X\otimes Y|\psi>$')) print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1)) from qiskit import QuantumCircuit from qiskit.opflow import CircuitOp qc=QuantumCircuit(3) qc.x(0) qc.y(1) qc.y(2) op=CircuitOp(qc) from IPython.display import display, Latex display(Latex(f'$<\psi|Y\otimes Y\otimes X|\psi>$')) print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1)) from qiskit import QuantumCircuit from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I import numpy as np psi = 1 / np.sqrt(2) * ((One ^ One^ One) + (Zero ^ Zero^ Zero)) op = X^X^X from IPython.display import display, Latex,Math display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|0>|0>+|1>|1>|1>)')) for i in range(4): if i==0: Op = X^X^X if i==1: Op = X^Y^Y if i==2: Op = Y^X^Y if i==3: Op = Y^Y^X print("\nOp =",Op) display(Latex(f'$<\psi|Op|\psi>$')) print("=",np.round(psi.adjoint().compose(Op).compose(psi).eval().real,1)) # Código tomado de https://github.com/lvillasen/Euclidean-Algorithm def f(i,N1,N2,n1,n2,c1,c2): n3=n1%n2 e3 = n1//n2 c3 = c1 -e3*c2 print("\t\t",n3,"= ",n1,"-",e3,"*",n2," (mod N1)") print("(",i,")\t",n3,"= ",c3,"*",N2," (mod N1)") return N1,N2,n2,n3,c2,c3 # Input the two integers here (N1 >N2) N1 = 51 N2 = 13 n1,n2,c1,c2 = N1,N2,0,1 print("( 1 )\t",N1,"= 0 (mod",N1,")") print("( 2 )\t",N2,"= ",N2," (mod",N1,")") i=3 while n2>1: N1,N2,n1,n2,c1,c2 = f(i,N1,N2,n1,n2,c1,c2) i+=1 if n2 == 0: print("\nThe greatest common divisor (GCD) of ",N1, " and " ,N2," is ",n1) if n2 == 1: print("\nThe inverse multiplicative of ",N2, " (mod ",N1,") is ",c2%N1,sep='') print("i.e., ",N2, " * ",c2%N1, " = 1 (mod ",N1,")" ,sep='') print("\nGCD(",N1, "," ,N2,") = ",n2) p =3490529510847650949147849619903898133417764638493387843990820577 q = 32769132993266709549961988190834461413177642967992942539798288533 N = p*q y = 200805001301070903002315180419000118050019172105011309190800151919090618010705 # Código tomado de https://github.com/lvillasen/Euclidean-Algorithm def f(i,N1,N2,n1,n2,c1,c2): n3=n1%n2 e3 = n1//n2 c3 = c1 -e3*c2 print("\t\t",n3,"= ",n1,"-",e3,"*",n2," (mod N1)") print("(",i,")\t",n3,"= ",c3,"*",N2," (mod N1)") return N1,N2,n2,n3,c2,c3 # Input the two integers here (N1 >N2) N1 = (p-1)*(q-1) N2 = 9007 n1,n2,c1,c2 = N1,N2,0,1 print("( 1 )\t",N1,"= 0 (mod",N1,")") print("( 2 )\t",N2,"= ",N2," (mod",N1,")") i=3 while n2>1: N1,N2,n1,n2,c1,c2 = f(i,N1,N2,n1,n2,c1,c2) i+=1 if n2 == 0: print("\nThe greatest common divisor (GCD) of ",N1, " and " ,N2," is ",n1) if n2 == 1: print("\nThe inverse multiplicative of ",N2, " (mod ",N1,") is ",c2%N1,sep='') print("i.e., ",N2, " * ",c2%N1, " = 1 (mod ",N1,")" ,sep='') # Código tomado de https://github.com/jacksoninfosec/youtube-videos/blob/master/modular_exp.py # https://www.youtube.com/watch?v=3Bh7ztqBpmw def mod_power(a, n, m): r = 1 while n > 0: if n & 1 == 1: r = (r * a) % m a = (a * a) % m n >>= 1 return r p =3490529510847650949147849619903898133417764638493387843990820577 q = 32769132993266709549961988190834461413177642967992942539798288533 N = p*q y = 96869613754622061477140922254355882905759991124574319874695120930816298225145708356931476622883989628013391990551829945157815154 d = 106698614368578024442868771328920154780709906633937862801226224496631063125911774470873340168597462306553968544513277109053606095 m = mod_power(y, d, N) print("m=",m) s = str(m) list =" ABCDEFGHIJKLMNOPQRSTUVWXYZ" for i in range(len(s)//2): print(s[2*i:2*i+2],end =" ") print() list =" ABCDEFGHIJKLMNOPQRSTUVWXYZ" for i in range(len(s)//2): print(list[int(s[2*i:2*i+2])],end =" ") p = 1000003 q = 1000291 N = p*q a =2 def f(i,N1,N2,n1,n2,c1,c2): n3=n1%n2 e3 = n1//n2 c3 = c1 -e3*c2 print("\t\t",n3,"= ",n1,"-",e3,"*",n2," (mod N1)") print("(",i,")\t",n3,"= ",c3,"*",N2," (mod N1)") return N1,N2,n2,n3,c2,c3 # Input the two integers here (N1 >N2) N1 = N N2 = a n1,n2,c1,c2 = N1,N2,0,1 print("( 1 )\t",N1,"= 0 (mod",N1,")") print("( 2 )\t",N2,"= ",N2," (mod",N1,")") i=3 while n2>1: N1,N2,n1,n2,c1,c2 = f(i,N1,N2,n1,n2,c1,c2) i+=1 if n2 == 0: print("\nThe greatest common divisor (GCD) of ",N1, " and " ,N2," is ",n1) if n2 == 1: print("\nThe inverse multiplicative of ",N2, " (mod ",N1,") is ",c2%N1,sep='') print("i.e., ",N2, " * ",c2%N1, " = 1 (mod ",N1,")" ,sep='') print("\n",N2, " y ",N1," son coprimos ") import numpy as np def mod_power(a, n, m): r = 1 while n > 0: if n & 1 == 1: r = (r * a) % m a = (a * a) % m n >>= 1 return r a=2 a = 3 p = 1000003 p=347# 1931 , 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999 q = 307 #, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, #p=61 q = 1931 p= 1933 N = p*q N = 15 a=4 print("N =",N,"a =",a," MCD(a,N)=",np.gcd(a,N)) #dat = [a**i % N for i in range(100)] i=2 while (mod_power(a, i, N)) > 1: #while (a**i % N) > 1: i += 2 r = i print("Periodo = ",r) dat = [a**i % N for i in range(3*r)] import matplotlib.pyplot as plt fig = plt.figure(figsize=(8, 8)) plt.plot(dat,'-*b') plt.grid() plt.draw() p= 122949829 q = 141650939 N = p*q i=3 while (N %i != 0): i += 2 print("Factores : ",i,N//i) import numpy as np print("Los factores primos son:",np.gcd(a**(r//2) +1,N),np.gcd(a**(r//2) -1,N)) import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from IPython.display import HTML def x(t): return 1+2*np.cos(2*np.pi*5*t)+3*np.sin(2*np.pi*7*t) T = 1 sr = 40 ts = np.linspace(0, T, sr*T) t = np.linspace(0, T, 1000) Corr_cos=np.zeros((sr*T)) Corr_sen=np.zeros((sr*T)) N=np.arange(0, sr*T) def Grafica(n): ax[0].clear() ax[1].clear() frec = n/T Corr_cos[n] = np.dot(x(ts),np.cos(-2*np.pi*n*ts/T)) Corr_sen[n] = np.dot(x(ts),np.sin(-2*np.pi*n*ts/T)) ax[0].plot(t, x(t),'b') ax[0].plot(t, np.cos(2*np.pi*n*t/T),'r') ax[0].plot(t, np.sin(2*np.pi*n*t/T),'g') ax[0].plot(ts, x(ts),'.b',ms=10) ax[0].plot(ts, np.cos(2*np.pi*n*ts/T),'.r',ms=10) ax[0].plot(ts, np.sin(2*np.pi*n*ts/T),'.g',ms=10) #ax[1].title('Frecuencia Señal de Correlación = {}'.format(frec)+ ' Hz, GS'+'= {}'.format(np.round(GS,1)), fontsize=18) ax[0].set_xlabel('t', fontsize=18) ax[0].set_ylabel('x(t)', fontsize=18) ax[0].grid() ax[1].plot(N, Corr_cos,'-r',ms=10,label='Corr Cos para k={}'.format(n)) ax[1].plot(N, Corr_sen,'-.g',ms=10,label='Corr Sen para k={}'.format(n)) #ax[2].title('Frecuencia Señal de Correlación = {}'.format(frec)+ ' Hz, GS'+'= {}'.format(np.round(GS,1)), fontsize=18) ax[1].set_xlabel('k', fontsize=18) ax[1].set_ylabel(r'$X_k$', fontsize=18) ax[1].grid() ax[1].legend() fig=plt.figure(figsize=(10,6), dpi= 100) ax= fig.subplots(2,1) anim = animation.FuncAnimation(fig, Grafica, frames=40 , interval=800) plt.close() HTML(anim.to_html5_video()) from qiskit.circuit import Gate U_f = Gate(name='U_f', num_qubits=2, params=[]) import qiskit as qk qr = qk.QuantumRegister(2) cr = qk.ClassicalRegister(2) qc = qk.QuantumCircuit(qr,cr) from qiskit import * qc = QuantumCircuit(8, 8) for q in range(4): qc.h(q) # And auxiliary register in state |1> qc.append(U_f [qr[0], qr[1]]) qc.barrier() qc.measure(range(4), range(4)) style = {'backgroundcolor': 'lightgreen'} qc.draw('mpl',fold=-1,style=style) # -1 means 'do not fold' import matplotlib.pyplot as plt import numpy as np from qiskit import QuantumCircuit, Aer, transpile, assemble from qiskit.visualization import plot_histogram import qiskit.quantum_info as qi from math import gcd from numpy.random import randint from fractions import Fraction print("Imports Successful") import qiskit.quantum_info as qi qc = QuantumCircuit(4,4) # Ponemos 4 qubits y 4 bits # Aplicamos algunas compuertas qc.x(0) qc.y(1) qc.z(2) qc.h(3) stv = qi.Statevector.from_instruction(qc) ## Create 7mod15 gate N = 15 m = int(np.ceil(np.log2(N))) import qiskit.quantum_info as qi U_qc = QuantumCircuit(m) #U_qc.x(0) U_qc.initialize('0010') U_qc.swap(0, 1) U_qc.swap(1, 2) U_qc.swap(2, 3) for q in range(4): U_qc.x(q) #U = U_qc.to_gate() stv = qi.Statevector.from_instruction(U_qc) #U.name ='{}Mod{}'.format(7, N) U_qc.draw('mpl',fold=-1,style=style) stv.draw('latex', prefix="|\\psi\\rangle =") def c_amod15(a, power): """Controlled multiplication by a mod 15""" if a not in [2,4,7,8,11,13]: raise ValueError("'a' must be 2,4,7,8,11 or 13") U = QuantumCircuit(4) for iteration in range(power): if a in [2,13]: U.swap(2,3) U.swap(1,2) U.swap(0,1) if a in [7,8]: U.swap(0,1) U.swap(1,2) U.swap(2,3) if a in [4, 11]: U.swap(1,3) U.swap(0,2) if a in [7,11,13]: for q in range(4): U.x(q) U = U.to_gate() U.name = "%i^%i mod 15" % (a, power) c_U = U.control() return c_U # Specify variables n_count = 8 # number of counting qubits a = 7 def qft_dagger(n): """n-qubit QFTdagger the first n qubits in circ""" qc = QuantumCircuit(n) # 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(-np.pi/float(2**(j-m)), m, j) qc.h(j) qc.name = "QFT†" return qc # Create QuantumCircuit with n_count counting qubits # plus 4 qubits for U to act on qc = QuantumCircuit(n_count + 4, n_count+ 4) # Initialize counting qubits # in state |+> for q in range(n_count): qc.h(q) # And auxiliary register in state |1> qc.x(n_count) qc.barrier() stv1 = qi.Statevector.from_instruction(qc) # Do controlled-U operations for q in range(n_count): qc.append(c_amod15(a, 2**q), [q] + [i+n_count for i in range(4)]) qc.barrier() stv2 = qi.Statevector.from_instruction(qc) #for qubit in range(8,12): # qc.measure(qubit,qubit) qc.barrier() # Do inverse-QFT qc.append(qft_dagger(n_count), range(n_count)) # Measure circuit qc.measure(range(n_count), range(n_count)) style = {'backgroundcolor': 'lightgreen'} qc.draw('mpl',fold=-1,style=style) # -1 means 'do not fold' stv1.draw('latex', prefix="|\\psi\\rangle =") stv2.draw('latex', prefix="|\\psi\\rangle =") aer_sim = Aer.get_backend('aer_simulator') t_qc = transpile(qc, aer_sim) qobj = assemble(t_qc) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) import cmath a = 2 def suma(i): b=0 for a in range(86): b+= cmath.exp(-2*np.pi*1j*6*i*a/512) return abs(b)**2 dat = [suma(i) for i in range(512)] probability = np.array(dat)/512/86 import plotly.express as px fig=px.line(probability,markers=True) fig.show() import numpy as np a=2 N=21 r=6 print("Los factores primos son:",np.gcd(a**(r//2) +1,N),np.gcd(a**(r//2) -1,N)) # Importing everything from qiskit import QuantumCircuit from qiskit import IBMQ, Aer, transpile, assemble from qiskit.visualization import plot_histogram def create_bell_pair(): """ Returns: QuantumCircuit: Circuit that produces a Bell pair """ qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): """Encodes a two-bit message on qc using the superdense coding protocol Args: qc (QuantumCircuit): Circuit to encode message on qubit (int): Which qubit to add the gate to msg (str): Two-bit message to send Returns: QuantumCircuit: Circuit that, when decoded, will produce msg Raises: ValueError if msg is wrong length or contains invalid characters """ if len(msg) != 2 or not set(msg).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 qc = create_bell_pair() # We'll add a barrier for visual separation qc.barrier() # At this point, qubit 0 goes to Alice and qubit 1 goes to Bob # Next, Alice encodes her message onto qubit 1. In this case, # we want to send the message '10'. You can try changing this # value and see how it affects the circuit message = '10' qc = encode_message(qc, 1, message) qc.barrier() # Alice then sends her qubit to Bob. # After recieving qubit 0, Bob applies the recovery protocol: qc = decode_message(qc) # Finally, Bob measures his qubits to read Alice's message qc.measure_all() # Draw our output qc.draw("mpl") from qiskit.visualization import plot_histogram backend = Aer.get_backend('qasm_simulator') job = execute(qc,backend, shots=1) result = job.result() print(result.get_counts(qc)) plot_histogram(result.get_counts(qc)) #initialization import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, assemble, transpile,execute from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.providers.ibmq import least_busy import qiskit.quantum_info as qi # import basic plot tools from qiskit.visualization import plot_histogram qc = QuantumCircuit(2) qc.h(0) # Oracle qc.h(1) # Oracle qc.cz(0,1) # Oracle # Diffusion operator (U_s) qc.h([0,1]) qc.z([0,1]) qc.cz(0,1) qc.h([0,1]) qc.measure_all() qc.draw('mpl') from qiskit.visualization import plot_histogram backend = Aer.get_backend('qasm_simulator') job = execute(qc,backend, shots=1000) result = job.result() print(result.get_counts(qc)) plot_histogram(result.get_counts(qc)) from qiskit import QuantumCircuit, transpile, assemble, Aer, execute import qiskit.quantum_info as qi def change_sign(circuit, target_state): # Aplicar una compuerta de fase controlada para cambiar el signo del estado objetivo # Crear un circuito auxiliar con un qubit de control y el estado objetivo como objetivo aux_circuit = QuantumCircuit(2) aux_circuit.x(1) # Preparar el estado objetivo # Aplicar una compuerta de fase controlada con el qubit de control en el estado |1⟩ aux_circuit.cp(-1 * target_state, 0, 1) # Deshacer la preparación del estado objetivo aux_circuit.x(1) # Agregar el circuito auxiliar al circuito principal circuit.compose(aux_circuit, inplace=True) # Crear el circuito cuántico con n qubits y n bits clásicos n = 3 circuit = QuantumCircuit(n, n) # Definir el estado objetivo al que se le cambiará el signo target_state = 0 # Por ejemplo, cambiamos el signo del componente |0...0⟩ # Aplicar la función change_sign al estado objetivo change_sign(circuit, target_state) import qiskit.quantum_info as qi qc = QuantumCircuit(4,4) # Ponemos 4 qubits y 4 bits # Aplicamos algunas compuertas qc.h(0) qc.h(1) qc.h(2) qc.h(3) change_sign(qc, 0) stv = qi.Statevector.from_instruction(qc) style = {'backgroundcolor': 'lightgreen'} qc.draw(output='mpl', style=style) stv.draw('latex', prefix="|\\psi\\rangle =") from qiskit import QuantumCircuit, transpile, assemble, Aer, execute from qiskit.quantum_info import Statevector # Crear un circuito cuántico con n qubits n = 3 circuit = QuantumCircuit(n) # Crear el estado ∑𝑖|𝑖⟩⟨𝑖| como un Statevector statevector = Statevector.from_label('101') # Estado inicial |000⟩ # Aplicar el operador de densidad diagonal a los qubits utilizando el initialize method circuit.initialize(statevector.data, range(n)) # Medir los qubits circuit.measure_all() # Simular y ejecutar el circuito simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=1) result = job.result() counts = result.get_counts(circuit) print(counts) from sklearn.datasets import load_iris iris_data = load_iris() print(iris_data.DESCR) X = iris_data.data[0:100] y = iris_data.target[0:100] print(X.shape,y.shape) for i in range(10): print(X[i,0:4],y[i]) from sklearn.preprocessing import MinMaxScaler import numpy as np X = MinMaxScaler(feature_range=(0,1)).fit_transform(X) for i in range(10): print(X[i,0:4],y[i]) from sklearn.model_selection import train_test_split from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 123 X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=0.8, random_state=algorithm_globals.random_seed ) print(X_train.shape, X_test.shape,y_train.shape,y_test.shape) for i in range(10): print(X_train[i],y_train[i]) import pandas as pd df = pd.read_csv("heart.csv") print(df.head()) #print('Number of rows:',df.shape[0], ' number of columns: ',df.shape[1]) X = df.iloc[:,:-1].values y = df.target.values print(X.shape,y.shape) from sklearn.preprocessing import MinMaxScaler import numpy as np X = MinMaxScaler(feature_range=(0,1)).fit_transform(X) for i in range(10): print(X[i,0:4],y[i]) from sklearn.model_selection import train_test_split from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 123 X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=0.8, random_state=algorithm_globals.random_seed ) print(X_train.shape, X_test.shape,y_train.shape,y_test.shape) import mglearn import matplotlib.pyplot as plt #from matplotlib.pyplot import figure #figure(figsize=(8, 6), dpi=80) #plt.rcParams["figure.figsize"] = (8,8) # generate dataset X, y = mglearn.datasets.make_forge() # plot dataset mglearn.discrete_scatter(X[:, 0], X[:, 1], y) plt.legend(["Class 0", "Class 1"], loc=4) plt.xlabel("First feature") plt.ylabel("Second feature") print("X.shape:", X.shape) mglearn.plots.plot_knn_classification(n_neighbors=5) from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import classification_report from sklearn import datasets #from skimage import exposure import numpy as np import sklearn for k in range(1,10): model = KNeighborsClassifier(n_neighbors=k) model.fit(X_train, y_train) predictions = model.predict(X_test) score = np.round(100*model.score(X_test, y_test),1) print ('k=',k,'Porcentaje de aciertos:',score) from sklearn.svm import SVC from sklearn.metrics import accuracy_score classifier = SVC(kernel='linear',random_state=0) classifier.fit(X_train,y_train) y_pred = classifier.predict(X_test) accuracy = accuracy_score(y_test,y_pred) print("Support Vector Machine :") print("Accuracy = ", accuracy) import sklearn import mglearn import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline from IPython.display import display display(mglearn.plots.plot_logistic_regression_graph()) display(mglearn.plots.plot_single_hidden_layer_graph()) display(mglearn.plots.plot_two_hidden_layer_graph()) from IPython.display import YouTubeVideo YouTubeVideo('aircAruvnKk', width=800, height=300) from IPython.display import YouTubeVideo YouTubeVideo('IHZwWFHWa-w', width=800, height=300) from IPython.display import YouTubeVideo YouTubeVideo('Ilg3gGewQ5U', width=800, height=300) from IPython.display import YouTubeVideo YouTubeVideo('tIeHLnjs5U8', width=800, height=300) from sklearn.neural_network import MLPClassifier from sklearn.metrics import accuracy_score classifier = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 5,5), random_state=1) classifier.fit(X_train,y_train) y_pred = classifier.predict(X_test) accuracy = accuracy_score(y_test,y_pred) print("Neural Network Classifier :") print("Accuracy = ", accuracy) from sklearn import datasets import matplotlib.pyplot as plt digits = datasets.load_digits() X = np.array(digits.data) Y = np.array(digits.target) fig=plt.figure(figsize=(10, 10)) for i in range(16): fig.add_subplot(4, 4, i+1) j = randint(0, len(y)) plt.imshow(np.reshape(X[j],(8,8)),cmap=plt.cm.gray_r, interpolation='nearest') num = str(y[j]) plt.title('N='+str(num),fontsize=15) plt.xticks(fontsize=10, rotation=90) plt.yticks(fontsize=10, rotation=0) from sklearn import datasets from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import classification_report import numpy as np from sklearn import svm import numpy as np import matplotlib.pyplot as plt from random import randint train_fraction = .8 train_len = int(train_fraction*len(X)) print ('Fraccion train:',train_fraction) digits = datasets.load_digits() X = np.array(digits.data) Y = np.array(digits.target) X_train = X[0:train_len] Y_train = Y[0:train_len] X_test = X[train_len:] Y_test = Y[train_len:] print ('Data shape:',X.shape) print ('X_train shape:',X_train.shape) print ('Y_train shape:',Y_train.shape) print ('X_test shape:',X_test.shape) print ('Y_test shape:',Y_test.shape) for k in range(1,10): model = KNeighborsClassifier(n_neighbors=k) model.fit(X_train, Y_train) predictions = model.predict(X_test) score = np.round(100*model.score(X_test, Y_test),1) print ('k=',k,'Porcentaje de aciertos:',score) import seaborn as sb import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix model = KNeighborsClassifier(n_neighbors=4) model.fit(X_train, Y_train) cm = confusion_matrix(Y_test, model.predict(X_test)) plt.subplots(figsize=(10, 6)) sb.heatmap(cm, annot = True, fmt = 'g') plt.xlabel("Predicted") plt.ylabel("Actual") plt.title("Confusion Matrix") plt.show() import matplotlib.pyplot as plt from random import randint """ #############################. 8x8 = 64 from sklearn import datasets digits = datasets.load_digits() X = digits.data y = digits.target print ( X.shape, y.shape ) #############################. 8x8 = 64 """ #############################. 28x28 = 784 from keras.datasets import mnist (X_train, y_train), (X_test, y_test) = mnist.load_data() print ( X_train.shape, X_test.shape, y_train.shape, y_test.shape ) X_train = X_train.reshape((60000,784)) X_test = X_test.reshape((10000,784)) print ( X_train.shape, X_test.shape, y_train.shape, y_test.shape ) X = X_test y = y_test X = X[0:2000] y = y[0:2000] #############################. 28x28 = 784 fig=plt.figure(figsize=(10, 10)) for i in range(16): fig.add_subplot(4, 4, i+1) j = randint(0, len(y)) #plt.imshow(np.reshape(X[j],(8,8)),cmap=plt.cm.gray_r, interpolation='nearest') plt.imshow(np.reshape(X[j],(28,28)),cmap=plt.cm.gray, interpolation='nearest') #plt.imshow(np.reshape(X[j],(28,28)),cmap=plt.cm.RdBu, interpolation='nearest') num = str(y[j]) plt.title('N='+str(num),fontsize=15) plt.xticks(fontsize=10, rotation=90) plt.yticks(fontsize=10, rotation=0) from sklearn import svm # Scale data before applying PCA from sklearn.decomposition import PCA from sklearn.manifold import TSNE from sklearn.preprocessing import StandardScaler scaler=StandardScaler() #############################. 8x8 = 64 from sklearn import datasets digits = datasets.load_digits() X = digits.data y = digits.target #############################. 8x8 = 64 """ #############################. 28x28 = 784 from keras.datasets import mnist (X_train, y_train), (X_test, y_test) = mnist.load_data() print ( X_train.shape, X_test.shape, y_train.shape, y_test.shape ) X_train = X_train.reshape((60000,784)) X_test = X_test.reshape((10000,784)) print ( X_train.shape, X_test.shape, y_train.shape, y_test.shape ) X = X_test y = y_test X = X[0:2000] y = y[0:2000] #############################. 28x28 = 784 """ print ( X.shape,y.shape) scaler.fit(X) scaled_data=scaler.transform(X) # Use fit and transform method pca = PCA(n_components=3) # project from 64 to 3 dimensions projected = pca.fit_transform(scaled_data) print(projected.shape) import plotly.express as px fig = px.scatter_3d(x=projected[:,0], y=projected[:,1], z=projected[:,2], symbol=y,color=y,color_continuous_scale=px.colors.sequential.Inferno) fig.update_layout(legend_orientation="h") fig.update_traces(marker=dict(size=4, line=dict(width=2, color='DarkSlateGrey')), selector=dict(mode='markers')) fig.show() from sklearn import svm # Scale data before applying PCA from sklearn.decomposition import PCA from sklearn.manifold import TSNE from sklearn.preprocessing import StandardScaler scaler=StandardScaler() print (X.shape,y.shape) scaler.fit(X) scaled_data=scaler.transform(X) # Use fit and transform method #tsne = TSNE(n_components=2, random_state=0) tsne = TSNE(n_components=3, random_state=0) projected = tsne.fit_transform(scaled_data) print(projected.shape) import plotly.express as px #fig = px.scatter(x=projected[:,0], y=projected[:,1], # symbol=y,color=y,color_continuous_scale=px.colors.sequential.Inferno) fig = px.scatter_3d(x=projected[:,0], y=projected[:,1], z=projected[:,2], symbol=y,color=y,color_continuous_scale=px.colors.sequential.Inferno) fig.update_layout(legend_orientation="h") fig.update_traces(marker=dict(size=8, line=dict(width=2, color='DarkSlateGrey')), selector=dict(mode='markers')) fig.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright from google.colab import files uploaded = files.upload() !ls import pandas as pd df = pd.read_csv("heart.csv") print(df.head()) print('Number of rows:',df.shape[0], ' number of columns: ',df.shape[1]) X = df.iloc[:,:-1].values y = df.target.values from sklearn import svm # Scale data before applying PCA from sklearn.decomposition import PCA from sklearn.manifold import TSNE from sklearn.preprocessing import StandardScaler scaler=StandardScaler() print (X.shape,y.shape) scaler.fit(X) scaled_data=scaler.transform(X) # Use fit and transform method #pca = PCA(n_components=2) # project from 13 to 3 dimensions pca = PCA(n_components=4) # project from 13 to 3 dimensions #tsne = TSNE(n_components=2, random_state=0) #tsne = TSNE(n_components=3, random_state=0) projected = pca.fit_transform(scaled_data) #projected = tsne.fit_transform(scaled_data) print(projected.shape) import plotly.express as px #fig = px.scatter(x=projected[:,0], y=projected[:,1], # symbol=y,color=y,color_continuous_scale=px.colors.sequential.Inferno) fig = px.scatter_3d(x=projected[:,0], y=projected[:,1], z=projected[:,2], symbol=y,color=y,color_continuous_scale=px.colors.sequential.Inferno) fig.update_layout(legend_orientation="h") fig.update_traces(marker=dict(size=8, line=dict(width=2, color='DarkSlateGrey')), selector=dict(mode='markers')) fig.show() from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X,y, random_state=0) print(X_train.shape,X_test.shape,y_train.shape,y_test.shape) from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import classification_report from sklearn import datasets #from skimage import exposure import numpy as np import sklearn for k in range(1,10): model = KNeighborsClassifier(n_neighbors=k) model.fit(X_train, y_train) predictions = model.predict(X_test) score = np.round(100*model.score(X_test, y_test),1) print ('k=',k,'Porcentaje de aciertos:',score) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( projected, y, random_state=0) print(X_train.shape,X_test.shape,y_train.shape,y_test.shape) from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import classification_report from sklearn import datasets #from skimage import exposure import numpy as np import sklearn for k in range(1,10): model = KNeighborsClassifier(n_neighbors=k) model.fit(X_train, y_train) predictions = model.predict(X_test) score = np.round(100*model.score(X_test, y_test),1) print ('k=',k,'Porcentaje de aciertos:',score) #Import svm model from sklearn.svm import SVC print(X_train.shape,X_test.shape,y_train.shape,y_test.shape) clf = SVC(kernel='rbf', C=1000, gamma=.1) # Linear Kernel clf.fit(X_train, y_train) y_pred = clf.predict(X_test) from sklearn import metrics print("Porcentaje de aciertos:",metrics.accuracy_score(y_test, y_pred)) from sklearn.model_selection import GridSearchCV # defining parameter range param_grid = {'C': [0.1, 10, 1000], 'gamma': [1, 0.01, 0.0001], 'kernel': ['rbf']} grid = GridSearchCV(SVC(),param_grid,refit=True,verbose=2) # fitting the model for grid search grid.fit(X_train, y_train) # print best parameter after tuning print(grid.best_params_) # print how our model looks after hyper-parameter tuning print(grid.best_estimator_) grid_predictions = grid.predict(X_test) # print classification report print(classification_report(y_test, grid_predictions)) from qiskit.circuit.library import ZZFeatureMap from qiskit.circuit.library import ZFeatureMap from qiskit.circuit.library import RealAmplitudes from qiskit.circuit.library import EfficientSU2 from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister,Aer, execute import numpy as np def my_circuit1(X, reps_feature_map,theta,rep_ansatz): feature_map = ZFeatureMap(feature_dimension=len(X), reps=reps_feature_map) qc = QuantumCircuit(len(X),1) qc.append(feature_map.decompose(), range(len(X))) qc.barrier() qc = qc.bind_parameters(X) #W = RealAmplitudes(num_qubits=len(X), reps=rep_ansatz) W = EfficientSU2(num_qubits=len(X), reps=rep_ansatz) #W = W.bind_parameters(theta) qc.append(W.decompose(), range(4)) qc.barrier() qc.measure(0, 0) return qc reps_feature_map = 1 rep_ansatz = 1 theta_dim = 4+4*rep_ansatz #theta = np.zeros(theta_dim) theta = range(theta_dim) qc = my_circuit1(X_train[0], 1,theta,rep_ansatz) qc.decompose().draw(output="mpl", fold=20) from qiskit import QuantumCircuit import numpy as np qc = QuantumCircuit(1) qc.p(np.pi/2,0) qc.decompose().draw(output="mpl", fold=20) from qiskit.circuit.library import ZZFeatureMap,ZFeatureMap num_features = len(X_train[0]) feature_map = ZFeatureMap(feature_dimension=num_features, reps=1) feature_map.decompose().draw(output="mpl", fold=20) from qiskit.circuit.library import RealAmplitudes from qiskit.circuit.library import EfficientSU2 num_features = len(X_train[0]) ansatz = RealAmplitudes(num_qubits=num_features, reps=1) ansatz.decompose().draw(output="mpl", fold=20) from qiskit.algorithms.optimizers import COBYLA,SPSA,SLSQP optimizer = COBYLA(maxiter=60) 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(X_train, y_train) elapsed = time.time() - start print(f"Training time: {round(elapsed)} seconds") train_score_q4 = vqc.score(X_train, y_train) test_score_q4 = vqc.score(X_test, y_test) print(f"Quantum VQC on the training dataset: {train_score_q4:.2f}") print(f"Quantum VQC on the test dataset: {test_score_q4:.2f}") from sklearn.datasets import load_iris iris_data = load_iris() print(iris_data.DESCR) X = iris_data.data[0:100] y = iris_data.target[0:100] print(X.shape,y.shape) for i in range(10): print(X[i,0:4],y[i]) from sklearn.preprocessing import MinMaxScaler import numpy as np X = MinMaxScaler(feature_range=(0,1)).fit_transform(X) for i in range(10): print(X[i,0:4],y[i]) from sklearn.model_selection import train_test_split from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 123 X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=0.8, random_state=algorithm_globals.random_seed ) print(X_train.shape, X_test.shape,y_train.shape,y_test.shape) for i in range(10): print(X_train[i],y_train[i]) from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister,Aer, execute import numpy as np import qiskit.quantum_info as qi def my_circuit0(X,theta): qc = QuantumCircuit(len(X),1) # Ponemos 3 qubits y 1 bit # Aplicamos algunas compuertas for i,X_i in enumerate (X): qc.h(i) qc.p(2*X_i,i) qc.barrier() for i in range(len(X)): qc.ry(theta[i],i) for i in range(len(X)-1,0,-1): qc.cx(i-1,i) for i in range(len(X)): qc.rx(theta[i+len(X)],i) for i in range(len(X)-1,0,-1): qc.cx(i-1,i) for i in range(len(X)): qc.rx(theta[i+2*len(X)],i) qc.barrier() qc.measure(0,0) return qc theta =range(12) qc = my_circuit0(X_train[0],theta) qc.draw(output='mpl') from qiskit.circuit.library import ZZFeatureMap from qiskit.circuit.library import ZFeatureMap from qiskit.circuit.library import RealAmplitudes from qiskit.circuit.library import EfficientSU2 from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister,Aer, execute import numpy as np def my_circuit1(X, reps_feature_map,theta,rep_ansatz): feature_map = ZFeatureMap(feature_dimension=len(X), reps=reps_feature_map) qc = QuantumCircuit(len(X),1) qc.append(feature_map.decompose(), range(len(X))) qc.barrier() qc = qc.bind_parameters(X) W = RealAmplitudes(num_qubits=len(X), reps=rep_ansatz) W = W.bind_parameters(theta) qc.append(W.decompose(), range(4)) qc.barrier() qc.measure(0, 0) return qc theta = np.zeros(12) #theta = range(12) qc = my_circuit1(X_train[0], 1,theta,2) qc.decompose().draw(output="mpl", fold=20) def prediction(X,theta,shots): #qc=my_circuit1(X, 1,theta,2) qc=my_circuit0(X,theta) simulator = Aer.get_backend('qasm_simulator') job = execute(qc, simulator, shots=shots) result = job.result() counts = result.get_counts() try: counts["0"] except: return 0 else: return counts["0"]/shots print(prediction(X_train[3],np.zeros(12),1000)) def loss (X,y,theta,shots): return (prediction(X,theta,shots)-y)**2 def loss_epoch (n_data,X,y,theta,shots): loss_initial = 0 for i in range(n_data): loss_initial += loss (X_train[i],y_train[i],theta,shots) return loss_initial/n_data print(loss(X_train[2],y[2],np.zeros(12),1000)) print(loss_epoch(80,X_train,y_train,np.zeros(12),1000)) def gradient(X,y,theta,shots): delta = .01 grad=np.zeros(len(theta)) grad=np.zeros(len(theta)) theta1 = theta.copy() L = loss(X,y,theta,shots) for j in range(len(theta)): theta_new = theta.copy() theta_new [j] += delta #print(theta,theta_new) grad[j]= (loss(X,y,theta_new,shots) -L)/delta return grad,L def gradient_epoch(n_data,X,y,theta,shots): delta = .01 grad=np.zeros(len(theta)) theta1 = theta.copy() L = loss_epoch(n_data,X,y,theta,shots) for j in range(len(theta)): theta_new = theta.copy() theta_new [j] += delta #print(theta,theta_new) grad [j]=(loss_epoch(n_data,X,y,theta_new,shots) -L)/delta return grad,L theta = np.zeros(12) shots = 10000 eta = 1 grad, L = gradient(X_train[2],y_train[2],theta,shots) print(theta) theta = theta - eta*grad print(theta) theta = np.zeros(12) grad, L = gradient_epoch(80,X_train,y_train,theta,shots) print(theta) theta = theta - eta*grad print(theta) def accuracy (N_points,X,y,theta,shots): acc = 0 for i in range(N_points): #print(prediction(X[i],theta,shots), y[i]) if (np.round(prediction(X[i],theta,shots),0) == y[i]): acc += 1 return (acc/N_points) accuracy (20,X_train,y_train,theta,shots) shots = 1000 n_data = 80 eta = 1 n_epochs = 50 from matplotlib import pyplot as plt from IPython.display import clear_output theta = np.zeros(12) loss_initial = 0 for i in range(n_data): loss_initial += loss(X_train[i],y_train[i],theta,shots) mean_loss = [loss_initial/n_data] acc_list = [accuracy (20,X_test,y_test,theta,shots)] plt.rcParams["figure.figsize"] = (12, 6) def graph(mean_loss,acc_list): clear_output(wait=True) fig, ax1 = plt.subplots() ax2 = ax1.twinx() ax1.plot(range(len(mean_loss)), mean_loss, 'g-') ax2.plot(range(len(mean_loss)), acc_list, 'b-') ax1.set_xlabel('Iteraciones sobre los Datos') ax1.set_ylabel('Función Loss', color='g') ax2.set_ylabel('Porcentaje de Aciertos en Test', color='b') plt.show() for j in range(n_epochs): if (j>0 and j%5 == 0): eta = eta/2 tot_loss = 0 for i in range(n_data): grad, L = gradient(X_train[i],y_train[i],theta,shots) theta = theta - eta * grad tot_loss += L mean_loss.append(tot_loss/n_data) acc_list.append(accuracy (20,X_test,y_test,theta,shots)) graph(mean_loss,acc_list) shots = 1000 n_data = 80 eta = 1 n_epochs = 50 from matplotlib import pyplot as plt from IPython.display import clear_output theta = np.zeros(12) loss_initial = 0 for i in range(n_data): loss_initial += loss (X_train[i],y_train[i],theta,shots) mean_loss = [loss_initial/n_data] acc_list = [accuracy (20,X_test,y_test,theta,shots)] plt.rcParams["figure.figsize"] = (12, 6) def graph(mean_loss,acc_list): clear_output(wait=True) fig, ax1 = plt.subplots() ax2 = ax1.twinx() ax1.plot(range(len(mean_loss)), mean_loss, 'g-') ax2.plot(range(len(mean_loss)), acc_list, 'b-') ax1.set_xlabel('Iteraciones sobre los Datos') ax1.set_ylabel('Función Loss', color='g') ax2.set_ylabel('Porcentaje de Aciertos en Test', color='b') plt.show() for j in range(n_epochs): if (j>0 and j%5 == 0): eta = eta/2 grad, L = gradient_epoch(80,X_train,y_train,theta,shots) theta = theta - eta * grad mean_loss.append(L) acc_list.append(accuracy (20,X_test,y_test,theta,shots)) graph(mean_loss,acc_list) plt.title("Accuracy for X_test against iteration") plt.xlabel("Iteration") plt.ylabel("Accuracy") plt.plot(range(len(acc_list)), acc_list) plt.grid() plt.show() from sklearn.datasets import load_iris iris_data = load_iris() print(iris_data.DESCR) X = iris_data.data[0:100] y = iris_data.target[0:100] print(X.shape,y.shape) for i in range(10): print(X[i,0:4],y[i]) from sklearn.preprocessing import MinMaxScaler import numpy as np X = MinMaxScaler(feature_range=(0,1)).fit_transform(X) for i in range(10): print(X[i,0:4],y[i]) from sklearn.model_selection import train_test_split from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 123 X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=0.8, random_state=algorithm_globals.random_seed ) print(X_train.shape, X_test.shape,y_train.shape,y_test.shape) from qiskit.circuit.library import ZZFeatureMap,ZFeatureMap num_features = X.shape[1] feature_map = ZFeatureMap(feature_dimension=num_features, reps=2) feature_map.decompose().draw(output="mpl", fold=20) from qiskit.circuit.library import RealAmplitudes from qiskit.circuit.library import EfficientSU2 ansatz = EfficientSU2(num_qubits=num_features, reps=1) ansatz.decompose().draw(output="mpl", fold=20) from qiskit.algorithms.optimizers import COBYLA # Constrained Optimization By Linear Approximation optimizer. # https://qiskit.org/documentation/stubs/qiskit.algorithms.optimizers.COBYLA.html from qiskit.algorithms.optimizers import SPSA # Simultaneous Perturbation Stochastic Approximation optimizer # https://qiskit.org/documentation/stubs/qiskit.algorithms.optimizers.SPSA.html from qiskit.algorithms.optimizers import SLSQP # Sequential Least SQuares Programming optimizer # https://qiskit.org/documentation/stubs/qiskit.algorithms.optimizers.SLSQP.html 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.grid() 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(X_train, y_train) elapsed = time.time() - start print(f"Training time: {round(elapsed)} seconds") train_score_q4 = vqc.score(X_train, y_train) test_score_q4 = vqc.score(X_test, y_test) print(f"Quantum VQC on the training dataset: {train_score_q4:.2f}") print(f"Quantum VQC on the test dataset: {test_score_q4:.2f}") from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 12345 from qiskit_machine_learning.datasets import ad_hoc_data adhoc_dimension = 2 train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data( training_size=20, test_size=5, n=adhoc_dimension, gap=0.3, plot_data=False, one_hot=False, include_sample_total=True, ) import matplotlib.pyplot as plt import numpy as np def plot_features(ax, features, labels, class_label, marker, face, edge, label): # A train plot ax.scatter( # x coordinate of labels where class is class_label features[np.where(labels[:] == class_label), 0], # y coordinate of labels where class is class_label features[np.where(labels[:] == class_label), 1], marker=marker, facecolors=face, edgecolors=edge, label=label, ) def plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total): plt.figure(figsize=(5, 5)) plt.ylim(0, 2 * np.pi) plt.xlim(0, 2 * np.pi) plt.imshow( np.asmatrix(adhoc_total).T, interpolation="nearest", origin="lower", cmap="RdBu", extent=[0, 2 * np.pi, 0, 2 * np.pi], ) # A train plot plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "A train") # B train plot plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B train") # A test plot plot_features(plt, test_features, test_labels, 0, "s", "b", "w", "A test") # B test plot plot_features(plt, test_features, test_labels, 1, "o", "r", "w", "B test") plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0) plt.title("Ad hoc dataset") plt.show() plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total) from qiskit.circuit.library import ZZFeatureMap from qiskit.primitives import Sampler from qiskit.algorithms.state_fidelities import ComputeUncompute from qiskit_machine_learning.kernels import FidelityQuantumKernel adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear") sampler = Sampler() fidelity = ComputeUncompute(sampler=sampler) adhoc_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=adhoc_feature_map) adhoc_matrix_train = adhoc_kernel.evaluate(x_vec=train_features) adhoc_matrix_test = adhoc_kernel.evaluate(x_vec=test_features, y_vec=train_features) fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].imshow( np.asmatrix(adhoc_matrix_train), interpolation="nearest", origin="upper", cmap="Blues" ) axs[0].set_title("Ad hoc training kernel matrix") axs[1].imshow(np.asmatrix(adhoc_matrix_test), interpolation="nearest", origin="upper", cmap="Reds") axs[1].set_title("Ad hoc testing kernel matrix") plt.show() from sklearn.svm import SVC adhoc_svc = SVC(kernel="precomputed") adhoc_svc.fit(adhoc_matrix_train, train_labels) adhoc_score_precomputed_kernel = adhoc_svc.score(adhoc_matrix_test, test_labels) print(f"Precomputed kernel classification test score: {adhoc_score_precomputed_kernel}") from qiskit_machine_learning.algorithms import QSVC qsvc = QSVC(quantum_kernel=adhoc_kernel) qsvc.fit(train_features, train_labels) qsvc_score = qsvc.score(test_features, test_labels) print(f"QSVC classification test score: {qsvc_score}") from IPython.display import IFrame IFrame("https://arxiv.org/pdf/1304.3061.pdf", width=600, height=300) !pip install pyscf !pip install --upgrade qiskit-nature from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.drivers import GaussianForcesDriver from qiskit_nature.second_q.mappers import DirectMapper from qiskit_nature.second_q.problems import HarmonicBasis from qiskit_nature.second_q.algorithms import GroundStateEigensolver #from qiskit_nature.drivers import PySCFDriver from qiskit_nature.second_q.drivers import PySCFDriver import matplotlib.pyplot as plt import numpy as np #driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") n=40 # Numero de puntos +1 d = [0.735*i/10 for i in range(1,n)] atom_array = [ "H 0 0 0; H 0 0 " + str(0.735*i/10) for i in range(1,n)] E =[] for i in range(0,n-1): driver = PySCFDriver( #atom="H 0 0 0; H 0 0 0.735", atom=atom_array[i], basis="sto3g", charge=0, spin=0, #unit=DistanceUnit.ANGSTROM, ) #basis = HarmonicBasis([2, 2, 2, 2]) vib_problem = driver.run() vib_problem.hamiltonian.truncation_order = 2 mapper = DirectMapper() solver_without_filter = NumPyMinimumEigensolver() #solver_with_filter = NumPyMinimumEigensolver( # filter_criterion=vib_problem.get_default_filter_criterion()) gsc_wo = GroundStateEigensolver(mapper, solver_without_filter) result_wo = gsc_wo.solve(vib_problem) #gsc_w = GroundStateEigensolver(mapper, solver_with_filter) #result_w = gsc_w.solve(vib_problem) #print(result_wo) #print(f"Total ground state energy = {result_wo.total_energies[0]:.4f}") #print("\n\n") #print(result_w) E.append(result_wo.total_energies[0]) plt.figure(figsize=(10, 6)) #print (E) plt.plot(d,E, '--bo', label='Energías vs distance') plt.grid() print ("Energía mininima =", np.round(min(E),5), " para d =", d[E.index(min(E))]) from IPython.display import YouTubeVideo YouTubeVideo('_ediOdFUr10', width=800, height=300) import pennylane as qml import numpy as np symbols = ["H", "H"] #coordinates = np.array([0.0, 0.0, 0, 0.0, 0.0, 0.735])# in Angtrons coordinates = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 1.3889487])# in au import pennylane as qml H, qubits = qml.qchem.molecular_hamiltonian(symbols, coordinates) print("Number of qubits = ", qubits) print("The Hamiltonian is ", H) dev = qml.device("default.qubit",wires=qubits) @qml.qnode(dev) def energy(state): qml.BasisState(np.array(state),wires=range(qubits)) return qml.expval(H) energy([1,1,0,0]) hf =qml.qchem.hf_state(electrons = 2, orbitals = 4) print("Estado de Hartree-Fock:", hf) print("Energía del estado base=",energy(hf),"Ha") print("Energía del estado base=",energy(hf)* 27.211386245988,"eV")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/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. """ Multiple-Control U3 gate. Not using ancillary qubits. """ import logging from sympy.combinatorics.graycode import GrayCode from qiskit import QuantumCircuit, QuantumRegister from qiskit.aqua.utils.controlled_circuit import apply_cu3 logger = logging.getLogger(__name__) def _apply_mcu3(circuit, theta, phi, lam, ctls, tgt): """Apply multi-controlled u3 gate from ctls to tgt with angles theta, phi, lam.""" n = len(ctls) gray_code = list(GrayCode(n).generate_gray()) last_pattern = None theta_angle = theta*(1/(2**(n-1))) phi_angle = phi*(1/(2**(n-1))) lam_angle = lam*(1/(2**(n-1))) for pattern in gray_code: if not '1' in pattern: continue if last_pattern is None: last_pattern = pattern #find left most set bit lm_pos = list(pattern).index('1') #find changed bit comp = [i != j for i, j in zip(pattern, last_pattern)] if True in comp: pos = comp.index(True) else: pos = None if pos is not None: if pos != lm_pos: circuit.cx(ctls[pos], ctls[lm_pos]) else: indices = [i for i, x in enumerate(pattern) if x == '1'] for idx in indices[1:]: circuit.cx(ctls[idx], ctls[lm_pos]) #check parity if pattern.count('1') % 2 == 0: #inverse apply_cu3(circuit, -theta_angle, phi_angle, lam_angle, ctls[lm_pos], tgt) else: apply_cu3(circuit, theta_angle, phi_angle, lam_angle, ctls[lm_pos], tgt) last_pattern = pattern def mcu3(self, theta, phi, lam, control_qubits, target_qubit): """ Apply Multiple-Controlled U3 gate Args: theta: angle theta phi: angle phi lam: angle lambda control_qubits: The list of control qubits target_qubit: The target qubit """ if isinstance(target_qubit, QuantumRegister) and len(target_qubit) == 1: target_qubit = target_qubit[0] temp = [] self._check_qargs(control_qubits) temp += control_qubits self._check_qargs([target_qubit]) temp.append(target_qubit) self._check_dups(temp) n_c = len(control_qubits) if n_c == 1: # cu3 apply_cu3(self, theta, phi, lam, control_qubits[0], target_qubit) else: _apply_mcu3(self, theta, phi, lam, control_qubits, target_qubit) QuantumCircuit.mcu3 = mcu3
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/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_right(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=80 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog.draw()
https://github.com/Qiskit/qiskit-transpiler-service
Qiskit
# -*- coding: utf-8 -*- # (C) Copyright 2024 IBM. All Rights Reserved. # # 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 import pytest from qiskit import QuantumCircuit from qiskit.circuit.library import QuantumVolume from qiskit.quantum_info import random_clifford from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager def create_random_circuit(total_n_ubits, cliffords_n_qubits, clifford_num): circuit = QuantumCircuit(total_n_ubits) nq = cliffords_n_qubits for c in range(clifford_num): qs = np.random.choice(range(circuit.num_qubits), size=nq, replace=False) circuit.compose( random_clifford(nq, seed=42).to_circuit(), qubits=qs.tolist(), inplace=True ) for q in qs: circuit.t(q) return circuit def create_linear_circuit(n_qubits, gates): circuit = QuantumCircuit(n_qubits) for q in range(n_qubits - 1): if gates == "cx": circuit.cx(q, q + 1) elif gates == "swap": circuit.swap(q, q + 1) elif gates == "cz": circuit.cz(q, q + 1) elif gates == "rzz": circuit.rzz(1.23, q, q + 1) return circuit @pytest.fixture(scope="module") def random_circuit_transpiled(backend, cmap_backend): circuit = create_random_circuit(27, 4, 2) qiskit_lvl3_transpiler = generate_preset_pass_manager( optimization_level=3, coupling_map=cmap_backend[backend] ) return qiskit_lvl3_transpiler.run(circuit) @pytest.fixture(scope="module") def qv_circ(): return QuantumVolume(10, depth=3, seed=42).decompose(reps=1) @pytest.fixture(scope="module", params=[3, 10, 30]) def cnot_circ(request): return create_linear_circuit(request.param, "cx") @pytest.fixture(scope="module", params=[3, 10, 30]) def swap_circ(request): return create_linear_circuit(request.param, "swap") @pytest.fixture(scope="module", params=[3, 10, 30]) def cz_circ(request): return create_linear_circuit(request.param, "cz") @pytest.fixture(scope="module", params=[3, 10, 30]) def rzz_circ(request): return create_linear_circuit(request.param, "rzz")
https://github.com/primaryobjects/oracle
primaryobjects
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>) out of four possible values.""" #import numpy and plot library import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector # import basic plot tools from qiskit.visualization import plot_histogram # define variables, 1) initialize qubits to zero n = 2 grover_circuit = QuantumCircuit(n) #define initialization function def initialize_s(qc, qubits): '''Apply a H-gate to 'qubits' in qc''' for q in qubits: qc.h(q) return qc ### begin grovers circuit ### #2) Put qubits in equal state of superposition grover_circuit = initialize_s(grover_circuit, [0,1]) # 3) Apply oracle reflection to marked instance x_0 = 3, (|11>) grover_circuit.cz(0,1) statevec = job_sim.result().get_statevector() from qiskit_textbook.tools import vector2latex vector2latex(statevec, pretext="|\\psi\\rangle =") # 4) apply additional reflection (diffusion operator) grover_circuit.h([0,1]) grover_circuit.z([0,1]) grover_circuit.cz(0,1) grover_circuit.h([0,1]) # 5) measure the qubits grover_circuit.measure_all() # Load IBM Q account and get the least busy backend device provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) from qiskit.tools.monitor import job_monitor job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) #highest amplitude should correspond with marked value x_0 (|11>)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 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. """Test the CSPLayout pass""" import unittest from time import process_time from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler import CouplingMap from qiskit.transpiler.passes import CSPLayout from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeTenerife, FakeRueschlikon, FakeTokyo, FakeYorktownV2 from qiskit.utils import optionals @unittest.skipUnless(optionals.HAS_CONSTRAINT, "needs python-constraint") class TestCSPLayout(QiskitTestCase): """Tests the CSPLayout pass""" seed = 42 def test_2q_circuit_2q_coupling(self): """A simple example, without considering the direction 0 - 1 qr1 - qr0 """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 dag = circuit_to_dag(circuit) pass_ = CSPLayout(CouplingMap([[0, 1]]), strict_direction=False, seed=self.seed) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr[0]], 1) self.assertEqual(layout[qr[1]], 0) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found") def test_3q_circuit_5q_coupling(self): """3 qubits in Tenerife, without considering the direction qr1 / | qr0 - qr2 - 3 | / 4 """ cmap5 = FakeTenerife().configuration().coupling_map qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 circuit.cx(qr[0], qr[2]) # qr0 -> qr2 circuit.cx(qr[1], qr[2]) # qr1 -> qr2 dag = circuit_to_dag(circuit) pass_ = CSPLayout(CouplingMap(cmap5), strict_direction=False, seed=self.seed) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr[0]], 3) self.assertEqual(layout[qr[1]], 2) self.assertEqual(layout[qr[2]], 4) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found") def test_3q_circuit_5q_coupling_with_target(self): """3 qubits in Yorktown, without considering the direction qr1 / | qr0 - qr2 - 3 | / 4 """ target = FakeYorktownV2().target qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 circuit.cx(qr[0], qr[2]) # qr0 -> qr2 circuit.cx(qr[1], qr[2]) # qr1 -> qr2 dag = circuit_to_dag(circuit) pass_ = CSPLayout(target, strict_direction=False, seed=self.seed) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr[0]], 3) self.assertEqual(layout[qr[1]], 2) self.assertEqual(layout[qr[2]], 4) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found") def test_9q_circuit_16q_coupling(self): """9 qubits in Rueschlikon, without considering the direction q0[1] - q0[0] - q1[3] - q0[3] - q1[0] - q1[1] - q1[2] - 8 | | | | | | | | q0[2] - q1[4] -- 14 ---- 13 ---- 12 ---- 11 ---- 10 --- 9 """ cmap16 = FakeRueschlikon().configuration().coupling_map qr0 = QuantumRegister(4, "q0") qr1 = QuantumRegister(5, "q1") circuit = QuantumCircuit(qr0, qr1) circuit.cx(qr0[1], qr0[2]) # q0[1] -> q0[2] circuit.cx(qr0[0], qr1[3]) # q0[0] -> q1[3] circuit.cx(qr1[4], qr0[2]) # q1[4] -> q0[2] dag = circuit_to_dag(circuit) pass_ = CSPLayout(CouplingMap(cmap16), strict_direction=False, seed=self.seed) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr0[0]], 9) self.assertEqual(layout[qr0[1]], 6) self.assertEqual(layout[qr0[2]], 7) self.assertEqual(layout[qr0[3]], 5) self.assertEqual(layout[qr1[0]], 14) self.assertEqual(layout[qr1[1]], 12) self.assertEqual(layout[qr1[2]], 1) self.assertEqual(layout[qr1[3]], 8) self.assertEqual(layout[qr1[4]], 10) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found") def test_2q_circuit_2q_coupling_sd(self): """A simple example, considering the direction 0 -> 1 qr1 -> qr0 """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 dag = circuit_to_dag(circuit) pass_ = CSPLayout(CouplingMap([[0, 1]]), strict_direction=True, seed=self.seed) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr[0]], 1) self.assertEqual(layout[qr[1]], 0) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found") def test_3q_circuit_5q_coupling_sd(self): """3 qubits in Tenerife, considering the direction qr0 ↙ ↑ qr2 ← qr1 ← 3 ↑ ↙ 4 """ cmap5 = FakeTenerife().configuration().coupling_map qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 circuit.cx(qr[0], qr[2]) # qr0 -> qr2 circuit.cx(qr[1], qr[2]) # qr1 -> qr2 dag = circuit_to_dag(circuit) pass_ = CSPLayout(CouplingMap(cmap5), strict_direction=True, seed=self.seed) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr[0]], 1) self.assertEqual(layout[qr[1]], 2) self.assertEqual(layout[qr[2]], 0) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found") def test_9q_circuit_16q_coupling_sd(self): """9 qubits in Rueschlikon, considering the direction q0[1] → q0[0] → q1[3] → q0[3] ← q1[0] ← q1[1] → q1[2] ← 8 ↓ ↑ ↓ ↓ ↑ ↓ ↓ ↑ q0[2] ← q1[4] → 14 ← 13 ← 12 → 11 → 10 ← 9 """ cmap16 = FakeRueschlikon().configuration().coupling_map qr0 = QuantumRegister(4, "q0") qr1 = QuantumRegister(5, "q1") circuit = QuantumCircuit(qr0, qr1) circuit.cx(qr0[1], qr0[2]) # q0[1] -> q0[2] circuit.cx(qr0[0], qr1[3]) # q0[0] -> q1[3] circuit.cx(qr1[4], qr0[2]) # q1[4] -> q0[2] dag = circuit_to_dag(circuit) pass_ = CSPLayout(CouplingMap(cmap16), strict_direction=True, seed=self.seed) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr0[0]], 9) self.assertEqual(layout[qr0[1]], 6) self.assertEqual(layout[qr0[2]], 7) self.assertEqual(layout[qr0[3]], 5) self.assertEqual(layout[qr1[0]], 14) self.assertEqual(layout[qr1[1]], 12) self.assertEqual(layout[qr1[2]], 1) self.assertEqual(layout[qr1[3]], 10) self.assertEqual(layout[qr1[4]], 8) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found") def test_5q_circuit_16q_coupling_no_solution(self): """5 qubits in Rueschlikon, no solution q0[1] ↖ ↗ q0[2] q0[0] q0[3] ↙ ↘ q0[4] """ cmap16 = FakeRueschlikon().configuration().coupling_map qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[2]) circuit.cx(qr[0], qr[3]) circuit.cx(qr[0], qr[4]) dag = circuit_to_dag(circuit) pass_ = CSPLayout(CouplingMap(cmap16), seed=self.seed) pass_.run(dag) layout = pass_.property_set["layout"] self.assertIsNone(layout) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "nonexistent solution") @staticmethod def create_hard_dag(): """Creates a particularly hard circuit (returns its dag) for Tokyo""" circuit = QuantumCircuit(20) circuit.cx(13, 12) circuit.cx(6, 0) circuit.cx(5, 10) circuit.cx(10, 7) circuit.cx(5, 12) circuit.cx(2, 15) circuit.cx(16, 18) circuit.cx(6, 4) circuit.cx(10, 3) circuit.cx(11, 10) circuit.cx(18, 16) circuit.cx(5, 12) circuit.cx(4, 0) circuit.cx(18, 16) circuit.cx(2, 15) circuit.cx(7, 8) circuit.cx(9, 6) circuit.cx(16, 17) circuit.cx(9, 3) circuit.cx(14, 12) circuit.cx(2, 15) circuit.cx(1, 16) circuit.cx(5, 3) circuit.cx(8, 12) circuit.cx(2, 1) circuit.cx(5, 3) circuit.cx(13, 5) circuit.cx(12, 14) circuit.cx(12, 13) circuit.cx(6, 4) circuit.cx(15, 18) circuit.cx(15, 18) return circuit_to_dag(circuit) def test_time_limit(self): """Hard to solve situations hit the time limit""" dag = TestCSPLayout.create_hard_dag() coupling_map = CouplingMap(FakeTokyo().configuration().coupling_map) pass_ = CSPLayout(coupling_map, call_limit=None, time_limit=1) start = process_time() pass_.run(dag) runtime = process_time() - start self.assertLess(runtime, 3) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "time limit reached") def test_call_limit(self): """Hard to solve situations hit the call limit""" dag = TestCSPLayout.create_hard_dag() coupling_map = CouplingMap(FakeTokyo().configuration().coupling_map) pass_ = CSPLayout(coupling_map, call_limit=1, time_limit=None) start = process_time() pass_.run(dag) runtime = process_time() - start self.assertLess(runtime, 1) self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "call limit reached") def test_seed(self): """Different seeds yield different results""" seed_1 = 42 seed_2 = 43 cmap5 = FakeTenerife().configuration().coupling_map qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 circuit.cx(qr[0], qr[2]) # qr0 -> qr2 circuit.cx(qr[1], qr[2]) # qr1 -> qr2 dag = circuit_to_dag(circuit) pass_1 = CSPLayout(CouplingMap(cmap5), seed=seed_1) pass_1.run(dag) layout_1 = pass_1.property_set["layout"] pass_2 = CSPLayout(CouplingMap(cmap5), seed=seed_2) pass_2.run(dag) layout_2 = pass_2.property_set["layout"] self.assertNotEqual(layout_1, layout_2) if __name__ == "__main__": unittest.main()
https://github.com/HuangJunye/Qiskit-for-GameDev
HuangJunye
#!/usr/bin/env python # # Copyright 2019 the original author or authors. # # 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 pygame from qiskit import BasicAer, execute from utils.colors import * from utils.fonts import * from utils.states import comp_basis_states class UnitaryGrid(pygame.sprite.Sprite): """Displays a unitary matrix grid""" def __init__(self, circuit): pygame.sprite.Sprite.__init__(self) self.image = None self.rect = None self.basis_states = comp_basis_states(circuit.width()) self.set_circuit(circuit) # def update(self): # # Nothing yet # a = 1 def set_circuit(self, circuit): backend_unit_sim = BasicAer.get_backend('unitary_simulator') job_sim = execute(circuit, backend_unit_sim) result_sim = job_sim.result() unitary = result_sim.get_unitary(circuit, decimals=3) # print('unitary: ', unitary) self.image = pygame.Surface([100 + len(unitary) * 50, 100 + len(unitary) * 50]) self.image.convert() self.image.fill(WHITE) self.rect = self.image.get_rect() block_size = 30 x_offset = 50 y_offset = 50 for y in range(len(unitary)): text_surface = ARIAL_16.render(self.basis_states[y], False, (0, 0, 0)) self.image.blit(text_surface,(x_offset, (y + 1) * block_size + y_offset)) for x in range(len(unitary)): text_surface = ARIAL_16.render(self.basis_states[x], False, (0, 0, 0)) self.image.blit(text_surface, ((x + 1) * block_size + x_offset, y_offset)) rect = pygame.Rect((x + 1) * block_size + x_offset, (y + 1) * block_size + y_offset, abs(unitary[y][x]) * block_size, abs(unitary[y][x]) * block_size) if abs(unitary[y][x]) > 0: pygame.draw.rect(self.image, BLACK, rect, 1)
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
shell-raiser
from qiskit import * from qiskit.tools.visualization import plot_bloch_multivector circuit = QuantumCircuit(1,1) #init ckt circuit.x(0) #Simulate it simulator = Aer.get_backend('statevector_simulator') #statevector describes the quantum gate state result = execute(circuit, backend=simulator).result() statevector = execute(circuit, backend=simulator).result().get_statevector() print(statevector) #draw ckt %matplotlib inline circuit.draw() #block sphere plot_bloch_multivector(statevector) circuit.measure([0], [0]) backend = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=backend, shots = 1024).result() counts = result.get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(counts) circuit = QuantumCircuit(1,1) #init ckt circuit.x(0) #Simulate it simulator = Aer.get_backend('unitary_simulator') #notice unitary over statevector result = execute(circuit, backend=simulator).result() unitary = result.get_unitary() print(unitary) %matplotlib inline circuit.draw()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Utils for using with Qiskit unit tests.""" import logging import os import unittest from enum import Enum from qiskit import __path__ as qiskit_path class Path(Enum): """Helper with paths commonly used during the tests.""" # Main SDK path: qiskit/ SDK = qiskit_path[0] # test.python path: qiskit/test/python/ TEST = os.path.normpath(os.path.join(SDK, '..', 'test', 'python')) # Examples path: examples/ EXAMPLES = os.path.normpath(os.path.join(SDK, '..', 'examples')) # Schemas path: qiskit/schemas SCHEMAS = os.path.normpath(os.path.join(SDK, 'schemas')) # VCR cassettes path: qiskit/test/cassettes/ CASSETTES = os.path.normpath(os.path.join(TEST, '..', 'cassettes')) # Sample QASMs path: qiskit/test/python/qasm QASMS = os.path.normpath(os.path.join(TEST, 'qasm')) def setup_test_logging(logger, log_level, filename): """Set logging to file and stdout for a logger. Args: logger (Logger): logger object to be updated. log_level (str): logging level. filename (str): name of the output file. """ # Set up formatter. log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:' ' %(message)s'.format(logger.name)) formatter = logging.Formatter(log_fmt) # Set up the file handler. file_handler = logging.FileHandler(filename) file_handler.setFormatter(formatter) logger.addHandler(file_handler) # Set the logging level from the environment variable, defaulting # to INFO if it is not a valid level. level = logging._nameToLevel.get(log_level, logging.INFO) logger.setLevel(level) class _AssertNoLogsContext(unittest.case._AssertLogsContext): """A context manager used to implement TestCase.assertNoLogs().""" # pylint: disable=inconsistent-return-statements def __exit__(self, exc_type, exc_value, tb): """ This is a modified version of TestCase._AssertLogsContext.__exit__(...) """ self.logger.handlers = self.old_handlers self.logger.propagate = self.old_propagate self.logger.setLevel(self.old_level) if exc_type is not None: # let unexpected exceptions pass through return False if self.watcher.records: msg = 'logs of level {} or higher triggered on {}:\n'.format( logging.getLevelName(self.level), self.logger.name) for record in self.watcher.records: msg += 'logger %s %s:%i: %s\n' % (record.name, record.pathname, record.lineno, record.getMessage()) self._raiseFailure(msg)
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import datetime import numpy as np from matplotlib import pyplot as plt import qiskit from qiskit import * from qiskit.opflow import X,Z,I from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA, SLSQP, SPSA from qiskit.opflow import CircuitSampler from qiskit.ignis.mitigation.measurement import CompleteMeasFitter # you will need to pip install qiskit-ignis from qiskit.ignis.mitigation.measurement import complete_meas_cal from scipy import sparse import scipy.sparse.linalg.eigen.arpack as arp from modules.utils import * anti = -1 L = 5 num_trash = 2 name = "ibmq_antiferro-1D-load_bogota-optimize-20points" # remove test at the end when running on a real device filename = "data/noisy_VQE_maxiter-500_Ising_L5_anti_-1_20" #"data/noisy_VQE_maxiter-100_Ising_L5_anti_-1_20_recycle" print("filename: ", filename, "notebook name: ", name) # where to get the simulated thetas values from? needs to contain a thetas_mitigated array filename_simulated_thetas = 'data/ibmq_antiferro-1D-load_bogota-optimize_thetas-loss-cost_run2.npz' load = False recompute = True # whether or not to recompute Magnetization, makes sense on device IBMQ.load_account() # this then automatically loads your saved account provider = IBMQ.get_provider(hub='ibm-q-research') device = provider.backend.ibmq_bogota print(device) backend = device #backend = qiskit.providers.aer.AerSimulator.from_backend(device) coupling_map = device.configuration().coupling_map noise_model = qiskit.providers.aer.noise.NoiseModel.from_backend(device) basis_gates = noise_model.basis_gates #aqua_globals.random_seed = seed qi = qiskit.utils.QuantumInstance(backend=backend, # , seed_simulator=seed, seed_transpiler=seed coupling_map=coupling_map, #, noise_model=noise_model, measurement_error_mitigation_cls= CompleteMeasFitter, cals_matrix_refresh_period=30 #How often to refresh the calibration matrix in measurement mitigation. in minutes ) # Very important, at the moment poorly coded so it needs to come back to this instance all the time ansatz = qiskit.circuit.library.TwoLocal(L,rotation_blocks="ry", entanglement_blocks='cz', entanglement="sca", reps=1) ansatz.draw("mpl") ansatz = qiskit.transpile(ansatz, backend) ansatz.draw("mpl") L = 5 num_trash = 2 anti = -1 VQE_params = np.load(filename + ".npz", allow_pickle=True) pick = np.arange(0,len(VQE_params['gx_list'])) gx_list = VQE_params['gx_list'][pick] gz_list = VQE_params['gz_list'][pick] opt_params = VQE_params['opt_params'][pick] Qmags = VQE_params["Qmag"][pick] Qen = VQE_params["Qen"][pick] Sen = VQE_params["Sen"][pick] Smags = VQE_params["Smag"][pick] gx_vals = np.unique(gx_list) gz_vals = np.unique(gz_list) if load: temp = np.load("data/" + name + "executed_mags-Es.npz",allow_pickle=True) Qmags = temp["Qmags"] Qen = temp["Qen"] Sen = temp["Sen"] Smags = temp["Smags"] verbose=1 if recompute: mag = QMag(L,anti) #magnetization operator (Qiskit) Smag = Mag(L,anti) #magnetization operator (numpy) Qen_executed=np.zeros(len(opt_params), dtype="complex") Qmags_executed=np.zeros(len(opt_params), dtype="complex") for j in range(len(opt_params)): t0 = datetime.datetime.now() gx = gx_list[j] gz = gz_list[j] H = QHIsing(L, anti, np.float32(gx), np.float32(gz)) # build Hamiltonian Op state = ansatz.assign_parameters(opt_params[j]) meas_outcome = ~StateFn(mag) @ StateFn(state) Qmags_executed[j] = CircuitSampler(qi).convert(meas_outcome).eval() #https://quantumcomputing.stackexchange.com/questions/12080/evaluating-expectation-values-of-operators-in-qiskit #e_outcome = ~StateFn(H) @ StateFn(state) #Qen_executed[j] = CircuitSampler(qi).convert(e_outcome).eval() #init_state, E, ham = ising_groundstate(L, anti, np.float64(gx), np.float64(gz)) #Sen[j] = E #Smags[j] = init_state.T.conj()@Smag@init_state #Magnetization with Numpy results print(f"{j+1} / {len(opt_params)}, gx = {gx:.2f}, gz = {gz:.2f}, time : {(datetime.datetime.now() - t0)}") np.savez("data/" + name + "executed_mags-Es.npz",Qmags=Qmags_executed, Qen=Qen_executed, Sen=Sen, Smags=Smags) # for large parameter space takes quite a while because of the exact diagonalization fig, axs = plt.subplots(ncols=2, figsize=(10,5)) ax = axs[0] ax.plot(gx_list, Qmags,"x--", label="noisy VQE simu") ax.plot(gx_list, Smags,"x--", label="ED") ax.set_xscale("log") if recompute or load: ax.plot(gx_list, Qmags_executed,"x--", label="IBMQ") ax.legend() ############################################################################## ### II - Training ########################################################### ############################################################################## # linear entangler (as in scales linearly with trash qubits) def get_entangler_map(L, num_trash, i_permut=1, nums_trash=[1,2]): result = [] nums_compressed = list(range(L)) for trashqubit in nums_trash: nums_compressed.remove(trashqubit) if nums_trash == None: #old way nums_compressed = list(range(L))[:L-num_trash] nums_trash = list(range(L))[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly for i in range(L-num_trash): result.append((repeated[i_permut + i], nums_compressed[i])) return result def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz", nums_trash = [1,2]): entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)] if nums_trash == None: nums_trash = list(range(L))[-num_trash:] circ = qiskit.circuit.library.TwoLocal(L, parametrized_gate, entangling_gate, entanglement, reps=num_trash, insert_barriers=insert_barriers, skip_final_rotation_layer=True ).assign_parameters(thetas[:-num_trash]) if insert_barriers: circ.barrier() for i in nums_trash: circ.ry(thetas[i], i) #circ.ry(circuit.Parameter(f'θ{i}'), L-i-1) return circ def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(num_trash, 'c') circ = QuantumCircuit(qreg, creg) circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=False)#.assign_parameters(thetas) # difference to bind? if measurement: for i in range(num_trash): circ.measure(qreg[L-i-1], creg[i]) if init_state is not None: if vqe: circ = ansatz.assign_parameters(init_state) + circ # needs to have ansatz defined somewhere in the script else: circ.initialize(init_state, qreg) return circ def feature_encoding(thetas, x): """ thetas: parameters to be optimized, x: Ising model parameter (eg. field) """ new_thetas = [] thetas = thetas.reshape((-1,2)) for theta in thetas: new_thetas.append(theta[0] * x + theta[1]) return new_thetas def calibrate_circuit(L, num_trash,shots=1000): qreg = QuantumRegister(L, 'q') # obtain calibration matrix qubit_list = [L-i-1 for i in range(num_trash)] # only need to calibrate the trash qubits circlabel = f'mcal_{datetime.datetime.now()}' meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qreg, circlabel=circlabel) cal_job = backend.run(meas_calibs, shots=shots) #, noise_model=noise_model) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel=circlabel) print(circlabel, meas_fitter.cal_matrix) return meas_fitter def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100, meas_fitter = None): circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) tcirc = qiskit.transpile(circ, backend) # Execute the circuit job_sim = backend.run(tcirc, shots=shots) # , seed_simulator=123, seed_transpiler=234 fix seed to make it reproducible result = job_sim.result() # Results without mitigation counts = result.get_counts() if meas_fitter != None: # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(result) counts = mitigated_results.get_counts(0) return counts meas_fitter = calibrate_circuit(L, num_trash) phis = opt_params # translate to Rikes naming gxs = gx_list gzs = gz_list def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ if vqe: init_state = phis[p] else: J, gx, gz = p init_state, _ = ising_groundstate(L, J, gx, gz) if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots, meas_fitter=meas_fitter) cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0) return cost/shots def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ cost = 0. n_samples = len(ising_params) for i, p in enumerate(ising_params): if param_encoding: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i], meas_fitter=meas_fitter) else: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, meas_fitter=meas_fitter) return cost/n_samples def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None, meas_fitter=None): if thetas is None: n_params = (2*L+2)*2 if param_encoding else (2*L+2) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer if pick_optimizer == "cobyla": optimizer = COBYLA(maxiter=max_iter, tol=0.0001) if pick_optimizer == "adam" or pick_optimizer == "ADAM": optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) if pick_optimizer == "spsa" or pick_optimizer == None: optimizer = SPSA(maxiter=max_iter, #blocking=True, #callback=store_intermediate_result, learning_rate=0.3, perturbation=0.1 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x, meas_fitter=meas_fitter)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted def run_inference(thetas, shots=1000, L=5, meas_fitter=None): points = 50 J = -1.0 x,y = np.meshgrid(gx_vals, gz_vals) cost = np.zeros((len(gx_vals) * len(gz_vals))) Smags = np.zeros((len(gx_vals) * len(gz_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) if not i%verbose: print(f"{i+1} / {len(opt_params)}, gx = {gx:.2f}, gz = {gz:.2f}, time : {verbose*(datetime.datetime.now() - t0)}") cost = cost.reshape((len(gx_vals), len(gz_vals))) return cost phys_params = [0] filename_simulated_thetas = 'data/ibmq_antiferro-1D-load_simu_thetas-loss-cost_run2.npz' #this was actually a mistake, should have been the run1 but seemed to have worked anyways thetas_guess = np.load(filename_simulated_thetas, allow_pickle=True)["thetas_mitigated"] # Training to = datetime.datetime.now() thetas_opt_mitigated, loss, accepted = optimize(phys_params, thetas = thetas_guess, max_iter=30, L=5,meas_fitter=meas_fitter) #, pick_optimizer="adam") plt.plot(loss) print(datetime.datetime.now() - t0) # Inference cost_mitigated = np.zeros((len(gx_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): t0 = datetime.datetime.now() cost_mitigated[i] = cost_function_single(thetas_opt_mitigated, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something if not i%verbose: print(f"{i+1} / {len(opt_params)}, gx = {p[0]:.2f}, gz = {p[1]:.2f}, time : {verbose*(datetime.datetime.now() - t0)}") np.savez("data/" + name + "_thetas-loss-cost_run1", cost_mitigated=cost_mitigated, thetas_mitigated=thetas_opt_mitigated, ) fig, ax = plt.subplots(ncols=1,figsize=(6,5)) ax.set_title("Mitigated results") cost = np.load("data/" + name + "_thetas-loss-cost_run1.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,".:", label="raw output") ax.plot(gx_list, Qmags,"x--", label="$\\langle \\sigma_z \\rangle$ noisy sim") ax.plot(gx_list, Qmags_executed,"x--", label="$\\langle \\sigma_z \\rangle$ ibmq_bogota") ax.set_xscale("log") for p in phys_params: ax.plot(gx_list[p],cost[p],"o",alpha=0.3,color="magenta") ax.legend() np.savez("data/" + name + "_thetas-loss-cost_run2", cost_mitigated=cost_mitigated, thetas_mitigated=thetas_opt_mitigated, ) filename_simulated_thetas = 'data/ibmq_antiferro-1D-load_bogota-optimize_thetas-loss-cost_run2.npz' fig, ax = plt.subplots(ncols=1,figsize=(6,5)) ax.set_title("Mitigated results") cost = np.load("data/" + name + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,".:", label="raw output") ax.plot(gx_list, Qmags,"x--", color="tab:orange", label="Qmag") ax.set_xscale("log") for p in phys_params: ax.plot(gx_list[p],cost[p],"o",alpha=0.3,color="magenta")
https://github.com/Keerthiraj-Nagaraj/IBM-quantum-challenge-2020
Keerthiraj-Nagaraj
from IPython.display import Image, display Image('ryoko_pillars.png') Image('lights_out_rule.png') Image('lights_out_prob.png') import numpy as np # import qiskit libraries from qiskit import IBMQ, Aer,QuantumRegister, ClassicalRegister, QuantumCircuit, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Operator from qiskit.tools.jupyter import * #provider = IBMQ.load_account() #import functions to plot from qiskit.visualization import plot_histogram # The starting pattern is represented by this list of numbers. # Please use it as an input for your solution. lights = [0, 1, 1, 1, 0, 0, 1, 1, 1] def week2a_ans_func(lights): ##### build your quantum circuit here def lights_oracle(qc, sol, board, orc_out, anc, c_out): flip_matrix = [[1,1,0,1,0,0,0,0,0], [1,1,1,0,1,0,0,0,0], [0,1,1,0,0,1,0,0,0], [1,0,0,1,1,0,1,0,0], [0,1,0,1,1,1,0,1,0], [0,0,1,0,1,1,0,0,1], [0,0,0,1,0,0,1,1,0], [0,0,0,0,1,0,1,1,1], [0,0,0,0,0,1,0,1,1]] for sol_bit in range(len(flip_matrix)): for board_bit in range(len(flip_matrix[sol_bit])): if flip_matrix[sol_bit][board_bit] == 1: qc.cx(sol[sol_bit], board[board_bit]) qc.barrier() for i in range(len(flip_matrix)): qc.x(board[i]) qc.barrier() qc.mct([board[0], board[1],board[2],board[3],board[4],board[5],board[6],board[7],board[8]], orc_out, [anc[0], anc[1],anc[2],anc[3],anc[4],anc[5],anc[6]], mode='v-chain') qc.barrier() for i in range(len(flip_matrix)): qc.x(board[i]) for sol_bit in range(len(flip_matrix)): for board_bit in range(len(flip_matrix[sol_bit])): if flip_matrix[sol_bit][board_bit] == 1: qc.cx(sol[sol_bit], board[board_bit]) def diffuser(nqubits): qc = QuantumCircuit(nqubits) for qubit in range(nqubits): qc.h(qubit) for qubit in range(nqubits): qc.x(qubit) qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) for qubit in range(nqubits): qc.x(qubit) for qubit in range(nqubits): qc.h(qubit) U_f0 = qc.to_gate() U_f0.name = "V" return U_f0 #def groverLights(lights): n = len(lights) r = int(np.round(np.pi/(4*np.arcsin(np.sqrt(1/3**n)))-1/2)) print(f'{3*n-1} qubits, {r} rounds') board = QuantumRegister(n, 'board') sol = QuantumRegister(n, 'solution') anc = QuantumRegister(n-2, 'anc') orc_out = QuantumRegister(1, 'oracle_out') c_out = ClassicalRegister(n, 'classical_bits') qc = QuantumCircuit(sol, board, orc_out, anc, c_out) for l in range(n): if lights[l] == 1: qc.x(board[l]) qc.x(orc_out) qc.h(orc_out) qc.barrier() qc.h(sol) qc.barrier() r = 1 for _ in range(r): lights_oracle(qc, sol, board, orc_out, anc, c_out) qc.barrier() qc.append(diffuser(n), sol) qc.barrier() qc.measure(sol, c_out) qc = qc.reverse_bits() ##### In addition, please make it a function that can solve the problem even with different inputs (lights). We do validation with different inputs. return qc # Submission code from qc_grader import prepare_ex2a, grade_ex2a, submit_ex2a # Execute your circuit with following prepare_ex2a() function. # The prepare_ex2a () function works like the execute() function with only QuantumCircuit as an argument. job = prepare_ex2a(week2a_ans_func) result = job.result() count = result.get_counts() original_problem_set_counts = count[0] original_problem_set_counts # The bit string with the highest number of observations is treated as the solution. # Check your answer by executing following code. # The quantum cost of the QuantumCircuit is obtained as the score. The quantum cost is related to rank only in the third week. grade_ex2a(job) # Submit your results by executing following code. You can submit as many times as you like during the period. submit_ex2a(job)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Qiskit's QuantumCircuit class.""" import numpy as np from ddt import data, ddt from qiskit import BasicAer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute from qiskit.circuit import Gate, Instruction, Measure, Parameter from qiskit.circuit.bit import Bit from qiskit.circuit.classicalregister import Clbit from qiskit.circuit.exceptions import CircuitError from qiskit.circuit.controlflow import IfElseOp from qiskit.circuit.library import CXGate, HGate from qiskit.circuit.library.standard_gates import SGate from qiskit.circuit.quantumcircuit import BitLocations from qiskit.circuit.quantumcircuitdata import CircuitInstruction from qiskit.circuit.quantumregister import AncillaQubit, AncillaRegister, Qubit from qiskit.pulse import DriveChannel, Gaussian, Play, Schedule from qiskit.quantum_info import Operator from qiskit.test import QiskitTestCase @ddt class TestCircuitOperations(QiskitTestCase): """QuantumCircuit Operations tests.""" @data(0, 1, -1, -2) def test_append_resolves_integers(self, index): """Test that integer arguments to append are correctly resolved.""" # We need to assume that appending ``Bit`` instances will always work, so we have something # to test against. qubits = [Qubit(), Qubit()] clbits = [Clbit(), Clbit()] test = QuantumCircuit(qubits, clbits) test.append(Measure(), [index], [index]) expected = QuantumCircuit(qubits, clbits) expected.append(Measure(), [qubits[index]], [clbits[index]]) self.assertEqual(test, expected) @data(np.int32(0), np.int8(-1), np.uint64(1)) def test_append_resolves_numpy_integers(self, index): """Test that Numpy's integers can be used to reference qubits and clbits.""" qubits = [Qubit(), Qubit()] clbits = [Clbit(), Clbit()] test = QuantumCircuit(qubits, clbits) test.append(Measure(), [index], [index]) expected = QuantumCircuit(qubits, clbits) expected.append(Measure(), [qubits[int(index)]], [clbits[int(index)]]) self.assertEqual(test, expected) @data( slice(0, 2), slice(None, 1), slice(1, None), slice(None, None), slice(0, 2, 2), slice(2, -1, -1), slice(1000, 1003), ) def test_append_resolves_slices(self, index): """Test that slices can be used to reference qubits and clbits with the same semantics that they have on lists.""" qregs = [QuantumRegister(2), QuantumRegister(1)] cregs = [ClassicalRegister(1), ClassicalRegister(2)] test = QuantumCircuit(*qregs, *cregs) test.append(Measure(), [index], [index]) expected = QuantumCircuit(*qregs, *cregs) for qubit, clbit in zip(expected.qubits[index], expected.clbits[index]): expected.append(Measure(), [qubit], [clbit]) self.assertEqual(test, expected) def test_append_resolves_scalar_numpy_array(self): """Test that size-1 Numpy arrays can be used to index arguments. These arrays can be passed to ``int``, which means they sometimes might be involved in spurious casts.""" test = QuantumCircuit(1, 1) test.append(Measure(), [np.array([0])], [np.array([0])]) expected = QuantumCircuit(1, 1) expected.measure(0, 0) self.assertEqual(test, expected) @data([3], [-3], [0, 1, 3]) def test_append_rejects_out_of_range_input(self, specifier): """Test that append rejects an integer that's out of range.""" test = QuantumCircuit(2, 2) with self.subTest("qubit"), self.assertRaisesRegex(CircuitError, "out of range"): opaque = Instruction("opaque", len(specifier), 1, []) test.append(opaque, specifier, [0]) with self.subTest("clbit"), self.assertRaisesRegex(CircuitError, "out of range"): opaque = Instruction("opaque", 1, len(specifier), []) test.append(opaque, [0], specifier) def test_append_rejects_bits_not_in_circuit(self): """Test that append rejects bits that are not in the circuit.""" test = QuantumCircuit(2, 2) with self.subTest("qubit"), self.assertRaisesRegex(CircuitError, "not in the circuit"): test.append(Measure(), [Qubit()], [test.clbits[0]]) with self.subTest("clbit"), self.assertRaisesRegex(CircuitError, "not in the circuit"): test.append(Measure(), [test.qubits[0]], [Clbit()]) with self.subTest("qubit list"), self.assertRaisesRegex(CircuitError, "not in the circuit"): test.append(Measure(), [[test.qubits[0], Qubit()]], [test.clbits]) with self.subTest("clbit list"), self.assertRaisesRegex(CircuitError, "not in the circuit"): test.append(Measure(), [test.qubits], [[test.clbits[0], Clbit()]]) def test_append_rejects_bit_of_wrong_type(self): """Test that append rejects bits of the wrong type in an argument list.""" qubits = [Qubit(), Qubit()] clbits = [Clbit(), Clbit()] test = QuantumCircuit(qubits, clbits) with self.subTest("c to q"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"): test.append(Measure(), [clbits[0]], [clbits[1]]) with self.subTest("q to c"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"): test.append(Measure(), [qubits[0]], [qubits[1]]) with self.subTest("none to q"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"): test.append(Measure(), [Bit()], [clbits[0]]) with self.subTest("none to c"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"): test.append(Measure(), [qubits[0]], [Bit()]) with self.subTest("none list"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"): test.append(Measure(), [[qubits[0], Bit()]], [[clbits[0], Bit()]]) @data(0.0, 1.0, 1.0 + 0.0j, "0") def test_append_rejects_wrong_types(self, specifier): """Test that various bad inputs are rejected, both given loose or in sublists.""" test = QuantumCircuit(2, 2) # Use a default Instruction to be sure that there's not overridden broadcasting. opaque = Instruction("opaque", 1, 1, []) with self.subTest("q"), self.assertRaisesRegex(CircuitError, "Invalid bit index"): test.append(opaque, [specifier], [0]) with self.subTest("c"), self.assertRaisesRegex(CircuitError, "Invalid bit index"): test.append(opaque, [0], [specifier]) with self.subTest("q list"), self.assertRaisesRegex(CircuitError, "Invalid bit index"): test.append(opaque, [[specifier]], [[0]]) with self.subTest("c list"), self.assertRaisesRegex(CircuitError, "Invalid bit index"): test.append(opaque, [[0]], [[specifier]]) @data([], [0], [0, 1, 2]) def test_append_rejects_bad_arguments_opaque(self, bad_arg): """Test that a suitable exception is raised when there is an argument mismatch.""" inst = QuantumCircuit(2, 2).to_instruction() qc = QuantumCircuit(3, 3) with self.assertRaisesRegex(CircuitError, "The amount of qubit arguments"): qc.append(inst, bad_arg, [0, 1]) with self.assertRaisesRegex(CircuitError, "The amount of clbit arguments"): qc.append(inst, [0, 1], bad_arg) def test_anding_self(self): """Test that qc &= qc finishes, which can be prone to infinite while-loops. This can occur e.g. when a user tries >>> other_qc = qc >>> other_qc &= qc # or qc2.compose(qc) """ qc = QuantumCircuit(1) qc.x(0) # must contain at least one operation to end up in a infinite while-loop # attempt addition, times out if qc is added via reference qc &= qc # finally, qc should contain two X gates self.assertEqual(["x", "x"], [x.operation.name for x in qc.data]) def test_compose_circuit(self): """Test composing two circuits""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc1 = QuantumCircuit(qr, cr) qc2 = QuantumCircuit(qr, cr) qc1.h(qr[0]) qc1.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) qc3 = qc1.compose(qc2) backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc3, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2}) self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place" self.assertDictEqual(qc2.count_ops(), {"measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_compose_circuit_and(self): """Test composing two circuits using & operator""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc1 = QuantumCircuit(qr, cr) qc2 = QuantumCircuit(qr, cr) qc1.h(qr[0]) qc1.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) qc3 = qc1 & qc2 backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc3, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2}) self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place" self.assertDictEqual(qc2.count_ops(), {"measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_compose_circuit_iand(self): """Test composing circuits using &= operator (in place)""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc1 = QuantumCircuit(qr, cr) qc2 = QuantumCircuit(qr, cr) qc1.h(qr[0]) qc1.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) qc1 &= qc2 backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc1, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 2}) # changes "in-place" self.assertDictEqual(qc2.count_ops(), {"measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_compose_circuit_fail_circ_size(self): """Test composing circuit fails when number of wires in circuit is not enough""" qr1 = QuantumRegister(2) qr2 = QuantumRegister(4) # Creating our circuits qc1 = QuantumCircuit(qr1) qc1.x(0) qc1.h(1) qc2 = QuantumCircuit(qr2) qc2.h([1, 2]) qc2.cx(2, 3) # Composing will fail because qc2 requires 4 wires self.assertRaises(CircuitError, qc1.compose, qc2) def test_compose_circuit_fail_arg_size(self): """Test composing circuit fails when arg size does not match number of wires""" qr1 = QuantumRegister(2) qr2 = QuantumRegister(2) qc1 = QuantumCircuit(qr1) qc1.h(0) qc2 = QuantumCircuit(qr2) qc2.cx(0, 1) self.assertRaises(CircuitError, qc1.compose, qc2, qubits=[0]) def test_tensor_circuit(self): """Test tensoring two circuits""" qc1 = QuantumCircuit(1, 1) qc2 = QuantumCircuit(1, 1) qc2.h(0) qc2.measure(0, 0) qc1.measure(0, 0) qc3 = qc1.tensor(qc2) backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc3, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2}) self.assertDictEqual(qc2.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place" self.assertDictEqual(qc1.count_ops(), {"measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_tensor_circuit_xor(self): """Test tensoring two circuits using ^ operator""" qc1 = QuantumCircuit(1, 1) qc2 = QuantumCircuit(1, 1) qc2.h(0) qc2.measure(0, 0) qc1.measure(0, 0) qc3 = qc1 ^ qc2 backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc3, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2}) self.assertDictEqual(qc2.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place" self.assertDictEqual(qc1.count_ops(), {"measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_tensor_circuit_ixor(self): """Test tensoring two circuits using ^= operator""" qc1 = QuantumCircuit(1, 1) qc2 = QuantumCircuit(1, 1) qc2.h(0) qc2.measure(0, 0) qc1.measure(0, 0) qc1 ^= qc2 backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc1, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 2}) # changes "in-place" self.assertDictEqual(qc2.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_measure_args_type_cohesion(self): """Test for proper args types for measure function.""" quantum_reg = QuantumRegister(3) classical_reg_0 = ClassicalRegister(1) classical_reg_1 = ClassicalRegister(2) quantum_circuit = QuantumCircuit(quantum_reg, classical_reg_0, classical_reg_1) quantum_circuit.h(quantum_reg) with self.assertRaises(CircuitError) as ctx: quantum_circuit.measure(quantum_reg, classical_reg_1) self.assertEqual(ctx.exception.message, "register size error") def test_copy_circuit(self): """Test copy method makes a copy""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) self.assertEqual(qc, qc.copy()) def test_copy_copies_registers(self): """Test copy copies the registers not via reference.""" qc = QuantumCircuit(1, 1) copied = qc.copy() copied.add_register(QuantumRegister(1, "additional_q")) copied.add_register(ClassicalRegister(1, "additional_c")) self.assertEqual(len(qc.qregs), 1) self.assertEqual(len(copied.qregs), 2) self.assertEqual(len(qc.cregs), 1) self.assertEqual(len(copied.cregs), 2) def test_copy_empty_like_circuit(self): """Test copy_empty_like method makes a clear copy.""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr, global_phase=1.0, name="qc", metadata={"key": "value"}) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) sched = Schedule(Play(Gaussian(160, 0.1, 40), DriveChannel(0))) qc.add_calibration("h", [0, 1], sched) copied = qc.copy_empty_like() qc.clear() self.assertEqual(qc, copied) self.assertEqual(qc.global_phase, copied.global_phase) self.assertEqual(qc.name, copied.name) self.assertEqual(qc.metadata, copied.metadata) self.assertEqual(qc.calibrations, copied.calibrations) copied = qc.copy_empty_like("copy") self.assertEqual(copied.name, "copy") def test_circuit_copy_rejects_invalid_types(self): """Test copy method rejects argument with type other than 'string' and 'None' type.""" qc = QuantumCircuit(1, 1) qc.h(0) with self.assertRaises(TypeError): qc.copy([1, "2", 3]) def test_circuit_copy_empty_like_rejects_invalid_types(self): """Test copy_empty_like method rejects argument with type other than 'string' and 'None' type.""" qc = QuantumCircuit(1, 1) qc.h(0) with self.assertRaises(TypeError): qc.copy_empty_like(123) def test_clear_circuit(self): """Test clear method deletes instructions in circuit.""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qc.clear() self.assertEqual(len(qc.data), 0) self.assertEqual(len(qc._parameter_table), 0) def test_measure_active(self): """Test measure_active Applies measurements only to non-idle qubits. Creates a ClassicalRegister of size equal to the amount of non-idle qubits to store the measured values. """ qr = QuantumRegister(4) cr = ClassicalRegister(2, "measure") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[2]) circuit.measure_active() expected = QuantumCircuit(qr) expected.h(qr[0]) expected.h(qr[2]) expected.add_register(cr) expected.barrier() expected.measure([qr[0], qr[2]], [cr[0], cr[1]]) self.assertEqual(expected, circuit) def test_measure_active_copy(self): """Test measure_active copy Applies measurements only to non-idle qubits. Creates a ClassicalRegister of size equal to the amount of non-idle qubits to store the measured values. """ qr = QuantumRegister(4) cr = ClassicalRegister(2, "measure") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[2]) new_circuit = circuit.measure_active(inplace=False) expected = QuantumCircuit(qr) expected.h(qr[0]) expected.h(qr[2]) expected.add_register(cr) expected.barrier() expected.measure([qr[0], qr[2]], [cr[0], cr[1]]) self.assertEqual(expected, new_circuit) self.assertFalse("measure" in circuit.count_ops().keys()) def test_measure_active_repetition(self): """Test measure_active in a circuit with a 'measure' creg. measure_active should be aware that the creg 'measure' might exists. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "measure") circuit = QuantumCircuit(qr, cr) circuit.h(qr) circuit.measure_active() self.assertEqual(len(circuit.cregs), 2) # Two cregs self.assertEqual(len(circuit.cregs[0]), 2) # Both length 2 self.assertEqual(len(circuit.cregs[1]), 2) def test_measure_all(self): """Test measure_all applies measurements to all qubits. Creates a ClassicalRegister of size equal to the total amount of qubits to store those measured values. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr) circuit.measure_all() expected = QuantumCircuit(qr, cr) expected.barrier() expected.measure(qr, cr) self.assertEqual(expected, circuit) def test_measure_all_not_add_bits_equal(self): """Test measure_all applies measurements to all qubits. Does not create a new ClassicalRegister if the existing one is big enough. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr, cr) circuit.measure_all(add_bits=False) expected = QuantumCircuit(qr, cr) expected.barrier() expected.measure(qr, cr) self.assertEqual(expected, circuit) def test_measure_all_not_add_bits_bigger(self): """Test measure_all applies measurements to all qubits. Does not create a new ClassicalRegister if the existing one is big enough. """ qr = QuantumRegister(2) cr = ClassicalRegister(3, "meas") circuit = QuantumCircuit(qr, cr) circuit.measure_all(add_bits=False) expected = QuantumCircuit(qr, cr) expected.barrier() expected.measure(qr, cr[0:2]) self.assertEqual(expected, circuit) def test_measure_all_not_add_bits_smaller(self): """Test measure_all applies measurements to all qubits. Raises an error if there are not enough classical bits to store the measurements. """ qr = QuantumRegister(3) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr, cr) with self.assertRaisesRegex(CircuitError, "The number of classical bits"): circuit.measure_all(add_bits=False) def test_measure_all_copy(self): """Test measure_all with inplace=False""" qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr) new_circuit = circuit.measure_all(inplace=False) expected = QuantumCircuit(qr, cr) expected.barrier() expected.measure(qr, cr) self.assertEqual(expected, new_circuit) self.assertFalse("measure" in circuit.count_ops().keys()) def test_measure_all_repetition(self): """Test measure_all in a circuit with a 'measure' creg. measure_all should be aware that the creg 'measure' might exists. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "measure") circuit = QuantumCircuit(qr, cr) circuit.measure_all() self.assertEqual(len(circuit.cregs), 2) # Two cregs self.assertEqual(len(circuit.cregs[0]), 2) # Both length 2 self.assertEqual(len(circuit.cregs[1]), 2) def test_remove_final_measurements(self): """Test remove_final_measurements Removes all measurements at end of circuit. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) circuit.remove_final_measurements() expected = QuantumCircuit(qr) self.assertEqual(expected, circuit) def test_remove_final_measurements_copy(self): """Test remove_final_measurements on copy Removes all measurements at end of circuit. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) new_circuit = circuit.remove_final_measurements(inplace=False) expected = QuantumCircuit(qr) self.assertEqual(expected, new_circuit) self.assertTrue("measure" in circuit.count_ops().keys()) def test_remove_final_measurements_copy_with_parameters(self): """Test remove_final_measurements doesn't corrupt ParameterTable See https://github.com/Qiskit/qiskit-terra/issues/6108 for more details """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") theta = Parameter("theta") circuit = QuantumCircuit(qr, cr) circuit.rz(theta, qr) circuit.measure(qr, cr) circuit.remove_final_measurements() copy = circuit.copy() self.assertEqual(copy, circuit) def test_remove_final_measurements_multiple_measures(self): """Test remove_final_measurements only removes measurements at the end of the circuit remove_final_measurements should not remove measurements in the beginning or middle of the circuit. """ qr = QuantumRegister(2) cr = ClassicalRegister(1) circuit = QuantumCircuit(qr, cr) circuit.measure(qr[0], cr) circuit.h(0) circuit.measure(qr[0], cr) circuit.h(0) circuit.measure(qr[0], cr) circuit.remove_final_measurements() expected = QuantumCircuit(qr, cr) expected.measure(qr[0], cr) expected.h(0) expected.measure(qr[0], cr) expected.h(0) self.assertEqual(expected, circuit) def test_remove_final_measurements_5802(self): """Test remove_final_measurements removes classical bits https://github.com/Qiskit/qiskit-terra/issues/5802. """ qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) circuit.remove_final_measurements() self.assertEqual(circuit.cregs, []) self.assertEqual(circuit.clbits, []) def test_remove_final_measurements_7089(self): """Test remove_final_measurements removes resulting unused registers even if not all bits were measured into. https://github.com/Qiskit/qiskit-terra/issues/7089. """ circuit = QuantumCircuit(2, 5) circuit.measure(0, 0) circuit.measure(1, 1) circuit.remove_final_measurements(inplace=True) self.assertEqual(circuit.cregs, []) self.assertEqual(circuit.clbits, []) def test_remove_final_measurements_bit_locations(self): """Test remove_final_measurements properly recalculates clbit indicies and preserves order of remaining cregs and clbits. """ c0 = ClassicalRegister(1) c1_0 = Clbit() c2 = ClassicalRegister(1) c3 = ClassicalRegister(1) # add an individual bit that's not in any register of this circuit circuit = QuantumCircuit(QuantumRegister(1), c0, [c1_0], c2, c3) circuit.measure(0, c1_0) circuit.measure(0, c2[0]) # assert cregs and clbits before measure removal self.assertEqual(circuit.cregs, [c0, c2, c3]) self.assertEqual(circuit.clbits, [c0[0], c1_0, c2[0], c3[0]]) # assert clbit indices prior to measure removal self.assertEqual(circuit.find_bit(c0[0]), BitLocations(0, [(c0, 0)])) self.assertEqual(circuit.find_bit(c1_0), BitLocations(1, [])) self.assertEqual(circuit.find_bit(c2[0]), BitLocations(2, [(c2, 0)])) self.assertEqual(circuit.find_bit(c3[0]), BitLocations(3, [(c3, 0)])) circuit.remove_final_measurements() # after measure removal, creg c2 should be gone, as should lone bit c1_0 # and c0 should still come before c3 self.assertEqual(circuit.cregs, [c0, c3]) self.assertEqual(circuit.clbits, [c0[0], c3[0]]) # there should be no gaps in clbit indices # e.g. c3[0] is now the second clbit self.assertEqual(circuit.find_bit(c0[0]), BitLocations(0, [(c0, 0)])) self.assertEqual(circuit.find_bit(c3[0]), BitLocations(1, [(c3, 0)])) def test_reverse(self): """Test reverse method reverses but does not invert.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.s(1) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) qc.x(0) qc.y(1) expected = QuantumCircuit(2, 2) expected.y(1) expected.x(0) expected.measure([0, 1], [0, 1]) expected.cx(0, 1) expected.s(1) expected.h(0) self.assertEqual(qc.reverse_ops(), expected) def test_repeat(self): """Test repeating the circuit works.""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.h(0).c_if(cr, 1) with self.subTest("repeat 0 times"): rep = qc.repeat(0) self.assertEqual(rep, QuantumCircuit(qr, cr)) with self.subTest("repeat 3 times"): inst = qc.to_instruction() ref = QuantumCircuit(qr, cr) for _ in range(3): ref.append(inst, ref.qubits, ref.clbits) rep = qc.repeat(3) self.assertEqual(rep, ref) @data(0, 1, 4) def test_repeat_global_phase(self, num): """Test the global phase is properly handled upon repeat.""" phase = 0.123 qc = QuantumCircuit(1, global_phase=phase) expected = np.exp(1j * phase * num) * np.identity(2) np.testing.assert_array_almost_equal(Operator(qc.repeat(num)).data, expected) def test_bind_global_phase(self): """Test binding global phase.""" x = Parameter("x") circuit = QuantumCircuit(1, global_phase=x) self.assertEqual(circuit.parameters, {x}) bound = circuit.bind_parameters({x: 2}) self.assertEqual(bound.global_phase, 2) self.assertEqual(bound.parameters, set()) def test_bind_parameter_in_phase_and_gate(self): """Test binding a parameter present in the global phase and the gates.""" x = Parameter("x") circuit = QuantumCircuit(1, global_phase=x) circuit.rx(x, 0) self.assertEqual(circuit.parameters, {x}) ref = QuantumCircuit(1, global_phase=2) ref.rx(2, 0) bound = circuit.bind_parameters({x: 2}) self.assertEqual(bound, ref) self.assertEqual(bound.parameters, set()) def test_power(self): """Test taking the circuit to a power works.""" qc = QuantumCircuit(2) qc.cx(0, 1) qc.rx(0.2, 1) gate = qc.to_gate() with self.subTest("power(int >= 0) equals repeat"): self.assertEqual(qc.power(4), qc.repeat(4)) with self.subTest("explicit matrix power"): self.assertEqual(qc.power(4, matrix_power=True).data[0].operation, gate.power(4)) with self.subTest("float power"): self.assertEqual(qc.power(1.23).data[0].operation, gate.power(1.23)) with self.subTest("negative power"): self.assertEqual(qc.power(-2).data[0].operation, gate.power(-2)) def test_power_parameterized_circuit(self): """Test taking a parameterized circuit to a power.""" theta = Parameter("th") qc = QuantumCircuit(2) qc.cx(0, 1) qc.rx(theta, 1) with self.subTest("power(int >= 0) equals repeat"): self.assertEqual(qc.power(4), qc.repeat(4)) with self.subTest("cannot to matrix power if parameterized"): with self.assertRaises(CircuitError): _ = qc.power(0.5) def test_control(self): """Test controlling the circuit.""" qc = QuantumCircuit(2, name="my_qc") qc.cry(0.2, 0, 1) c_qc = qc.control() with self.subTest("return type is circuit"): self.assertIsInstance(c_qc, QuantumCircuit) with self.subTest("test name"): self.assertEqual(c_qc.name, "c_my_qc") with self.subTest("repeated control"): cc_qc = c_qc.control() self.assertEqual(cc_qc.num_qubits, c_qc.num_qubits + 1) with self.subTest("controlled circuit has same parameter"): param = Parameter("p") qc.rx(param, 0) c_qc = qc.control() self.assertEqual(qc.parameters, c_qc.parameters) with self.subTest("non-unitary operation raises"): qc.reset(0) with self.assertRaises(CircuitError): _ = qc.control() def test_control_implementation(self): """Run a test case for controlling the circuit, which should use ``Gate.control``.""" qc = QuantumCircuit(3) qc.cx(0, 1) qc.cry(0.2, 0, 1) qc.t(0) qc.append(SGate().control(2), [0, 1, 2]) qc.iswap(2, 0) c_qc = qc.control(2, ctrl_state="10") cgate = qc.to_gate().control(2, ctrl_state="10") ref = QuantumCircuit(*c_qc.qregs) ref.append(cgate, ref.qubits) self.assertEqual(ref, c_qc) @data("gate", "instruction") def test_repeat_appended_type(self, subtype): """Test repeat appends Gate if circuit contains only gates and Instructions otherwise.""" sub = QuantumCircuit(2) sub.x(0) if subtype == "gate": sub = sub.to_gate() else: sub = sub.to_instruction() qc = QuantumCircuit(2) qc.append(sub, [0, 1]) rep = qc.repeat(3) if subtype == "gate": self.assertTrue(all(isinstance(op.operation, Gate) for op in rep.data)) else: self.assertTrue(all(isinstance(op.operation, Instruction) for op in rep.data)) def test_reverse_bits(self): """Test reversing order of bits.""" qc = QuantumCircuit(3, 2) qc.h(0) qc.s(1) qc.cx(0, 1) qc.measure(0, 1) qc.x(0) qc.y(1) qc.global_phase = -1 expected = QuantumCircuit(3, 2) expected.h(2) expected.s(1) expected.cx(2, 1) expected.measure(2, 0) expected.x(2) expected.y(1) expected.global_phase = -1 self.assertEqual(qc.reverse_bits(), expected) def test_reverse_bits_boxed(self): """Test reversing order of bits in a hierarchical circuit.""" wide_cx = QuantumCircuit(3) wide_cx.cx(0, 1) wide_cx.cx(1, 2) wide_cxg = wide_cx.to_gate() cx_box = QuantumCircuit(3) cx_box.append(wide_cxg, [0, 1, 2]) expected = QuantumCircuit(3) expected.cx(2, 1) expected.cx(1, 0) self.assertEqual(cx_box.reverse_bits().decompose(), expected) self.assertEqual(cx_box.decompose().reverse_bits(), expected) # box one more layer to be safe. cx_box_g = cx_box.to_gate() cx_box_box = QuantumCircuit(4) cx_box_box.append(cx_box_g, [0, 1, 2]) cx_box_box.cx(0, 3) expected2 = QuantumCircuit(4) expected2.cx(3, 2) expected2.cx(2, 1) expected2.cx(3, 0) self.assertEqual(cx_box_box.reverse_bits().decompose().decompose(), expected2) def test_reverse_bits_with_registers(self): """Test reversing order of bits when registers are present.""" qr1 = QuantumRegister(3, "a") qr2 = QuantumRegister(2, "b") qc = QuantumCircuit(qr1, qr2) qc.h(qr1[0]) qc.cx(qr1[0], qr1[1]) qc.cx(qr1[1], qr1[2]) qc.cx(qr1[2], qr2[0]) qc.cx(qr2[0], qr2[1]) expected = QuantumCircuit(qr2, qr1) expected.h(qr1[2]) expected.cx(qr1[2], qr1[1]) expected.cx(qr1[1], qr1[0]) expected.cx(qr1[0], qr2[1]) expected.cx(qr2[1], qr2[0]) self.assertEqual(qc.reverse_bits(), expected) def test_reverse_bits_with_overlapped_registers(self): """Test reversing order of bits when registers are overlapped.""" qr1 = QuantumRegister(2, "a") qr2 = QuantumRegister(bits=[qr1[0], qr1[1], Qubit()], name="b") qc = QuantumCircuit(qr1, qr2) qc.h(qr1[0]) qc.cx(qr1[0], qr1[1]) qc.cx(qr1[1], qr2[2]) qr2 = QuantumRegister(bits=[Qubit(), qr1[0], qr1[1]], name="b") expected = QuantumCircuit(qr2, qr1) expected.h(qr1[1]) expected.cx(qr1[1], qr1[0]) expected.cx(qr1[0], qr2[0]) self.assertEqual(qc.reverse_bits(), expected) def test_reverse_bits_with_registerless_bits(self): """Test reversing order of registerless bits.""" q0 = Qubit() q1 = Qubit() c0 = Clbit() c1 = Clbit() qc = QuantumCircuit([q0, q1], [c0, c1]) qc.h(0) qc.cx(0, 1) qc.x(0).c_if(1, True) qc.measure(0, 0) expected = QuantumCircuit([c1, c0], [q1, q0]) expected.h(1) expected.cx(1, 0) expected.x(1).c_if(0, True) expected.measure(1, 1) self.assertEqual(qc.reverse_bits(), expected) def test_reverse_bits_with_registers_and_bits(self): """Test reversing order of bits with registers and registerless bits.""" qr = QuantumRegister(2, "a") q = Qubit() qc = QuantumCircuit(qr, [q]) qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.cx(qr[1], q) expected = QuantumCircuit([q], qr) expected.h(qr[1]) expected.cx(qr[1], qr[0]) expected.cx(qr[0], q) self.assertEqual(qc.reverse_bits(), expected) def test_reverse_bits_with_mixed_overlapped_registers(self): """Test reversing order of bits with overlapped registers and registerless bits.""" q = Qubit() qr1 = QuantumRegister(bits=[q, Qubit()], name="qr1") qr2 = QuantumRegister(bits=[qr1[1], Qubit()], name="qr2") qc = QuantumCircuit(qr1, qr2, [Qubit()]) qc.h(q) qc.cx(qr1[0], qr1[1]) qc.cx(qr1[1], qr2[1]) qc.cx(2, 3) qr2 = QuantumRegister(2, "qr2") qr1 = QuantumRegister(bits=[qr2[1], q], name="qr1") expected = QuantumCircuit([Qubit()], qr2, qr1) expected.h(qr1[1]) expected.cx(qr1[1], qr1[0]) expected.cx(qr1[0], qr2[0]) expected.cx(1, 0) self.assertEqual(qc.reverse_bits(), expected) def test_cnot_alias(self): """Test that the cnot method alias adds a cx gate.""" qc = QuantumCircuit(2) qc.cnot(0, 1) expected = QuantumCircuit(2) expected.cx(0, 1) self.assertEqual(qc, expected) def test_inverse(self): """Test inverse circuit.""" qr = QuantumRegister(2) qc = QuantumCircuit(qr, global_phase=0.5) qc.h(0) qc.barrier(qr) qc.t(1) expected = QuantumCircuit(qr) expected.tdg(1) expected.barrier(qr) expected.h(0) expected.global_phase = -0.5 self.assertEqual(qc.inverse(), expected) def test_compare_two_equal_circuits(self): """Test to compare that 2 circuits are equal.""" qc1 = QuantumCircuit(2, 2) qc1.h(0) qc2 = QuantumCircuit(2, 2) qc2.h(0) self.assertTrue(qc1 == qc2) def test_compare_two_different_circuits(self): """Test to compare that 2 circuits are different.""" qc1 = QuantumCircuit(2, 2) qc1.h(0) qc2 = QuantumCircuit(2, 2) qc2.x(0) self.assertFalse(qc1 == qc2) def test_compare_circuits_with_single_bit_conditions(self): """Test that circuits with single-bit conditions can be compared correctly.""" qreg = QuantumRegister(1, name="q") creg = ClassicalRegister(1, name="c") qc1 = QuantumCircuit(qreg, creg, [Clbit()]) qc1.x(0).c_if(qc1.cregs[0], 1) qc1.x(0).c_if(qc1.clbits[-1], True) qc2 = QuantumCircuit(qreg, creg, [Clbit()]) qc2.x(0).c_if(qc2.cregs[0], 1) qc2.x(0).c_if(qc2.clbits[-1], True) self.assertEqual(qc1, qc2) # Order of operations transposed. qc1 = QuantumCircuit(qreg, creg, [Clbit()]) qc1.x(0).c_if(qc1.cregs[0], 1) qc1.x(0).c_if(qc1.clbits[-1], True) qc2 = QuantumCircuit(qreg, creg, [Clbit()]) qc2.x(0).c_if(qc2.clbits[-1], True) qc2.x(0).c_if(qc2.cregs[0], 1) self.assertNotEqual(qc1, qc2) # Single-bit condition values not the same. qc1 = QuantumCircuit(qreg, creg, [Clbit()]) qc1.x(0).c_if(qc1.cregs[0], 1) qc1.x(0).c_if(qc1.clbits[-1], True) qc2 = QuantumCircuit(qreg, creg, [Clbit()]) qc2.x(0).c_if(qc2.cregs[0], 1) qc2.x(0).c_if(qc2.clbits[-1], False) self.assertNotEqual(qc1, qc2) def test_compare_a_circuit_with_none(self): """Test to compare that a circuit is different to None.""" qc1 = QuantumCircuit(2, 2) qc1.h(0) qc2 = None self.assertFalse(qc1 == qc2) def test_overlapped_add_bits_and_add_register(self): """Test add registers whose bits have already been added by add_bits.""" qc = QuantumCircuit() for bit_type, reg_type in ( [Qubit, QuantumRegister], [Clbit, ClassicalRegister], [AncillaQubit, AncillaRegister], ): bits = [bit_type() for _ in range(10)] reg = reg_type(bits=bits) qc.add_bits(bits) qc.add_register(reg) self.assertEqual(qc.num_qubits, 20) self.assertEqual(qc.num_clbits, 10) self.assertEqual(qc.num_ancillas, 10) def test_overlapped_add_register_and_add_register(self): """Test add registers whose bits have already been added by add_register.""" qc = QuantumCircuit() for bit_type, reg_type in ( [Qubit, QuantumRegister], [Clbit, ClassicalRegister], [AncillaQubit, AncillaRegister], ): bits = [bit_type() for _ in range(10)] reg1 = reg_type(bits=bits) reg2 = reg_type(bits=bits) qc.add_register(reg1) qc.add_register(reg2) self.assertEqual(qc.num_qubits, 20) self.assertEqual(qc.num_clbits, 10) self.assertEqual(qc.num_ancillas, 10) def test_from_instructions(self): """Test from_instructions method.""" qreg = QuantumRegister(4) creg = ClassicalRegister(3) a, b, c, d = qreg x, y, z = creg circuit_1 = QuantumCircuit(2, 1) circuit_1.x(0) circuit_2 = QuantumCircuit(2, 1) circuit_2.y(0) def instructions(): yield CircuitInstruction(HGate(), [a], []) yield CircuitInstruction(CXGate(), [a, b], []) yield CircuitInstruction(Measure(), [a], [x]) yield CircuitInstruction(Measure(), [b], [y]) yield CircuitInstruction(IfElseOp((z, 1), circuit_1, circuit_2), [c, d], [z]) def instruction_tuples(): yield HGate(), [a], [] yield CXGate(), [a, b], [] yield CircuitInstruction(Measure(), [a], [x]) yield Measure(), [b], [y] yield IfElseOp((z, 1), circuit_1, circuit_2), [c, d], [z] def instruction_tuples_partial(): yield HGate(), [a] yield CXGate(), [a, b], [] yield CircuitInstruction(Measure(), [a], [x]) yield Measure(), [b], [y] yield IfElseOp((z, 1), circuit_1, circuit_2), [c, d], [z] circuit = QuantumCircuit.from_instructions(instructions()) circuit_tuples = QuantumCircuit.from_instructions(instruction_tuples()) circuit_tuples_partial = QuantumCircuit.from_instructions(instruction_tuples_partial()) expected = QuantumCircuit([a, b, c, d], [x, y, z]) for instruction in instructions(): expected.append(instruction.operation, instruction.qubits, instruction.clbits) self.assertEqual(circuit, expected) self.assertEqual(circuit_tuples, expected) self.assertEqual(circuit_tuples_partial, expected) def test_from_instructions_bit_order(self): """Test from_instructions method bit order.""" qreg = QuantumRegister(2) creg = ClassicalRegister(2) a, b = qreg c, d = creg def instructions(): yield CircuitInstruction(HGate(), [b], []) yield CircuitInstruction(CXGate(), [a, b], []) yield CircuitInstruction(Measure(), [b], [d]) yield CircuitInstruction(Measure(), [a], [c]) circuit = QuantumCircuit.from_instructions(instructions()) self.assertEqual(circuit.qubits, [b, a]) self.assertEqual(circuit.clbits, [d, c]) circuit = QuantumCircuit.from_instructions(instructions(), qubits=qreg) self.assertEqual(circuit.qubits, [a, b]) self.assertEqual(circuit.clbits, [d, c]) circuit = QuantumCircuit.from_instructions(instructions(), clbits=creg) self.assertEqual(circuit.qubits, [b, a]) self.assertEqual(circuit.clbits, [c, d]) circuit = QuantumCircuit.from_instructions( instructions(), qubits=iter([a, b]), clbits=[c, d] ) self.assertEqual(circuit.qubits, [a, b]) self.assertEqual(circuit.clbits, [c, d]) def test_from_instructions_metadata(self): """Test from_instructions method passes metadata.""" qreg = QuantumRegister(2) a, b = qreg def instructions(): yield CircuitInstruction(HGate(), [a], []) yield CircuitInstruction(CXGate(), [a, b], []) circuit = QuantumCircuit.from_instructions(instructions(), name="test", global_phase=0.1) expected = QuantumCircuit([a, b], global_phase=0.1) for instruction in instructions(): expected.append(instruction.operation, instruction.qubits, instruction.clbits) self.assertEqual(circuit, expected) self.assertEqual(circuit.name, "test") class TestCircuitPrivateOperations(QiskitTestCase): """Direct tests of some of the private methods of QuantumCircuit. These do not represent functionality that we want to expose to users, but there are some cases where private methods are used internally (similar to "protected" access in .NET or "friend" access in C++), and we want to make sure they work in those cases.""" def test_previous_instruction_in_scope_failures(self): """Test the failure paths of the peek and pop methods for retrieving the most recent instruction in a scope.""" test = QuantumCircuit(1, 1) with self.assertRaisesRegex(CircuitError, r"This circuit contains no instructions\."): test._peek_previous_instruction_in_scope() with self.assertRaisesRegex(CircuitError, r"This circuit contains no instructions\."): test._pop_previous_instruction_in_scope() with test.for_loop(range(2)): with self.assertRaisesRegex(CircuitError, r"This scope contains no instructions\."): test._peek_previous_instruction_in_scope() with self.assertRaisesRegex(CircuitError, r"This scope contains no instructions\."): test._pop_previous_instruction_in_scope() def test_pop_previous_instruction_removes_parameters(self): """Test that the private "pop instruction" method removes parameters from the parameter table if that instruction is the only instance.""" x, y = Parameter("x"), Parameter("y") test = QuantumCircuit(1, 1) test.rx(y, 0) last_instructions = test.u(x, y, 0, 0) self.assertEqual({x, y}, set(test.parameters)) instruction = test._pop_previous_instruction_in_scope() self.assertEqual(list(last_instructions), [instruction]) self.assertEqual({y}, set(test.parameters)) def test_decompose_gate_type(self): """Test decompose specifying gate type.""" circuit = QuantumCircuit(1) circuit.append(SGate(label="s_gate"), [0]) decomposed = circuit.decompose(gates_to_decompose=SGate) self.assertNotIn("s", decomposed.count_ops())
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/Ilan-Bondarevsky/qiskit_algorithm
Ilan-Bondarevsky
import numpy as np from qiskit import BasicAer, execute from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, AncillaRegister, Aer, transpile from qiskit.tools.visualization import plot_histogram from qiskit.circuit.gate import Gate import sys sys.path.insert(0, "D:/myProjects/AfekaCodeProjects/codeProjects/FinalProject_qiskit/qiskit_algorithm") import bit_functions def condition_phase_shift(k): qc = QuantumCircuit(2) #control qbit and qbit to oparate on angle = np.pi / (2**(k-1)) qc.cp(angle, 0, 1) qc.name = str(k) return qc qc = QuantumCircuit(3) def set_start_state(qc, number, start_qubit): bin_num = bin(number) for i in range(1, len(bin_num)+1): if bin_num[-i] == '1': qc.x(i+start_qubit-1) def adder(n, kind = "fixed"): #n is the number of qubits requer for one number qc = QuantumCircuit(QuantumRegister(n), AncillaRegister(n + (1 if kind == "half" else 0) )) for j in range(n): for k in range(j, n): power = k - j + 1 angle = 2*np.pi / (2**power) qc.cp(angle, j, n+k, label=str(power)) if kind == "half": for i in range(n): angle = 2*np.pi / (2**(i+2)) qc.cp(angle, n-1-i, 2*n) qc.name = f"ADD_{n}" return qc def subtracter(n): qc = adder(n, "half").inverse() qc.name = f"SUB_{n}" return qc def adder_classic_a(n, a, kind = "fixed"): #n is the number of qubits require for one number qc = QuantumCircuit(QuantumRegister(n + (1 if kind == "half" else 0))) bit_field_a = bit_functions.full_bitfield(a, n) for j in range(n): if bit_field_a[n-1-j] == 1: for k in range(j, n): power = k - j + 1 angle = 2*np.pi / (2**power) # k starts from 0 but in the article in start from 1 qc.p(angle, k) if kind == "half": for i in range(n): if bit_field_a[n-1-i] == 1: angle = 2*np.pi / (2**(n-i+1)) qc.p(angle, n) qc = qc.to_gate() qc.name = f"ɸ ADD_{a}" return qc def subtracter_classic_a(n, a): qc = adder_classic_a(n, a, "half").inverse() qc.name = f"ɸ SUB_{a}" return qc def qft(n, swap = True): """n-qubit QFT the first n qubits in circ""" qc = QuantumCircuit(n) for j in range(n-1, -1, -1): qc.h(j) for m in range(j-1, -1, -1): qc.cp(np.pi/float(2**(j-m)), j, m, label=f"{j-m+1}") # Don't forget the Swaps! if swap: for qubit in range(n//2): qc.swap(qubit, n-qubit-1) qc = qc.to_gate() qc.name = "QFT" return qc def qft_dagger(n, swap = True): """n-qubit QFTdagger the first n qubits in circ""" qc = QuantumCircuit(n) # Don't forget the Swaps! if swap: for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-np.pi/float(2**(j-m)), m, j) qc.h(j) qc = qc.to_gate() qc.name = "QFT†" return qc def add_mod_n(a, N): n = bit_functions.bit_length(N) qr = QuantumRegister(n+3) ar = AncillaRegister(1) qc = QuantumCircuit(qr, ar) qc.append(adder_classic_a(n, a, "half").control(2), [0, 1] + list(range(2, n+3))) qc.append(subtracter_classic_a(n, N), range(2, n+3)) qc.append(qft_dagger(n+1, False), range(2, n+3)) qc.cx(n+2, n+3) qc.append(qft(n+1, False), range(2, n+3)) qc.append(adder_classic_a(n, N, "half").control(1), [n+3] + list(range(2, n+3))) qc.append(subtracter_classic_a(n, a).control(2), [0, 1] + list(range(2, n+3))) qc.append(qft_dagger(n+1, False), range(2, n+3)) qc.x(n+2) qc.cx(n+2, n+3) qc.x(n+2) qc.append(qft(n+1, False), range(2, n+3)) qc.append(adder_classic_a(n, a, "half").control(2), [0, 1] + list(range(2, n+3))) qc = qc.to_gate() qc.name = f"ɸ ADD_{a}_mod_{N}" return qc def c_mult_a_mod_n(a, N): n = bit_functions.bit_length(N) qr = QuantumRegister(2*n+4) qc = QuantumCircuit(qr) qc.append(qft(n+1, False), range(n+2, 2*n+3)) for i in range(n): number = (a * 2**i)%N qc.append(add_mod_n(number, N), [0, i+1] + list(range(n+2, 2*n+4))) qc.append(qft_dagger(n+1, False), range(n+2, 2*n+3)) qc.name = f"CMULT({a}) mod {N}" return qc def inverse_c_mult_a_mod_n(a, N): qc = c_mult_a_mod_n(a, N).inverse() qc.name = f"CMULT({a}) mod {N}†" return qc def U(N, a, power): a_pow = a**power n = bit_functions.bit_length(N) qc = QuantumCircuit(2*n + 4) qc.append(c_mult_a_mod_n(a_pow, N), range(2*n + 4)) for i in range(1, n+2): qc.cswap(0, i, i+n+1, label=f'{i} to {i+n}') if np.gcd(a_pow, N) != 1: raise ArithmeticError(f"inverse of {a}^{power} mod {N} doesn't exists") i_a = pow(a_pow, -1, N) qc.append(inverse_c_mult_a_mod_n(i_a, N), range(2*n+4)) qc.name = f"U{a}^{power} mod {N}" return qc def shor_circiut(N, a): """Creates the Shor's circuit and returns it Args: N (int): The number we want to factor a (int): A guess number to base the circuit on. The gdc between N and a must be 1 Returns: QuantumCircuit: circuit of Shor's algorithm """ n = bit_functions.bit_length(N) qc = QuantumCircuit(4*n+3, 2*n) qc.h(range(2*n)) qc.x(2*n) for i in range(2*n): qc.append(U(N,a,2**i), [i] + list(range(2*n, 4*n+3))) qc.append(qft_dagger(2*n, True), range(2*n)) qc.measure(range(2*n), range(2*n)) return qc if __name__ == "__main__": qc = shor_circiut(15,4) print(qc.draw())
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. """Tests for the wrapper functionality.""" import sys import unittest from unittest.mock import patch from unittest.mock import MagicMock from io import StringIO import qiskit from qiskit import providers from qiskit.tools.monitor import backend_overview, backend_monitor from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeProviderFactory, FakeBackend, FakeVigo class TestBackendOverview(QiskitTestCase): """Tools test case.""" def _restore_ibmq(self): if not self.import_error: qiskit.IBMQ = self.ibmq_back else: del qiskit.IBMQ if self.prov_backup: providers.ibmq = self.prov_backup else: del providers.ibmq def _restore_ibmq_mod(self): if self.ibmq_module_backup is not None: sys.modules["qiskit.providers.ibmq"] = self.ibmq_module_backup else: sys.modules.pop("qiskit.providers.ibmq") def setUp(self): super().setUp() ibmq_mock = MagicMock() ibmq_mock.IBMQBackend = FakeBackend if "qiskit.providers.ibmq" in sys.modules: self.ibmq_module_backup = sys.modules["qiskit.providers.ibmq"] else: self.ibmq_module_backup = None sys.modules["qiskit.providers.ibmq"] = ibmq_mock self.addCleanup(self._restore_ibmq_mod) if hasattr(qiskit, "IBMQ"): self.import_error = False else: self.import_error = True qiskit.IBMQ = None self.ibmq_back = qiskit.IBMQ qiskit.IBMQ = FakeProviderFactory() self.addCleanup(self._restore_ibmq) if hasattr(providers, "ibmq"): self.prov_backup = providers.ibmq else: self.prov_backup = None providers.ibmq = MagicMock() @patch("qiskit.tools.monitor.overview.get_unique_backends", return_value=[FakeVigo()]) def test_backend_overview(self, _): """Test backend_overview""" with patch("sys.stdout", new=StringIO()) as fake_stdout: backend_overview() stdout = fake_stdout.getvalue() self.assertIn("Operational:", stdout) self.assertIn("Avg. T1:", stdout) self.assertIn("Num. Qubits:", stdout) @patch("qiskit.tools.monitor.overview.get_unique_backends", return_value=[FakeVigo()]) def test_backend_monitor(self, _): """Test backend_monitor""" for back in [FakeVigo()]: if not back.configuration().simulator: backend = back break with patch("sys.stdout", new=StringIO()) as fake_stdout: backend_monitor(backend) stdout = fake_stdout.getvalue() self.assertIn("Configuration", stdout) self.assertIn("Qubits [Name / Freq / T1 / T2 / ", stdout) for gate in backend.properties().gates: if gate.gate not in ["id"] and len(gate.qubits) == 1: self.assertIn(gate.gate.upper() + " err", stdout) self.assertIn("Readout err", stdout) self.assertIn("Multi-Qubit Gates [Name / Type / Gate Error]", stdout) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeBoeblingen backend = FakeBoeblingen() ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) circ = transpile(ghz, backend, scheduling_method="asap") circ.draw(output='mpl')
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # define a quantum register with one qubit q = QuantumRegister(1,"qreg") # define a classical register with one bit # it stores the measurement result of the quantum part c = ClassicalRegister(1,"creg") # define our quantum circuit qc = QuantumCircuit(q,c) # apply h-gate (Hadamard: quantum coin-flipping) to the first qubit qc.h(q[0]) # measure the first qubit, and store the result in the first classical bit qc.measure(q,c) # draw the circuit by using matplotlib qc.draw(output='mpl') # re-run the cell if the figure is not displayed # execute the circuit 10000 times in the local simulator job = execute(qc,Aer.get_backend('qasm_simulator'),shots=10000) counts = job.result().get_counts(qc) print(counts) # print the outcomes print() n_zeros = counts['0'] n_ones = counts['1'] print("State 0 is observed with frequency %",100*n_zeros/(n_zeros+n_ones)) print("State 1 is observed with frequency %",100*n_ones/(n_zeros+n_ones)) # we can show the result by using histogram print() from qiskit.visualization import plot_histogram plot_histogram(counts) # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # define a quantum register with one qubit q2 = QuantumRegister(1,"qreg2") # define a classical register with one bit # it stores the measurement result of the quantum part c2 = ClassicalRegister(1,"creg2") # define our quantum circuit qc2 = QuantumCircuit(q2,c2) # apply h-gate (Hadamard: quantum coin-flipping) to the first qubit qc2.h(q2[0]) # apply h-gate (Hadamard: quantum coin-flipping) to the first qubit once more qc2.h(q2[0]) # measure the first qubit, and store the result in the first classical bit qc2.measure(q2,c2) # draw the circuit by using matplotlib qc2.draw(output='mpl') # re-run the cell if the figure is not displayed # execute the circuit 10000 times in the local simulator job = execute(qc2,Aer.get_backend('qasm_simulator'),shots=10000) counts2 = job.result().get_counts(qc2) print(counts2) # print the outcomes # # your solution is here # # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # define a quantum register with one qubit q = QuantumRegister(1,"qreg") # define a classical register with one bit # it stores the measurement result of the quantum part c = ClassicalRegister(1,"creg") # define our quantum circuit qc = QuantumCircuit(q,c) # apply x-gate to the first qubit qc.x(q[0]) # apply h-gate (Hadamard: quantum coin-flipping) to the first qubit qc.h(q[0]) # measure the first qubit, and store the result in the first classical bit qc.measure(q,c) # draw the circuit by using matplotlib qc.draw(output='mpl') # re-run the cell if the figure is not displayed # execute the circuit and read the results job = execute(qc,Aer.get_backend('qasm_simulator'),shots=10000) counts = job.result().get_counts(qc) print(counts) # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # define a quantum register with one qubit q2 = QuantumRegister(1,"qreg2") # define a classical register with one bit # it stores the measurement result of the quantum part c2 = ClassicalRegister(1,"creg2") # define our quantum circuit qc2 = QuantumCircuit(q2,c2) # apply x-gate to the first qubit qc2.x(q2[0]) # apply h-gate (Hadamard: quantum coin-flipping) to the first qubit twice qc2.h(q2[0]) qc2.h(q2[0]) # measure the first qubit, and store the result in the first classical bit qc2.measure(q2,c2) # draw the circuit by using matplotlib qc2.draw(output='mpl') # re-run the cell if the figure is not displayed # execute the circuit and read the results job = execute(qc2,Aer.get_backend('qasm_simulator'),shots=10000) counts2 = job.result().get_counts(qc2) print(counts2)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit # Create a Quantum Circuit acting on a quantum register of three qubits circ = QuantumCircuit(3) # Add a H gate on qubit 0, putting this qubit in superposition. circ.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting # the qubits in a Bell state. circ.cx(0, 1) # Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting # the qubits in a GHZ state. circ.cx(0, 2) circ.draw('mpl') from qiskit.quantum_info import Statevector # Set the intial state of the simulator to the ground state using from_int state = Statevector.from_int(0, 2**3) # Evolve the state by the quantum circuit state = state.evolve(circ) #draw using latex state.draw('latex') from qiskit.visualization import array_to_latex #Alternative way of representing in latex array_to_latex(state) state.draw('qsphere') state.draw('hinton') from qiskit.quantum_info import Operator U = Operator(circ) # Show the results U.data # Create a Quantum Circuit meas = QuantumCircuit(3, 3) meas.barrier(range(3)) # map the quantum measurement to the classical bits meas.measure(range(3), range(3)) # The Qiskit circuit object supports composition. # Here the meas has to be first and front=True (putting it before) # as compose must put a smaller circuit into a larger one. qc = meas.compose(circ, range(3), front=True) #drawing the circuit qc.draw('mpl') # Adding the transpiler to reduce the circuit to QASM instructions # supported by the backend from qiskit import transpile # Use AerSimulator from qiskit_aer import AerSimulator backend = AerSimulator() # First we have to transpile the quantum circuit # to the low-level QASM instructions used by the # backend qc_compiled = transpile(qc, backend) # Execute the circuit on the qasm simulator. # We've set the number of repeats of the circuit # to be 1024, which is the default. job_sim = backend.run(qc_compiled, shots=1024) # Grab the results from the job. result_sim = job_sim.result() counts = result_sim.get_counts(qc_compiled) print(counts) from qiskit.visualization import plot_histogram plot_histogram(counts) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/apozas/qaoa-color
apozas
# Copied and modified from qiskit_aqua.algorithms.adaptive.qaoa.qaoa.py # and qiskit_aqua.algorithms.adaptive.qaoa.varform.py # ============================================================================= import logging from qiskit_aqua.algorithms import QuantumAlgorithm from qiskit_aqua import AquaError, PluggableType, get_pluggable_class from qiskit_aqua.algorithms.adaptive import VQE from qiskit_aqua.algorithms.adaptive.qaoa.varform import QAOAVarForm logger = logging.getLogger(__name__) class constrainedQAOA(VQE): """ The Quantum Approximate Optimization Algorithm. See https://arxiv.org/abs/1411.4028 """ CONFIGURATION = { 'name': 'QAOA.Variational', 'description': 'Quantum Approximate Optimization Algorithm', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'qaoa_schema', 'type': 'object', 'properties': { 'operator_mode': { 'type': 'string', 'default': 'matrix', 'oneOf': [ {'enum': ['matrix', 'paulis', 'grouped_paulis']} ] }, 'p': { 'type': 'integer', 'default': 1, 'minimum': 1 }, 'initial_point': { 'type': ['array', 'null'], "items": { "type": "number" }, 'default': None }, 'batch_mode': { 'type': 'boolean', 'default': False } }, 'additionalProperties': False }, 'problems': ['ising'], 'depends': ['optimizer'], 'defaults': { 'optimizer': { 'name': 'COBYLA' }, } } def __init__(self, cost, optimizer, mixer, p=1, initial_state=None, operator_mode='matrix', initial_point=None, batch_mode=False, aux_operators=None): """ Args: operator (Operator): Qubit operator operator_mode (str): operator mode, used for eval of operator p (int) : the integer parameter p as specified in https://arxiv.org/abs/1411.4028 optimizer (Optimizer) : the classical optimization algorithm. initial_point (numpy.ndarray) : optimizer initial point. """ self.validate(locals()) var_form = constrainedQAOAVarForm(cost, p, mixer, initial_state) super().__init__(cost, var_form, optimizer, operator_mode=operator_mode, initial_point=initial_point) @classmethod def init_params(cls, params, algo_input): """ Initialize via parameters dictionary and algorithm input instance Args: params (dict): parameters dictionary algo_input (EnergyInput): EnergyInput instance """ if algo_input is None: raise AquaError("EnergyInput instance is required.") operator = algo_input.qubit_op qaoa_params = params.get(QuantumAlgorithm.SECTION_KEY_ALGORITHM) operator_mode = qaoa_params.get('operator_mode') p = qaoa_params.get('p') initial_point = qaoa_params.get('initial_point') batch_mode = qaoa_params.get('batch_mode') # Set up optimizer opt_params = params.get(QuantumAlgorithm.SECTION_KEY_OPTIMIZER) optimizer = get_pluggable_class(PluggableType.OPTIMIZER, opt_params['name']).init_params(opt_params) return cls(operator, optimizer, p=p, operator_mode=operator_mode, initial_point=initial_point, batch_mode=batch_mode, aux_operators=algo_input.aux_ops) class constrainedQAOAVarForm(QAOAVarForm): def __init__(self, cost_operator, p, mixer_operator=None, initial_state=None): super().__init__(cost_operator, p, initial_state) if mixer_operator is None: v = np.zeros(self._cost_operator.num_qubits) ws = np.eye(self._cost_operator.num_qubits) self._mixer_operator = reduce( lambda x, y: x + y, [ Operator([[1, Pauli(v, ws[i, :])]]) for i in range(self._cost_operator.num_qubits) ] ) else: self._mixer_operator = mixer_operator from functools import reduce from itertools import product from qiskit import BasicAer, QuantumRegister from qiskit_aqua import QuantumInstance from qiskit_aqua import Operator, run_algorithm from qiskit.quantum_info import Pauli from qiskit_aqua.components.optimizers import COBYLA from qiskit_aqua.components.initial_states import Custom #from constrainedqaoa import constrainedQAOA import numpy as np import qutip as qt edges = [(0, 1), (1, 2), (2, 0)] vertices = 3 colors = 3 n_qubits = vertices * colors zr = np.zeros(n_qubits) ws = np.eye(n_qubits) up = qt.basis(2, 0) dn = qt.basis(2, 1) def W(size, copies): initial_list = [dn] + [up] * (size - 1) cycles = [[initial_list[i - j] for i in range(size)] for j in range(size)] W_1copy = sum([qt.tensor(states) for states in cycles]) return qt.tensor([W_1copy] * copies) amplitudes = W(colors, vertices).full().T.tolist()[0] init_state = Custom(n_qubits, state_vector=amplitudes) W(colors, vertices) cost_operator = reduce( lambda x, y: x + y, [ Operator([[1, (Pauli(ws[colors*v1 + j, :], zr) *Pauli(ws[colors*v2 + j, :], zr))]]) for (v1, v2), j in product(edges, range(colors)) ] ) mixer_operator = reduce( lambda x, y: x + y, [ Operator([[1, (Pauli(zr, ws[colors*i + j, :]) *Pauli(zr, ws[colors*i + (j+1) % colors, :]))]]) + Operator([[1, (Pauli(ws[colors*i + j % colors, :], ws[colors*i + j % colors, :]) *Pauli(ws[colors*i + (j+1) % colors, :], ws[colors*i + (j+1) % colors, :]))]]) for i, j in product(range(vertices), range(colors)) ] ) # Fix redundancies if colors == 2: mixer_operator.scaling_coeff(1/2) cobyla = COBYLA() cobyla.set_options(maxiter=250) p = 1 # steps of QAOA constrained = constrainedQAOA(cost_operator, cobyla, mixer_operator, p, init_state) from qiskit import IBMQ IBMQ.load_accounts() # Please input the 20 qubit architecture! backend = IBMQ.get_backend('ibmq_20_tokyo') quantum_instance = QuantumInstance(backend=backend_melbourne) result = constrained.run(quantum_instance) result['eigvals'] np.round(result['eigvecs'], 4) result['eval_count'] np.savetxt('3_triangle_3colors_p1_20q_qpu', result['eigvecs'][0])
https://github.com/veenaiyuri/qiskit-education
veenaiyuri
from QiskitEducation import * qc = QuantumAlgorithm(3,3) qc.h(qc.q[0]) qc.h(qc.q[1]) qc.cx(qc.q[1], qc.q[2]) qc.cx(qc.q[0], qc.q[1]) qc.h(qc.q[0]) qc.measure(qc.q[0], qc.c[0]) qc.measure(qc.q[1], qc.c[1]) qc.cx(qc.q[1], qc.q[2]) qc.cz(qc.q[0], qc.q[2]) qc.h(qc.q[2]) qc.measure(qc.q[2], qc.c[2]) print(qc.execute()['counts'])
https://github.com/mgg39/qiskit-networks
mgg39
import numpy as np import qiskit class Node: """ Object class for the empty Nodes. """ def __init__(self, name: str, location: list, elements: list, ports: list): """ Constructor of the Node. :param name: the name of the Node. :param location: defined location of the Node within a topology. :param elements: list of network elements within the Node. :param ports: list of ports within the Node. """ self.name = name """ Set the name of the Node. """ self.location = location """ Set the location address of the Node. """ def get_name(self) -> str: """ Return the name of the Node. """ return self.name def get_location(self) -> list: """ Return the location address of the Node. Should be described as a 2D or 3D array. """ if len(self.location) == 2: self.dimension_topology = 2 elif len(self.location) == 3: self.dimension_topology = 3 else: self.dimension_topology = np.nan print("Node.location has an incorrect dimensionality. Please define the location through the use of a 2D or a 3D grid system.") return self.location def elements(self) -> list: """ Return the list of element within the Node. """ return self.elements def ports(self) -> list: """ Return ports within the Node. """ return self.ports
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)) ghz.draw(output='mpl')
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
PacktPublishing
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created Nov 2020 @author: hassi """ # Importing Qiskit from qiskit import QuantumCircuit # Import display circuit from our Grover collection from ch9_grover_functions import display_circuit def main(): # First, let's see a phase shift print("Ch 9: Phase kickback") print("--------------------") print("\nLet's start with initalizing a single qubit to |0>...") qc1 = QuantumCircuit(1) display_circuit(qc1,True,False) input("Press Enter to set the qubit in superposition...") qc1.h(0) display_circuit(qc1,True,False) input("Press Enter to add a phase shift...") qc1.z(0) display_circuit(qc1,True,False) input("Press Enter to create a two qubit circuit...") qc = QuantumCircuit(2) display_circuit(qc,True,False) input("Press Enter to set qubits in superposition...") qc.h([0,1]) display_circuit(qc,True,False) input("Press Enter to phase shift second qubit using Z gate...") qc.z(1) display_circuit(qc,True,False) input("Press Enter to phase shift first qubit using Z gate...") qc.z(0) display_circuit(qc,True,False) input("Press Enter to create a new circuit...") qc = QuantumCircuit(2) display_circuit(qc,True,False) input("Press Enter to set qubits in superposition...") qc.h([0,1]) display_circuit(qc,True,False) input("Press Enter to phase shift second qubit using Z gate...") qc.z(1) display_circuit(qc,True,False) input("Press Enter to add a CX...") qc.cx(0,1) display_circuit(qc,True,False) if __name__ == '__main__': 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/abbarreto/qiskit4
abbarreto
https://github.com/xtophe388/QISKIT
xtophe388
from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute from qiskit import register, available_backends, get_backend #import Qconfig and set APIToken and API url import sys sys.path.append("../../") # go to parent dir import Qconfig qx_config = { "APItoken": Qconfig.APItoken, "url": Qconfig.config['url']} #set api register(qx_config['APItoken'], qx_config['url']) import math, scipy, copy, time import numpy as np def AddDelay (script,q,num,delay): for _ in range(delay): for address in range(num): script.iden(q[address]) def AddCnot(script,q,control,target,device): # set the coupling map # b in coupling_map[a] means a CNOT with control qubit a and target qubit b can be implemented # this is essentially just copy and pasted from # https://github.com/IBM/qiskit-qx-info/tree/master/backends/ibmqx3 # https://github.com/IBM/qiskit-qx-info/tree/master/backends/ibmqx5 # but with a few stylistic changes coupling_map = {} coupling_map['ibmqx3'] = {0: [1], 1: [2], 2: [3], 3: [14], 4: [3, 5], 5: [], 6: [7, 11], 7: [10], 8: [7], 9: [10, 8], 10:[], 11: [10], 12: [5, 11, 13], 13: [4, 14], 14:[], 15: [0, 14]} coupling_map['ibmqx5'] = {0:[],1:[0,2], 2:[3], 3:[4, 14], 4:[], 5:[4], 6:[5,7,11], 7:[10], 8:[7], 9:[8, 10], 10:[], 11:[10], 12:[5, 11, 13], 13:[4, 14], 14:[], 15:[0, 2, 14]} simulator = (device not in ['ibmqx3','ibmqx5']) # if simulator, just do the CNOT if simulator: script.cx(q[control], q[target]) # same if the coupling map allows it elif target in coupling_map[device][control]: script.cx(q[control], q[target]) # if it can be done the other way round we conjugate with Hadamards elif ( control in coupling_map[device][target] ): script.h(q[control]) script.h(q[target]) script.cx(q[target], q[control]) script.h(q[control]) script.h(q[target]) else: print('Qubits ' + str(control) + ' and ' + str(target) + ' cannot be entangled.') def GetAddress (codeQubit,offset,simulator): if (simulator): address = 2*codeQubit + offset else: address = (5-2*codeQubit-offset)%16 #address = (6+2*codeQubit+offset)%16 # this can be used to go clockwise instead return address def RunRepetition(bit,d,device,delay,totalRuns): # set the number of shots to use on the backend shots = 8192 # determine whether a simulator is used simulator = (device not in ['ibmqx3','ibmqx5']) # if the simulator is used, we declare the minimum number of qubits required if (simulator): num = 2*d # for the real device there are always 16 else: num = 16 repetitionScript = [] # we create a batch job of totalRuns identical runs for run in range(totalRuns): # set up registers and program q = QuantumRegister(num) c = ClassicalRegister(num) repetitionScript.append( QuantumCircuit(q, c) ) # now we insert all the quantum gates to be applied # a barrier is inserted between each section of the code to prevent the complilation doing things we don't want it to # the stored bit is initialized by repeating it across all code qubits same state # since qubits are automatically initialized as 0, we just need to do Xs if b=1 if (bit==1): for codeQubit in range(d): repetitionScript[run].x( q[GetAddress(codeQubit,0,simulator)] ) # also do it for the single qubit on the end for comparision repetitionScript[run].x( q[GetAddress(d-1,1,simulator)] ) repetitionScript[run].barrier() # if the code is simulated add rotations for error like effects (and a barrier) AddDelay(repetitionScript[run],q,num,delay) # we then start the syndrome measurements by doing CNOTs between each code qubit and the next ancilla along the line for codeQubit in range(d-1): AddCnot(repetitionScript[run],q,GetAddress(codeQubit,0,simulator),GetAddress(codeQubit,1,simulator),device) repetitionScript[run].barrier() # if the code is simulated add rotations for error like effects (and a barrier) AddDelay(repetitionScript[run],q,num,delay) # next we perform CNOTs between each code qubit and the previous ancilla along the line for codeQubit in range(1,d): AddCnot(repetitionScript[run],q,GetAddress(codeQubit,0,simulator),GetAddress(codeQubit,-1,simulator),device) repetitionScript[run].barrier() # if the code is simulated add rotations for error like effects (and a barrier) AddDelay(repetitionScript[run],q,num,delay) # all qubits are then measured for address in range(num): repetitionScript[run].measure(q[address], c[address]) # noise is turned on if simulator is used #repetitionScript[run].noise(int(simulator)) # run the job (if the device is available) backends = available_backends() backend = get_backend(device) print('Status of '+device+':',backend.status) dataNeeded = True while dataNeeded==True: if backend.status["available"] is True: print("\nThe device is available, so the following job is being submitted.\n") print(repetitionScript[1].qasm()) shots_device = 1000 job = execute(repetitionScript, backend, shots=shots, skip_translation=True) results = [] for run in range(totalRuns): results.append( job.result().get_counts(repetitionScript[run]) ) dataNeeded = False else: print("\nThe device is not available, so we will wait for a while.") time.sleep(600) # the raw data states the number of runs for which each outcome occurred # we convert this to fractions before output. for run in range(totalRuns): for key in results[run].keys(): results[run][key] = results[run][key]/shots # return the results return results def AddProbToResults(prob,string,results): if string not in results.keys(): results[string] = 0 results[string] += prob def CalculateError(encodedBit,results,table): # total prob of error will be caculated by looping over all strings # some will end up being ignored, so we'll also need to renormalize error = 0 renorm = 1 # all strings from our sample are looped over for string in results.keys(): # we find the probability P(string|encodedBit) from the lookup table right = 0 if string in table[encodedBit].keys(): right = table[encodedBit][string] # as is the probability P(string|!encodedBit) wrong = 0 if string in table[(encodedBit+1)%2].keys(): wrong = table[(encodedBit+1)%2][string] # if this is a string for which P(string|!encodedBit)>P(string|encodedBit), the decoding fails # the probabilty for this sample is then added to the error if (wrong>right): error += results[string] # if P(string|!encodedBit)=P(string|encodedBit)=0 we have no data to decode, so we should ignore this sample # otherwise if P(string|!encodedBit)=P(string|encodedBit), the decoder randomly chooses between them # P(failure|string) is therefore 0.5 in this case elif (wrong==right): if wrong==0: renorm -= results[string] else: error += 0.5*results[string] # otherwise the decoding succeeds, and we don't care about that if renorm==0: error = 1 else: error = error/renorm return error def GetData(device,minSize,maxSize,totalRuns,delay): # loop over code sizes that will fit on the chip (d=3 to d=8) for d in range(minSize,maxSize+1): print("\n\n**d = " + str(d) + "**") # get data for each encoded bit value for bit in range(2): # run the job and put results in resultsRaw results = RunRepetition(bit,d,device,delay,totalRuns) delayString = "" if delay>0: delayString = '_delay='+str(delay) for run in range(totalRuns): f = open('Repetition_Code_Results/'+device+'/results_d=' + str(d) + delayString + '_run=' + str(run) + '_bit=' + str(bit) + '.txt', 'w') f.write( str(results[run]) ) f.close() def ProcessData(device,encodedBit,minSize,maxSize,totalRuns,delay): # determine whether a simulator is used simulator = (device not in ['ibmqx3','ibmqx5']) # initialize list used to store the calculated means and variances for results from the codes codeResults = [[[0]*4 for _ in range(j)] for j in range(minSize,maxSize+1)] singleResults = [[[0]*2 for _ in range(16)] for _ in range(minSize,maxSize+1)] # singleResults[d-minSize][j][0] is the probability of state 1 for qubit j when used in a code of distance d # singleResults[d-minSize][j][1] is the variance for the above # the results will show that the case of partial decoding requires more analysis # for this reason we will also output combinedCodeResults, which is all runs of codeResults combined # here we initialize list of combined results from the code only case combinedResultsCode = [[{} for _ in range(minSize,maxSize+1) ] for _ in range(2)] for d in range(minSize,maxSize+1): # we loop over code sizes and runs to create the required dictionaries of data: # resultsFull, resultsCode and resultsSingle (and well as the things used to make them) # the results that come fresh from the backend resultsVeryRaw = [[{} for _ in range(2)] for run in range(0,totalRuns)] resultsRaw = [[{} for _ in range(2)] for run in range(0,totalRuns)] # the results from the full code (including ancillas) # resultsFull[k] gives results for the effective distance d-k code obtained by ignoring the last k code qubits and ancillas resultsFull = [[[{} for _ in range(d)] for _ in range(2)] for run in range(0,totalRuns)] # the same but with ancilla results excluded resultsCode = [[[{} for _ in range(d)] for _ in range(2)] for run in range(0,totalRuns)] # results each single bit resultsSingle = [[[{} for _ in range(16)] for _ in range(2)] for run in range(0,totalRuns)] for run in range(0,totalRuns): # we get results for both possible encoded bits for bit in range(2): delayString = "" if delay>0: delayString = '_delay='+str(delay) # get results for this run from file f = open('Repetition_Code_Results/'+device+'/results_d=' + str(d) + delayString + '_run=' + str(run) + '_bit=' + str(bit) + '.txt') resultsVeryRaw[run][bit] = eval(f.read()) f.close() # loop over all keys in the raw results and look at the ones without strings as values # since all such entries should have a bit string as a key, we call it stringVeryRaw for stringVeryRaw in resultsVeryRaw[run][bit].keys(): if resultsVeryRaw[run][bit][stringVeryRaw] is not str: # create a new dictionary in which each key is padded to a bit string of length 16 stringRaw = stringVeryRaw.rjust(16,'0') resultsRaw[run][bit][stringRaw] = resultsVeryRaw[run][bit][stringVeryRaw] # now stringRaw only has data in the correct format # let's loop over its entries and process stuff for stringRaw in resultsRaw[run][bit].keys(): # get the prob corresponding to this string probToAdd = resultsRaw[run][bit][stringRaw] # first we deal with resultsFull and resultsCode # loop over all truncated codes relevant for this d for k in range(d): # distance of this truncated code dd = d-k # extract the bit string relevant for resultsFull # from left to right this will alternate between code and ancilla qubits in increasing order stringFull = '' for codeQubit in range(dd): # add bit value for a code qubit... stringFull += stringRaw[15-GetAddress(codeQubit,0,simulator)] if (codeQubit!=(d-1)): #...and then the ancilla next to it (if we haven't reached the end of the code) stringFull += stringRaw[15-GetAddress(codeQubit,1,simulator)] # remove ancilla bits from this to get the string for resultsCode stringCode = "" for n in range(dd): stringCode += stringFull[2*n] AddProbToResults(probToAdd,stringFull,resultsFull[run][bit][k]) AddProbToResults(probToAdd,stringCode,resultsCode[run][bit][k]) # now we'll do results single # the qubits are listed in the order they are in the code # so for each code qubit for jj in range(8): # loop over it and its neighbour for offset in range(2): stringSingle = stringRaw[15-GetAddress(jj,offset,simulator)] AddProbToResults(probToAdd,stringSingle,resultsSingle[run][bit][2*jj+offset]) # combined this run's resultsCode with the total, using the k=0 values for stringCode in resultsCode[run][bit][0].keys(): probToAdd = resultsCode[run][bit][0][stringCode]/10 AddProbToResults(probToAdd,stringCode,combinedResultsCode[bit][d-minSize]) for run in range(0,totalRuns): # initialize list used to store the calculated means and variances for results from the codes codeSample = [[0]*2 for _ in range(d)] # here # codeSample gives the results # codeSample[0] gives results for the whole code # codeSample[k][0] is the error prob when decoding uses both code and ancilla qubits # codeSample[k][1] is the error prob when decoding uses only code qubits singleSample = [0]*16 # singleSample[j] is the probability of state 1 for qubit j when the required bit value is encoded # write results in for k in range(d): # calculate look up tables by averaging over all other runs fullTable = [{} for _ in range(2)] codeTable = [{} for _ in range(2)] for b in range(2): for r in [rr for rr in range(totalRuns) if rr!=run]: for string in resultsFull[r][b][k]: AddProbToResults(resultsFull[r][b][k][string]/(totalRuns-1),string,fullTable[b]) for string in resultsCode[r][b][k]: AddProbToResults(resultsCode[r][b][k][string]/(totalRuns-1),string,codeTable[b]) # then calculate corresponding errors codeSample[k][0] = CalculateError(encodedBit,resultsFull[run][encodedBit][k],fullTable) codeSample[k][1] = CalculateError(encodedBit,resultsCode[run][encodedBit][k],codeTable) for j in range(16): if '1' in resultsSingle[run][encodedBit][j].keys(): singleSample[j] = resultsSingle[run][encodedBit][j]['1'] # add results from this run to the overall means and variances for k in range(d): for l in range(2): codeResults[d-minSize][k][2*l] += codeSample[k][l] / totalRuns # means codeResults[d-minSize][k][2*l+1] += codeSample[k][l]**2 / totalRuns # variances for j in range(16): singleResults[d-minSize][j][0] += singleSample[j] / totalRuns singleResults[d-minSize][j][1] += singleSample[j]**2 / totalRuns # finish the variances by subtracting the square of the mean for k in range(d): for l in range(1,2,4): codeResults[d-minSize][k][l] -= codeResults[d-minSize][k][l-1]**2 for j in range(16): singleResults[d-minSize][j][1] -= singleResults[d-minSize][j][0]**2 # return processed results return codeResults, singleResults, combinedResultsCode def MakeGraph(X,Y,y,axisLabel,labels=[],legendPos='upper right',verbose=False,log=False,tall=False): from matplotlib import pyplot as plt plt.rcParams.update({'font.size': 30}) markers = ["o","^","h","D","*"] # if verbose, print the numbers to screen if verbose==True: print("\nX values") print(X) for j in range(len(Y)): print("\nY values for "+labels[j]) print(Y[j]) print("\nError bars") print(y[j]) print("") # convert the variances of varY into widths of error bars for j in range(len(y)): for k in range(len(y[j])): y[j][k] = math.sqrt(y[j][k]/2) if tall: plt.figure(figsize=(20,20)) else: plt.figure(figsize=(20,10)) # add in the series for j in range(len(Y)): marker = markers[j%len(markers)] if labels==[]: plt.errorbar(X, Y[j], marker = marker, markersize=20, yerr = y[j], linewidth=5) else: plt.errorbar(X, Y[j], label=labels[j], marker = marker, markersize=20, yerr = y[j], linewidth=5) plt.legend(loc=legendPos) # label the axes plt.xlabel(axisLabel[0]) plt.ylabel(axisLabel[1]) # make sure X axis is fully labelled plt.xticks(X) # logarithms if required if log==True: plt.yscale('log') # make the graph plt.show() plt.rcParams.update(plt.rcParamsDefault) # set device to use # this also sets the maximum d. We only go up to 6 on the simulator userInput = input("Do you want results for a real device? (input Y or N) If not, results will be from a simulator. \n").upper() if (userInput=="Y"): device = 'ibmqx3' else: device = 'ibmq_qasm_simulator' # determine the delay userInput = input("What value of the delay do you want results for? \n").upper() delay = 0 try: delay = int(userInput) except: pass # determine the code sizes to be considered userInput = input("What is the minimum size code you wish to consider? (input 3, 4, 5, 6, 7 or 8) \n").upper() if userInput in ['3','4','5','6','7','8']: minSize = int(userInput) else: minSize = 3 userInput = input("What is the maximum size code you wish to consider? (input a number no less than the minimum, but no larger than 8) \n").upper() if userInput in ['3','4','5','6','7','8']: maxSize = int(userInput) else: maxSize = 8 # determine whether data needs to be taken if device=='ibmqx5': dataAlready = True else: userInput = input("Do you want to process saved data? (Y/N) If not, new data will be obtained. \n").upper() if (userInput=="Y"): dataAlready = True else: dataAlready = False # set number of runs used for stats # totalRuns is for a repetition code of length d totalRuns = 10 # if we need data, we get it if (dataAlready==False): # get the required data for the desired number of runs GetData(device,minSize,maxSize,totalRuns,delay) codeResults = [[],[]] singleResults = [[],[]] for encodedBit in range(2): try: codeResults[encodedBit], singleResults[encodedBit], combinedResultsCode = ProcessData(device,encodedBit,minSize,maxSize,totalRuns,delay) except Exception as e: print(e) # plot for single qubit data for each code distance for d in range(minSize,maxSize+1): X = range(16) Y = [] y = [] # a series for each encoded bit for encodedBit in range(2): Y.append([singleResults[encodedBit][d-minSize][j][0] for j in range(16)]) y.append([singleResults[encodedBit][d-minSize][j][1] for j in range(16)]) # make graph print("\n\n***Final state of each qubit for code of distance d = " + str(d) + "***") MakeGraph(X,Y,y,['Qubit position in code','Probability of 1']) for encodedBit in range(2): # separate plots for each encoded bit X = range(minSize,maxSize+1) Y = [] y = [] for dec in range(2): # dec=0 corresponds to full decoding, and 1 to partial Y.append([codeResults[encodedBit][d-minSize][0][2*dec+0] for d in range(minSize,maxSize+1)]) y.append([codeResults[encodedBit][d-minSize][0][2*dec+1] for d in range(minSize,maxSize+1)]) # minimum error value for the single qubit memory is found and plotted as a comparsion (with max error bars) simulator = (device not in ['ibmqx3','ibmqx5']) minSingle = min([singleResults[encodedBit][d-minSize][GetAddress(d-1,1,simulator)][0] for d in range(minSize,maxSize+1)]) maxSingle = max([singleResults[encodedBit][d-minSize][GetAddress(d-1,1,simulator)][1] for d in range(minSize,maxSize+1)]) Y.append([minSingle]*(maxSize-minSize+1)) y.append([maxSingle]*(maxSize-minSize+1)) print("\n\n***Encoded " + str(encodedBit) + "***") MakeGraph(X,Y,y,['Code distance, d','Error probability, P'], labels=['Full decoding','Partial decoding','Single qubit memory'],legendPos='lower left',log=True,verbose=True) for encodedBit in range(2): # separate plots for each encoded bit for decoding in ['full','partial']: dec = (decoding=='partial') # this is treated as 0 if full and 1 if partial X = range(1,maxSize+1) Y = [] y = [] labels = [] for d in range(minSize,maxSize+1):# series for each code size seriesY = [math.nan]*(maxSize) seriesy = [math.nan]*(maxSize) for k in range(d): seriesY[d-k-1] = codeResults[encodedBit][d-minSize][k][2*dec+0] seriesy[d-k-1] = codeResults[encodedBit][d-minSize][k][2*dec+1] Y.append(seriesY) y.append(seriesy) labels.append('d='+str(d)) print("\n\n***Encoded " + str(encodedBit) + " with " + dec*"partial" + (1-dec)*"full" + " decoding***") MakeGraph(X,Y,y,['Effective code distance','Logical error probability'], labels=labels,legendPos = 'upper right') def MakeModelTables (q,d): # outputs an array of two dictionaries for the lookup table for a simple model of a distance d code # q[0] is prob of 0->1 noise, and q[1] is prob of 1->0 # no disinction is made between strings with the same number of errors # the prob for all are assigned to a single string, all with 0s on the left and 1s on the right modelResults = [{},{}] bit = ["0","1"] for encodedBit in range(2): for errors in range(d+1): if encodedBit==0: string = "0"*(d-errors)+"1"*errors else: string = "0"*errors+"1"*(d-errors) modelResults[encodedBit][string] = scipy.special.binom(d,errors) * q[encodedBit]**errors * (1-q[encodedBit])**(d-errors) return modelResults def TotalLogical (p0,d,p1=0): # outputs total logical error prob for a single or two round code P0 = CalculateError( encodedBit, MakeModelTables([p0,p0],d)[0], MakeModelTables([p0,p0],d) ) P1 = CalculateError( encodedBit, MakeModelTables([p0,p0],d)[1], MakeModelTables([p1,p1],d) ) return P0*(1-P1) + P1*(1-P0) for encodedBit in range(2): # separate plots for each encoded bit p = [0]*2 # here is where we'll put p_0 and p_1 bar = [0]*2 for dec in [1,0]: # dec=0 corresponds to full decoding, and 1 to partial # get the results we want to fit to realResults = [codeResults[encodedBit][d-minSize][0][2*dec] for d in range(minSize,maxSize+1)] # search possible values intul we find a minimum (assumed to be global) # first we do the partial decoding to get p (which is stored in p[0]) # then the full decoding to get p[1]=p_1 minimizing = True delta = 0.001 q = delta diff =[math.inf,math.inf] while minimizing: q += delta # set new q diff[0] = diff[1] # copy diff value for last p # calculate diff for new q diff[1] = 0 for d in range(minSize,maxSize+1): if dec==1: Q = TotalLogical(q,d) else: Q = TotalLogical(p[0]-q,d,p1=q) diff[1] += ( math.log( realResults[d-minSize] ) - math.log( Q ) )**2 # see if a minimum has been found minimizing = ( diff[0]>diff[1] ) # go back a step on p to get pSum p[1-dec] = q - delta # get diff per qubit bar[1-dec] = math.exp(math.sqrt( diff[0]/(maxSize-minSize+1) )) p[0] = p[0] - p[1] # put p_0 in p[0] (instead of p) print("\n\n***Encoded " + str(encodedBit) + "***\n" ) for j in [0,1]: print(" p_"+str(j)+" = " + str(p[j]) + " with fit values typically differing by a factor of " + str(bar[j]) + "\n") plottedMinSize = max(4,minSize) # we won't print results for d=3 for clarity X = range(plottedMinSize,maxSize+1) Y = [] y = [] # original plots for dec in range(2): # dec=0 corresponds to full decoding, and 1 to partial # results from the device Y.append([codeResults[encodedBit][d-minSize][0][2*dec+0] for d in range(plottedMinSize,maxSize+1)]) y.append([codeResults[encodedBit][d-minSize][0][2*dec+1] for d in range(plottedMinSize,maxSize+1)]) # fit lines for dec in range(2): if dec==1: Y.append([TotalLogical(p[0]+p[1],d) for d in range(plottedMinSize,maxSize+1)]) else: Y.append([TotalLogical(p[0],d,p1=p[1]) for d in range(plottedMinSize,maxSize+1)]) y.append([0]*(maxSize-plottedMinSize+1)) MakeGraph(X,Y,y,['Code distance, d','Error probability, P'], labels=['Full decoding','Partial decoding','Full decoding (model)','Partial decoding (model)'],legendPos='lower left',log=True) # for each code distance and each encoded bit value, we'll create a list of the probabilities for each possible number of errors # list is initialized with zeros errorNum = [[[0]*(d+1) for d in range(minSize,maxSize+1)] for _ in range(2)] for d in range(minSize,maxSize+1): for bit in range(2): # for each code distance and each encoded bit value we look at all possible result strings for string in combinedResultsCode[bit][d-minSize]: # count the number of errors in each string num = 0 for j in range(d): num += ( int( string[j] , 2 ) + bit )%2 # add prob to corresponding number of errors errorNum[bit][d-minSize][num] += combinedResultsCode[bit][d-minSize][string] # the we make a graph for each, and print a title Y0 = [y if y>0 else math.nan for y in errorNum[0][d-minSize]] Y1 = [y if y>0 else math.nan for y in errorNum[1][d-minSize]] print("\n\n***Probability of errors on code qubits for d = " + str(d) + "***") MakeGraph(range(d+1),[Y0,Y1],[[0]*(d+1)]*2,['Number of code qubit errors','Probability (log base 10)'], labels=['Encoded 0','Encoded 1'],legendPos='upper right',log=True) # actually, we make two graphs. This one plots the number of 1s rather than errors, and so the plot for encoded 1 is inverted # Y0 in this graph is as before Y1 = Y1[::-1] # but Y1 has its order inverted print("\n\n***Probability for number of 1s in code qubit result for d = " + str(d) + "***") MakeGraph(range(d+1),[Y0,Y1],[[0]*(d+1)]*2,['Number of 1s in code qubit result','Probability (log base 10)'], labels=['Encoded 0','Encoded 1'],legendPos='center right',log=True)
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')