repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/pochangl/qiskit-experiment
pochangl
''' This program sets up the Half Adder and the Full Adder and creates a .tex file with the gate geometry. It also evaluates the result with a qasm quantum simulator ''' from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, \ execute, result, Aer import os import shutil import numpy as np import lib.adder as adder import lib.quantum_logic as logic LaTex_folder_Adder_gates = str(os.getcwd())+'/Latex_quantum_gates/Adder-gates/' if not os.path.exists(LaTex_folder_Adder_gates): os.makedirs(LaTex_folder_Adder_gates) else: shutil.rmtree(LaTex_folder_Adder_gates) os.makedirs(LaTex_folder_Adder_gates) qubit_space = ['0','1'] ## Half Adder (my version) print("Test Half Adder (my version",'\n') for add0 in qubit_space: # loop over all possible additions for add1 in qubit_space: q = QuantumRegister(3, name = 'q') c = ClassicalRegister(2, name = 'c') qc = QuantumCircuit(q,c) for qubit in q: qc.reset(qubit) # initialisation if(add0== '1'): qc.x(q[0]) if(add1 == '1'): qc.x(q[1]) adder.Half_Adder(qc, q[0],q[1],q[2]) qc.measure(q[0], c[0]) qc.measure(q[2], c[1]) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1000) results = job.result() count = results.get_counts() print('|0', add0, '>', '+', '|0', add1, '>', '\t', count) ## Plot a sketch of the gate q = QuantumRegister(3, name = 'q') c = ClassicalRegister(2, name = 'c') qc = QuantumCircuit(q,c) qc.reset(q[2]) adder.Half_Adder(qc, q[0],q[1],q[2]) qc.measure(q[1], c[0]) qc.measure(q[2], c[1]) LaTex_code = qc.draw(output='latex_source', justify=None) # draw the circuit f_name = 'Half_Adder_gate_Benjamin.tex' with open(LaTex_folder_Adder_gates+f_name, 'w') as f: f.write(LaTex_code) ## Half Adder for two qubits (Beyond Classical book version) print("Test Half Adder Beyond Classical") for add0 in qubit_space: # loop over all possible additions for add1 in qubit_space: q = QuantumRegister(5, name = 'q') c = ClassicalRegister(2, name = 'c') qc = QuantumCircuit(q,c) # initialisation if(add0 == '1'): qc.x(q[0]) if(add1 == '1'): qc.x(q[1]) logic.XOR(qc, q[0],q[1],q[2]) qc.barrier(q) logic.AND(qc, q[0], q[1], q[3]) qc.barrier(q) qc.measure(q[2], c[0]) qc.measure(q[3], c[1]) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1000) results = job.result() count = results.get_counts() print('|0', add0, '>', '+', '|0', add1, '>', '\t', count) if(add0=='0' and add1=='1'): LaTex_code = qc.draw(output='latex_source', justify=None) # draw the circuit f_name = 'Half_Adder_gate_Beyond_Classical.tex' with open(LaTex_folder_Adder_gates+f_name, 'w') as f: f.write(LaTex_code) ## Full Adder for addition of two-qubits |q1>, |q2>, and a carry bit |qd> # from another calculation using a anxiliary bit |q0> with a carry qubit |cq> # which is initialised to |0> # iteration over all possible values for |q1>, |q2>, and |qd> print('\n',"Full Adder Test (my version)") for qubit_2 in qubit_space: for qubit_1 in qubit_space: for qubit_d in qubit_space: string_q1 = str(qubit_1) string_q2 = str(qubit_2) string_qd = str(qubit_d) q1 = QuantumRegister(1, name ='q1') q2 = QuantumRegister(1, name = 'q2') qd = QuantumRegister(1, name = 'qd') q0 = QuantumRegister(1, name = 'q0') c = ClassicalRegister(2, name = 'c') qc = QuantumCircuit(q1,q2,qd,q0,c) for qubit in q1: qc.reset(qubit) for qubit in q2: qc.reset(qubit) for qubit in qd: qc.reset(qubit) for qubit in q0: qc.reset(qubit) # initialise qubits which should be added for i, qubit in enumerate(q1): if(string_q1[i] == '1'): qc.x(qubit) print(1,end="") else: print(0,end="") print('\t',end="") for i, qubit in enumerate(q2): if(string_q2[i] == '1'): qc.x(qubit) print(1,end="") else: print(0,end="") print('\t',end="") for i, qubit in enumerate(qd): if(string_qd[i] == '1'): qc.x(qubit) print(1,end="") else: print(0,end="") print('\t',end="") adder.Full_Adder(qc, q1, q2, qd, q0, c[0]) qc.measure(q0, c[1]) # check the results backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1000) results = job.result() count = results.get_counts() print('|', qubit_1, '>', '+', '|', qubit_2, '>', '+', '|', qubit_d, '> = ' , '\t', count) if(qubit_1 == '0' and qubit_2 == '0' and qubit_d == '0'): LaTex_code = qc.draw(output='latex_source') # draw the circuit f_name = 'Full_Adder_gate_Benjamin.tex' with open(LaTex_folder_Adder_gates+f_name, 'w') as f: f.write(LaTex_code) ## Test for adding two two-qubit numbers |q1> and |q2> for qubit1_0 in qubit_space: for qubit1_1 in qubit_space: for qubit2_0 in qubit_space: for qubit2_1 in qubit_space: string_q1 = str(qubit1_1)+str(qubit1_0) string_q2 = str(qubit2_1)+str(qubit2_0) q1 = QuantumRegister(2, name ='q1') q2 = QuantumRegister(2, name = 'q2') # qubit to store carry over for significiant bit q0 = QuantumRegister(1, name = 'q0') c = ClassicalRegister(3, name = 'c') qc = QuantumCircuit(q1,q2,q0,c) for qubit in q1: qc.reset(qubit) qc.reset(q2) qc.reset(q0) # initialise qubits which should be added for i, qubit in enumerate(q1): if(string_q1[i] == '1'): qc.x(qubit) print(1,end="") else: print(0,end="") print('\t',end="") for i, qubit in enumerate(q2): if(string_q2[i] == '1'): qc.x(qubit) print(1,end="") else: print(0,end="") print('\t',end="") adder.Half_Adder(qc,q1[-1],q2[-1],q0) qc.measure(q2[-1],c[0]) adder.Full_Adder(qc, q1[-2],q2[-2], q0, q2[-1], c[1]) qc.measure(q2[-1], c[2]) # check the results backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1000) results = job.result() count = results.get_counts() print('|', qubit1_1, qubit1_0, '>', '+', '|', qubit2_1, qubit2_0, '> = ' , '\t', count) if(qubit1_1 == '0' and qubit1_0 == '1' and qubit2_1 == '0' and qubit2_0 == '0'): LaTex_code = qc.draw(output='latex_source') # draw the circuit # export QASM code qc.qasm(filename="one_plus_one.qasm") f_name = 'Adder_gate_for_two_two-qubit_numbers.tex' with open(LaTex_folder_Adder_gates+f_name, 'w') as f: f.write(LaTex_code) ## Adder for two arbitrary binary numbers # randomly draw number of bits from the numbers to add bit_number_q1 = int(np.ceil(10*np.random.rand()))+2 bit_number_q2 = int(np.ceil(10*np.random.rand()))+2 # prepare two random binary numbers string_q1 = [] string_q2 = [] for i in range(bit_number_q1): #string_q1.append(1) string_q1.append(int(np.round(np.random.rand()))) for i in range(bit_number_q2): string_q2.append(int(np.round(np.random.rand()))) while(len(string_q1)<len(string_q2)): string_q1 = np.insert(string_q1, 0, 0, axis=0) while(len(string_q1)>len(string_q2)): string_q2 = np.insert(string_q2, 0, 1, axis=0) string_q1 = np.array(string_q1) string_q2 = np.array(string_q2) q1 = QuantumRegister(len(string_q1), name = 'q1') q2 = QuantumRegister(len(string_q2), name = 'q2') # qubit to store carry over for initial half adder q0 = QuantumRegister(1, name = 'q0') c = ClassicalRegister(len(string_q1)+1, name = 'c') qc = QuantumCircuit(q1,q2,q0,c) for qubit in q1: qc.reset(qubit) for qubit in q2: qc.reset(qubit) qc.reset(q0) # initialise qubits which should be added for i, qubit in enumerate(q1): if(string_q1[i] == 1): qc.x(qubit) print(1,end="") else: print(0,end="") print('\n',end="") for i, qubit in enumerate(q2): if(string_q2[i] == 1): qc.x(qubit) print(1,end="") else: print(0,end="") print('\n') # initial addition of least significant bits and determining carry bit adder.Half_Adder(qc, q1[-1], q2[-1], q0) qc.measure(q2[-1], c[0]) # adding of next significant bits adder.Full_Adder(qc, q1[-2], q2[-2], q0, q2[-1], c[1]) # adding of other digits by full adder cascade for i in range(2, len(string_q1)): adder.Full_Adder(qc, q1[-i-1], # bit to add q2[-i-1], # bit to add #(and to measure as next significant bit) q2[-i+1], # carry from last calculation q2[-i], # carry for next calculation c[i]) qc.measure(q2[-len(string_q1)+1], c[len(string_q1)]) # check the results backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=10) results = job.result() count = results.get_counts() print(count) LaTex_code = qc.draw(output='latex_source') # draw the circuit f_name = 'Adder_gate_for_'+str(string_q1)+'_and_'+str(string_q2)+'.tex' print(f_name) with open(LaTex_folder_Adder_gates+f_name, 'w') as f: f.write(LaTex_code)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test for the converter dag dependency to dag circuit and dag circuit to dag dependency.""" import unittest from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.converters.dag_to_dagdependency import dag_to_dagdependency from qiskit.converters.dagdependency_to_dag import dagdependency_to_dag from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.test import QiskitTestCase class TestCircuitToDagDependency(QiskitTestCase): """Test DAGCircuit to DAGDependency.""" def test_circuit_and_dag_dependency(self): """Check convert to dag dependency and back""" qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit_in = QuantumCircuit(qr, cr) circuit_in.h(qr[0]) circuit_in.h(qr[1]) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.x(qr[0]).c_if(cr, 0x3) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.measure(qr[2], cr[2]) dag_in = circuit_to_dag(circuit_in) dag_dependency = dag_to_dagdependency(dag_in) dag_out = dagdependency_to_dag(dag_dependency) self.assertEqual(dag_out, dag_in) def test_circuit_and_dag_dependency2(self): """Check convert to dag dependency and back also when the option ``create_preds_and_succs`` is False.""" qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit_in = QuantumCircuit(qr, cr) circuit_in.h(qr[0]) circuit_in.h(qr[1]) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.x(qr[0]).c_if(cr, 0x3) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.measure(qr[2], cr[2]) dag_in = circuit_to_dag(circuit_in) dag_dependency = dag_to_dagdependency(dag_in, create_preds_and_succs=False) dag_out = dagdependency_to_dag(dag_dependency) self.assertEqual(dag_out, dag_in) def test_metadata(self): """Test circuit metadata is preservered through conversion.""" meta_dict = {"experiment_id": "1234", "execution_number": 4} qr = QuantumRegister(2) circuit_in = QuantumCircuit(qr, metadata=meta_dict) circuit_in.h(qr[0]) circuit_in.cx(qr[0], qr[1]) circuit_in.measure_all() dag = circuit_to_dag(circuit_in) self.assertEqual(dag.metadata, meta_dict) dag_dependency = dag_to_dagdependency(dag) self.assertEqual(dag_dependency.metadata, meta_dict) dag_out = dagdependency_to_dag(dag_dependency) self.assertEqual(dag_out.metadata, meta_dict) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, execute from qiskit.visualization import plot_error_map from qiskit.providers.fake_provider import FakeVigoV2 backend = FakeVigoV2() plot_error_map(backend)
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Deutsch-Jozsa Benchmark Program - QSim """ import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = [ "_common", "_common/qsim" ] sys.path[1:1] = [ "../../_common", "../../_common/qsim" ] import execute as ex import metrics as metrics from execute import BenchmarkResult # Benchmark Name benchmark_name = "Deutsch-Jozsa" np.random.seed(0) verbose = False # saved circuits for display QC_ = None C_ORACLE_ = None B_ORACLE_ = None ############### Circuit Definition # Create a constant oracle, appending gates to given circuit def constant_oracle (input_size, num_qubits): #Initialize first n qubits and single ancilla qubit qc = QuantumCircuit(num_qubits, name=f"Uf") output = np.random.randint(2) if output == 1: qc.x(input_size) global C_ORACLE_ if C_ORACLE_ == None or num_qubits <= 6: if num_qubits < 9: C_ORACLE_ = qc return qc # Create a balanced oracle. # Perform CNOTs with each input qubit as a control and the output bit as the target. # Vary the input states that give 0 or 1 by wrapping some of the controls in X-gates. def balanced_oracle (input_size, num_qubits): #Initialize first n qubits and single ancilla qubit qc = QuantumCircuit(num_qubits, name=f"Uf") b_str = "10101010101010101010" # permit input_string up to 20 chars for qubit in range(input_size): if b_str[qubit] == '1': qc.x(qubit) qc.barrier() for qubit in range(input_size): qc.cx(qubit, input_size) qc.barrier() for qubit in range(input_size): if b_str[qubit] == '1': qc.x(qubit) global B_ORACLE_ if B_ORACLE_ == None or num_qubits <= 6: if num_qubits < 9: B_ORACLE_ = qc return qc # Create benchmark circuit def DeutschJozsa (num_qubits, type): # Size of input is one less than available qubits input_size = num_qubits - 1 # allocate qubits qr = QuantumRegister(num_qubits); cr = ClassicalRegister(input_size); qc = QuantumCircuit(qr, cr, name=f"dj-{num_qubits}-{type}") for qubit in range(input_size): qc.h(qubit) qc.x(input_size) qc.h(input_size) qc.barrier() # Add a constant or balanced oracle function if type == 0: Uf = constant_oracle(input_size, num_qubits) else: Uf = balanced_oracle(input_size, num_qubits) qc.append(Uf, qr) qc.barrier() for qubit in range(num_qubits): qc.h(qubit) # uncompute ancilla qubit, not necessary for algorithm qc.x(input_size) qc.barrier() for i in range(input_size): qc.measure(i, i) # to get the partial_probability # save smaller circuit and oracle subcircuit example for display global QC_ if QC_ == None or num_qubits <= 6: if num_qubits < 9: QC_ = qc # return a handle to the circuit return qc ############### Result Data Analysis # Analyze and print measured results # Expected result is always the type, so fidelity calc is simple def analyze_and_print_result (qc, result, num_qubits, type, num_shots): # Size of input is one less than available qubits input_size = num_qubits - 1 if result.backend_name == 'dm_simulator': benchmark_result = BenchmarkResult(result, num_shots) probs = benchmark_result.get_probs(num_shots) # get results as measured probability else: probs = result.get_counts(qc) # get results as measured counts if verbose: print(f"For type {type} measured: {probs}") # create the key that is expected to have all the measurements (for this circuit) if type == 0: key = '0'*input_size else: key = '1'*input_size # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist) return probs, fidelity ################ Benchmark Loop # Execute program with default parameters def run (min_qubits=3, max_qubits=8, skip_qubits=1, max_circuits=3, num_shots=100, backend_id='dm_simulator', provider_backend=None, #hub="ibm-q", group="open", project="main", exec_options=None, context=None): print(f"{benchmark_name} Benchmark Program - QSim") # validate parameters (smallest circuit is 3 qubits) max_qubits = max(3, max_qubits) min_qubits = min(max(3, min_qubits), max_qubits) skip_qubits = max(1, skip_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # create context identifier if context is None: context = f"{benchmark_name} Benchmark" ########## # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, num_qubits, type, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) probs, fidelity = analyze_and_print_result(qc, result, num_qubits, int(type), num_shots) metrics.store_metric(num_qubits, type, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, #hub=hub, group=group, project=project, exec_options=exec_options, context=context) ########## # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): input_size = num_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2, max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # loop over only 2 circuits for type in range( num_circuits ): # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = DeutschJozsa(num_qubits, type).reverse_bits() # reverse_bits() is applying to handle the change in endianness metrics.store_metric(num_qubits, type, 'create_time', time.time()-ts) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, type, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nConstant Oracle 'Uf' ="); print(C_ORACLE_ if C_ORACLE_ != None else " ... too large or not used!") print("\nBalanced Oracle 'Uf' ="); print(B_ORACLE_ if B_ORACLE_ != None else " ... too large or not used!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim") # if main, execute method if __name__ == '__main__': ex.local_args() # calling local_args() needed while taking noise parameters through command line arguments (for individual benchmarks) run()
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
%run qlatvia.py draw_qubit() sqrttwo=2**0.5 draw_quantum_state(1,0,"") draw_quantum_state(1/sqrttwo,1/sqrttwo,"|+>") # drawing the angle with |0>-axis from matplotlib.pyplot import gca, text from matplotlib.patches import Arc gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=0,theta2=45) ) text(0.08,0.05,'.',fontsize=30) text(0.21,0.09,'\u03C0/4') %run qlatvia.py draw_qubit() sqrttwo=2**0.5 draw_quantum_state(0,0,"") draw_quantum_state(1/sqrttwo,1/sqrttwo,"|+>") # line of reflection for Hadamard from matplotlib.pyplot import arrow arrow(-1.109,-0.459,2.218,0.918,linestyle='dotted',color='red') # drawing the angle with |0>-axis from matplotlib.pyplot import gca, text from matplotlib.patches import Arc gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=0,theta2=22.5) ) text(0.09,0.015,'.',fontsize=30) text(0.25,0.03,'\u03C0/8') gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=22.5,theta2=45) ) text(0.075,0.065,'.',fontsize=30) text(0.21,0.16,'\u03C0/8') %run qlatvia.py draw_qubit() # line of reflection for Hadamard from matplotlib.pyplot import arrow arrow(-1.109,-0.459,2.218,0.918,linestyle='dotted',color='red') # # your code is here # # visually draw the reflections # second draw sqrttwo=2**0.5 draw_quantum_state(0,1,"|1>") draw_quantum_state(1/sqrttwo,-1/sqrttwo,"|->") %run qlatvia.py draw_qubit() # line of reflection for Hadamard from matplotlib.pyplot import arrow arrow(-1.109,-0.459,2.218,0.918,linestyle='dotted',color='red') # # your code is here # sqrttwo=2**0.5 draw_quantum_state(-1,0,"-|0>") draw_quantum_state(-1/sqrttwo,-1/sqrttwo,"-|+>") %run qlatvia.py draw_qubit() # line of reflection for Hadamard from matplotlib.pyplot import arrow arrow(-1.109,-0.459,2.218,0.918,linestyle='dotted',color='red') # # your code is here # sqrttwo=2**0.5 draw_quantum_state(0,-1,"-|1>") draw_quantum_state(-1/sqrttwo,1/sqrttwo,"-|->") %run qlatvia.py draw_qubit() # line of reflection for Hadamard from matplotlib.pyplot import arrow arrow(-1.109,-0.459,2.218,0.918,linestyle='dotted',color='red') # # your code is here # # create a random quantum state random_state = random_quantum_state2() # draw random draw_quantum_state(random_state[0],random_state[1],"randomState") # apply hadamard sqrttwo=2**0.5 next_state = [random_state[0] * (1/sqrttwo) + random_state[1] * (1/sqrttwo), random_state[0] * (1/sqrttwo) + random_state[1] * -(1/sqrttwo)] # draw the state draw_quantum_state(next_state[0],next_state[1],"refectState") %run qlatvia.py draw_qubit() # # your code is here # random_state = random_quantum_state2() # draw random draw_quantum_state(random_state[0],random_state[1],"randomState") # find the reflection to x-axis # apply hadamard sqrttwo=2**0.5 next_state = [random_state[0] * (1/sqrttwo) + random_state[1] * (1/sqrttwo), random_state[0] * (1/sqrttwo) + random_state[1] * -(1/sqrttwo)] # draw the state draw_quantum_state(next_state[0],next_state[1],"refectState") %run qlatvia.py draw_qubit() # the line y=x from matplotlib.pyplot import arrow arrow(-1,-1,2,2,linestyle='dotted',color='red') # # your code is here # random_state = random_quantum_state2() # draw random draw_quantum_state(random_state[0],random_state[1],"randomState") # find the reflection to x-axis # apply hadamard sqrttwo=2**0.5 next_state = [random_state[0] * 0 + random_state[1] * 1, random_state[0] * 1 + random_state[1] * 0] # draw the state # not operator -> switches x and y draw_quantum_state(next_state[0],next_state[1],"refectState") %run qlatvia.py draw_qubit() # # your code is here # # line of reflection from matplotlib.pyplot import arrow #arrow(x,y,dx,dy,linestyle='dotted',color='red') # # # draw_quantum_state(x,y,"name") import numpy as np import math # method for reflection matrix def get_reflection_matrix(theta): reflect_matrix = np.array([[math.cos(2 * theta), math.sin(2 * theta)],[math.sin(2 * theta), -math.cos(2 * theta)]]) return reflect_matrix # obtain a random quantum state random_quantum_state = np.array(random_quantum_state2()) draw_quantum_state(random_quantum_state[0],random_quantum_state[1],"q-state") theta = math.pi/8 reflected_state = np.matmul(get_reflection_matrix(theta), random_quantum_state) draw_quantum_state(reflected_state[0],reflected_state[1],"reflect-q-state") arrow(0,0,math.cos(theta),math.sin(theta),linestyle='dotted',color='red')
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/Rishwi/Beyond-Classical-a-quantum-computing-crash-course-using-qiskit
Rishwi
# -*- coding: utf-8 -*- """Bernstein_Vazirani_forStrings.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/14Uww12SEbmiNPfWr5udfr3tL-393ge7N """ #pip install qiskit # Commented out IPython magic to ensure Python compatibility. from qiskit import * from qiskit.tools.visualization import plot_histogram stt="Hello world" res = ''.join(format(ord(i), 'b') for i in stt) print(res) s = res n = len(s) circuit = QuantumCircuit(n+1,n) circuit.x(n) circuit.barrier() circuit.h(range(n+1)) circuit.barrier() for i, tf in enumerate(reversed(s)): if tf == '1': circuit.cx(i, n) circuit.barrier() circuit.h(range(n+1)) circuit.barrier() circuit.measure(range(n), range(n)) # %matplotlib inline circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=simulator, shots=1).result() plot_histogram(result.get_counts(circuit)) kk=result.get_counts() kkk=list(kk.keys()) strrr=kkk[0] print(strrr) res=strrr #i'm changing res variable, so, now i don't know what's in res i=0 mainstr=[] while i<len(res): if res[i:i+6] != '100000': sk=res[i:i+7] i=i+7 ssk=int(sk, base=2) print(ssk) mainstr.append(chr(ssk)) elif res[i:i+6] == '100000': i=i+6 mainstr.append(" ") print(''.join(mainstr))
https://github.com/Morcu/Qiskit_Hands-on-lab
Morcu
from qiskit import * from qiskit.tools.visualization import plot_histogram import numpy as np def NOT(input1): ''' NOT gate This function takes a binary string input ('0' or '1') and returns the opposite binary output'. ''' q = QuantumRegister(1) # a qubit in which to encode and manipulate the input c = ClassicalRegister(1) # a bit to store the output qc = QuantumCircuit(q, c) # this is where the quantum program goes # 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 input1=='1': qc.x( q[0] ) # Now we've encoded the input, we can do a NOT on it using x qc.x( q[0] ) # Finally, we extract the |0⟩/|1⟩ output of the qubit and encode it in the bit c[0] qc.measure( q[0], c[0] ) # 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 = execute(qc,backend,shots=1) output = next(iter(job.result().get_counts())) return output print('\nResults for the NOT gate') for input in ['0','1']: print(' Input',input,'gives output',NOT(input)) def XOR(input1,input2): ''' XOR gate Takes two binary strings as input and gives one as output. The output is '0' when the inputs are equal and '1' otherwise. ''' q = QuantumRegister(2) # two qubits in which to encode and manipulate the input c = ClassicalRegister(1) # a bit to store the output qc = QuantumCircuit(q, c) # this is where the quantum program goes # Input codification if input1=='1': qc.x( q[0] ) if input2=='1': qc.x( q[1] ) # YOUR QUANTUM PROGRAM GOES HERE qc.cx(q[0],q[1]) qc.measure(q[1],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO # 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 = execute(qc,backend,shots=1,memory=True) output = job.result().get_memory()[0] return output # The output is '0' when the inputs are equal and '1' otherwise. print('\nResults for the XOR gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' Inputs',input1,input2,'give output',XOR(input1,input2)) def AND(input1,input2): ''' AND gate Takes two binary strings as input and gives one as output. The output is '1' only when both the inputs are '1'. ''' q = QuantumRegister(3) # two qubits in which to encode the input, and one for the output c = ClassicalRegister(1) # a bit to store the output qc = QuantumCircuit(q, c) # this is where the quantum program goes # Input codification if input1=='1': qc.x( q[0] ) if input2=='1': qc.x( q[1] ) # YOUR QUANTUM PROGRAM GOES HERE qc.ccx(q[0], q[1], q[2]) qc.measure(q[2],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO # 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 = execute(qc,backend,shots=1,memory=True) output = job.result().get_memory()[0] return output # The output is '1' only when both the inputs are '1'. print('\nResults for the AND gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' Inputs',input1,input2,'give output',AND(input1,input2)) def NAND(input1,input2): ''' NAND gate Takes two binary strings as input and gives one as output. The output is '0' only when both the inputs are '1'. ''' q = QuantumRegister(3) # two qubits in which to encode the input, and one for the output c = ClassicalRegister(1) # a bit to store the output qc = QuantumCircuit(q, c) # this is where the quantum program goes # Input codification if input1=='1': qc.x( q[0] ) if input2=='1': qc.x( q[1] ) qc.ccx(q[0], q[1], q[2]) qc.x( q[2] ) # YOUR QUANTUM PROGRAM GOES HERE qc.measure(q[2],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO # 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 = execute(qc,backend,shots=1,memory=True) output = job.result().get_memory()[0] return output # The output is '0' only when both the inputs are '1'. print('\nResults for the NAND gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' Inputs',input1,input2,'give output',NAND(input1,input2)) def OR(input1,input2): ''' OR gate Takes two binary strings as input and gives one as output. The output is '1' if either input is '1'. ''' q = QuantumRegister(3) # two qubits in which to encode the input, and one for the output c = ClassicalRegister(1) # a bit to store the output qc = QuantumCircuit(q, c) # this is where the quantum program goes # Input codification if input1=='1': qc.x( q[0] ) if input2=='1': qc.x( q[1] ) qc.cx(q[0],q[1]) qc.cx(q[1],q[2]) qc.x( q[2] ) # YOUR QUANTUM PROGRAM GOES HERE qc.measure(q[2],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO # 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 = execute(qc,backend,shots=1,memory=True) output = job.result().get_memory()[0] return output # The output is '1' if either input is '1'. print('\nResults for the OR gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' Inputs',input1,input2,'give output',OR(input1,input2)) print('\nResults for the NOT gate') for input in ['0','1']: print(' Input',input,'gives output',NOT(input)) print('\nResults for the XOR gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' Inputs',input1,input2,'give output',XOR(input1,input2)) print('\nResults for the AND gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' Inputs',input1,input2,'give output',AND(input1,input2)) print('\nResults for the NAND gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' Inputs',input1,input2,'give output',NAND(input1,input2)) print('\nResults for the OR gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' Inputs',input1,input2,'give output',OR(input1,input2))
https://github.com/LarianeMohceneMouad/Variation-Circuit-Based-Hybrid-Quantum-Classical-Binary-Algorithm
LarianeMohceneMouad
from sklearn import model_selection, datasets, svm from qiskit import QuantumCircuit, Aer, IBMQ, QuantumRegister, ClassicalRegister import numpy as np import qiskit import copy import matplotlib.pyplot as plt np.random.seed(42) iris = datasets.load_iris() X = iris.data[0:100] Y = iris.target[0:100] X_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size=0.33, random_state=42) N = 4 def feature_map(X, encoding_type): q = QuantumRegister(N) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) if encoding_type == 'rx': for i, x in enumerate(X): qc.rx(x, i) elif encoding_type == 'ry': for i, x in enumerate(X): qc.ry(x, i) elif encoding_type == 'rz': for i, x in enumerate(X): qc.rz(x, i) return qc, c # feature map test qc,c = feature_map(X[0], 'rx') qc.draw('mpl') def variational_circuit(qc, theta, rotation_type): for i in range(N-1): qc.cnot(i, i+1) qc.cnot(N-1, 0) if rotation_type == 'rx': for i in range(N): qc.rx(theta[i], i) elif rotation_type == 'ry': for i in range(N): qc.ry(theta[i], i) elif rotation_type == 'rz': for i in range(N): qc.rz(theta[i], i) return qc qc = variational_circuit(qc, np.ones(4), 'ry') qc.draw('mpl') def quantum_nn(X, theta, shots, encoding_type, rotation_type, simulator=True): qc, c = feature_map(X, encoding_type) qc = variational_circuit(qc, theta, rotation_type) qc.measure(0, c) backend = Aer.get_backend('qasm_simulator') if simulator == False: provider = IBMQ.load_account() backend = provider.get_backend('ibm_oslo') job = qiskit.execute(qc, backend, shots=shots) result = job.result() counts = result.get_counts(qc) return counts['1']/shots qc, c = feature_map(X[0], 'rz') qc = variational_circuit(qc, np.ones(4), 'rz') qc.measure(0, c) backend = Aer.get_backend('qasm_simulator') job = qiskit.execute(qc, backend, shots=5000) result = job.result() counts = result.get_counts(qc) print(counts) # quantum_nn test quantum_nn(X[0], np.ones(4), 5000, 'rx', 'ry') def loss(prediction, target): return(prediction-target)**2 # loss test loss(quantum_nn(X[0], [0.9, 0.9, 0.9, 0.9], 5000, 'rx', 'ry'), Y[0]) def gradient(X, Y, theta, delta, shots, encoding_type, rotation_type): grad = [] for i in range(len(theta)): dtheta = copy.copy(theta) dtheta[i] += delta prediction_1 = quantum_nn(X, dtheta, shots, encoding_type, rotation_type) prediction_2 = quantum_nn(X, theta, shots, encoding_type, rotation_type) grad.append((loss(prediction_1, Y) - loss(prediction_2, Y)) / delta) return np.array(grad) gradient(X[0], Y[0], np.ones(4), 0.01, 5000, 'rx', 'ry') def accuracy(X, Y, theta, shots, encoding_type, rotation_type): counter = 0 for X_i, Y_i, in zip(X, Y): prediction = quantum_nn(X_i, theta, shots, encoding_type, rotation_type) if prediction < 0.5 and Y_i == 0: counter += 1 elif prediction >= 0.5 and Y_i == 1: counter += 1 return counter/len(Y) # Accuracy test accuracy(X_test, Y_test, [-1.5, 1.2, 0.6, -0.2], 1000, 'rx', 'ry') def get_best_weight(accuracies, weights): return(weights[accuracies.index(max(accuracies))]) N = 4 def model(x_train, y_train, x_test, y_test, learning_rate, epochs, theta, shots, encoding_type, rotation_type, delta, optimizing_weights=False): loss_list = [] acc_list = [] weights_list = [] print('Epoch \t Loss \t Training Accuracy \t theta') for i in range(epochs): loss_tmp = [] for X_i, Y_i in zip(x_train, y_train): prediction = quantum_nn(X_i, theta, shots, encoding_type, rotation_type) loss_tmp.append(loss(prediction, Y_i)) # update theta new_theta = theta - learning_rate * gradient(X_i, Y_i, theta, delta, shots, encoding_type, rotation_type) if loss(quantum_nn(X_i, new_theta, shots, encoding_type, rotation_type), Y_i) < loss(quantum_nn(X_i, theta, shots, encoding_type, rotation_type), Y_i): theta = new_theta loss_list.append(np.mean(loss_tmp)) acc_list.append(accuracy(X_train, Y_train, theta, shots, encoding_type, rotation_type)) weights_list.append(theta) print(f'{i} \t {round(loss_list[-1], 3)} \t {round(acc_list[-1], 3)} \t {theta} \t {len(weights_list)}') if optimizing_weights==True: acc = accuracy(x_test, y_test, get_best_weight(acc_list, weights_list), shots, encoding_type=encoding_gate, rotation_type=rotation_gate) return acc, get_best_weight(acc_list, weights_list), theta, loss_list, acc_list, weights_list else: acc = accuracy(x_test, y_test, theta, shots, encoding_type=encoding_gate, rotation_type=rotation_gate) return acc, theta, loss_list, acc_list, weights_list gates = ['rx', 'ry', 'rz'] results = {} for encoding_gate in gates: for rotation_gate in gates: circuit_type = encoding_gate + '-' + rotation_gate if circuit_type != 'rz-rz': print(f'Circuit type : {circuit_type} -> encoding : {encoding_gate} rotation : {rotation_gate}') acc, theta, loss_list, acc_list, weights_history = model(X_train, Y_train, X_test, Y_test, learning_rate=0.05, epochs=10, theta=np.ones(N), shots=5000, encoding_type=encoding_gate, rotation_type=rotation_gate, delta=0.01) results.update({circuit_type: {'accuracy': acc, 'theta': theta, 'loss_list':loss_list, 'acc_list':acc_list, 'weights_history_list':weights_history}}) print(f" {circuit_type} accuracy : {results.get(circuit_type).get('accuracy')}") gates = ['rx', 'ry', 'rz'] labels = [] accuracies = [] for encoding_gate in gates: for rotation_gate in gates: circuit_type = encoding_gate + '-' + rotation_gate if circuit_type != 'rz-rz': labels.append(circuit_type) accuracies.append(results.get(circuit_type).get('accuracy')) plt.bar(labels, accuracies) plt.show() gates = ['rx', 'ry', 'rz'] labels = [] accuracies = [] for encoding_gate in gates: for rotation_gate in gates: circuit_type = encoding_gate + '-' + rotation_gate if circuit_type != 'rz-rz': plt.plot([x for x in range(1, 11)], results.get(circuit_type).get('acc_list'), label=circuit_type) plt.xticks([x for x in range(1, 11)]) plt.yticks(np.arange (0, 1.1, 0.1)) plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.title('Circuit Type accuracy effect') plt.legend() plt.show() N = 4 def model_1(x_train, y_train, x_test, y_test, learning_rate, epochs, theta, shots, encoding_type, rotation_type, delta, optimizing_weights=False): loss_list = [] acc_list = [] weights_list = [] loss_val = 1 i = 0 print('Epoch \t Loss \t Training Accuracy \t theta') while loss_val > 0.17: loss_tmp = [] for X_i, Y_i in zip(x_train, y_train): prediction = quantum_nn(X_i, theta, shots, encoding_type, rotation_type) loss_tmp.append(loss(prediction, Y_i)) # update theta new_theta = theta - learning_rate * gradient(X_i, Y_i, theta, delta, shots, encoding_type, rotation_type) if loss(quantum_nn(X_i, new_theta, shots, encoding_type, rotation_type), Y_i) < loss(quantum_nn(X_i, theta, shots, encoding_type, rotation_type), Y_i): theta = new_theta loss_val = np.mean(loss_tmp) loss_list.append(np.mean(loss_tmp)) acc_list.append(accuracy(X_train, Y_train, theta, shots, encoding_type, rotation_type)) weights_list.append(theta) print(f'{i} \t {round(loss_list[-1], 3)} \t {round(acc_list[-1], 3)} \t {theta} \t {len(weights_list)}') i = i + 1 return theta, loss_list, acc_list, weights_list theta_b, loss_list_b, acc_list_b, weights_history_b = model_1(X_train, Y_train, X_test, Y_test, learning_rate=0.05, epochs=20, theta=np.ones(N), shots=5000, encoding_type='ry', rotation_type='ry', delta=0.01) N = 4 def model_2(x_train, y_train, x_test, y_test, learning_rate, epochs, theta, shots, encoding_type, rotation_type, delta, optimizing_weights=False): loss_list = [] acc_list = [] weights_list = [] print('Epoch \t Loss \t Training Accuracy \t theta') for i in range(epochs): loss_tmp = [] for X_i, Y_i in zip(x_train, y_train): prediction = quantum_nn(X_i, theta, shots, encoding_type, rotation_type) loss_tmp.append(loss(prediction, Y_i)) # update theta new_theta = theta - learning_rate * gradient(X_i, Y_i, theta, delta, shots, encoding_type, rotation_type) if loss(quantum_nn(X_i, new_theta, shots, encoding_type, rotation_type), Y_i) < loss(quantum_nn(X_i, theta, shots, encoding_type, rotation_type), Y_i): theta = new_theta loss_list.append(np.mean(loss_tmp)) acc_list.append(accuracy(X_train, Y_train, theta, shots, encoding_type, rotation_type)) weights_list.append(theta) print(f'{i} \t {round(loss_list[-1], 3)} \t {round(acc_list[-1], 3)} \t {theta} \t {len(weights_list)}') return theta, loss_list, acc_list, weights_list for learning_rate in [0.001, 0.01, 0.05, 0.1]: theta, loss_list, acc_list, weights_history = model_2(X_train, Y_train, X_test, Y_test, learning_rate=learning_rate, epochs=20, theta=np.ones(N), shots=5000, encoding_type='ry', rotation_type='ry', delta=0.01) acc = accuracy(X_test, Y_test, theta, 5000, encoding_type='ry', rotation_type='ry') results.update({learning_rate: {'accuracy': acc, 'theta': theta, 'loss_list':loss_list, 'acc_list':acc_list, 'weights_history_list':weights_history}}) print(f" Learning rate : {learning_rate} accuracy : {results.get(learning_rate).get('accuracy')}") for learning_rate in [0.001, 0.01, 0.05, 0.1]: plt.plot([x for x in range(1, 21)], results.get(learning_rate).get('acc_list'), label=learning_rate) plt.xticks([x for x in range(1, 21)]) plt.yticks(np.arange (0, 1.1, 0.1)) plt.xlabel('eposhs') plt.ylabel('Accuracy') plt.title('learning rates - accuracy effect') plt.legend() plt.show() n_shots_results = {} for n_shots in [1000, 5000, 10000, 50000]: theta, loss_list, acc_list, weights_history = model_2(X_train, Y_train, X_test, Y_test, learning_rate=0.05, epochs=20, theta=np.ones(N), shots=n_shots, encoding_type='ry', rotation_type='ry', delta=0.01) acc = accuracy(X_test, Y_test, theta, n_shots, encoding_type='ry', rotation_type='ry') n_shots_results.update({n_shots: {'accuracy': acc, 'theta': theta, 'loss_list':loss_list, 'acc_list':acc_list, 'weights_history_list':weights_history}}) print(f" Number of Shots : {n_shots} accuracy : {n_shots_results.get(n_shots).get('accuracy')}") shots_list = [1000, 5000, 10000, 50000] for n_shots in shots_list: plt.plot([x for x in range(1, 21)], n_shots_results.get(n_shots).get('acc_list'), label=n_shots) plt.xticks([x for x in range(1, 21)]) plt.yticks(np.arange (0, 1.1, 0.1)) plt.xlabel('n_shots') plt.ylabel('Accuracy') plt.title('number of shots - accuracy effecta') plt.legend() plt.show() delta_results = {} for delta in [0.01, 0.05, 0.1, 1]: theta, loss_list, acc_list, weights_history = model_2(X_train, Y_train, X_test, Y_test, learning_rate=0.1, epochs=20, theta=np.ones(N), shots=1000, encoding_type='ry', rotation_type='ry', delta=delta) acc = accuracy(X_test, Y_test, theta, 1000, encoding_type='ry', rotation_type='ry') delta_results.update({delta: {'accuracy': acc, 'theta': theta, 'loss_list':loss_list, 'acc_list':acc_list, 'weights_history_list':weights_history}}) print(f" Delta : {delta} accuracy : {delta_results.get(delta).get('accuracy')}") for delta in [0.01, 0.05, 0.1, 1]: plt.plot([x for x in range(1, 21)], delta_results.get(delta).get('acc_list'), label=delta) plt.xticks([x for x in range(1, 21)]) plt.yticks(np.arange (0, 1.1, 0.1)) plt.xlabel('eposhs') plt.ylabel('Accuracy') plt.title('Delta - accuracy effect') plt.legend() plt.show() def feature_map_2(X, theta): n = 4 qr = QuantumRegister(4) c = ClassicalRegister(1) qc = QuantumCircuit(qr,c ) for i, x in enumerate(X): qc.ry(x, i) for i in range(n-1): qc.cx(i, i+1) qc.barrier() for i in range(4): qc.rz(theta[i], i) qc.barrier() for i in reversed(range(n-1)): qc.cx(i, i+1) qc.h(0) return qc, c qc, c = feature_map_2(X[0], np.ones(4)) qc.draw('mpl') def quantum_nn(X, theta, shots, encoding_type=None, rotation_type=None, simulator=True): qc, c = feature_map_2(X, theta) qc.measure(0, c) backend = Aer.get_backend('qasm_simulator') if simulator == False: provider = IBMQ.load_account() backend = provider.get_backend('ibm_oslo') job = qiskit.execute(qc, backend, shots=shots) result = job.result() counts = result.get_counts(qc) return counts['1']/shots def accuracy(X, Y, theta, shots): counter = 0 for X_i, Y_i, in zip(X, Y): prediction = quantum_nn(X_i, theta, shots) if prediction < 0.5 and Y_i == 0: counter += 1 elif prediction >= 0.5 and Y_i == 1: counter += 1 return counter/len(Y) def gradient(X, Y, theta, delta, shots): grad = [] for i in range(len(theta)): dtheta = copy.copy(theta) dtheta[i] += delta prediction_1 = quantum_nn(X, dtheta, shots) prediction_2 = quantum_nn(X, theta, shots) grad.append((loss(prediction_1, Y) - loss(prediction_2, Y)) / delta) return np.array(grad) N = 4 def model_5(x_train, y_train, x_test, y_test, learning_rate, epochs, theta, shots, delta, optimizing_weights=False): loss_list = [] acc_list = [] weights_list = [] print('Epoch \t Loss \t Training Accuracy \t theta') for i in range(epochs): loss_tmp = [] for X_i, Y_i in zip(x_train, y_train): prediction = quantum_nn(X_i, theta, shots) loss_tmp.append(loss(prediction, Y_i)) # update theta new_theta = theta - learning_rate * gradient(X_i, Y_i, theta, delta, shots) if loss(quantum_nn(X_i, new_theta, shots), Y_i) < loss(quantum_nn(X_i, theta, shots), Y_i): theta = new_theta loss_list.append(np.mean(loss_tmp)) acc_list.append(accuracy(X_train, Y_train, theta, shots)) weights_list.append(theta) print(f'{i} \t {round(loss_list[-1], 3)} \t {round(acc_list[-1], 3)} \t {theta} \t {len(weights_list)}') return theta, loss_list, acc_list, weights_list theta, loss_list, acc_list, weights_list = model_5(X_train, Y_train, X_test, Y_test, 0.01, 30, [1, 1, 1, 1], 5000, 0.01) accuracy(X_test, Y_test, theta, 5000) plt.plot([x for x in range(1, 31)], acc_list) plt.xticks([x for x in range(1, 31)]) plt.yticks(np.arange (0, 1.1, 0.1)) plt.xlabel('eposhs') plt.ylabel('Accuracy') plt.title('Accuracy') plt.legend() plt.show() from qiskit.circuit.library import ZZFeatureMap num_features = X_train.shape[1] feature_map = ZZFeatureMap(feature_dimension=num_features, reps=1) feature_map.decompose().draw(output="mpl", fold=20) from qiskit.circuit.library import RealAmplitudes ansatz = RealAmplitudes(num_qubits=num_features, reps=3) ansatz.decompose().draw(output="mpl", fold=20) from qiskit.algorithms.optimizers import COBYLA optimizer = COBYLA(maxiter=100) from qiskit.primitives import Sampler sampler = Sampler() from matplotlib import pyplot as plt from IPython.display import clear_output objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) def callback_graph(weights, obj_func_eval): clear_output(wait=True) objective_func_vals.append(obj_func_eval) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() import time from qiskit_machine_learning.algorithms.classifiers import VQC vqc = VQC( sampler=sampler, feature_map=feature_map, ansatz=ansatz, optimizer=optimizer, callback=callback_graph, ) # clear objective value history objective_func_vals = [] start = time.time() vqc.fit(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 QNN on the training dataset: {accuracy(X_train, Y_train, theta, 5000):.2f}") print(f"Quantum QNN on the test dataset: {accuracy(X_test, Y_test, theta, 5000):.2f}") print(f"Quantum VQC on the training dataset: {train_score_q4:.2f}") print(f"Quantum VQC on the test dataset: {test_score_q4:.2f}")
https://github.com/osamarais/qiskit_iterative_solver
osamarais
import qiskit from qiskit import QuantumCircuit, QuantumRegister from qiskit.extensions import UnitaryGate import numpy as np from scipy.linalg import fractional_matrix_power from scipy.io import loadmat, savemat from copy import deepcopy # problems = ((1,4),(1,8),(1,16),(2,4),(2,8),(2,16),(3,4),(3,16),(4,4),(4,16),(5,6),(5,20),(6,4),(6,16),(7,6),(7,20)) problems = ((5,6),(5,20),(6,4),(6,16),(7,6),(7,20)) def CR_phi_d(phi, d, register_1, register_2): circuit = QuantumCircuit(register_1,register_2,name = 'CR_( \\phi \\tilde {})'.format(d)) circuit.cnot(register_2,register_1,ctrl_state=0) circuit.rz(phi*2, register_1) circuit.cnot(register_2,register_1,ctrl_state=0) return circuit for problem in problems: problem_number = problem[0] size = problem[1] iterations = int(np.floor(128/size -1)) # iterations = 7 K = np.array( loadmat('N_{}_problem_{}.mat'.format(size,problem_number)) ).item()['A'] R = np.array( loadmat('N_{}_problem_{}.mat'.format(size,problem_number)) ).item()['R'] B = np.array( loadmat('N_{}_problem_{}.mat'.format(size,problem_number)) ).item()['B'] f = np.array( loadmat('N_{}_problem_{}.mat'.format(size,problem_number)) ).item()['f'] f = f/np.linalg.norm(f) print('|R|_2 = {}'.format(np.linalg.norm(R,2))) A = np.eye((iterations+1)*size,(iterations+1)*size) for block in range(iterations): A[(block+1)*size:(block+2)*size,(block)*size:(block+1)*size] = -R # A[(block+1)*size:(block+2)*size,(block)*size:(block+1)*size] = -np.eye(size) A_orig = deepcopy(A) # Normalize the matrix using the upper bound A = A/2 np.linalg.norm(A,2) RHS_provided = True A_shape = np.shape(A_orig) # Hermitian Dilation # Only if A is not Hermitian from copy import deepcopy if np.any(A != A.conj().T): A = np.block([ [np.zeros(np.shape(A)),A], [A.conj().T,np.zeros(np.shape(A))] ]) HD = True else: HD = False print(HD) if RHS_provided: b = np.zeros(((iterations+1)*size,1)) for block in range(iterations): b[(block+1)*size:(block+2)*size,:] = f b = b / np.linalg.norm(b,2) b = b.flatten() b_orig = deepcopy(b) if HD: b = np.concatenate([b,np.zeros(b.shape)]) print(b) if np.size(A)>1: A_num_qubits = int(np.ceil(np.log2(np.shape(A)[0]))) padding_size = 2**A_num_qubits - np.shape(A)[0] if padding_size > 0: A = np.block([ [A, np.zeros([np.shape(A)[0],padding_size])], [np.zeros([padding_size,np.shape(A)[0]]), np.zeros([padding_size,padding_size])] ]) else: A_num_qubits = 1 padding_size = 1 A = np.array([[A,0],[0,0]]) print(A_num_qubits) print(padding_size) print(A) # If RHS is given, it also needs to be padded if RHS_provided: b = np.pad(b,(0,padding_size)) O = np.block([ [A , -fractional_matrix_power(np.eye(np.shape(A)[0]) - np.linalg.matrix_power(A,2),0.5)], [fractional_matrix_power(np.eye(np.shape(A)[0]) - np.linalg.matrix_power(A,2),0.5) , A] ]) print(O) # We also need to get the block-encoding size, i.e. m, used to encode A in U_A m = int(np.log2(np.shape(O)[0]) - A_num_qubits) O_A_num_qubits = int(np.log2(np.shape(O)[0])) print('m = {} \nNumber of Qubits for O_A is {}'.format(m,O_A_num_qubits)) blockA = UnitaryGate(O,label='O_A') register_1 = QuantumRegister(size = 1, name = '|0>') register_2 = QuantumRegister(size = m, name = '|0^m>') register_3 = QuantumRegister(size = O_A_num_qubits-m, name = '|\\phi>') from scipy.io import loadmat phi_angles = np.array( loadmat('phi_k_50_14.mat') ).item()['phi'] phi_tilde_angles = np.zeros(np.shape(phi_angles)) temp = np.zeros(np.shape(phi_angles)) # plot QSP angles for d,phi in enumerate(phi_angles): if d==0 or d==np.size(phi_angles)-1: temp[d] = phi_angles[d] - np.pi/4 else: temp[d] = phi_angles[d] phase_angles = phi_angles.reshape(phi_angles.shape[0]) circuit = QuantumCircuit(register_1, register_2, register_3, name = 'QSP') if RHS_provided: circuit.initialize(b,list(reversed(register_3))) # First thing is to Hadamard the ancilla qubit since we want Re(P(A)) circuit.h(register_1) # Note: QSPPACK produces symmetric phase angles, so reversing phase angles is unnecessary # for d, phi in enumerate(reversed(phase_angles)): for d, phi in reversed(list(enumerate(phase_angles))): circuit = circuit.compose(CR_phi_d(phi,d,register_1,register_2)) if d>0: # The endianness of the bits matters. Need to change the order of the bits circuit.append(blockA,list(reversed(register_3[:])) + register_2[:]) # Apply the final Hadamard gate circuit.h(register_1) circuit = circuit.reverse_bits() circuit.size() from qiskit import transpile circuit = transpile(circuit) from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute from qiskit import Aer Aer.backends() # solver = 'unitary' solver = 'statevector' machine = "CPU" # machine = "GPU" # precision = "single" precision = "double" if solver=='unitary': # backend = Aer.get_backend('unitary_simulator',precision = 'double',device="GPU") backend = Aer.get_backend('unitary_simulator',precision = precision,device=machine) job = execute(circuit, backend, shots=0) result = job.result() QSP_unitary = result.get_unitary(circuit,100) QSP_matrix = np.array(QSP_unitary.to_matrix()) print(QSP_matrix) elif solver=='statevector': backend = Aer.get_backend('statevector_simulator',precision = precision,device=machine) # backend = Aer.get_backend('statevector_simulator',precision = 'double',device="GPU") job = execute(circuit, backend, shots=0) result = job.result() QSP_statevector = result.get_statevector() print(QSP_statevector) if solver=='statevector': # We can ignore the padding size and directly use the size of b (considering Hermitian dilation) if HD: P_A_b = np.real(QSP_statevector.data[int(b_orig.shape[0]):(2*b_orig.shape[0])]) else: P_A_b = np.real(QSP_statevector.data[0:b.shape[0]]) P_A_b = P_A_b/np.linalg.norm(P_A_b) if solver=='statevector': expected_P_A_b = np.linalg.solve(A_orig,b_orig) expected_P_A_b = expected_P_A_b/np.linalg.norm(expected_P_A_b) exact_solution = np.linalg.solve(K,f) x_exact_normalized = exact_solution x_exact_normalized = x_exact_normalized/np.linalg.norm(x_exact_normalized) error_actual = [] if solver=='statevector': for iteration_number in range(1,iterations): e = x_exact_normalized - (P_A_b[iteration_number*size:(iteration_number+1)*size]/np.linalg.norm(P_A_b[iteration_number*size:(iteration_number+1)*size])).reshape(np.shape(x_exact_normalized)) error_actual.append(np.linalg.norm(e)) error_expected = [] if solver=='statevector': for iteration_number in range(1,iterations): e = x_exact_normalized - (expected_P_A_b[iteration_number*size:(iteration_number+1)*size]/np.linalg.norm(expected_P_A_b[iteration_number*size:(iteration_number+1)*size])).reshape(np.shape(x_exact_normalized)) error_expected.append(np.linalg.norm(e)) mdic = {"classical":error_expected,"quantum":error_actual,"kappa":np.linalg.cond(A_orig)} savemat("output_N_{}_problem_{}.mat".format(size,problem_number), mdic)
https://github.com/alvinli04/Quantum-Steganography
alvinli04
import qiskit from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute from qiskit import Aer from qiskit import IBMQ from qiskit.compiler import transpile from time import perf_counter from qiskit.tools.visualization import plot_histogram import numpy as np import math ''' params --------------- picture: square 2d array of integers representing grayscale values assume the length (n) is some power of 2 return --------------- a flattened representation of picture using bitstrings (boolean arrays) ''' def convert_to_bits (picture): n = len(picture) ret = [] for i in range(n): for j in range(n): value = picture[i][j] bitstring = bin(value)[2:] ret.append([0 for i in range(8 - len(bitstring))] + [1 if c=='1' else 0 for c in bitstring]) return ret ''' params ---------------- bitStr: a representation of an image using bitstrings to represent grayscale values return ---------------- A quantum circuit containing the NEQR representation of the image ''' def neqr(bitStr, quantumImage, idx, intensity): newBitStr = bitStr numOfQubits = quantumImage.num_qubits quantumImage.draw() print("Number of Qubits:", numOfQubits) # ----------------------------------- # Drawing the Quantum Circuit # ----------------------------------- lengthIntensity = intensity.size lengthIdx = idx.size quantumImage.i([intensity[lengthIntensity-1-i] for i in range(lengthIntensity)]) quantumImage.h([idx[lengthIdx-1-i] for i in range(lengthIdx)]) numOfPixels = len(newBitStr) for i in range(numOfPixels): bin_ind = bin(i)[2:] bin_ind = (lengthIdx - len(bin_ind)) * '0' + bin_ind bin_ind = bin_ind[::-1] # X-gate (enabling zero-controlled nature) for j in range(len(bin_ind)): if bin_ind[j] == '0': quantumImage.x(idx[j]) # Configuring CCNOT (ccx) gates with control and target qubits for j in range(len(newBitStr[i])): if newBitStr[i][j] == 1: quantumImage.mcx(idx, intensity[lengthIntensity-1-j]) # X-gate (enabling zero-controlled nature) for j in range(len(bin_ind)): if bin_ind[j] == '0': quantumImage.x(idx[j]) quantumImage.barrier()
https://github.com/usamisaori/quantum-expressibility-entangling-capability
usamisaori
import numpy as np import qiskit from qiskit import QuantumCircuit import matplotlib.pyplot as plt from qiskit.circuit import QuantumCircuit, Parameter import warnings warnings.filterwarnings('ignore') theta = Parameter("θ") phi = Parameter("φ") lamb = Parameter("λ") def sampleCircuitA(layer=1, qubits=4): circuit = QuantumCircuit(qubits) for i in range(layer): for i in range(qubits - 1): circuit.cx(i, i + 1) circuit.cx(qubits - 1, 0) for i in range(qubits - 1): circuit.cx(i, i + 1) circuit.cx(qubits - 1, 0) circuit.barrier() for i in range(qubits): circuit.u3(theta, phi, lamb, i) return circuit circuitA = sampleCircuitA(qubits=4) circuitA.draw(output='mpl') def sampleCircuitB1(layer=1, qubits=4): circuit = QuantumCircuit(qubits) for i in range(qubits): circuit.u1(theta, i) for i in range(layer): for j in range(qubits - 1): circuit.cz(j, j + 1) circuit.cz(qubits - 1, 0) circuit.barrier() for j in range(qubits): circuit.u1(theta, j) return circuit def sampleCircuitB2(layer=1, qubits=4): circuit = QuantumCircuit(qubits) for i in range(qubits): circuit.u2(phi, lamb, i) for i in range(layer): for j in range(qubits - 1): circuit.cz(j, j + 1) circuit.cz(qubits - 1, 0) circuit.barrier() for j in range(qubits): circuit.u2(phi, lamb, j) return circuit def sampleCircuitB3(layer=1, qubits=4): circuit = QuantumCircuit(qubits) for i in range(qubits): circuit.u3(theta, phi, lamb, i) for i in range(layer): for j in range(qubits - 1): circuit.cz(j, j + 1) circuit.cz(qubits - 1, 0) circuit.barrier() for j in range(qubits): circuit.u3(theta, phi, lamb, j) return circuit circuitB1 = sampleCircuitB1(qubits=4) circuitB1.draw(output='mpl') circuitB2 = sampleCircuitB2(qubits=4) circuitB2.draw(output='mpl') circuitB3 = sampleCircuitB3(qubits=4) circuitB3.draw(output='mpl') def sampleCircuitC(layer=1, qubits=4): circuit = QuantumCircuit(qubits) for i in range(layer): for j in range(qubits): circuit.ry(theta, j) circuit.crx(theta, qubits - 1, 0) for j in range(qubits - 1, 0, -1): circuit.crx(theta, j - 1, j) circuit.barrier() for j in range(qubits): circuit.ry(theta, j) circuit.crx(theta, 3, 2) circuit.crx(theta, 0, 3) circuit.crx(theta, 1, 0) circuit.crx(theta, 2, 1) return circuit circuitC = sampleCircuitC(qubits=4) circuitC.draw(output='mpl') def sampleCircuitD(layer=1, qubits=4): circuit = QuantumCircuit(qubits) for i in range(layer): for j in range(qubits): circuit.rx(theta, j) circuit.rz(theta, j) for j in range(qubits - 1, -1, -1): for k in range(qubits - 1, -1, -1): if j != k: circuit.crx(theta, j, k) circuit.barrier() for j in range(qubits): circuit.rx(theta, j) circuit.rz(theta, j) return circuit circuitD = sampleCircuitD(qubits=4) circuitD.draw(output='mpl') def sampleCircuitE(layer=1, qubits=4): circuit = QuantumCircuit(qubits) for i in range(layer): for j in range(qubits): circuit.rx(theta, j) circuit.rz(theta, j) for j in range(1, qubits, 2): circuit.crx(theta, j, j - 1) for j in range(qubits): circuit.rx(theta, j) circuit.rz(theta, j) for j in range(2, qubits, 2): circuit.crx(theta, j, j - 1) return circuit circuitE = sampleCircuitE(qubits=4) circuitE.draw(output='mpl') def sampleCircuitF(layer=1, qubits=4): circuit = QuantumCircuit(qubits) for i in range(layer): for j in range(qubits): circuit.rx(theta, j) circuit.rz(theta, j) circuit.crx(theta, qubits - 1, 0) for j in range(qubits - 1, 0, -1): circuit.crx(theta, j - 1, j) return circuit circuitF = sampleCircuitF(qubits=4) circuitF.draw(output='mpl') def sampleEncoding(qubits): circuit = QuantumCircuit(qubits) for i in range(qubits): circuit.h(i) circuit.ry(theta, i) return circuit circuit = sampleEncoding(4) circuit.draw(output='mpl') # demo: circuit = sampleEncoding(5).compose(sampleCircuitB3(layer=2, qubits=5)) circuit.draw(output='mpl')
https://github.com/ShabaniLab/qiskit-hackaton-2019
ShabaniLab
import numpy as np from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister from ising_kitaev import initialize_chain, braid_chain, rotate_to_measurement_basis, add_measurement, initialize_coupler zeeman_ferro = 0.01 zeeman_para = 10 initial_config = np.array([zeeman_ferro]*3 + [zeeman_para]*9) qreg = QuantumRegister(13) creg = ClassicalRegister(3) qcirc = QuantumCircuit(qreg, creg) initialize_chain(qcirc, qreg, initial_config, 'up') initialize_coupler(qcirc, qreg) qcirc.draw() braid_chain(qcirc, qreg, np.pi, 40, initial_config, 1.4, 0.25, 0.25, 2, 40, method='both') qcirc.depth() add_measurement(qcirc, qreg, creg, [0, 1, 2]) from qiskit import Aer, execute backend = Aer.get_backend('qasm_simulator') job = execute(qcirc, backend, shots=2000) job.status() result = job.result() print(result.get_counts())
https://github.com/C2QA/bosonic-qiskit
C2QA
# To use the package locally, add the C2QA repository's root folder to the path prior to importing c2qa. import os import sys module_path = os.path.abspath(os.path.join("../..")) if module_path not in sys.path: sys.path.append(module_path) # Cheat to get MS Visual Studio Code Jupyter server to recognize Python venv module_path = os.path.abspath(os.path.join("../../venv/Lib/site-packages")) if module_path not in sys.path: sys.path.append(module_path) import c2qa import qiskit import numpy as np import c2qa.util as util import matplotlib.pyplot as plt import matplotlib numberofmodes=5 numberofqubits=numberofmodes numberofqubitspermode=3 cutoff=2**numberofqubitspermode qmr = c2qa.QumodeRegister(num_qumodes=numberofmodes, num_qubits_per_qumode=numberofqubitspermode) qbr = qiskit.QuantumRegister(size=numberofqubits) cbr = qiskit.ClassicalRegister(size=1) circuit = c2qa.CVCircuit(qmr, qbr, cbr) sm = [0,0,1,0,0] for i in range(qmr.num_qumodes): circuit.cv_initialize(sm[i], qmr[i]) def bch(circuit, qm, qb, U, dt): arg = np.sqrt((U/4)*dt) circuit.cv_c_rx(arg, qm, qb) circuit.cv_c_r(arg, qm, qb) circuit.cv_c_rx(-arg, qm, qb) circuit.cv_c_r(-arg, qm, qb) def eiht(circuit, qma, qmb, qba, qbb, J, U, mu, dt): circuit.cv_bs(-J*dt, qmb, qma) circuit.cv_r(-((U/2)+mu)*dt, qma) circuit.cv_r(-((U/2)+mu)*dt, qmb) bch(circuit, qma, qba, U/2, dt) bch(circuit, qmb, qbb, U/2, dt) return circuit def trotterise_BH(circuit, numberofmodes, numberofqubits, qmr, qbr, cutoff, N, J, U, mu, dt): occs=[np.zeros((N,numberofmodes)),np.zeros((N,numberofqubits))] # Trotterise. i*dt corresponds to the timestep i, of length from the previous timestep dt. for i in range(N): print("dt+1", i*dt) # Trotterise according to the brickwork format to make depth of circuit 2 and not number of timesteps (because each site needs to be part of a gate with the site to the left and a gate with the site to the right. for j in range(0,numberofmodes-1,2): eiht(circuit, qmr[j+1], qmr[j], qbr[j], qbr[j+1], J, U, mu, dt) for j in range(1,numberofmodes-1,2): eiht(circuit, qmr[j+1], qmr[j], qbr[j], qbr[j+1], J, U, mu, dt) stateop, result, fock_counts = c2qa.util.simulate(circuit) occupation = util.stateread(stateop, qbr.size, numberofmodes, 4,verbose=False) occs[0][i]=np.array(list(occupation[0][0])) occs[1][i]=np.array(list(occupation[0][1])) return occs dt=0.1 N=10 J=1 U=0.1 mu=1 occupations = trotterise_BH(circuit, numberofmodes, numberofqubits, qmr, qbr, cutoff, N, J, U, mu, dt) plt.pcolormesh(np.arange(numberofmodes+1)-numberofmodes//2-0.5,np.arange(N+1)*dt,occupations[0],cmap=matplotlib.cm.Blues,linewidth=0,rasterized=True) plt.title("$J=1$, $U=0.1$, $\mu=1$") plt.xlabel("Modes") plt.ylabel("Time") cbar = plt.colorbar() cbar.ax.get_yaxis().labelpad = 15 cbar.set_label("Mode occupation", rotation=270) plt.rcParams["figure.figsize"] = (6,3) plt.tight_layout() plt.savefig("BH.pdf")
https://github.com/Praween-em/QiskitBasics
Praween-em
#!/usr/bin/env python # coding: utf-8 # In[1]: from qiskit import * # In[2]: qr = QuantumRegister(2) # In[3]: cr = ClassicalRegister(2) # In[4]: circuit = QuantumCircuit(qr,cr) # In[5]: get_ipython().run_line_magic('matplotlib', 'inline') # In[6]: circuit.draw() # In[7]: circuit.h(qr[0]) # In[8]: circuit.draw(output='mpl') # In[9]: circuit.cx(qr[0], qr[1]) # In[10]: circuit.draw(output='mpl') # In[11]: circuit.measure(qr,cr) # In[12]: circuit.draw(output='mpl') # In[15]: simulator = Aer.get_backend('qasm_simulator') # In[17]: result = execute(circuit, backend=simulator).result() # In[18]: from qiskit.tools.visualization import plot_histogram # In[19]: plot_histogram(result.get_counts(circuit)) # In[20]: IBMQ.load_account() # In[21]: provider = IBMQ.get_provider('ibm-q') # In[26]: qcomp = provider.get_backend('ibm_brisbane') # In[27]: job = execute(circuit, backend=qcomp) # In[28]: from qiskit.tools.monitor import job_monitor # In[32]: job_monitor(job) # In[33]: result=job.result() # In[34]: plot_histogram(result.get_counts(circuit)) # In[ ]:
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Grover's algorithm.""" import itertools import unittest from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np from ddt import data, ddt, idata, unpack from qiskit import BasicAer, QuantumCircuit from qiskit_algorithms import AmplificationProblem, Grover from qiskit.circuit.library import GroverOperator, PhaseOracle from qiskit.primitives import Sampler from qiskit.quantum_info import Operator, Statevector from qiskit.utils import QuantumInstance, algorithm_globals from qiskit.utils.optionals import HAS_TWEEDLEDUM @ddt class TestAmplificationProblem(QiskitAlgorithmsTestCase): """Test the amplification problem.""" def setUp(self): super().setUp() oracle = QuantumCircuit(2) oracle.cz(0, 1) self._expected_grover_op = GroverOperator(oracle=oracle) @data("oracle_only", "oracle_and_stateprep") def test_groverop_getter(self, kind): """Test the default construction of the Grover operator.""" oracle = QuantumCircuit(2) oracle.cz(0, 1) if kind == "oracle_only": problem = AmplificationProblem(oracle, is_good_state=["11"]) expected = GroverOperator(oracle) else: stateprep = QuantumCircuit(2) stateprep.ry(0.2, [0, 1]) problem = AmplificationProblem( oracle, state_preparation=stateprep, is_good_state=["11"] ) expected = GroverOperator(oracle, stateprep) self.assertEqual(Operator(expected), Operator(problem.grover_operator)) @data("list_str", "list_int", "statevector", "callable") def test_is_good_state(self, kind): """Test is_good_state works on different input types.""" if kind == "list_str": is_good_state = ["01", "11"] elif kind == "list_int": is_good_state = [1] # means bitstr[1] == '1' elif kind == "statevector": is_good_state = Statevector(np.array([0, 1, 0, 1]) / np.sqrt(2)) else: def is_good_state(bitstr): # same as ``bitstr in ['01', '11']`` return bitstr[1] == "1" possible_states = [ "".join(list(map(str, item))) for item in itertools.product([0, 1], repeat=2) ] oracle = QuantumCircuit(2) problem = AmplificationProblem(oracle, is_good_state=is_good_state) expected = [state in ["01", "11"] for state in possible_states] actual = [problem.is_good_state(state) for state in possible_states] self.assertListEqual(expected, actual) @ddt class TestGrover(QiskitAlgorithmsTestCase): """Test for the functionality of Grover""" def setUp(self): super().setUp() with self.assertWarns(DeprecationWarning): self.statevector = QuantumInstance( BasicAer.get_backend("statevector_simulator"), seed_simulator=12, seed_transpiler=32 ) self.qasm = QuantumInstance( BasicAer.get_backend("qasm_simulator"), seed_simulator=12, seed_transpiler=32 ) self._sampler = Sampler() self._sampler_with_shots = Sampler(options={"shots": 1024, "seed": 123}) algorithm_globals.random_seed = 123 @unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test") @data("ideal", "shots", False) def test_implicit_phase_oracle_is_good_state(self, use_sampler): """Test implicit default for is_good_state with PhaseOracle.""" grover = self._prepare_grover(use_sampler) oracle = PhaseOracle("x & y") problem = AmplificationProblem(oracle) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "11") @idata(itertools.product(["ideal", "shots", False], [[1, 2, 3], None, 2])) @unpack def test_iterations_with_good_state(self, use_sampler, iterations): """Test the algorithm with different iteration types and with good state""" grover = self._prepare_grover(use_sampler, iterations) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @idata(itertools.product(["shots", False], [[1, 2, 3], None, 2])) @unpack def test_iterations_with_good_state_sample_from_iterations(self, use_sampler, iterations): """Test the algorithm with different iteration types and with good state""" grover = self._prepare_grover(use_sampler, iterations, sample_from_iterations=True) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @data("ideal", "shots", False) def test_fixed_iterations_without_good_state(self, use_sampler): """Test the algorithm with iterations as an int and without good state""" grover = self._prepare_grover(use_sampler, iterations=2) problem = AmplificationProblem(Statevector.from_label("111")) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @idata(itertools.product(["ideal", "shots", False], [[1, 2, 3], None])) @unpack def test_iterations_without_good_state(self, use_sampler, iterations): """Test the correct error is thrown for none/list of iterations and without good state""" grover = self._prepare_grover(use_sampler, iterations=iterations) problem = AmplificationProblem(Statevector.from_label("111")) with self.assertRaisesRegex( TypeError, "An is_good_state function is required with the provided oracle" ): if not use_sampler: with self.assertWarns(DeprecationWarning): grover.amplify(problem) else: grover.amplify(problem) @data("ideal", "shots", False) def test_iterator(self, use_sampler): """Test running the algorithm on an iterator.""" # step-function iterator def iterator(): wait, value, count = 3, 1, 0 while True: yield value count += 1 if count % wait == 0: value += 1 grover = self._prepare_grover(use_sampler, iterations=iterator()) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @data("ideal", "shots", False) def test_growth_rate(self, use_sampler): """Test running the algorithm on a growth rate""" grover = self._prepare_grover(use_sampler, growth_rate=8 / 7) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @data("ideal", "shots", False) def test_max_num_iterations(self, use_sampler): """Test the iteration stops when the maximum number of iterations is reached.""" def zero(): while True: yield 0 grover = self._prepare_grover(use_sampler, iterations=zero()) n = 5 problem = AmplificationProblem(Statevector.from_label("1" * n), is_good_state=["1" * n]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(len(result.iterations), 2**n) @data("ideal", "shots", False) def test_max_power(self, use_sampler): """Test the iteration stops when the maximum power is reached.""" lam = 10.0 grover = self._prepare_grover(use_sampler, growth_rate=lam) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) result = grover.amplify(problem) self.assertEqual(len(result.iterations), 0) @data("ideal", "shots", False) def test_run_circuit_oracle(self, use_sampler): """Test execution with a quantum circuit oracle""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) grover = self._prepare_grover(use_sampler) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) @data("ideal", "shots", False) def test_run_state_vector_oracle(self, use_sampler): """Test execution with a state vector oracle""" mark_state = Statevector.from_label("11") problem = AmplificationProblem(mark_state, is_good_state=["11"]) grover = self._prepare_grover(use_sampler) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) @data("ideal", "shots", False) def test_run_custom_grover_operator(self, use_sampler): """Test execution with a grover operator oracle""" oracle = QuantumCircuit(2) oracle.cz(0, 1) grover_op = GroverOperator(oracle) problem = AmplificationProblem( oracle=oracle, grover_operator=grover_op, is_good_state=["11"] ) grover = self._prepare_grover(use_sampler) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) def test_optimal_num_iterations(self): """Test optimal_num_iterations""" num_qubits = 7 for num_solutions in range(1, 2**num_qubits): amplitude = np.sqrt(num_solutions / 2**num_qubits) expected = round(np.arccos(amplitude) / (2 * np.arcsin(amplitude))) actual = Grover.optimal_num_iterations(num_solutions, num_qubits) self.assertEqual(actual, expected) def test_construct_circuit(self): """Test construct_circuit""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) grover = Grover() constructed = grover.construct_circuit(problem, 2, measurement=False) grover_op = GroverOperator(oracle) expected = QuantumCircuit(2) expected.h([0, 1]) expected.compose(grover_op.power(2), inplace=True) self.assertTrue(Operator(constructed).equiv(Operator(expected))) @data("ideal", "shots", False) def test_circuit_result(self, use_sampler): """Test circuit_result""" oracle = QuantumCircuit(2) oracle.cz(0, 1) # is_good_state=['00'] is intentionally selected to obtain a list of results problem = AmplificationProblem(oracle, is_good_state=["00"]) grover = self._prepare_grover(use_sampler, iterations=[1, 2, 3, 4]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) if use_sampler: for i, dist in enumerate(result.circuit_results): keys, values = zip(*sorted(dist.items())) if i in (0, 3): self.assertTupleEqual(keys, ("11",)) np.testing.assert_allclose(values, [1], atol=0.2) else: self.assertTupleEqual(keys, ("00", "01", "10", "11")) np.testing.assert_allclose(values, [0.25, 0.25, 0.25, 0.25], atol=0.2) else: expected_results = [ {"11": 1024}, {"00": 238, "01": 253, "10": 263, "11": 270}, {"00": 238, "01": 253, "10": 263, "11": 270}, {"11": 1024}, ] self.assertEqual(result.circuit_results, expected_results) @data("ideal", "shots", False) def test_max_probability(self, use_sampler): """Test max_probability""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) grover = self._prepare_grover(use_sampler) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertAlmostEqual(result.max_probability, 1.0) @unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test") @data("ideal", "shots", False) def test_oracle_evaluation(self, use_sampler): """Test oracle_evaluation for PhaseOracle""" oracle = PhaseOracle("x1 & x2 & (not x3)") problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring) grover = self._prepare_grover(use_sampler) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertTrue(result.oracle_evaluation) self.assertEqual("011", result.top_measurement) def test_sampler_setter(self): """Test sampler setter""" grover = Grover() grover.sampler = self._sampler self.assertEqual(grover.sampler, self._sampler) def _prepare_grover( self, use_sampler, iterations=None, growth_rate=None, sample_from_iterations=False ): """Prepare Grover instance for test""" if use_sampler == "ideal": grover = Grover( sampler=self._sampler, iterations=iterations, growth_rate=growth_rate, sample_from_iterations=sample_from_iterations, ) elif use_sampler == "shots": grover = Grover( sampler=self._sampler_with_shots, iterations=iterations, growth_rate=growth_rate, sample_from_iterations=sample_from_iterations, ) else: with self.assertWarns(DeprecationWarning): grover = Grover( quantum_instance=self.qasm, iterations=iterations, growth_rate=growth_rate, sample_from_iterations=sample_from_iterations, ) return grover if __name__ == "__main__": unittest.main()
https://github.com/dcavar/q
dcavar
!pip install -U --user qiskit !pip install -U --user qiskit_ibm_runtime !pip install -U --user qiskit_aer !pip install -U --user matplotlib !pip install -U --user pylatexenc import qiskit import secret qc = qiskit.QuantumCircuit(2) qc.h(0) qc.cx(0, 1) x = qc.draw(output='mpl') x from qiskit.quantum_info import Pauli ZZ = Pauli('ZZ') ZI = Pauli('ZI') IZ = Pauli('IZ') XX = Pauli('XX') XI = Pauli('XI') IX = Pauli('IX') observables = [ZZ, ZI, IZ, XX, XI, IX] from qiskit_aer.primitives import Estimator estimator = Estimator() job = estimator.run([qc] * len(observables), observables) job.result() import matplotlib.pyplot as plt data = ["ZZ", "ZI", "IZ", "XX", "XI", "IX"] values = job.result().values plt.plot(data, values, '-o') plt.xlabel('Observables') plt.ylabel('Expectation value') plt.show()
https://github.com/ohadlev77/sat-circuits-engine
ohadlev77
# Copyright 2022-2023 Ohad Lev. # 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, # or in the root directory of this package("LICENSE.txt"). # 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. """ GroverConstraintsOperator class. """ from itertools import chain from typing import Optional from qiskit import QuantumCircuit, QuantumRegister from qiskit.transpiler.passes import RemoveBarriers from sat_circuits_engine.constraints_parse import ParsedConstraints from sat_circuits_engine.circuit.single_constraint import SingleConstraintBlock class GroverConstraintsOperator(QuantumCircuit): """ A quantum circuit implementation of Grover's operator constructed for a specific combination of constraints defined by a user. """ def __init__( self, parsed_constraints: ParsedConstraints, num_input_qubits: int, insert_barriers: Optional[bool] = True, ) -> None: """ Args: parsed_constraints (ParsedConstraints): a dict-like object that associates every (single) constraint string (the keys) with its `SingleConstraintParsed` object (the values). num_input_qubits (int): number of qubits in the input register. insert_barriers (Optional[bool] = True): if True, barriers will be inserted to separate between constraints. """ self.num_input_qubits = num_input_qubits self.parsed_constraints = parsed_constraints self.insert_barriers = insert_barriers # Construction a `SingleConstraintBlock` object for every constraint. A few more # attributes defined within self.constraints_blocks_build(), see its docstrings for details. self.constraints_blocks_build() # Initializing the quantum circuit that implements the Grover operator we seek for self.input_reg = QuantumRegister(self.num_input_qubits, "input_reg") self.comparison_aux_reg = QuantumRegister(self.comparison_aux_width, "comparison_aux_reg") self.left_aux_reg = QuantumRegister(self.left_aux_width, "left_aux_reg") self.right_aux_reg = QuantumRegister(self.right_aux_width, "right_aux_reg") self.out_reg = QuantumRegister(self.out_qubits_amount, "out_reg") self.ancilla = QuantumRegister(1, "ancilla") super().__init__( self.input_reg, self.left_aux_reg, self.right_aux_reg, self.comparison_aux_reg, self.out_reg, self.ancilla, name="Operator", ) # Assembling `self` to a complete Grover operator self.assemble() def __repr__(self) -> str: if self.parsed_constraints.high_level_constraints_string is not None: repr_string = self.parsed_constraints.high_level_constraints_string else: repr_string = self.parsed_constraints.constraints_string return f"{self.__class__.__name__}('{repr_string}')" def constraints_blocks_build(self) -> None: """ Parses the `self.parsed_constraints` attribute and defines the attributes: - `self.single_constraints_objects` (List[SingleConstraintBlock]): a list of `SingleConstraintBlock` objects, each built from a single constraint string. - `self.comparison_aux_qubits_needed` (List[int]): a list of auxiliary qubits needed for implementing the comparison between the two sides of the constraint's equation. - `self.left_aux_qubits_needed` (List[int]): a list of auxiliary qubits needed for implementing arithmetics on the left side of the constraint's equation. - `self.right_aux_qubits_needed` (List[int]): a list of auxiliary qubits needed for implementing arithmetics on the right side of the constraint's equation. - `self.comparison_aux_width` (int): Total number of comparison aux qubits. - `self.left_aux_width` (int): Total number of left aux qubits. - `self.right_aux_width` (int): Total number of right aux qubits. - `self.out_qubits_amount` (int): the number of "out qubits" needed, while each "out qubit" is used to write the result of applying a single constraint into (|1> if the constraint is satisfied, |0> otherwise). """ # For each constraint we build a `SingleConstraintBlock` object self.single_constraints_objects = list( map(SingleConstraintBlock, self.parsed_constraints.values()) ) # Sorting the constraints such that the most costly ones will be the first and last # (First and last constraint are not uncomputed - only when the whole operator is uncomputed). self.single_constraints_objects.sort(key=lambda x: x.transpiled.count_ops()["cx"], reverse=True) self.single_constraints_objects.append(self.single_constraints_objects[0]) self.single_constraints_objects.pop(0) self.comparison_aux_qubits_needed = [] self.left_aux_qubits_needed = [] self.right_aux_qubits_needed = [] # For each we count which and how many aux qubits are needed for constraint_block in self.single_constraints_objects: if "comparison_aux" in constraint_block.regs.keys(): self.comparison_aux_qubits_needed.append(len(constraint_block.regs["comparison_aux"][0])) else: self.comparison_aux_qubits_needed.append(0) self.left_aux_qubits_needed.append(len(constraint_block.regs["sides_aux"][0])) self.right_aux_qubits_needed.append(len(constraint_block.regs["sides_aux"][1])) # Total number of qubits for each type self.comparison_aux_width = sum(self.comparison_aux_qubits_needed) self.left_aux_width = sum(self.left_aux_qubits_needed) self.right_aux_width = sum(self.right_aux_qubits_needed) self.out_qubits_amount = len(self.single_constraints_objects) def assemble(self) -> None: """ Assembles a whole Grover operator (`self`) by performing the following steps: (1) Allocating qubits for each `SingleConstraintBlock` object (from `self.single_constraints_objects`) - for input qubits, auxiliary qubits of all kinds and a single "out" qubit for each constraint. (2) Appending all the `SingleConstraintBlock` objects. (3) Applying a "marking" operation by applying some controlled-not gate to the ancilla qubit. (4) Appending an uncomputation of the entire operation assembled in (1) + (2). """ # Iterating over constraints, appending one `SingleConstraintBlock` object in each iteration for count, constraint_block in enumerate(self.single_constraints_objects): # Defining the `qargs` paramater for the `constraint_block` to be appended to `self` qargs = [] # Appending the input bits indexes from both sides of the constraint's equation to `qargs` left_input_qubits = list(chain(*constraint_block.parsed_data.sides_bit_indexes[0])) if left_input_qubits: qargs += self.input_reg[left_input_qubits] right_input_qubits = list(chain(*constraint_block.parsed_data.sides_bit_indexes[1])) if right_input_qubits: qargs += self.input_reg[right_input_qubits] # Appending the various aux bits indexes to `qargs` for aux_tuple in [ (self.left_aux_qubits_needed, self.left_aux_reg), (self.right_aux_qubits_needed, self.right_aux_reg), (self.comparison_aux_qubits_needed, self.comparison_aux_reg), ]: if aux_tuple[0][count] != 0: aux_bottom_index = sum(aux_tuple[0][0:count]) aux_top_index = aux_bottom_index + aux_tuple[0][count] qargs += aux_tuple[1][aux_bottom_index:aux_top_index][::-1] # Appending blocks of constraints to `self` # First constraint if count == 0: qargs.append(self.out_reg[count]) self.append(instruction=constraint_block, qargs=qargs) # If there is only one constraint if self.out_qubits_amount == 1: # Saving inverse for future uncomputation qc_dagger = self.inverse() qc_dagger.name = "Uncomputation" # "Marking" states by writing to ancilla self.cx(self.out_reg[count], self.ancilla) # Last constraint elif count == len(self.single_constraints_objects) - 1: qargs.append(self.out_reg[count]) self.append(instruction=constraint_block, qargs=qargs) # Barriers are used for visualization purposes and should be removed before transpiling if self.insert_barriers: self.barrier() # Saving inverse for future uncomputation qc_dagger = RemoveBarriers()(self.inverse()) qc_dagger.name = "Uncomputation" # "Marking" states by writing to ancilla self.ccx(self.out_reg[count - 1], self.out_reg[count], self.ancilla) # Intermidate constraints else: qargs.append(self.out_reg[count + 1]) # Chaining constraints with RCCX gates, to avoid costly MCX gate all over the out qubits self.append(instruction=constraint_block, qargs=qargs) self.rccx(self.out_reg[count + 1], self.out_reg[count - 1], self.out_reg[count]) self.append(instruction=constraint_block.inverse(), qargs=qargs) # Barriers are used for visualization purposes and should be removed before transpiling if self.insert_barriers: self.barrier() # Applying uncomputation self.append(instruction=qc_dagger, qargs=self.qubits)
https://github.com/robinsonvs/tcc-information-systems
robinsonvs
from qiskit import QuantumCircuit as qc from qiskit import QuantumRegister as qr from qiskit import transpile from qiskit.providers import Backend from qiskit.result import Counts from qiskit_ibm_runtime import QiskitRuntimeService from matplotlib.pyplot import show, subplots, xticks, yticks from matplotlib.backend_bases import MouseEvent from math import pi, sqrt from heapq import nlargest from qiskit_aer import AerSimulator """Feel free to modify the following constants.""" N: int = 5 # Number of qubits SEARCH_VALUES: set[int] = { 11, 9, 0, 3 } # Set of m nonnegative integers to search for using Grover's algorithm (i.e. TARGETS in base 10) SHOTS: int = 10000 # Amount of times the algorithm is simulated FONTSIZE: int = 10 # Histogram's font size """Unless you know what you are doing, please do not modify the following constants, otherwise you risk breaking the program.""" TARGETS: set[str] = { f"{s:0{N}b}" for s in SEARCH_VALUES } # Set of m N-qubit binary strings representing target state(s) (i.e. SEARCH_VALUES in base 2) QUBITS: qr = qr(N, "qubit") # N-qubit quantum register #BACKEND_NAME: str = "ibmq_qasm_simulator" # Name of backend to run the algorithm on #BACKEND: Backend = QiskitRuntimeService().backend(BACKEND_NAME) # Backend to run the algorithm on BACKEND: Backend = AerSimulator() def print_circuit(circuit: qc, name: str = "") -> None: """Print quantum circuit. Args: circuit (qc): Quantum circuit to print. name (str, optional): Quantum circuit's name. Defaults to None. """ print(f"\n{name}:" if name else "") print(f"{circuit}") def oracle(targets: set[str] = TARGETS, name: str = "Oracle", display_oracle: bool = True) -> qc: """Mark target state(s) with negative phase. Args: targets (set[str]): N-qubit binary string(s) representing target state(s). Defaults to TARGETS. name (str, optional): Quantum circuit's name. Defaults to "Oracle". display_oracle (bool, optional): Whether or not to display oracle. Defaults to True. Returns: qc: Quantum circuit representation of oracle. """ # Create N-qubit quantum circuit for oracle oracle = qc(QUBITS, name = name) for target in targets: # Reverse target state since Qiskit uses little-endian for qubit ordering target = target[::-1] # Flip zero qubits in target for i in range(N): if target[i] == "0": oracle.x(i) # Pauli-X gate # Simulate (N - 1)-control Z gate oracle.h(N - 1) # Hadamard gate oracle.mcx(list(range(N - 1)), N - 1) # (N - 1)-control Toffoli gate oracle.h(N - 1) # Hadamard gate # Flip back to original state for i in range(N): if target[i] == "0": oracle.x(i) # Pauli-X gate # Display oracle, if applicable if display_oracle: print_circuit(oracle, "ORACLE") return oracle def diffuser(name: str = "Diffuser", display_diffuser: bool = True) -> qc: """Amplify target state(s) amplitude, which decreases the amplitudes of other states and increases the probability of getting the correct solution (i.e. target state(s)). Args: name (str, optional): Quantum circuit's name. Defaults to "Diffuser". display_diffuser (bool, optional): Whether or not to display diffuser. Defaults to True. Returns: qc: Quantum circuit representation of diffuser (i.e. Grover's diffusion operator). """ # Create N-qubit quantum circuit for diffuser diffuser = qc(QUBITS, name = name) diffuser.h(QUBITS) # Hadamard gate diffuser.append(oracle({"0" * N}), list(range(N))) # Oracle with all zero target state diffuser.h(QUBITS) # Hadamard gate # Display diffuser, if applicable if display_diffuser: print_circuit(diffuser, "DIFFUSER") return diffuser def grover(oracle: qc = oracle(), diffuser: qc = diffuser(), name: str = "Grover Circuit", display_grover: bool = True) -> qc: """Create quantum circuit representation of Grover's algorithm, which consists of 4 parts: (1) state preparation/initialization, (2) oracle, (3) diffuser, and (4) measurement of resulting state. Steps 2-3 are repeated an optimal number of times (i.e. Grover's iterate) in order to maximize probability of success of Grover's algorithm. Args: oracle (qc, optional): Quantum circuit representation of oracle. Defaults to oracle(). diffuser (qc, optional): Quantum circuit representation of diffuser. Defaults to diffuser(). name (str, optional): Quantum circuit's name. Defaults to "Grover Circuit". display_grover (bool, optional): Whether or not to display grover circuit. Defaults to True. Returns: qc: Quantum circuit representation of Grover's algorithm. """ # Create N-qubit quantum circuit for Grover's algorithm grover = qc(QUBITS, name = name) # Intialize qubits with Hadamard gate (i.e. uniform superposition) grover.h(QUBITS) # # Apply barrier to separate steps grover.barrier() # Apply oracle and diffuser (i.e. Grover operator) optimal number of times for _ in range(int((pi / 4) * sqrt((2 ** N) / len(TARGETS)))): grover.append(oracle, list(range(N))) grover.append(diffuser, list(range(N))) # Measure all qubits once finished grover.measure_all() # Display grover circuit, if applicable if display_grover: print_circuit(grover, "GROVER CIRCUIT") return grover def outcome(winners: list[str], counts: Counts) -> None: """Print top measurement(s) (state(s) with highest frequency) and target state(s) in binary and decimal form, determine if top measurement(s) equals target state(s), then print result. Args: winners (list[str]): State(s) (N-qubit binary string(s)) with highest probability of being measured. counts (Counts): Each state and its respective frequency. """ print("WINNER(S):") print(f"Binary = {winners}\nDecimal = {[ int(key, 2) for key in winners ]}\n") print("TARGET(S):") print(f"Binary = {TARGETS}\nDecimal = {SEARCH_VALUES}\n") if not all(key in TARGETS for key in winners): print("Target(s) not found...") else: winners_frequency, total = 0, 0 for value, frequency in counts.items(): if value in winners: winners_frequency += frequency total += frequency print(f"Target(s) found with {winners_frequency / total:.2%} accuracy!") def display_results(results: Counts, combine_other_states: bool = True) -> None: """Print outcome and display histogram of simulation results. Args: results (Counts): Each state and its respective frequency. combine_other_states (bool, optional): Whether to combine all non-winning states into 1 bar labeled "Others" or not. Defaults to True. """ # State(s) with highest count and their frequencies winners = { winner : results.get(winner) for winner in nlargest(len(TARGETS), results, key = results.get) } # Print outcome outcome(list(winners.keys()), results) # X-axis and y-axis value(s) for winners, respectively winners_x_axis = [ str(winner) for winner in [*winners] ] winners_y_axis = [ *winners.values() ] # All other states (i.e. non-winners) and their frequencies others = {state : frequency for state, frequency in results.items() if state not in winners} # X-axis and y-axis value(s) for all other states, respectively other_states_x_axis = "Others" if combine_other_states else [*others] other_states_y_axis = [ sum([*others.values()]) ] if combine_other_states else [ *others.values() ] # Create histogram for simulation results figure, axes = subplots(num = "Grover's Algorithm — Results", layout = "constrained") axes.bar(winners_x_axis, winners_y_axis, color = "green", label = "Target") axes.bar(other_states_x_axis, other_states_y_axis, color = "red", label = "Non-target") axes.legend(fontsize = FONTSIZE) axes.grid(axis = "y", ls = "dashed") axes.set_axisbelow(True) # Set histogram title, x-axis title, and y-axis title respectively axes.set_title(f"Outcome of {SHOTS} Simulations", fontsize = int(FONTSIZE * 1.45)) axes.set_xlabel("States (Qubits)", fontsize = int(FONTSIZE * 1.3)) axes.set_ylabel("Frequency", fontsize = int(FONTSIZE * 1.3)) # Set font properties for x-axis and y-axis labels respectively xticks(fontsize = FONTSIZE, family = "monospace", rotation = 0 if combine_other_states else 70) yticks(fontsize = FONTSIZE, family = "monospace") # Set properties for annotations displaying frequency above each bar annotation = axes.annotate("", xy = (0, 0), xytext = (5, 5), xycoords = "data", textcoords = "offset pixels", ha = "center", va = "bottom", family = "monospace", weight = "bold", fontsize = FONTSIZE, bbox = dict(facecolor = "white", alpha = 0.4, edgecolor = "None", pad = 0) ) def hover(event: MouseEvent) -> None: """Display frequency above each bar upon hovering over it. Args: event (MouseEvent): Matplotlib mouse event. """ visibility = annotation.get_visible() if event.inaxes == axes: for bars in axes.containers: for bar in bars: cont, _ = bar.contains(event) if cont: x, y = bar.get_x() + bar.get_width() / 2, bar.get_y() + bar.get_height() annotation.xy = (x, y) annotation.set_text(y) annotation.set_visible(True) figure.canvas.draw_idle() return if visibility: annotation.set_visible(False) figure.canvas.draw_idle() # Display histogram id = figure.canvas.mpl_connect("motion_notify_event", hover) show() figure.canvas.mpl_disconnect(id) if __name__ == "__main__": # Generate quantum circuit for Grover's algorithm grover_circuit = grover() # Simulate Grover's algorithm with a Qiskit backend and get results #with BACKEND.open_session() as session: # results = BACKEND.run(transpile(grover_circuit, BACKEND, optimization_level = 2), shots = SHOTS).result() new_circuit = transpile(grover_circuit, BACKEND) result = BACKEND.run(new_circuit).result() results = result.get_counts(grover_circuit) # Get each state's frequency and display simulation results display_results(results, False)
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
#!/usr/bin/env python3 # Author: Daniel Escanez-Exposito from qiskit import QuantumCircuit from random import vonmisesvariate as random_angle from qiskit.circuit.library import UGate from crypto.elgamal.sender import Sender from crypto.elgamal.receiver import Receiver from qiskit.quantum_info import Statevector import qiskit.quantum_info as qi import numpy as np ELGAMAL_SIMULATOR = 'ElGamal SIMULATOR' ## An implementation of the ElGamal protocol ## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html class ElGamalAlgorithm: ## Run the implementation of ElGamal protocol def run(self, message): msg_qc = QuantumCircuit(1, name='message') msg_sv = Statevector([complex(x) for x in message.split(',')]) msg_qc.initialize(msg_sv) u1, u2 = self.public_keys_generation() # Receiver Bob bob = Receiver('Bob', u1, u2) bob.generate_keys() # Sender Alice alice = Sender('Alice', u1, u2) alice.set_message(msg_qc) alice.generate_keys() alice.compute_shared_secret(bob.public_key) # Encryption c1 = alice.public_key c2 = alice.get_encripted_message() # Decryption bob.compute_shared_secret(c1) decrypted_message = bob.decrypt_message(c2) encrypted_message = c2 shared_secret = alice.shared_secret decrypted_message_sv = qi.Statevector.from_instruction(decrypted_message) encrypted_message_sv = qi.Statevector.from_instruction(encrypted_message) return msg_sv, encrypted_message, decrypted_message, encrypted_message_sv, decrypted_message_sv, alice, bob ## Gets random public matrices def public_keys_generation(self): u1 = QuantumCircuit(1, name='U1') u1.append(UGate(random_angle(0, 0), random_angle(0, 0), random_angle(0, 0)), [0]) u2 = QuantumCircuit(1, name='U2') u2.append(UGate(random_angle(0, 0), random_angle(0, 0), random_angle(0, 0)), [0]) return (u1, u2)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.tools.visualization import circuit_drawer q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) circuit_drawer(qc, output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl')
https://github.com/arian-code/nptel_quantum_assignments
arian-code
import numpy as np # Import Qiskit from qiskit import QuantumCircuit from qiskit import Aer, transpile from qiskit.tools.visualization import plot_histogram, plot_state_city from qiskit import * from qiskit.tools.monitor import job_monitor import qiskit.quantum_info as qi Aer.backends() simulator = Aer.get_backend('aer_simulator') # Set initial state to generated statevector circ = QuantumCircuit(7, 6) circ.x(6) circ.barrier() circ.h(0) circ.h(1) circ.h(2) circ.h(3) circ.h(4) circ.h(5) circ.h(6) circ.barrier() circ.x(2) circ.cx(3,6) circ.cx(0,6) circ.cx(5,6) circ.x(3) circ.cx(3,6) circ.x(0) circ.barrier() circ.h(0) circ.h(1) circ.h(2) circ.h(3) circ.h(4) circ.h(5) circ.h(6) circ.barrier() circ.measure(range(6), range(6)) circ.draw() # execute the quantum circuit backend = BasicAer.get_backend('qasm_simulator') # the device to run on result = backend.run(transpile(circ, backend), shots=1000).result() counts = result.get_counts(circ) print(counts) plot_histogram(counts)
https://github.com/qiskit-community/community.qiskit.org
qiskit-community
from qiskit import * qc = QuantumCircuit() qr = QuantumRegister(2,'qreg') qc.add_register( qr ) qc.qregs qc.draw(output='mpl') qc.h() qc.h( qr[0] ) qc.cx( qr[0], qr[1] ); qc.draw(output='mpl') vector_sim = Aer.get_backend('statevector_simulator') Aer.backends() job = execute( qc, vector_sim ) ket = job.result().get_statevector() for amplitude in ket: print(amplitude) new_qc = QuantumCircuit( qr ) new_qc.initialize( ket, qr ) new_qc.draw(output='mpl') cr = ClassicalRegister(2,'creg') qc.add_register(cr) qc.measure(qr[0],cr[0]) qc.measure(qr[1],cr[1]) qc.draw(output='mpl') emulator = Aer.get_backend('qasm_simulator') job = execute( qc, emulator, shots=8192 ) hist = job.result().get_counts() print(hist) from qiskit.tools.visualization import plot_histogram plot_histogram( hist ) job = execute( qc, emulator, shots=10, memory=True ) samples = job.result().get_memory() print(samples) qubit = QuantumRegister(8) bit = ClassicalRegister(8) circuit = QuantumCircuit(qubit,bit) circuit.x(qubit[7]) circuit.measure(qubit,bit) # this is a way to do all the qc.measure(qr8[j],cr8[j]) at once execute( circuit, emulator, shots=8192 ).result().get_counts() qc = QuantumCircuit(3) qc.h(1) qc.draw(output='mpl') qc = QuantumCircuit(2,1) qc.h(0) qc.cx(0,1) qc.measure(1,0) qc.draw(output='mpl') sub_circuit = QuantumCircuit(3, name='toggle_cx') sub_circuit.cx(0,1) sub_circuit.cx(1,2) sub_circuit.cx(0,1) sub_circuit.cx(1,2) sub_circuit.draw(output='mpl') toggle_cx = sub_circuit.to_instruction() qr = QuantumRegister(4) new_qc = QuantumCircuit(qr) new_qc.append(toggle_cx, [qr[1],qr[2],qr[3]]) new_qc.draw(output='mpl') IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() for backend in provider.backends(): print( backend.status() ) real_device = provider.get_backend('ibmq_16_melbourne') properties = real_device.properties() coupling_map = real_device.configuration().coupling_map from qiskit.providers.aer import noise noise_model = noise.device.basic_device_noise_model(properties) qc = QuantumCircuit(2,2) qc.x(1) qc.measure(0,0) qc.measure(1,1) job = execute(qc, emulator, shots=1024, noise_model=noise_model, coupling_map=coupling_map, basis_gates=noise_model.basis_gates) job.result().get_counts()
https://github.com/Naphann/Solving-TSP-Grover
Naphann
import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer import numpy as np from math import floor, ceil %matplotlib inline def max_number(arr_size): return (2 ** arr_size)-1 def check_min_circuit(a, threshold): max = max_number(a) foo = max - threshold binary = format(foo, 'b')[::-1] print(binary) extra = a - len(binary) for i in range(extra): binary = "0" + binary print(binary) for i in range(a): if int(binary[i])==1: qc1.x(_q[i]) _q = QuantumRegister(5) qc1 = QuantumCircuit(_q) check_min_circuit(5, 20) qc1.draw()
https://github.com/1chooo/Quantum-Oracle
1chooo
# %% [markdown] # # 第六章原始程式碼 # %% #program 6.1a Define classical oracle f1 for unstructured search def f1(x): if x=='01': return '1' else: return '0' print(f1('00'),f1('01'),f1('10'),f1('11')) # %% #program 6.1b Define classical oracle f2 for unstructured search def f2(x): if x=='001': return '1' else: return '0' print(f2('000'),f2('001'),f2('010'),f2('011'),f2('100'),f2('101'),f2('110'),f2('111')) # %% #program 6.1c Define classical oracle f3 for unstructured search def f3(x): if x=='101': return '1' else: return '0' print(f3('000'),f3('001'),f3('010'),f3('011'),f3('100'),f3('101'),f3('110'),f3('111')) # %% #Program 6.1d Solve unstructured search prob. with classical code import itertools def unstructured_search(f,n): iter = itertools.product([0,1], repeat=n) lst = [''.join(map(str, item)) for item in iter] for s in lst: if f(s)=='1': return s print(unstructured_search(f1,2)) print(unstructured_search(f2,3)) print(unstructured_search(f3,3)) # %% #Program 6.2 Define quantum oracle for input solution='00' from qiskit import QuantumRegister,QuantumCircuit qrx = QuantumRegister(2,'x') qc = QuantumCircuit(qrx) qc.x([0,1]) qc.cz(0,1) qc.x([0,1]) print("The quantum circuit of phase oracle for input solution='00':") qc.draw('mpl') # %% #Program 6.3 Define quantum oracle for input solution='01' from qiskit import QuantumRegister,QuantumCircuit qrx = QuantumRegister(2,'x') qc = QuantumCircuit(qrx) qc.x(1) qc.cz(0,1) qc.x(1) print("The quantum circuit of phase oracle for input solution='01':") qc.draw('mpl') # %% #Program 6.4 Define quantum oracle for input solution='10' from qiskit import QuantumRegister,QuantumCircuit qrx = QuantumRegister(2,'x') qc = QuantumCircuit(qrx) qc.x(0) qc.cz(1,0) qc.x(0) print("The quantum circuit of phase oracle for input solution='10':") qc.draw('mpl') # %% #Program 6.5 Define quantum oracle for input solution='11' from qiskit import QuantumRegister,QuantumCircuit qrx = QuantumRegister(2,'x') qc = QuantumCircuit(qrx) qc.cz(1,0) print("The quantum circuit of phase oracle for input solution='11':") qc.draw('mpl') # %% #Program 6.6 Grover alg. with oracle for input solution='10' from qiskit import QuantumCircuit,execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram qc = QuantumCircuit(2,2) qc.h([0,1]) qc.barrier() qc.x(0) qc.cz(1,0) qc.x(0) qc.barrier() qc.h([0,1]) qc.x([0,1]) qc.cz(0,1) qc.x([0,1]) qc.h([0,1]) qc.barrier() qc.measure([0,1],[0,1]) print("The quantum circuit of Grover's algorithm for input solution='10':") display(qc.draw('mpl')) sim = AerSimulator() job=execute(qc, backend=sim, shots=1000) result = job.result() counts = result.get_counts(qc) print("Total counts for qubit states are:",counts) display(plot_histogram(counts)) # %% #Program 6.7 Grover alg. with oracle for input solution='101' from qiskit import QuantumCircuit,execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram from math import pi qc = QuantumCircuit(3,3) qc.h([0,1,2]) qc.barrier() for repeat in range(2): qc.x(1) qc.mcp(pi,[0,1],2) qc.x(1) qc.barrier() qc.h([0,1,2]) qc.x([0,1,2]) qc.mcp(pi,[0,1],2) qc.x([0,1,2]) qc.h([0,1,2]) qc.barrier() qc.measure([0,1,2],[0,1,2]) print("The quantum circuit of Grover's algorithm for input solution='101':") display(qc.draw('mpl')) sim = AerSimulator() job=execute(qc, backend=sim, shots=1000) result = job.result() counts = result.get_counts(qc) print("Total counts for qubit states are:",counts) display(plot_histogram(counts)) # %% #Program 6.8 Solve Hamiltonian cycle prob. for clique-4 with Grover alg. from qiskit import QuantumCircuit,execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram from math import pi qc = QuantumCircuit(6,6) qc.h(range(6)) qc.barrier() for repeat in range(3): qc.x([4,5]) qc.mcp(pi,list(range(5)),5) qc.x([4,5]) qc.barrier() qc.x([1,3]) qc.mcp(pi,list(range(5)),5) qc.x([1,3]) qc.barrier() qc.x([0,2]) qc.mcp(pi,list(range(5)),5) qc.x([0,2]) qc.barrier() qc.h(range(6)) qc.x(range(6)) qc.mcp(pi,list(range(5)),5) qc.x(range(6)) qc.h(range(6)) qc.barrier() qc.measure(range(6),range(6)) print("The quantum circuit of Grover's algorithm:") display(qc.draw('mpl')) sim = AerSimulator() job=execute(qc, backend=sim, shots=1000) result = job.result() counts = result.get_counts(qc) display(plot_histogram(counts)) print("Total counts for qubit states are:",counts) sorted_counts=sorted(counts.items(),key=lambda x:x[1], reverse=True) print("The solutions to the Hamiltonian cycle problem are:") #find_all_ones=lambda s:[x for x in range(s.find('1'), len(s)) if s[x]=='1'] find_all_ones=lambda s:[x for x in range(len(s)) if s[x]=='1'] for i in range(3): #It is konw there are (4-1)!/2=3 solutions scstr=sorted_counts[i][0] #scstr: string in sorted_counts print(scstr,end=' (') reverse_scstr=scstr[::-1] #reverse scstr for LSB at the right all_ones=find_all_ones(reverse_scstr) for one in all_ones[0:-1]: print('e'+str(one)+'->',end='') print('e'+str(all_ones[-1])+')')
https://github.com/TRSasasusu/qiskit-quantum-zoo
TRSasasusu
"""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/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# # your code is here # (you may find the values by hand (in mind) as well) # import numpy as np v = np.array([0, -0.1, 0.3, 0.4, 0.5]) v_square = v ** 2 print(v_square) a = 1 - np.sum(v_square[1:]) a = np.sqrt(a) print("a: "+ str(a)) u = np.array([1/np.sqrt(2), -1/np.sqrt(3)]) u_square = u ** 2 print(u_square) b0 = 1/(1 - np.sum(u_square)) print("b: " + str(b0)) #%%writefile FILENAME.py # for storing the content of this cell, # comment out the the first line (by modifying the FILENAME) # and then execute the cell # # later, you can execute your saved content by using %run FILENAME.py # # # you may define your first function in a separate cell # and then save it to a file for using it later # from random import randrange def random_quantum_state(): # quantum state quantum_state=[0,0] r = randrange(101) r = r / 100 r = np.sqrt(r) if randrange(2) == 0: # randomly make the value negative r = -1 * r quantum_state[0] = r # second entry quantum_state[1] = np.sqrt(1 - r**2) return quantum_state # # your code is here # quantum_state = random_quantum_state() print(quantum_state) hadamard_matrix = np.array([[(1/(np.sqrt(2))), (1/(np.sqrt(2)))],[(1/(np.sqrt(2))), (-1/(np.sqrt(2)))]]) new_quantum_state = np.matmul(hadamard_matrix, np.array(quantum_state)) print(new_quantum_state) def verify_quantum_state(quantum_state): square_of_state = np.power(quantum_state, 2) summation = np.sum(square_of_state) return np.sqrt(summation) print(verify_quantum_state(quantum_state)) print("should be close to 1: " + str(verify_quantum_state(new_quantum_state))) results = [] for test in range(100): quantum_state = random_quantum_state() sums = verify_quantum_state(quantum_state) results.append(sums) summation = np.sum(np.array(sums)) print(summation)
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
import sys, os sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/../../') from composer.qs_circuit import QSCircuit from qiskit import execute, BasicAer SIZE = 3 SIZE_OUTPUT = 2 ** SIZE for i in range(0, 2 ** SIZE): a = format(i, '0' + str(SIZE) + 'b') a_indexes = list(range(0, SIZE)) flipped_a_indexes = list(range(SIZE, 2 * SIZE)) output_indexes = list(range(2 * SIZE, 2 * SIZE + SIZE_OUTPUT)) aux_index = 2 * SIZE + SIZE_OUTPUT CIRCUIT_SIZE = 2 * SIZE + SIZE_OUTPUT + 1 qc = QSCircuit(CIRCUIT_SIZE) qc.set_reg(a[::-1], a_indexes) qc.decoder(a_indexes, output_indexes, flipped_a_indexes, aux_index) qc.measure(output_indexes, range(len(output_indexes))) # print(qc) backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1) counts = job.result().get_counts(qc) print(a, '-', list(counts.keys())[0][-SIZE_OUTPUT:])
https://github.com/wyqian1027/Qiskit-Fall-Fest-USC-2022
wyqian1027
import numpy as np from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_bloch_multivector, array_to_latex from grader import * language(False) phi_plus = QuantumCircuit(2) phi_plus.h(0) phi_plus.cnot(0, 1) phi_plus.draw('mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') result = execute(phi_plus, backend).result().get_statevector() array_to_latex(result) phi_minus = QuantumCircuit(2) ##### ================================== # Write your solution in here. phi_minus.h(0) phi_minus.z(0) phi_minus.cnot(0, 1) ##### ================================== phi_minus.draw('mpl') # This cell will tell you if what you did gives the correct result. # Just take it as an indication, the tests do not take into consideration every possible option # If you think that your answer is (in)correct and the grader says different, just ask me please # Don't try to tamper with the code, please :) ex1_grader(phi_minus) psi_plus = QuantumCircuit(2) ##### ================================== # Write your solution in here. psi_plus.h(0) psi_plus.x(1) psi_plus.cnot(0, 1) ##### ================================== psi_plus.draw('mpl') ex2_grader(psi_plus) psi_minus = QuantumCircuit(2) ##### ================================== # Write your solution in here. psi_minus.h(0) psi_minus.x(1) psi_minus.z(0) psi_minus.cnot(0, 1) ##### ================================== psi_minus.draw('mpl') ex3_grader(psi_minus) GHZ = QuantumCircuit(3) ##### ================================== # Write your solution in here. GHZ.h(0) GHZ.cnot(0, 1) GHZ.cnot(0, 2) ##### ================================== GHZ.draw('mpl') ex4_grader(GHZ) Even = QuantumCircuit(3) ##### ================================== # Write your solution in here. Even.h(0) Even.h(1) Even.cnot(0, 2) Even.cnot(1, 2) ##### ================================== Even.draw('mpl') ex5_grader(Even) Odd = QuantumCircuit(3) ##### ================================== # Write your solution in here. Odd.h(0) Odd.h(1) Odd.x(2) Odd.cnot(0, 2) Odd.cnot(1, 2) ##### ================================== Odd.draw('mpl') ex6_grader(Odd) def measure_z_axis(qc, qubit, cbit): #Measurements have to be saved in classical bits qc.measure(qubit, cbit) def measure_x_axis(qc, qubit, cbit): ##### ================================== # Write your solution in here. qc.h(qubit) qc.measure(qubit, cbit) ##### ================================== ex7_grader(measure_x_axis) def expectation_value_single_qubit(qc, nshots=8092): # Run the given circuit that is already measuring the selected basis backend_shots = Aer.get_backend('qasm_simulator') counts = execute(qc, backend_shots, shots=nshots).result().get_counts() #Counts is a dictionary that contains the number of zeros and the number of ones measured # This is just to make things easier in your solution if '1' not in counts.keys(): counts['1'] = 0 if '0' not in counts.keys(): counts['0'] = 0 # Get the number of times that 0 and 1 were measured n_zeros = counts['0'] n_ones = counts['1'] # Compute the probabilities p_0 = n_zeros/nshots p_1 = n_ones/nshots #OR 1-p_0 expectation_value = 1*p_0+(-1)*p_1 return expectation_value # Measure <Z> over a state that you like qc_z = QuantumCircuit(1,1) measure_z_axis(qc_z, 0, 0) print('<Z>=', expectation_value_single_qubit(qc_z)) qc_z.draw('mpl') # Measure <X> over a state that you like qc_x = QuantumCircuit(1,1) measure_x_axis(qc_x, 0, 0) print('<X>=', expectation_value_single_qubit(qc_x)) qc_x.draw('mpl') ##### ================================== # Write your solution in here. measure_strings = ['ZZ', 'ZX', 'XZ', 'XX'] # Create bell state circuit qc = QuantumCircuit(2,2) qc.h(0) qc.cnot(0, 1) # For each of the operators that we want to measure (ZZ, ZX, XZ and XX) create a new circuit (maybe using qc.copy()) # that measures along that axis. chsh_circuits = [] for string in measure_strings: qc1 = qc.copy() if string[0] == 'Z': measure_z_axis(qc1, 0, 0) if string[0] == 'X': measure_x_axis(qc1, 0, 0) if string[1] == 'Z': measure_z_axis(qc1, 1, 1) if string[1] == 'X': measure_x_axis(qc1, 1, 1) chsh_circuits.append(qc1) ##### ================================== chsh_circuits[0].draw('mpl') chsh_circuits[1].draw('mpl') chsh_circuits[2].draw('mpl') chsh_circuits[3].draw('mpl') # I couldn't come up with tests that would not give the answer away if you looked at the code so you are on your own here! # We can run all the circuits at the same time and then post process the data nshots = 8092 # The more shots, the less error backend_shots = Aer.get_backend('qasm_simulator') counts_list = execute(chsh_circuits, backend_shots, shots=nshots).result().get_counts() counts_list ##### ================================== # Write your solution in here. exp_dict = {} # For each of the circuits, take the counts that you got from that circuit, compute the probability # of each state and combine them together being very careful of which sign goes with which term for i in range(len(chsh_circuits)): string = measure_strings[i] #ZZ, ZX, XZ and XX counts = counts_list[i] exp = 0. for element in counts: parity = (-1)**(int(element[0])+int(element[1])) #print(element, parity) exp += counts[element]*parity exp_dict[string] = exp/nshots # You might want to take some inspiration from the function expectation_value_single_qubit # If you are completely lost and don't know how to solve this, just ask ##### ================================== # If you don't know if your answer is correct you can compute the results by hand # (it's probably easier than doing this) and check if everything is working ##### ================================== # Write your solution in here. exp_AB = np.sqrt(1/2)*(exp_dict['ZZ']-exp_dict['XZ']) exp_Ab = np.sqrt(1/2)*(exp_dict['ZX']-exp_dict['XX']) exp_aB = np.sqrt(1/2)*(exp_dict['ZZ']+exp_dict['XZ']) exp_ab = np.sqrt(1/2)*(exp_dict['ZX']+exp_dict['XX']) CHSH = exp_AB - exp_Ab + exp_aB + exp_ab ##### ================================== print('Your result is <CHSH>=', CHSH) print('The correct result is <CHSH>=', 2*np.sqrt(2)) ##### ================================== # Write your solution in here. Can_entanglement_be_teleported = True #Write True or False :D ##### ================================== # There is no grader for this question hehe ##### ================================== # Write your solution in here. Where_did_the_bell_pair_go = 'To the last two qubits' ##### ================================== # There is no grader for this question hehe ##### ================================== # Write your solution in here. ##### ================================== import qiskit.tools.jupyter %qiskit_version_table
https://github.com/C2QA/bosonic-qiskit
C2QA
# To use the package locally, add the C2QA repository's root folder to the path prior to importing c2qa. import os import sys module_path = os.path.abspath(os.path.join("../..")) if module_path not in sys.path: sys.path.append(module_path) # Cheat to get MS Visual Studio Code Jupyter server to recognize Python venv module_path = os.path.abspath(os.path.join("../../venv/Lib/site-packages")) if module_path not in sys.path: sys.path.append(module_path) import c2qa import qiskit from qiskit import QuantumCircuit from qiskit.circuit import Gate from math import pi qc = QuantumCircuit(2) qmr0 = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=2) qr0 = qiskit.QuantumRegister(size=1) circuit0 = c2qa.CVCircuit(qmr0, qr0) # Initialize your qubit (should have no effect on Fock state Wigner function) circuit0.initialize([1,0], qr0[0]) # circuit0.initialize([0,1], qr0[0]) # Initialize the qumode to a zero Fock sate circuit0.cv_initialize(0, qmr0[0]) # ... Your circtuit here ... state0, _, _ = c2qa.util.simulate(circuit0) print(state0) # c2qa.wigner.plot_wigner_function() will perform a partial trace to separate the qumode from the qubit state for you, the call below is to log its output as an example. print(c2qa.util.trace_out_qubits(circuit0, state0)) c2qa.wigner.plot_wigner(circuit0, state0) qmr1 = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=2) qr1 = qiskit.QuantumRegister(size=1) circuit1 = c2qa.CVCircuit(qmr1, qr1) # Initialize your qubit (should have no effect on Fock state Wigner function) circuit1.initialize([1,0], qr1[0]) # circuit1.initialize([0,1], qr1[0]) # Initialize the qumode to a one Fock sate circuit1.cv_initialize(1, qmr1[0]) # ... Your circtuit here ... state1, _, _ = c2qa.util.simulate(circuit1) print(state1) # c2qa.wigner.plot_wigner_function() will perform a partial trace to separate the qumode from the qubit state for you, the call below is to log its output as an example. print(c2qa.util.trace_out_qubits(circuit1, state1)) c2qa.wigner.plot_wigner(circuit1, state1) import numpy qmr2 = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=2) qr2 = qiskit.QuantumRegister(size=1) circuit2 = c2qa.CVCircuit(qmr2, qr2) # Initialize your qubit (should have no effect on Fock state Wigner function) circuit2.initialize([1,0], qr2[0]) # circuit1.initialize([0,1], qr1[0]) # Initialize the qumode to a zero Fock sate (ie. the vaccuum) circuit2.cv_initialize(0, qmr2[0]) # Displace the vaccuum using the displacement gate # Displace the quasi-probability distribution along the position axis x with a real number # circuit2.cv_d(numpy.pi/2,qmr1[0]) # Displace the quasi-probability distribution along the momentum axis with an imaginary number circuit2.cv_d(numpy.pi/2*1j,qmr2[0]) state2, _, _ = c2qa.util.simulate(circuit2) print(state2) # c2qa.wigner.plot_wigner_function() will perform a partial trace to separate the qumode from the qubit state for you, the call below is to log its output as an example. print(c2qa.util.trace_out_qubits(circuit2, state2)) c2qa.wigner.plot_wigner(circuit2, state2) # Not the expected behavior of displacing the vaccuum, which should simply shift the quasi-probability distribution without distorting it. # Augment the number of qubits per mode qmr3 = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=6) qr3 = qiskit.QuantumRegister(size=1) circuit3 = c2qa.CVCircuit(qmr3, qr3) # Initialize your qubit (should have no effect on Fock state Wigner function) circuit3.initialize([1,0], qr3[0]) # circuit1.initialize([0,1], qr1[0]) # Initialize the qumode to a zero Fock sate (ie. the vaccuum) circuit3.cv_initialize(0, qmr3[0]) # Displace the vaccuum using the displacement gate # Displace the quasi-probability distribution along the position axis x with a real number # circuit2.cv_d(numpy.pi/2,qmr1[0]) # Displace the quasi-probability distribution along the momentum axis with an imaginary number circuit3.cv_d(numpy.pi/2*1j,qmr3[0]) state3, _, _ = c2qa.util.simulate(circuit3) occ =c2qa. util.stateread(state3, 1, 1, 6) print(state3) # c2qa.wigner.plot_wigner_function() will perform a partial trace to separate the qumode from the qubit state for you, the call below is to log its output as an example. print(c2qa.util.trace_out_qubits(circuit3, state3)) c2qa.wigner.plot_wigner(circuit3, state3) # This is the expected behavior of displacing the vaccuum: # a simple shift the quasi-probability distribution without distorting it, creating a coherent state. def cv_ecdX(qc, qbr, qmr, qm, alpha): qc.ry(-np.pi / 2, qbr[0]) qc.cv_ecd(alpha/2, qmr[qm], qbr[0]) qc.ry(np.pi / 2, qbr[0]) return qc def cv_ecdY(qc, qbr, qmr, qm, alpha): qc.rx(-np.pi / 2, qbr[0]) qc.cv_ecd(alpha/2, qmr[qm], qbr[0]) qc.rx(np.pi / 2, qbr[0]) return qc import numpy as np # Augment the number of qubits per mode qmr = c2qa.QumodeRegister(num_qumodes=2, num_qubits_per_qumode=6) qbr = qiskit.QuantumRegister(size=1) qc = c2qa.CVCircuit(qmr, qbr) # Initialize your qubit (should have no effect on Fock state Wigner function) qc.initialize([1,0], qbr[0]) # initialise in x (just h) or y eigenstate qc.h(qbr[0]) qc.rz(np.pi/2,qbr[0]) # Initialize the qumode to a zero Fock sate (ie. the vaccuum) qc.cv_initialize(0, qmr[0]) qc.cv_initialize(0, qmr[1]) alpha = 1j/2 qc = cv_ecdX(qc, qbr, qmr, 0, alpha) qc = cv_ecdY(qc, qbr, qmr, 1, alpha) qc = cv_ecdX(qc, qbr, qmr, 0, -alpha) qc = cv_ecdY(qc, qbr, qmr, 1, -alpha) alpha = 1/2 qc = cv_ecdX(qc, qbr, qmr, 0, alpha) qc = cv_ecdY(qc, qbr, qmr, 1, alpha) qc = cv_ecdX(qc, qbr, qmr, 0, -alpha) qc = cv_ecdY(qc, qbr, qmr, 1, -alpha) state, _, _ = c2qa.util.simulate(qc) # # c2qa.wigner.plot_wigner_function() will perform a partial trace to separate the qumode from the qubit state for you, the call below is to log its output as an example. # print(c2qa.util.trace_out_qubits(qc, state)) c2qa.wigner.plot_wigner(qc, state, method="iterative")
https://github.com/soultanis/Quantum-Database-Search
soultanis
operation DatabaseOracleFromInts( markedElement : Int, markedQubit: Qubit, databaseRegister: Qubit[] ) : Unit { body (...) { (ControlledOnInt(markedElement, X))(databaseRegister, markedQubit); } adjoint auto; controlled auto; adjoint controlled auto; } ControlledOnInt? operation PrepareDatabaseRegister( markedElement : Int, idxMarkedQubit: Int, startQubits: Qubit[] ) : Unit { body (...) { let flagQubit = startQubits[idxMarkedQubit]; let databaseRegister = Exclude([idxMarkedQubit], startQubits); // Apply 𝑈. ApplyToEachCA(H, databaseRegister); // Apply 𝐷. DatabaseOracleFromInts(markedElement, flagQubit, databaseRegister); } adjoint auto; controlled auto; adjoint controlled auto; } function GroverStatePrepOracle(markedElement : Int) : StateOracle { return StateOracle(PrepareDatabaseRegister(markedElement, _, _)); } function GroverSearch( markedElement: Int, nIterations: Int, idxMarkedQubit: Int ) : (Qubit[] => Unit : Adjoint, Controlled) { return AmpAmpByOracle(nIterations, GroverStatePrepOracle(markedElement), idxMarkedQubit); } operation ApplyQuantumSearch() : (Result, Int) { let nIterations = 6; let nDatabaseQubits = 6; let markedElement = 3; // Allocate variables to store measurement results. mutable resultSuccess = Zero; mutable numberElement = 0; using ((markedQubit, databaseRegister) = (Qubit(), Qubit[nDatabaseQubits])) { // Implement the quantum search algorithm. (GroverSearch(markedElement, nIterations, 0))([markedQubit] + databaseRegister); // Measure the marked qubit. On success, this should be One. set resultSuccess = MResetZ(markedQubit); // Measure the state of the database register post-selected on // the state of the marked qubit. let resultElement = MultiM(databaseRegister); set numberElement = PositiveIntFromResultArr(resultElement); // These reset all qubits to the |0〉 state, which is required // before deallocation. ResetAll(databaseRegister); } // Returns the measurement results of the algorithm. return (resultSuccess, numberElement); } %simulate ApplyQuantumSearch %version
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """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/BoschSamuel/QizGloria
BoschSamuel
from qiskit import * import torch from torch.autograd import Function class myExp(Function): @staticmethod def forward(ctx, i): result = i.exp() ctx.save_for_backward(result) return result @staticmethod def backward(ctx, grad_output): result, = ctx.saved_tensors return grad_output * result x = torch.tensor([[1., -1.], [1., 1.]], requires_grad=True) myexp = myExp.apply y1 = x**2 y2 = myexp(y1).sum().backward() x.grad np.ones(1) import numpy as np import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import matplotlib.pyplot as plt %matplotlib inline parameters = np.random.rand(3) shots = 1000 circuit = QuantumCircuit(2, 2) def add_measurements(circuit): nr_qubits = circuit.n_qubits circuit.measure(range(nr_qubits), range(nr_qubits)) return circuit def add_x_rotation(circuit): nr_qubits = circuit.n_qubits for i in range(nr_qubits): circuit.rx(np.pi/2, i) return circuit def add_y_rotation(circuit): nr_qubits = circuit.n_qubits for i in range(nr_qubits): circuit.ry(np.pi/2, i) return circuit def execute_job(circuit, shots): simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=shots) result = job.result() counts = result.get_counts(circuit) return counts def N_qubit_expectation(circuit, shots, measurement='Z'): if measurement=='Z': print("Measure in Z") nr_qubits = circuit.n_qubits circuit = add_measurements(circuit) counts = execute_job(circuit, shots) return N_qubit_expectation_Z(counts, shots, nr_qubits) if measurement=='X': print("Measure in X") nr_qubits = circuit.n_qubits circuit = add_x_rotation(circuit) #circuit.h(0) circuit = add_measurements(circuit) counts = execute_job(circuit, shots) return N_qubit_expectation_Z(counts, shots, nr_qubits), circuit if measurement=='Y': nr_qubits = circuit.n_qubits circuit = add_y_rotation(circuit) circuit = add_measurements(circuit) counts = execute_job(circuit, shots) return N_qubit_expectation_Z(counts, shots, nr_qubits) else: print("Measurement type not yet defined") def N_qubit_expectation_Z(counts, shots, nr_qubits): expects = np.zeros(nr_qubits) for key in counts.keys(): perc = counts[key]/shots check = np.array([(float(key[i])-1/2)*2*perc for i in range(nr_qubits)]) expects += check return expects def one_qubit_expectation_Z(counts, shots): probs = sorted([(i, c/shots) for i, c in counts.items()]) P = np.float64(np.array(probs)[:, 1]) print(P[0], P[1]) return P[0]*1 + P[1]*-1 def one_qubit_error(counts, shots, Z_traget): return (one_qubit_expectation_Z(counts, shots)- Z_target)**2 def N_qubit_error(counts, shots, nr_qubits, target_array): return ((N_qubit_expectation_Z(counts, shots, nr_qubits)-target_array)**2).sum() #circuit = add_measurements(circuit) #counts = execute_job(circuit, 1000) expects, circuit = N_qubit_expectation(circuit, shots, measurement="X") circuit.draw() print(expects, circuit) circuit.n_qubits class QiskitCircuit(): def __init__(self,shots): self.theta = Parameter('Theta') self.phi = Parameter('Phi') self.lam = Parameter('Lambda') self.shots = shots def create_circuit(): qr = QuantumRegister(1,'q') cr = ClassicalRegister(1,'c') ckt = QuantumCircuit(qr,cr) ckt.h(qr[0]) ckt.barrier() ckt.u3(self.theta,self.phi,self.lam,qr[0]) ckt.barrier() ckt.measure(qr,cr) return ckt self.circuit = create_circuit() def N_qubit_expectation_Z(self,counts, shots, nr_qubits): expects = np.zeros(nr_qubits) for key in counts.keys(): perc = counts[key]/shots check = np.array([(float(key[i])-1/2)*2*perc for i in range(nr_qubits)]) expects += check return expects def bind(self,parameters): [self.theta,self.phi,self.lam] = parameters self.circuit.data[2][0]._params = parameters return self.circuit def run(self): backend = Aer.get_backend('qasm_simulator') job_sim = execute(self.circuit,backend,shots=self.shots) result_sim = job_sim.result() counts = result_sim.get_counts(self.circuit) return self.N_qubit_expectation_Z(counts,self.shots,1) class TorchCircuit(Function): @staticmethod def forward(ctx, i): if not hasattr(ctx, 'QiskitCirc'): ctx.QiskitCirc = QiskitCircuit(shots=100000) ckt = ctx.QiskitCirc.bind([i[0][0].item(), i[0][1].item(), i[0][2].item()]) exp_value = ctx.QiskitCirc.run() result = torch.tensor([[exp_value]]) ctx.save_for_backward(result, i) print(result) return result @staticmethod def backward(ctx, grad_output): eps = 0.01 forward_tensor, i = ctx.saved_tensors input_numbers = [i[0][0].item(), i[0][1].item(), i[0][2].item()] gradient = [0,0,0] for k in range(len(input_numbers)): input_eps = input_numbers input_eps[k] = input_numbers[k] + eps _ckt = ctx.QiskitCirc.bind(input_eps) exp_value = ctx.QiskitCirc.run()[0] result_eps = torch.tensor([[exp_value]]) gradient_result = (exp_value - forward_tensor[0][0].item()) gradient[k] = gradient_result result = torch.tensor([gradient]) return result.float() * grad_output.float() # useful additional packages import matplotlib.pyplot as plt import matplotlib.axes as axes %matplotlib inline import numpy as np import networkx as nx from qiskit import BasicAer from qiskit.tools.visualization import plot_histogram from qiskit.aqua import run_algorithm from qiskit.aqua.input import EnergyInput from qiskit.aqua.translators.ising import max_cut, tsp from qiskit.aqua.algorithms import VQE, ExactEigensolver from qiskit.aqua.components.optimizers import SPSA from qiskit.aqua.components.variational_forms import RY from qiskit.aqua import QuantumInstance # setup aqua logging import logging from qiskit.aqua import set_qiskit_aqua_logging # Generating a graph of 4 nodes n=4 # Number of nodes in graph G=nx.Graph() G.add_nodes_from(np.arange(0,n,1)) elist=[(0,1,1.0),(0,2,1.0),(0,3,1.0),(1,2,1.0),(2,3,1.0)] # tuple is (i,j,weight) where (i,j) is the edge G.add_weighted_edges_from(elist) colors = ['r' for node in G.nodes()] pos = nx.spring_layout(G) default_axes = plt.axes(frameon=True) nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, ax=default_axes, pos=pos) from docplex.mp.model import Model from qiskit.aqua.translators.ising import docplex n=4 w = np.zeros([n,n]) for i in range(n): for j in range(n): temp = G.get_edge_data(i,j,default=0) if temp != 0: w[i,j] = temp['weight'] print(w) qubitOp, offset = max_cut.get_max_cut_qubitops(w) algo_input = EnergyInput(qubitOp) mdl = Model(name='max_cut') x = {i: mdl.binary_var(name='x_{0}'.format(i)) for i in range(n)} # Object function max_cut_func = mdl.sum(w[i,j]* x[i] * ( 1 - x[j] ) for i in range(n) for j in range(n)) mdl.maximize(max_cut_func) # No constraints for Max-Cut problems. qubitOp_docplex, offset_docplex = docplex.get_qubitops(mdl) seed = 10598 spsa = SPSA(max_trials=300) ry = RY(qubitOp.num_qubits, depth=1, entanglement='linear') vqe = VQE(qubitOp, ry, spsa) print(vqe.setting) backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed) parameters = np.random.rand(8) circuits = vqe.construct_circuit(parameters) print(circuits[0]) algorithm_cfg = {'name': 'VQE'} dictio = {'problem': {'name': 'ising'},'algorithm': algorithm_cfg} vqe.energy_evaluation(parameters) import torch import numpy as np from torchvision import datasets, transforms batch_size_train = 64 batch_size_test = 1000 learning_rate = 0.01 momentum = 0.5 log_interval = 10 torch.backends.cudnn.enabled = False transform=torchvision.transforms.Compose([ torchvision.transforms.ToTensor()]) mnist_trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transform) labels = mnist_trainset.targets #get labels labels = labels.numpy() idx1 = np.where(labels == 0) #search all zeros idx2 = np.where(labels == 1) # search all ones idx = np.concatenate((idx1[0],idx2[0])) # concatenate their indices mnist_trainset.targets = labels[idx] mnist_trainset.data = mnist_trainset.data[idx] print(mnist_trainset) train_loader = torch.utils.data.DataLoader(mnist_trainset, batch_size=batch_size_train, shuffle=True) import torch.nn as nn import torch.nn.functional as F import torch.optim as optim class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.fc1 = nn.Linear(320, 50) self.fc2 = nn.Linear(50, 2) def forward(self, x): x = F.relu(F.max_pool2d(self.conv1(x), 2)) x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) x = x.view(-1, 320) x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training) x = self.fc2(x) return F.softmax(x) network = Net() optimizer = optim.SGD(network.parameters(), lr=learning_rate, momentum=momentum) epochs = 3 for epoch in range(epochs): for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() output = network(data) loss = F.nll_loss(output, target) loss.backward() optimizer.step() print(loss) length = target.shape[0] print(length) for i in range(length): print(target[i], output[i][1])
https://github.com/abbarreto/qiskit2
abbarreto
%run init.ipynb from qiskit import * nshots = 8192 qiskit.IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main') simulator = Aer.get_backend('qasm_simulator') device = provider.get_backend('ibmq_lima') from qiskit.tools.visualization import plot_histogram from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor def qc_ent_dist(): qc = QuantumCircuit(2, name = 'E dist') qc.h([0]); qc.cx(0, 1) return qc qc_ent_dist_ = qc_ent_dist(); qc_ent_dist_.draw(output = 'mpl') def qc_bb_cb(): qc = QuantumCircuit(2, name = 'BB->CB') qc.cx(0,1); qc.h(0) return qc qc_bb_cb_ = qc_bb_cb(); qc_bb_cb_.draw(output = 'mpl') def qc_teleport(th, ph, lb): qc = QuantumCircuit(3) qc_ent_dist_ = qc_ent_dist(); qc.append(qc_ent_dist_, [1, 2]) # distribuição de emaranhamento qc.barrier() qc.u(th, ph, lb, [0]) # Preparação do estado a ser teletransportado qc.barrier() qc_bb_cb_ = qc_bb_cb(); qc.append(qc_bb_cb_, [0, 1]) # Base de Bell para base computacional qc.barrier() qc.cx(1, 2); qc.cz(0, 2) # infor clássica + unitária de Bob return qc qc_teleport_ = qc_teleport(0.1, 0.5, 0); qc_teleport_.decompose().draw(output = 'mpl') import numpy as np import math th, ph, lb = 0, 0, 0; rho_teo = np.array([[math.cos(th/2)**2, (math.cos(ph)+1j*math.sin(ph))*math.sin(th/2)*math.cos(th/2)], [(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2)*math.cos(th/2), math.sin(th/2)**2]]) qc_teleport_ = qc_teleport(0.1, 0.5, 0) qstc = state_tomography_circuits(qc_teleport_, [2]) # simulação job = qiskit.execute(qstc, Aer.get_backend('qasm_simulator'), shots = nshots) qstf = StateTomographyFitter(job.result(), qstc) rho_sim = qstf.fit(method='lstsq') print('rho_teo = ', rho_teo) print('rho_sim = ', rho_sim) # experimento job = qiskit.execute(qstc, backend = device, shots = nshots) job_monitor(job) qstf = StateTomographyFitter(job.result(), qstc) rho_exp = qstf.fit(method = 'lstsq') print('rho_exp = ', rho_exp) F = qiskit.quantum_info.state_fidelity(rho_teo, rho_exp); print('F = ', F) # variar th em cos(th/2)|0>+exp(i*ph)sin(th/2)|1>
https://github.com/jatin-47/QGSS-2021
jatin-47
# General tools import numpy as np import matplotlib.pyplot as plt # Qiskit Circuit Functions from qiskit import execute,QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile import qiskit.quantum_info as qi # Tomography functions from qiskit.ignis.verification.tomography import process_tomography_circuits, ProcessTomographyFitter from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter import warnings warnings.filterwarnings('ignore') target = QuantumCircuit(2) #target = # YOUR CODE HERE target.h(0) target.h(1) target.rx(np.pi/2,0) target.rx(np.pi/2,1) target.cx(0,1) target.p(np.pi,1) target.cx(0,1) target_unitary = qi.Operator(target) target.draw('mpl') from qc_grader import grade_lab5_ex1 # Note that the grading function is expecting a quantum circuit with no measurements grade_lab5_ex1(target) simulator = Aer.get_backend('qasm_simulator') qpt_circs = process_tomography_circuits(target,measured_qubits=[0,1])# YOUR CODE HERE qpt_job = execute(qpt_circs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192) qpt_result = qpt_job.result() # YOUR CODE HERE qpt_tomo= ProcessTomographyFitter(qpt_result,qpt_circs) Choi_qpt= qpt_tomo.fit(method='lstsq') fidelity = qi.average_gate_fidelity(Choi_qpt,target_unitary) from qc_grader import grade_lab5_ex2 # Note that the grading function is expecting a floating point number grade_lab5_ex2(fidelity) # T1 and T2 values for qubits 0-3 T1s = [15000, 19000, 22000, 14000] T2s = [30000, 25000, 18000, 28000] # Instruction times (in nanoseconds) time_u1 = 0 # virtual gate time_u2 = 50 # (single X90 pulse) time_u3 = 100 # (two X90 pulses) time_cx = 300 time_reset = 1000 # 1 microsecond time_measure = 1000 # 1 microsecond from qiskit.providers.aer.noise import thermal_relaxation_error from qiskit.providers.aer.noise import NoiseModel # QuantumError objects errors_reset = [thermal_relaxation_error(t1, t2, time_reset) for t1, t2 in zip(T1s, T2s)] errors_measure = [thermal_relaxation_error(t1, t2, time_measure) for t1, t2 in zip(T1s, T2s)] errors_u1 = [thermal_relaxation_error(t1, t2, time_u1) for t1, t2 in zip(T1s, T2s)] errors_u2 = [thermal_relaxation_error(t1, t2, time_u2) for t1, t2 in zip(T1s, T2s)] errors_u3 = [thermal_relaxation_error(t1, t2, time_u3) for t1, t2 in zip(T1s, T2s)] errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand( thermal_relaxation_error(t1b, t2b, time_cx)) for t1a, t2a in zip(T1s, T2s)] for t1b, t2b in zip(T1s, T2s)] # Add errors to noise model noise_thermal = NoiseModel() for j in range(4): noise_thermal.add_quantum_error(errors_measure[j],'measure',[j]) noise_thermal.add_quantum_error(errors_reset[j],'reset',[j]) noise_thermal.add_quantum_error(errors_u3[j],'u3',[j]) noise_thermal.add_quantum_error(errors_u2[j],'u2',[j]) noise_thermal.add_quantum_error(errors_u1[j],'u1',[j]) for k in range(4): noise_thermal.add_quantum_error(errors_cx[j][k],'cx',[j,k]) # YOUR CODE HERE from qc_grader import grade_lab5_ex3 # Note that the grading function is expecting a NoiseModel grade_lab5_ex3(noise_thermal) np.random.seed(0) noise_qpt_circs = process_tomography_circuits(target,measured_qubits=[0,1])# YOUR CODE HERE noise_qpt_job = execute(noise_qpt_circs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192,noise_model=noise_thermal) noise_qpt_result = noise_qpt_job.result() # YOUR CODE HERE noise_qpt_tomo= ProcessTomographyFitter(noise_qpt_result,noise_qpt_circs) noise_Choi_qpt= noise_qpt_tomo.fit(method='lstsq') fidelity = qi.average_gate_fidelity(noise_Choi_qpt,target_unitary) from qc_grader import grade_lab5_ex4 # Note that the grading function is expecting a floating point number grade_lab5_ex4(fidelity) np.random.seed(0) # YOUR CODE HERE #qr = QuantumRegister(2) qubit_list = [0,1] meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list) meas_calibs_job = execute(meas_calibs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192,noise_model=noise_thermal) cal_results = meas_calibs_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, qubit_list=qubit_list) Cal_result = meas_fitter.filter.apply(noise_qpt_result) # YOUR CODE HERE Cal_qpt_tomo= ProcessTomographyFitter(Cal_result,noise_qpt_circs) Cal_Choi_qpt= Cal_qpt_tomo.fit(method='lstsq') fidelity = qi.average_gate_fidelity(Cal_Choi_qpt,target_unitary) from qc_grader import grade_lab5_ex5 # Note that the grading function is expecting a floating point number grade_lab5_ex5(fidelity)
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# 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. """ Test circuits and reference outputs for non-Clifford gate instructions. """ import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit # ========================================================================== # T-gate # ========================================================================== def t_gate_circuits_deterministic(final_measure=True): """T-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # T circuit = QuantumCircuit(*regs) circuit.t(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # T.X circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.barrier(qr) circuit.t(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def t_gate_counts_deterministic(shots, hex_counts=True): """T-gate circuits reference counts.""" targets = [] if hex_counts: # T targets.append({'0x0': shots}) # T.X targets.append({'0x1': shots}) else: # T targets.append({'0': shots}) # T.X targets.append({'1': shots}) return targets def t_gate_statevector_deterministic(): """T-gate circuits reference statevectors.""" targets = [] # T targets.append(np.array([1, 0])) # T.X targets.append(np.array([0, 1 + 1j]) / np.sqrt(2)) return targets def t_gate_unitary_deterministic(): """T-gate circuits reference unitaries.""" targets = [] # T targets.append(np.diag([1, (1 + 1j) / np.sqrt(2)])) # T.X targets.append(np.array([[0, 1], [(1 + 1j) / np.sqrt(2), 0]])) return targets def t_gate_circuits_nondeterministic(final_measure=True): """T-gate test circuits with non-deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # T.H circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.t(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # X.T.H circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.t(qr) circuit.barrier(qr) circuit.x(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H.T.T.H = H.S.H circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.t(qr) circuit.barrier(qr) circuit.t(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def t_gate_counts_nondeterministic(shots, hex_counts=True): """T-gate circuits reference counts.""" targets = [] if hex_counts: # T.H targets.append({'0x0': shots / 2, '0x1': shots / 2}) # X.T.H targets.append({'0x0': shots / 2, '0x1': shots / 2}) # H.T.T.H = H.S.H targets.append({'0x0': shots / 2, '0x1': shots / 2}) else: # T.H targets.append({'0': shots / 2, '1': shots / 2}) # X.T.H targets.append({'0': shots / 2, '1': shots / 2}) # H.T.T.H = H.S.H targets.append({'0': shots / 2, '1': shots / 2}) return targets def t_gate_statevector_nondeterministic(): """T-gate circuits reference statevectors.""" targets = [] # T.H targets.append(np.array([1 / np.sqrt(2), 0.5 + 0.5j])) # X.T.H targets.append(np.array([0.5 + 0.5j, 1 / np.sqrt(2)])) # H.T.T.H = H.S.H targets.append(np.array([1 + 1j, 1 - 1j]) / 2) return targets def t_gate_unitary_nondeterministic(): """T-gate circuits reference unitaries.""" targets = [] # T.H targets.append( np.array([[1 / np.sqrt(2), 1 / np.sqrt(2)], [0.5 + 0.5j, -0.5 - 0.5j]])) # X.T.H targets.append( np.array([[0.5 + 0.5j, -0.5 - 0.5j], [1 / np.sqrt(2), 1 / np.sqrt(2)]])) # H.T.T.H = H.S.H targets.append(np.array([[1 + 1j, 1 - 1j], [1 - 1j, 1 + 1j]]) / 2) return targets # ========================================================================== # T^dagger-gate # ========================================================================== def tdg_gate_circuits_deterministic(final_measure=True): """Tdg-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # Tdg circuit = QuantumCircuit(*regs) circuit.tdg(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H.Tdg.T.H = I circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.t(qr) circuit.barrier(qr) circuit.tdg(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def tdg_gate_counts_deterministic(shots, hex_counts=True): """Sdg-gate circuits reference counts.""" targets = [] if hex_counts: # Tdg targets.append({'0x0': shots}) # H.Tdg.T.H = I targets.append({'0x0': shots}) else: # Tdg targets.append({'0': shots}) # H.Tdg.T.H = I targets.append({'0': shots}) return targets def tdg_gate_statevector_deterministic(): """Sdg-gate circuits reference statevectors.""" targets = [] # Tdg targets.append(np.array([1, 0])) # H.Tdg.T.H = I targets.append(np.array([1, 0])) return targets def tdg_gate_unitary_deterministic(): """Tdg-gate circuits reference unitaries.""" targets = [] # Tdg targets.append(np.diag([1, (1 - 1j) / np.sqrt(2)])) # H.Tdg.T.H = I targets.append(np.eye(2)) return targets def tdg_gate_circuits_nondeterministic(final_measure=True): """Tdg-gate test circuits with non-deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # Tdg.H circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.tdg(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # X.Tdg.H circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.tdg(qr) circuit.barrier(qr) circuit.x(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H.Tdg.Tdg.H = H.Sdg.H circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.tdg(qr) circuit.barrier(qr) circuit.tdg(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def tdg_gate_counts_nondeterministic(shots, hex_counts=True): """Tdg-gate circuits reference counts.""" targets = [] if hex_counts: # Tdg.H targets.append({'0x0': shots / 2, '0x1': shots / 2}) # X.Tdg.H targets.append({'0x0': shots / 2, '0x1': shots / 2}) # H.Tdg.Tdg.H = H.Sdg.H targets.append({'0x0': shots / 2, '0x1': shots / 2}) else: # Tdg.H targets.append({'0': shots / 2, '1': shots / 2}) # X.Tdg.H targets.append({'0': shots / 2, '1': shots / 2}) # H.Tdg.Tdg.H = H.Sdg.H targets.append({'0': shots / 2, '1': shots / 2}) return targets def tdg_gate_statevector_nondeterministic(): """Tdg-gate circuits reference statevectors.""" targets = [] # Tdg.H targets.append(np.array([1 / np.sqrt(2), 0.5 - 0.5j])) # X.Tdg.H targets.append(np.array([0.5 - 0.5j, 1 / np.sqrt(2)])) # H.Tdg.Tdg.H = H.Sdg.H targets.append(np.array([1 - 1j, 1 + 1j]) / 2) return targets def tdg_gate_unitary_nondeterministic(): """Tdg-gate circuits reference unitaries.""" targets = [] # Tdg.H targets.append( np.array([[1 / np.sqrt(2), 1 / np.sqrt(2)], [0.5 - 0.5j, -0.5 + 0.5j]])) # X.Tdg.H targets.append( np.array([[0.5 - 0.5j, -0.5 + 0.5j], [1 / np.sqrt(2), 1 / np.sqrt(2)]])) # H.Tdg.Tdg.H = H.Sdg.H targets.append(np.array([[1 - 1j, 1 + 1j], [1 + 1j, 1 - 1j]]) / 2) return targets # ========================================================================== # CCX-gate # ========================================================================== def ccx_gate_circuits_deterministic(final_measure=True): """CCX-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(3) if final_measure: cr = ClassicalRegister(3) regs = (qr, cr) else: regs = (qr, ) # CCX(0,1,2) circuit = QuantumCircuit(*regs) circuit.ccx(qr[0], qr[1], qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # (I^X^X).CCX(0,1,2).(I^X^X) -> |100> circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.ccx(qr[0], qr[1], qr[2]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CCX(2,1,0) circuit = QuantumCircuit(*regs) circuit.ccx(qr[2], qr[1], qr[0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # (X^X^I).CCX(2,1,0).(X^X^I) -> |001> circuit = QuantumCircuit(*regs) circuit.x(qr[1]) circuit.barrier(qr) circuit.x(qr[2]) circuit.barrier(qr) circuit.ccx(qr[2], qr[1], qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.x(qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def ccx_gate_counts_deterministic(shots, hex_counts=True): """CCX-gate circuits reference counts.""" targets = [] if hex_counts: # CCX(0,1,2) targets.append({'0x0': shots}) # (I^X^X).CCX(0,1,2).(I^X^X) -> |100> targets.append({'0x4': shots}) # CCX(2,1,0) targets.append({'0x0': shots}) # (X^X^I).CCX(2,1,0).(X^X^I) -> |001> targets.append({'0x1': shots}) else: # CCX(0,1,2) targets.append({'000': shots}) # (I^X^X).CCX(0,1,2).(I^X^X) -> |100> targets.append({'000': shots}) # CCX(2,1,0) targets.append({'000': shots}) # (X^X^I).CCX(2,1,0).(X^X^I) -> |001> targets.append({'001': shots}) return targets def ccx_gate_statevector_deterministic(): """CCX-gate circuits reference statevectors.""" targets = [] zero_state = np.array([1, 0, 0, 0, 0, 0, 0, 0]) # CCX(0,1,2) targets.append(zero_state) # (I^X^X).CCX(0,1,2).(I^X^X) -> |100> targets.append(np.array([0, 0, 0, 0, 1, 0, 0, 0])) # CCX(2,1,0) targets.append(zero_state) # (X^X^I).CCX(2,1,0).(X^X^I) -> |001> targets.append(np.array([0, 1, 0, 0, 0, 0, 0, 0])) return targets def ccx_gate_unitary_deterministic(): """CCX-gate circuits reference unitaries.""" targets = [] # CCX(0,1,2) targets.append( np.array([[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0, 0, 0]])) # (I^X^X).CCX(0,1,2).(I^X^X) -> |100> targets.append( np.array([[0, 0, 0, 0, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1]])) # CCX(2,1,0) targets.append( np.array([[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0]])) # (X^X^I).CCX(2,1,0).(X^X^I) -> |001> targets.append( np.array([[0, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1]])) return targets def ccx_gate_circuits_nondeterministic(final_measure=True): """CCX-gate test circuits with non-deterministic counts.""" circuits = [] qr = QuantumRegister(3) if final_measure: cr = ClassicalRegister(3) regs = (qr, cr) else: regs = (qr, ) # (I^X^I).CCX(0,1,2).(I^X^H) -> |000> + |101> circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.ccx(qr[0], qr[1], qr[2]) circuit.barrier(qr) circuit.x(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # (X^I^I).CCX(2,1,0).(X^H^I) -> |000> + |011> circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.barrier(qr) circuit.x(qr[2]) circuit.barrier(qr) circuit.ccx(qr[2], qr[1], qr[0]) circuit.barrier(qr) circuit.x(qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def ccx_gate_counts_nondeterministic(shots, hex_counts=True): """CCX-gate circuits reference counts.""" targets = [] if hex_counts: # (I^X^I).CCX(0,1,2).(I^X^H) -> |000> + |101> targets.append({'0x0': shots / 2, '0x5': shots / 2}) # (X^I^I).CCX(2,1,0).(X^H^I) -> |000> + |011> targets.append({'0x0': shots / 2, '0x3': shots / 2}) else: # (I^X^I).CCX(0,1,2).(I^X^H) -> |000> + |101> targets.append({'000': shots / 2, '101': shots / 2}) # (X^I^I).CCX(2,1,0).(X^H^I) -> |000> + |011> targets.append({'000': shots / 2, '011': shots / 2}) return targets def ccx_gate_statevector_nondeterministic(): """CCX-gate circuits reference statevectors.""" targets = [] # (I^X^I).CCX(0,1,2).(I^X^H) -> |000> + |101> targets.append(np.array([1, 0, 0, 0, 0, 1, 0, 0]) / np.sqrt(2)) # (X^I^I).CCX(2,1,0).(X^H^I) -> |000> + |011> targets.append(np.array([1, 0, 0, 1, 0, 0, 0, 0]) / np.sqrt(2)) return targets def ccx_gate_unitary_nondeterministic(): """CCX-gate circuits reference unitaries.""" targets = [] # (I^X^I).CCX(0,1,2).(I^X^H) -> |000> + |101> targets.append( np.array([[1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, -1, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 1, -1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 0, 0], [1, -1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, -1]]) / np.sqrt(2)) # (X^I^I).CCX(2,1,0).(X^H^I) -> |000> + |011> targets.append( np.array([[1, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 1, 0, 0, 0, 0], [0, 1, 0, -1, 0, 0, 0, 0], [1, 0, -1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 1, 0], [0, 0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 0, 1, 0, -1, 0], [0, 0, 0, 0, 0, 1, 0, -1]]) / np.sqrt(2)) return targets # ========================================================================== # CSWAP-gate (Fredkin) # ========================================================================== def cswap_gate_circuits_deterministic(final_measure): """cswap-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(3) if final_measure: cr = ClassicalRegister(3) regs = (qr, cr) else: regs = (qr, ) # CSWAP(0,1,2) # -> |000> circuit = QuantumCircuit(*regs) circuit.cswap(qr[0], qr[1], qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(X^I^I) -> |100> circuit = QuantumCircuit(*regs) circuit.x(qr[2]) circuit.barrier(qr) circuit.cswap(qr[0], qr[1], qr[2]) circuit.barrier(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(I^X^I) -> |010> circuit = QuantumCircuit(*regs) circuit.x(qr[1]) circuit.barrier(qr) circuit.cswap(qr[0], qr[1], qr[2]) circuit.barrier(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(X^X^I) -> |110> circuit = QuantumCircuit(*regs) circuit.x(qr[1]) circuit.x(qr[2]) circuit.barrier(qr) circuit.cswap(qr[0], qr[1], qr[2]) circuit.barrier(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(I^I^X) -> |001> circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.barrier(qr) circuit.cswap(qr[0], qr[1], qr[2]) circuit.barrier(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(I^X^X -> |101> circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.x(qr[1]) circuit.barrier(qr) circuit.cswap(qr[0], qr[1], qr[2]) circuit.barrier(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(X^I^X) -> |011> circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.x(qr[2]) circuit.barrier(qr) circuit.cswap(qr[0], qr[1], qr[2]) circuit.barrier(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(X^X^X) -> |111> circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.x(qr[1]) circuit.x(qr[2]) circuit.barrier(qr) circuit.cswap(qr[0], qr[1], qr[2]) circuit.barrier(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(1,0,2).(I^X^X) -> |110> circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.x(qr[1]) circuit.barrier(qr) circuit.cswap(qr[1], qr[0], qr[2]) circuit.barrier(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(2,1,0).(X^I^X) -> |110> circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.x(qr[2]) circuit.barrier(qr) circuit.cswap(qr[2], qr[1], qr[0]) circuit.barrier(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def cswap_gate_counts_deterministic(shots, hex_counts=True): """"cswap-gate circuits reference counts.""" targets = [] if hex_counts: # CSWAP(0,1,2) # -> |000> targets.append({'0x0': shots}) # CSWAP(0,1,2).(X^I^I) -> |100> targets.append({'0x4': shots}) # CSWAP(0,1,2).(I^X^I) -> |010> targets.append({'0x2': shots}) # CSWAP(0,1,2).(X^X^I) -> |110> targets.append({'0x6': shots}) # CSWAP(0,1,2).(I^I^X). -> |001> targets.append({'0x1': shots}) # CSWAP(0,1,2).(I^X^X) -> |101> targets.append({'0x5': shots}) # CSWAP(0,1,2).(X^I^X) -> |011> targets.append({'0x3': shots}) # CSWAP(0,1,2).(X^X^X) -> |111> targets.append({'0x7': shots}) # CSWAP(1,0,2).(I^X^X) -> |110> targets.append({'0x6': shots}) # CSWAP(2,1,0).(X^I^X) -> |110> targets.append({'0x6': shots}) else: # CSWAP(0,1,2) # -> |000> targets.append({'000': shots}) # CSWAP(0,1,2).(X^I^I) -> |100> targets.append({'100': shots}) # CSWAP(0,1,2).(I^X^I) -> |010> targets.append({'010': shots}) # CSWAP(0,1,2).(X^X^I) -> |110> targets.append({'110': shots}) # CSWAP(0,1,2).(I^I^X) -> |001> targets.append({'001': shots}) # CSWAP(0,1,2).(I^X^X) -> |101> targets.append({'101': shots}) # CSWAP(0,1,2).(X^I^X) -> |011> targets.append({'011': shots}) # CSWAP(0,1,2).(X^X^X) -> |111> targets.append({'111': shots}) # CSWAP(1,0,2).(I^X^X) -> |110> targets.append({'110': shots}) # CSWAP(2,1,0).(X^I^X) -> |110> targets.append({'110': shots}) return targets def cswap_gate_circuits_nondeterministic(final_measure=True): """cswap-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(3) if final_measure: cr = ClassicalRegister(3) regs = (qr, cr) else: regs = (qr, ) # CSWAP(0,1,2).(H^H^H) circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.h(qr[1]) circuit.h(qr[2]) circuit.cswap(qr[0], qr[1], qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(X^I^H). -> |100> + |011> circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.x(qr[2]) circuit.cswap(qr[0], qr[1], qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(I^X^H). -> |010> + |101> circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.x(qr[1]) circuit.cswap(qr[0], qr[1], qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(I^H^I) -> |010>+|000> circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.cswap(qr[0], qr[1], qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(H^I^I) -> |100>+|000> circuit = QuantumCircuit(*regs) circuit.h(qr[2]) circuit.cswap(qr[0], qr[1], qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(I^I^H) -> |001>+|000> circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.cswap(qr[0], qr[1], qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(X^X^H) -> |110> + |111> circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.x(qr[1]) circuit.x(qr[2]) circuit.cswap(qr[0], qr[1], qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def cswap_gate_counts_nondeterministic(shots, hex_counts=True): targets = [] if hex_counts: # CSWAP(0,1,2).(H^H^H) -> |---> targets.append({ '0x0': shots / 8, '0x1': shots / 8, '0x2': shots / 8, '0x3': shots / 8, '0x4': shots / 8, '0x5': shots / 8, '0x6': shots / 8, '0x7': shots / 8, }) # CSWAP(0,1,2).(X^I^H). -> |100> + |011> targets.append({'0x3': shots / 2, '0x4': shots / 2}) # CSWAP(0,1,2).(I^X^H). -> |010> + |101> targets.append({'0x2': shots / 2, '0x5': shots / 2}) # CSWAP(0,1,2).(I^H^I) -> |0-0> targets.append({'0x2': shots / 2, '0x0': shots / 2}) # CSWAP(0,1,2).(H^I^I) -> |-00> targets.append({'0x4': shots / 2, '0x0': shots / 2}) # CSWAP(0,1,2).(I^I^H) -> |00-> targets.append({'0x0': shots / 2, '0x1': shots / 2}) # CSWAP(0,1,2).(X^X^H) -> |110> + |111> targets.append({'0x6': shots / 2, '0x7': shots / 2}) else: # CSWAP(0,1,2).(H^H^H) -> |---> targets.append({ '000': shots / 8, '001': shots / 8, '010': shots / 8, '011': shots / 8, '100': shots / 8, '101': shots / 8, '110': shots / 8, '111': shots / 8, }) # CSWAP(0,1,2).(X^I^H). -> |100> + |011> targets.append({'011': shots / 2, '100': shots / 2}) # CSWAP(0,1,2).(I^X^H). -> |010> + |101> targets.append({'010': shots / 2, '101': shots / 2}) # CSWAP(0,1,2).(I^H^I) -> |0-0> targets.append({'010': shots / 2, '000': shots / 2}) # CSWAP(0,1,2).(H^I^I) -> |-00> targets.append({'100': shots / 2, '000': shots / 2}) # CSWAP(0,1,2).(I^I^H) -> |00-> targets.append({'001': shots / 2, '000': shots / 2}) # CSWAP(0,1,2).(X^X^H) -> |110> + |111> targets.append({'110': shots / 2, '111': shots / 2}) return targets def cswap_gate_statevector_deterministic(): targets = [] # CSWAP(0,1,2) # -> |000> targets.append(np.array([1, 0, 0, 0, 0, 0, 0, 0])) # CSWAP(0,1,2).(X^I^I) -> |100> targets.append(np.array([0, 0, 0, 0, 1, 0, 0, 0])) # CSWAP(0,1,2).(I^X^I) -> |010> targets.append(np.array([0, 0, 1, 0, 0, 0, 0, 0])) # CSWAP(0,1,2).(X^X^I) -> |110> targets.append(np.array([0, 0, 0, 0, 0, 0, 1, 0])) # CSWAP(0,1,2).(I^I^X) -> |001> targets.append(np.array([0, 1, 0, 0, 0, 0, 0, 0])) # CSWAP(0,1,2).(I^X^X) -> |101> targets.append(np.array([0, 0, 0, 0, 0, 1, 0, 0])) # CSWAP(0,1,2).(X^I^X) -> |011> targets.append(np.array([0, 0, 0, 1, 0, 0, 0, 0])) # CSWAP(0,1,2).(X^X^X) -> |111> targets.append(np.array([0, 0, 0, 0, 0, 0, 0, 1])) # CSWAP(1,0,2).(I^X^X) -> |110> targets.append(np.array([0, 0, 0, 0, 0, 0, 1, 0])) # CSWAP(2,1,0).(X^I^X) -> |110> targets.append(np.array([0, 0, 0, 0, 0, 0, 1, 0])) return targets def cswap_gate_statevector_nondeterministic(): targets = [] # CSWAP(0,1,2).(H^H^H) -> |---> targets.append(np.array([1, 1, 1, 1, 1, 1, 1, 1]) / np.sqrt(8)) # CSWAP(0,1,2).(X^I^H). -> |100> + |011> targets.append(np.array([0, 0, 0, 1, 1, 0, 0, 0]) / np.sqrt(2)) # CSWAP(0,1,2).(I^X^H). -> |010> + |101> targets.append(np.array([0, 0, 1, 0, 0, 1, 0, 0]) / np.sqrt(2)) # CSWAP(0,1,2).(I^H^I) -> |0-0> targets.append(np.array([1, 0, 1, 0, 0, 0, 0, 0]) / np.sqrt(2)) # CSWAP(0,1,2).(H^I^I) -> |-00> targets.append(np.array([1, 0, 0, 0, 1, 0, 0, 0]) / np.sqrt(2)) # CSWAP(0,1,2).(I^I^H) -> |00-> targets.append(np.array([1, 1, 0, 0, 0, 0, 0, 0]) / np.sqrt(2)) # CSWAP(0,1,2).(X^X^H) -> |110> + |111> targets.append(np.array([0, 0, 0, 0, 0, 0, 1, 1]) / np.sqrt(2)) return targets def cswap_gate_unitary_deterministic(): """cswap-gate circuits reference unitaries.""" targets = [] # CSWAP(0,1,2) # -> |000> targets.append( np.array([[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1]])) # CSWAP(0,1,2).(X^I^I) -> |100> targets.append( np.array([[0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0]])) # CSWAP(0,1,2).(I^X^I) -> |010> targets.append( np.array([[0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0]])) # CSWAP(0,1,2).(X^X^I) -> |110> targets.append( np.array([[0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0]])) # CSWAP(0,1,2).(I^I^X) -> |001> targets.append( np.array([[0, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0]])) # CSWAP(0,1,2).(I^X^X) -> |101> targets.append( np.array([[0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0]])) # CSWAP(0,1,2).(X^I^X) -> |011> targets.append( np.array([[0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0]])) # CSWAP(0,1,2).(X^X^X) -> |111> targets.append( np.array([[0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0]])) # CSWAP(1,0,2).(I^X^X) -> |110> targets.append( np.array([[0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0]])) # CSWAP(2,1,0).(X^I^X) -> |110> targets.append( np.array([[0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0]])) return targets def cswap_gate_unitary_nondeterministic(): """cswap-gate circuits reference unitaries.""" targets = [] targets.append( np.array([[ 0.35355339, 0.35355339, 0.35355339, 0.35355339, 0.35355339, 0.35355339, 0.35355339, 0.35355339 ], [ 0.35355339, -0.35355339, 0.35355339, -0.35355339, 0.35355339, -0.35355339, 0.35355339, -0.35355339 ], [ 0.35355339, 0.35355339, -0.35355339, -0.35355339, 0.35355339, 0.35355339, -0.35355339, -0.35355339 ], [ 0.35355339, -0.35355339, 0.35355339, -0.35355339, -0.35355339, 0.35355339, -0.35355339, 0.35355339 ], [ 0.35355339, 0.35355339, 0.35355339, 0.35355339, -0.35355339, -0.35355339, -0.35355339, -0.35355339 ], [ 0.35355339, -0.35355339, -0.35355339, 0.35355339, 0.35355339, -0.35355339, -0.35355339, 0.35355339 ], [ 0.35355339, 0.35355339, -0.35355339, -0.35355339, -0.35355339, -0.35355339, 0.35355339, 0.35355339 ], [ 0.35355339, -0.35355339, -0.35355339, 0.35355339, -0.35355339, 0.35355339, 0.35355339, -0.35355339 ]])) targets.append( np.array([[0, 0, 0, 0, 0.70710678, 0.70710678, 0, 0], [0, 0, 0, 0, 0.70710678, -0.70710678, 0, 0], [0, 0, 0, 0, 0, 0, 0.70710678, 0.70710678], [0.70710678, -0.70710678, 0, 0, 0, 0, 0, 0], [0.70710678, 0.70710678, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0.70710678, -0.70710678], [0, 0, 0.70710678, 0.70710678, 0, 0, 0, 0], [0, 0, 0.70710678, -0.70710678, 0, 0, 0, 0]])) targets.append( np.array([[0, 0, 0.70710678, 0.70710678, 0, 0, 0, 0], [0, 0, 0.70710678, -0.70710678, 0, 0, 0, 0], [0.70710678, 0.70710678, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0.70710678, -0.70710678], [0, 0, 0, 0, 0, 0, 0.70710678, 0.70710678], [0.70710678, -0.70710678, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0.70710678, 0.70710678, 0, 0], [0, 0, 0, 0, 0.70710678, -0.70710678, 0, 0]])) targets.append( np.array([[0.70710678, 0, 0.70710678, 0, 0, 0, 0, 0], [0, 0.70710678, 0, 0.70710678, 0, 0, 0, 0], [0.70710678, 0, -0.70710678, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0.70710678, 0, 0.70710678], [0, 0, 0, 0, 0.70710678, 0, 0.70710678, 0], [0, 0.70710678, 0, -0.70710678, 0, 0, 0, 0], [0, 0, 0, 0, 0.70710678, 0, -0.70710678, 0], [0, 0, 0, 0, 0, 0.70710678, 0, -0.70710678]])) targets.append( np.array([[0.70710678, 0, 0, 0, 0.70710678, 0, 0, 0], [0, 0.70710678, 0, 0, 0, 0.70710678, 0, 0], [0, 0, 0.70710678, 0, 0, 0, 0.70710678, 0], [0, 0.70710678, 0, 0, 0, -0.70710678, 0, 0], [0.70710678, 0, 0, 0, -0.70710678, 0, 0, 0], [0, 0, 0, 0.70710678, 0, 0, 0, 0.70710678], [0, 0, 0.70710678, 0, 0, 0, -0.70710678, 0], [0, 0, 0, 0.70710678, 0, 0, 0, -0.70710678]])) targets.append( np.array([[0.70710678, 0.70710678, 0, 0, 0, 0, 0, 0], [0.70710678, -0.70710678, 0, 0, 0, 0, 0, 0], [0, 0, 0.70710678, 0.70710678, 0, 0, 0, 0], [0, 0, 0, 0, 0.70710678, -0.70710678, 0, 0], [0, 0, 0, 0, 0.70710678, 0.70710678, 0, 0], [0, 0, 0.70710678, -0.70710678, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0.70710678, 0.70710678], [0, 0, 0, 0, 0, 0, 0.70710678, -0.70710678]])) targets.append( np.array([[0, 0, 0, 0, 0, 0, 0.70710678, 0.70710678], [0, 0, 0, 0, 0, 0, 0.70710678, -0.70710678], [0, 0, 0, 0, 0.70710678, 0.70710678, 0, 0], [0, 0, 0.70710678, -0.70710678, 0, 0, 0, 0], [0, 0, 0.70710678, 0.70710678, 0, 0, 0, 0], [0, 0, 0, 0, 0.70710678, -0.70710678, 0, 0], [0.70710678, 0.70710678, 0, 0, 0, 0, 0, 0], [0.70710678, -0.70710678, 0, 0, 0, 0, 0, 0]])) return targets # ========================================================================== # CU1 # ========================================================================== def cu1_gate_circuits_nondeterministic(final_measure): circuits = [] qr = QuantumRegister(2) if final_measure: cr = ClassicalRegister(2) regs = (qr, cr) else: regs = (qr, ) # H^X.CU1(0,0,1).H^X circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.x(qr[0]) circuit.cp(0, qr[0], qr[1]) circuit.x(qr[0]) circuit.h(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H^I.CU1(pi,0,1).H^I circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.cp(np.pi, qr[0], qr[1]) circuit.h(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H^X.CU1(pi/4,0,1).H^X circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.x(qr[0]) circuit.cp(np.pi / 4, qr[0], qr[1]) circuit.x(qr[0]) circuit.h(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H^X.CU1(pi/2,0,1).H^X circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.x(qr[0]) circuit.cp(np.pi / 2, qr[0], qr[1]) circuit.x(qr[0]) circuit.h(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H^X.CU1(pi,0,1).H^X circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.x(qr[0]) circuit.cp(np.pi, qr[0], qr[1]) circuit.x(qr[0]) circuit.h(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H^H.CU1(0,0,1).H^H circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.h(qr[0]) circuit.cp(0, qr[0], qr[1]) circuit.h(qr[0]) circuit.h(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H^H.CU1(pi/2,0,1).H^H circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.h(qr[0]) circuit.cp(np.pi / 2, qr[0], qr[1]) circuit.h(qr[0]) circuit.h(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H^H.CU1(pi,0,1).H^H circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.h(qr[0]) circuit.cp(np.pi, qr[0], qr[1]) circuit.h(qr[0]) circuit.h(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def cu1_gate_counts_nondeterministic(shots, hex_counts=True): """CU1-gate circuits reference counts.""" targets = [] if hex_counts: # H^X.CU1(0,0,1).H^X targets.append({'0x0': shots}) # H^I.CU1(pi,0,1).H^I targets.append({'0x0': shots}) # H^X.CU1(pi/4,0,1).H^X targets.append({ '0x0': shots * (0.25 * (2 + np.sqrt(2))), '0x2': shots * (0.25 * (2 - np.sqrt(2))) }) # H^X.CU1(pi/2,0,1).H^X targets.append({'0x0': shots * 0.5, '0x2': shots * 0.5}) # H^X.CU1(pi,0,1).H^X targets.append({'0x2': shots}) # H^H.CU1(0,0,1).H^H targets.append({'0x0': shots}) # H^H.CU1(pi/2,0,1).H^H targets.append({ '0x0': shots * 0.625, '0x1': shots * 0.125, '0x2': shots * 0.125, '0x3': shots * 0.125 }) # H^H.CU1(pi,0,1).H^H targets.append({ '0x0': shots * 0.25, '0x1': shots * 0.25, '0x2': shots * 0.25, '0x3': shots * 0.25 }) else: # H^X.CU1(0,0,1).H^X targets.append({'00': shots}) # H^I.CU1(pi,0,1).H^I targets.append({'00': shots}) # H^X.CU1(pi/4,0,1).H^X targets.append({'00': shots * 0.85, '10': shots * 0.15}) # H^X.CU1(pi/2,0,1).H^X targets.append({'00': shots * 0.5, '10': shots * 0.5}) # H^X.CU1(pi,0,1).H^X targets.append({'10': shots}) # H^H.CU1(0,0,1).H^H targets.append({'00': shots}) # H^H.CU1(pi/2,0,1).H^H targets.append({ '00': shots * 0.5125, '01': shots * 0.125, '10': shots * 0.125, '11': shots * 0.125 }) # H^H.CU1(pi,0,1).H^H targets.append({ '00': shots * 0.25, '01': shots * 0.25, '10': shots * 0.25, '11': shots * 0.25 }) return targets def cu1_gate_statevector_nondeterministic(): targets = [] # H^X.CU1(0,0,1).H^X targets.append(np.array([1, 0, 0, 0])) # H^I.CU1(pi,0,1).H^I targets.append(np.array([1, 0, 0, 0])) # H^X.CU1(pi/4,0,1).H^X targets.append( np.array([(0.25 * (2 + np.sqrt(2))) + (1 / (2 * np.sqrt(2))) * 1j, 0, (0.25 * (2 - np.sqrt(2))) - (1 / (2 * np.sqrt(2))) * 1j, 0])) # H^X.CU1(pi/2,0,1).H^X targets.append(np.array([0.5 + 0.5j, 0, 0.5 - 0.5j, 0])) # H^X.CU1(pi,0,1).H^X targets.append(np.array([0, 0, 1, 0])) # H^H.CU1(0,0,1).H^H targets.append(np.array([1, 0, 0, 0])) # H^H.CU1(pi/2,0,1).H^H targets.append( np.array([0.75 + 0.25j, 0.25 - 0.25j, 0.25 - 0.25j, -0.25 + 0.25j])) # H^H.CU1(pi,0,1).H^H targets.append(np.array([0.5, 0.5, 0.5, -0.5])) return targets def cu1_gate_unitary_nondeterministic(): targets = [] # H^X.CU1(0,0,1).H^X targets.append(np.eye(4)) # H^I.CU1(pi,0,1).H^I targets.append( np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]])) # H^X.CU1(pi/4,0,1).H^X targets.append( np.array([[(0.25 * (2 + np.sqrt(2))) + (1 / (2 * np.sqrt(2))) * 1j, 0, (0.25 * (2 - np.sqrt(2))) - (1 / (2 * np.sqrt(2))) * 1j, 0], [0, 1, 0, 0], [(0.25 * (2 - np.sqrt(2))) - (1 / (2 * np.sqrt(2))) * 1j, 0, (0.25 * (2 + np.sqrt(2))) + (1 / (2 * np.sqrt(2))) * 1j, 0], [0, 0, 0, 1]])) # H^X.CU1(pi/2,0,1).H^X targets.append( np.array([[0.5 + 0.5j, 0, 0.5 - 0.5j, 0], [0, 1, 0, 0], [0.5 - 0.5j, 0, 0.5 + 0.5j, 0], [0, 0, 0, 1]])) # H^X.CU1(pi,0,1).H^X targets.append( np.array([[0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1]])) # H^H.CU1(0,0,1).H^H targets.append(np.eye(4)) # H^H.CU1(pi/2,0,1).H^H targets.append( (0.75 + 0.25j) * np.eye(4) + (0.25 - 0.25j) * np.array([[0, 1, 1, -1], [1, 0, -1, 1], [1, -1, 0, 1], [-1, 1, 1, 0]])) # H^H.CU1(pi,0,1).H^H targets.append( 0.5 * np.array([[1, 1, 1, -1], [1, 1, -1, 1], [1, -1, 1, 1], [-1, 1, 1, 1]])) return targets # ========================================================================== # CU3 # ========================================================================== def cu3_gate_circuits_deterministic(final_measure): circuits = [] qr = QuantumRegister(2) if final_measure: cr = ClassicalRegister(2) regs = (qr, cr) else: regs = (qr, ) # I^X.CI.I^X circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.cu(0, 0, 0, 0, qr[0], qr[1]) circuit.x(qr[0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX circuit = QuantumCircuit(*regs) circuit.cu(np.pi, 0, np.pi, 0, qr[0], qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # I^X.CX.I^X circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.cu(np.pi, 0, np.pi, 0, qr[0], qr[1]) circuit.x(qr[0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H^X.CH.I^X circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.cu(np.pi / 2, 0, np.pi, 0, qr[0], qr[1]) circuit.x(qr[0]) circuit.h(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # I^X.CRX(pi).I^X circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.cu(np.pi, -np.pi / 2, np.pi / 2, 0, qr[0], qr[1]) circuit.x(qr[0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # I^X.CRY(pi).I^X circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.cu(np.pi, 0, 0, 0, qr[0], qr[1]) circuit.x(qr[0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def cu3_gate_unitary_deterministic(): targets = [] # I^X.CI.I^X targets.append(np.eye(4)) # CX targets.append( np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]])) # I^X.CX.I^X targets.append( np.array([[0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1]])) # H^X.CH.I^X targets.append( np.array([[1, 0, 0, 0], [0, 1 / np.sqrt(2), 0, 1 / np.sqrt(2)], [0, 0, 1, 0], [0, 1 / np.sqrt(2), 0, -1 / np.sqrt(2)]])) # I^X.CRX(pi).I^X targets.append( np.array([[0, 0, -1j, 0], [0, 1, 0, 0], [-1j, 0, 0, 0], [0, 0, 0, 1]])) # I^X.CRY(pi).I^X targets.append( np.array([[0, 0, -1, 0], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1]])) return targets def cu3_gate_statevector_deterministic(): init_state = np.array([1, 0, 0, 0]) targets = [mat.dot(init_state) for mat in cu3_gate_unitary_deterministic()] return targets def cu3_gate_counts_deterministic(shots, hex_counts=True): """CU2-gate circuits reference counts.""" probs = [np.abs(vec)**2 for vec in cu3_gate_statevector_deterministic()] targets = [] for prob in probs: if hex_counts: targets.append({hex(i): shots * p for i, p in enumerate(prob)}) else: counts = {} for i, p in enumerate(prob): key = bin(i)[2:] key = (2 - len(key)) * '0' + key counts[key] = shots * p targets.append(counts) return targets
https://github.com/1chooo/Quantum-Oracle
1chooo
from qiskit import execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qrx = QuantumRegister(3, 'x') qry = QuantumRegister(1, 'y') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qrx, qry, cr) qc.h(qrx) qc.x(qry) qc.h(qry) qc.barrier() qc.x(qry) qc.barrier() qc.h(qrx) qc.h(qry) qc.measure(qrx, cr) qc.draw("mpl") sim = AerSimulator() job = execute(qc, backend = sim, shots = 1000) result = job.result() counts = result.get_counts(qc) print("Counts: ", counts) plot_histogram(counts)
https://github.com/benkoehlL/Qiskit_Playground
benkoehlL
''' This program performs the Berstein-Vazirani algorithm to guess a secret code ''' from qiskit import * from qiskit.visualization import plot_histogram from matplotlib.pyplot import plot, draw, show import numpy as np import os, shutil LaTex_folder_Berstein_Vazirani = str(os.getcwd())+'/Latex_quantum_gates/Berstein_Vazarani/' if not os.path.exists(LaTex_folder_Berstein_Vazirani): os.makedirs(LaTex_folder_Berstein_Vazirani) else: shutil.rmtree(LaTex_folder_Berstein_Vazirani) os.makedirs(LaTex_folder_Berstein_Vazirani) ## guess a secret binary number s = '110101' #secret number/code n = len(s) qc = QuantumCircuit(n+1,n) qc.x(n) qc.barrier() qc.h(range(n+1)) qc.barrier() # to separate steps for i, tf in enumerate(reversed(s)): if(tf == '1'): qc.cx(i,n) qc.barrier() qc.h(range(n+1)) qc.barrier() qc.measure(range(n), range(n)) # create a LaTex file for the algorithm LaTex_code = qc.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit f_name = 'Berstein_Vazirani.tex' with open(LaTex_folder_Berstein_Vazirani+f_name, 'w') as f: f.write(LaTex_code) # simulate the algorithm simulator = Aer.get_backend('qasm_simulator') job = execute(qc, simulator, shots=1) results = job.result() count = results.get_counts() plot_histogram(results.get_counts(qc)) print(count) draw() show(block=True) ## guess a secret string string = 'Thank you for the nice book' bit_string = [] # convert string to bit-string for c in string: bits_letter = format(ord(c), 'b') for bit in bits_letter: bit_string.append(bit) n = len(bit_string) qc = QuantumCircuit(n+1,n) qc.x(n) qc.barrier() qc.h(range(n+1)) qc.barrier() # to separate steps for i, tf in enumerate(reversed(bit_string)): if(tf == '1'): qc.cx(i,n) qc.barrier() qc.h(range(n+1)) qc.barrier() qc.measure(range(n), range(n)) simulator = Aer.get_backend('qasm_simulator') job = execute(qc, simulator, shots=1) results = job.result() count = results.get_counts() plot_histogram(results.get_counts(qc)) print(len(bit_string),'\n', count) draw() show(block=True)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, execute from qiskit.visualization import plot_error_map from qiskit.providers.fake_provider import FakeVigoV2 backend = FakeVigoV2() plot_error_map(backend)
https://github.com/Gopal-Dahale/qiskit-qulacs
Gopal-Dahale
"""QulacsBackend class.""" import copy import time import uuid from collections import Counter from typing import List, Union import numpy as np from qiskit import QuantumCircuit from qiskit.providers import BackendV1 as Backend from qiskit.providers import JobStatus, Options from qiskit.providers.models import QasmBackendConfiguration from qiskit.result import Result from qiskit.result.models import ExperimentResult, ExperimentResultData import qulacs from qulacs.circuit import QuantumCircuitOptimizer from .adapter import MAX_QUBITS, qiskit_to_qulacs from .backend_utils import BASIS_GATES, available_devices, generate_config from .qulacs_job import QulacsJob from .version import __version__ class QulacsBackend(Backend): """QulacsBackend class.""" _BASIS_GATES = BASIS_GATES _DEFAULT_CONFIGURATION = { "backend_name": "qulacs_simulator", "backend_version": __version__, "n_qubits": MAX_QUBITS, "url": "https://github.com/Gopal-Dahale/qiskit-qulacs", "simulator": True, "local": True, "conditional": True, "open_pulse": False, "memory": True, "max_shots": int(1e6), "description": "A Qulacs fast quantum circuit simulator", "coupling_map": None, "basis_gates": _BASIS_GATES, "gates": [], } _SIMULATION_DEVICES = ("CPU", "GPU") _AVAILABLE_DEVICES = None def __init__( self, configuration=None, properties=None, provider=None, **backend_options ): # Update available devices for class if QulacsBackend._AVAILABLE_DEVICES is None: QulacsBackend._AVAILABLE_DEVICES = available_devices( QulacsBackend._SIMULATION_DEVICES ) # Default configuration if configuration is None: configuration = QasmBackendConfiguration.from_dict( QulacsBackend._DEFAULT_CONFIGURATION ) super().__init__( configuration, provider=provider, ) # Initialize backend properties self._properties = properties # Set options from backend_options dictionary if backend_options is not None: self.set_options(**backend_options) # Quantum circuit optimizer (if needed) self.qc_opt = QuantumCircuitOptimizer() self.class_suffix = { "GPU": "Gpu", "CPU": "", } @classmethod def _default_options(cls): return Options( # Global options shots=0, device="CPU", seed_simulator=None, # Quantum Circuit Optimizer options qco_enable=False, qco_method="light", qco_max_block_size=2, ) def __repr__(self): """String representation of an QulacsBackend.""" name = self.__class__.__name__ display = f"'{self.name()}'" return f"{name}({display})" def available_devices(self): """Return the available simulation methods.""" return copy.copy(self._AVAILABLE_DEVICES) def _execute_circuits_job(self, circuits, states, run_options, job_id=""): """Run a job""" shots = run_options.shots seed = ( run_options.seed_simulator if run_options.seed_simulator else np.random.randint(1000) ) # Start timer start = time.time() expt_results = [] if shots: for state, circuit in zip(states, circuits): circuit.update_quantum_state(state) n = circuit.get_qubit_count() samples = state.sampling(shots, seed) bitstrings = [format(x, f"0{n}b") for x in samples] counts = dict(Counter(bitstrings)) expt_results.append( ExperimentResult( shots=shots, success=True, status=JobStatus.DONE, data=ExperimentResultData(counts=counts, memory=bitstrings), ) ) else: for state, circuit in zip(states, circuits): circuit.update_quantum_state(state) # Statevector expt_results.append( ExperimentResult( shots=shots, success=True, status=JobStatus.DONE, data=ExperimentResultData( statevector=state.get_vector(), ), ) ) return Result( backend_name=self.name(), backend_version=self.configuration().backend_version, job_id=job_id, qobj_id=0, success=True, results=expt_results, status=JobStatus.DONE, time_taken=time.time() - start, ) def run( self, run_input: Union[QuantumCircuit, List[QuantumCircuit]], **run_options, ) -> QulacsJob: run_input = [run_input] if isinstance(run_input, QuantumCircuit) else run_input run_input = list(qiskit_to_qulacs(run_input)) config = ( generate_config(self.options, run_options) if run_options else self.options ) # Use GPU if available if config.device not in self.available_devices(): if config.device == "GPU": raise ValueError("GPU support not installed. Install qulacs-gpu.") raise ValueError(f"Device {config.device} not found.") class_name = f'QuantumState{self.class_suffix.get(config.device, "")}' state_class = getattr(qulacs, class_name) # Use Quantum Circuit Optimizer if config.qco_enable: if config.qco_method == "light": for circuit in run_input: self.qc_opt.optimize_light(circuit) elif config.qco_method == "greedy": for circuit in run_input: self.qc_opt.optimize(circuit, config.qco_max_block_size) # Create quantum states states = [state_class(circuit.get_qubit_count()) for circuit in run_input] # Submit job job_id = str(uuid.uuid4()) qulacs_job = QulacsJob( self, job_id, self._execute_circuits_job, circuits=run_input, states=states, run_options=config, ) qulacs_job.submit() return qulacs_job
https://github.com/bertolinocastro/quantum-computing-algorithms
bertolinocastro
# A Quantum Circuit to Construct All Maximal Cliques Using Grover’s Search Algorithm ## Chu Ryang Wie ### DOI: https://arxiv.org/abs/1711.06146v2 import matplotlib #matplotlib.use('Agg') import matplotlib.pyplot as plt from qiskit import * # IBMQ.load_account() from qiskit.visualization import * n = 3 # size of network psi = QuantumRegister(n, name='psi') # cliques states data = QuantumRegister(n**2, name='data') # data A+I states ancl = QuantumRegister(n**2, name='ancl') # ancilla states cpsi = ClassicalRegister(n, name='cpsi') # classical register for measurement cdata = ClassicalRegister(n**2, name='cdata') # classical register for measurement cancl = ClassicalRegister(n**2, name='cancl') # classical register for measurement #extra_ancl = QuantumRegister(n**2, name='extra_ancl') qc = QuantumCircuit(psi, data, ancl, cpsi, cdata, cancl, name='maximal cliques') import numpy as np A = np.array([ # creating adjacency matrix [0,1,0], [1,0,1], [0,1,0] ], dtype=np.int) AI = A+ np.eye(n, dtype=np.int) # setting network structure on data qubits for ij, cij in enumerate(AI.flatten()): if cij: qc.x(data[ij]) # putting cliques on uniform superposition for j in range(n): qc.h(psi[j]) def V(): for j in range(n): for i in range(n): # applying 'intersect operator' as defined in paper qc.barrier() # standard toffoli qc.ccx(psi[j], data[j*n+i], ancl[j*n+i]) # toffoli variant - 1st ctrl qbit works when 0 qc.x(psi[j]) qc.ccx(psi[j], data[j*n+i], ancl[j*n+i]) # toffoli variant - 1st & 2nd ctrl qbit work when 0 qc.x(data[j*n+i]) qc.ccx(psi[j], data[j*n+i], ancl[j*n+i]) # undoing NOT operations qc.x(psi[j]) qc.x(data[j*n+i]) def W(): for j in range(n): # trying to use multi-controlled toffoli gate available in qiskit (not sure if it works) #qc.mct(ancl[j::n], psi[j], extra_ancl) #QuantumCircuit.mct(q_controls, q_target, q_ancilla, mode='basic') qc.barrier() qc.mct(ancl[j::n], psi[j], None, mode='noancilla') def flip_ket_0(): for j in range(n): qc.x(psi[j]) qc.h(psi[n-1]) qc.barrier() qc.mct(psi[:-1], psi[-1], None, mode='noancilla') qc.barrier() qc.h(psi[n-1]) for j in range(n): qc.x(psi[j]) def O(): qc.barrier() V() qc.barrier() W() qc.barrier() flip_ket_0() qc.barrier() W() qc.barrier() V() def G(): qc.barrier() for j in range(n): qc.h(psi[j]) qc.barrier() for j in range(n): qc.x(psi[j]) qc.barrier() qc.h(psi[-1]) qc.barrier() qc.mct(psi[:-1],psi[-1],None,mode='noancilla') qc.barrier() qc.h(psi[-1]) qc.barrier() for j in range(n): qc.x(psi[j]) qc.barrier() for j in range(n): qc.h(psi[j]) O() G() qc.barrier() qc.measure(psi, cpsi) qc.measure(data, cdata) qc.measure(ancl, cancl) fig = circuit_drawer(qc, output='mpl', filename='circuit.pdf', fold=300) #fig res = execute(qc, Aer.get_backend('qasm_simulator'), shots=4096).result() print(res) print(res.get_counts()) plot_histogram(res.get_counts()) # Running on IBMQ Experience # saving account credentials first #IBMQ.save_account('MY_TOKEN_ID') # loading IBMQ session provider = IBMQ.load_account() backend = provider.backends(simulator=True,operational=True)[0] res = execute(qc, backend, shots=8192).result() plot_histogram(res.get_counts()) # TODO: create circuit for n=2 network and test it on melbourne qpu.
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.problems.second_quantization.lattice.lattices import LineLattice from qiskit_nature.problems.second_quantization.lattice.models import FermiHubbardModel line = LineLattice(2) fermi = FermiHubbardModel.uniform_parameters(line, 2.0, 4.0, 3.0) print(fermi.second_q_ops()) # Note: the trailing `s` from qiskit_nature.second_q.hamiltonians.lattices import LineLattice from qiskit_nature.second_q.hamiltonians import FermiHubbardModel line = LineLattice(2) fermi = FermiHubbardModel(line.uniform_parameters(2.0, 4.0), 3.0) print(fermi.second_q_op()) # Note: NO trailing `s` import numpy as np from qiskit_nature.problems.second_quantization.lattice.models import FermiHubbardModel interaction = np.array([[4.0, 2.0], [2.0, 4.0]]) fermi = FermiHubbardModel.from_parameters(interaction, 3.0) print(fermi.second_q_ops()) # Note: the trailing `s` import numpy as np from qiskit_nature.second_q.hamiltonians.lattices import Lattice from qiskit_nature.second_q.hamiltonians import FermiHubbardModel interaction = np.array([[4.0, 2.0], [2.0, 4.0]]) lattice = Lattice.from_adjacency_matrix(interaction) fermi = FermiHubbardModel(lattice, 3.0) print(fermi.second_q_op()) # Note: NO trailing `s` from qiskit_nature.problems.second_quantization.lattice.lattices import LineLattice from qiskit_nature.problems.second_quantization.lattice.models import IsingModel line = LineLattice(2) ising = IsingModel.uniform_parameters(line, 2.0, 4.0) print(ising.second_q_ops()) # Note: the trailing `s` from qiskit_nature.second_q.hamiltonians.lattices import LineLattice from qiskit_nature.second_q.hamiltonians import IsingModel line = LineLattice(2) ising = IsingModel(line.uniform_parameters(2.0, 4.0)) print(ising.second_q_op()) # Note: NO trailing `s` import numpy as np from qiskit_nature.problems.second_quantization.lattice.models import IsingModel interaction = np.array([[4.0, 2.0], [2.0, 4.0]]) ising = IsingModel.from_parameters(interaction) print(ising.second_q_ops()) # Note: the trailing `s` import numpy as np from qiskit_nature.second_q.hamiltonians.lattices import Lattice from qiskit_nature.second_q.hamiltonians import IsingModel interaction = np.array([[4.0, 2.0], [2.0, 4.0]]) lattice = Lattice.from_adjacency_matrix(interaction) ising = IsingModel(lattice) print(ising.second_q_op()) # Note: NO trailing `s` import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/TRSasasusu/qiskit-quantum-zoo
TRSasasusu
from typing import Optional import math import numpy as np import matplotlib.pyplot as plt from sympy import gcdex from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, assemble from qiskit.visualization import plot_histogram from sympy import Rational, gcdex from sympy.ntheory.continued_fraction import continued_fraction, continued_fraction_convergents from qft import qft from elementary import ax_modM from order_finding import order_finding from classical_utils import decode_bin def discrete_log(a: int, b: int, p: int, show_hist: Optional[bool] = False, coef_t: Optional[int] = 1) -> int: """Shor's discrete log algorithm: given $a,b,p\in\mathbb{Z}$, it finds $s$ such that $a^s\equiv b\pmod p$. Args: a (int): $a$ b (int): $b$ p (int): $p$ """ r = order_finding(x=a, N=p, show_hist=False) t = coef_t * int(np.ceil(np.log2(p))) first_register = QuantumRegister(t) second_register = QuantumRegister(t) third_register = QuantumRegister(2 * t) auxiliary_register_mid = QuantumRegister(t) auxiliary_register_end = QuantumRegister(6 * t - 2) classical_register = ClassicalRegister(2 * t) qc = QuantumCircuit( first_register, second_register, third_register, auxiliary_register_mid, auxiliary_register_end, classical_register, ) qc.h(first_register) qc.h(second_register) qc.append(ax_modM(a=b, M=p, N_len=t), list(first_register) + list(auxiliary_register_mid) + list(third_register) + list(auxiliary_register_end)) qc.append(ax_modM(a=a, M=p, N_len=t, x_0_at_first=False), list(second_register) + list(auxiliary_register_mid) + list(third_register) + list(auxiliary_register_end)) qc.append(qft(n=t).inverse(), first_register) qc.append(qft(n=t).inverse(), second_register) qc.measure(list(first_register) + list(second_register), classical_register) #qc.measure(third_register, classical_register) backend = Aer.get_backend('aer_simulator_matrix_product_state')#('aer_simulator') qc = transpile(qc, backend) job = backend.run(qc, shots=10000) hist = job.result().get_counts() if show_hist: figsize_x = max(7 * (len(hist) // 8), 7) plot_histogram(hist, figsize=(figsize_x, 5)) plt.savefig(f'img/discrete_log_a{a}_b{b}_p{p}_r{r}_t{t}.png', bbox_inches='tight') for measured_key, _ in sorted(hist.items(), key=lambda x: x[1], reverse=True): tilde_l_per_r = Rational(decode_bin(measured_key[:t]), 2 ** t) # decoded from second register: $\widetilde{l/r}$ if tilde_l_per_r == 0: continue l = None for fraction in continued_fraction_convergents(continued_fraction(tilde_l_per_r)): if fraction.denominator == r: l = fraction.numerator # get correct $l$ break if l is None: continue tilde_beta_per_r = Rational(decode_bin(measured_key[-t:]), 2 ** t) # decoded from first register: $\widetilde{\beta/r}$ if tilde_beta_per_r == 0: if pow(a, 0, p) == b: # the case where b == 1 return r # returning 0 is also ok continue beta = None for fraction in continued_fraction_convergents(continued_fraction(tilde_beta_per_r)): if fraction.denominator == r: beta = fraction.numerator # get correct $\beta$ break if beta is None: continue s, alpha, _ = gcdex(l, -r) s = int(s * beta) if pow(a, s, p) == b: return s raise Exception('s is NOT found!') if __name__ == '__main__': #print(discrete_log(a=2, b=4, p=7, show_hist=True)) #print(discrete_log(a=3, b=5, p=11, show_hist=True, coef_t=2)) print(discrete_log(a=2, b=1, p=3, show_hist=True, coef_t=1))
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
PavanCyborg
import matplotlib.pyplot as plt import numpy as np from qiskit import QuantumCircuit, Aer, execute, transpile, assemble, QuantumRegister, ClassicalRegister from qiskit.visualization import plot_histogram def binary(num,length): #converts an integer to a binary number with defined length b = bin(num)[2:] return "0"*(length-len(b))+str(b) ncon = 4 controlreg = QuantumRegister(ncon,"control") hreg = QuantumRegister(1,"y") cc = ClassicalRegister(ncon,"cc") #xi = np.random.randint(0,2**ncon-1) #xi as in the greek letter xi = 7 R = int(np.pi/4*np.sqrt(2**ncon)) qc = QuantumCircuit(controlreg,hreg,cc) def Uf(controlreg,hreg,xi,ncon): #the oracle gate, a multi=controlled x gate which is one iff the input = xi hcirc = QuantumCircuit(hreg) circ = QuantumCircuit(controlreg,hreg) xiBin = binary(xi,ncon) zerolist = [i for i in range(ncon) if (xiBin[i] == "0")] circ.x(zerolist) circ.mct(list(range(ncon)),ncon) circ.x(zerolist) circ.name = "Uf" return circ def ccz(controls=2): #multi controlled Z gate (decomposed here as a multi controlled X with H gates placed either side) circ = QuantumCircuit(controls+1) circ.h(controls) circ.mct(list(range(controls)),[controls]) circ.h(controls) circ.name = "c"*controls+"z" return circ def diffusion(ncon): #https://rdcu.be/cLzsq circ = QuantumCircuit(ncon) circ.h(range(ncon)) circ.x(range(ncon)) circ.append(ccz(ncon-1),list(range(ncon))) circ.barrier() circ.x(range(ncon)) circ.h(range(ncon)) circ.name = "Diffusion" return circ Ufgate = Uf(controlreg,hreg,xi,ncon) qc.x(hreg[0]) qc.h(hreg[0]) qc.h(range(ncon)) for e in range(R): qc.barrier() qc.append(Ufgate,controlreg[:]+hreg[:]) qc.barrier() qc.append(diffusion(ncon).decompose(),controlreg[:ncon]) qc.barrier() qc.measure([controlreg[i] for i in range(ncon-1,-1,-1)],cc,) print(xi) qc.draw(plot_barriers=False,fold = -1,output = "latex") ?aersim aersim = Aer.get_backend('aer_simulator') #set memory=True to see measurements tqc = transpile(qc,aersim) results = aersim.run(tqc,shots=10000).result() plot_histogram(results.get_counts()) aersim = Aer.get_backend('aer_simulator') #set memory=True to see measurements tqc = transpile(qc,aersim) results = aersim.run(tqc,shots=10000).result() d = results.get_counts() oldkeys = list(d.keys()) for key in oldkeys: d[str(int(key,2))] = d[key] del d[key] x = np.arange(0,2**ncon-1,1) y = np.zeros(len(x)) for i,xi in enumerate(x): if str(xi) in d.keys(): y[i] = d[str(xi)] plt.xlim(-1,2**ncon) plt.bar(x,y,color=(0.4,0.6,1)) controlreg,hreg = QuantumRegister(4,"control"),QuantumRegister(1,"y") xi = 7 hcirc = QuantumCircuit(hreg) circ = QuantumCircuit(controlreg,hreg) xiBin = binary(xi,ncon) zerolist = [i for i in range(ncon) if (xiBin[i] == "0")] circ.x(zerolist) circ.mct(list(range(ncon)),ncon) circ.x(zerolist) circ.name = "Uf" circ.draw(output="latex") circ = QuantumCircuit(ncon) circ.h(range(ncon)) circ.x(range(ncon)) circ.h(ncon-1) circ.mct(list(range(ncon-1)),[ncon-1]) circ.h(ncon-1) circ.barrier() circ.x(range(ncon)) circ.h(range(ncon)) circ.name = "Diffusion" circ.draw(output="latex",plot_barriers=False) from qiskit import IBMQ IBMQ.enable_account("") provider = IBMQ.get_provider(hub='ibm-q') provider.backends() backend = provider.get_backend("ibmq_quito") res = backend.retrieve_job("622a012c9e029c54a90deedc").result() plot_histogram(res.get_counts()) nbits = 4 d = res.get_counts() oldkeys = list(d.keys()) for key in oldkeys: d[str(int(key,2))] = d[key] del d[key] x = list(range(0,7))+list(range(8,16)) xi, yi = 7,d["7"]/10000 del d["7"] y = [d[str(xi)]/10000 for xi in x] plt.xlim(-1,15.9) plt.bar(x,y,color=(0.4,0.6,1)) plt.bar(xi,yi,color=(1,0,0)) plt.ylabel("Probability") plt.xlabel("x")
https://github.com/henotrix/quantum-practice
henotrix
from qiskit import * from oracle_generation import generate_oracle get_bin = lambda x, n: format(x, 'b').zfill(n) def gen_circuits(min,max,size): circuits = [] secrets = [] ORACLE_SIZE = size for i in range(min,max+1): cur_str = get_bin(i,ORACLE_SIZE-1) (circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str) circuits.append(circuit) secrets.append(secret) return (circuits, secrets)
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np import hhl_components as cmp import matplotlib.pyplot as plt from qiskit import QuantumCircuit from qiskit import Aer, execute from qiskit.visualization import plot_histogram # Initialize parameters t0 = 2 * np.pi r = 6 A = [[3.75, 2.25, 1.25, -0.75], [2.25, 3.75, 0.75, -1.25], [1.25, 0.75, 3.75, -2.25], [-0.75, -1.25, -2.25, 3.75]] b = [0.5, 0.5, 0.5, 0.5] x = [-0.0312, 0.2188, 0.3437, 0.4062] p = [i ** 2 for i in x] basis = ['00', '01', '10', '11'] # Build circuit circ = QuantumCircuit(7, 3) circ.initialize(b, range(2)) circ.append(cmp.ad_hoc_hhl(A, t0, r), range(7)) circ.measure(6, 2) circ.measure([0, 1], [0, 1]) # Get simulators qasm = Aer.get_backend('qasm_simulator') svsm = Aer.get_backend('statevector_simulator') # QASM simulation job = execute(circ, qasm, shots=1024) counts = job.result().get_counts() measured_data = {} expected_data = {basis[i]: np.floor(p[i] * 1024) for i in range(4)} for key in counts.keys(): if key[0] == '1': measured_data[key[1::]] = counts[key] plot_histogram([expected_data, measured_data], title='HHL QASM Simulation', legend=['expected', 'measured']) plt.subplots_adjust(left=0.15, right=0.72, top=0.9, bottom=0.15) plt.show()
https://github.com/qiskit-community/qiskit-hackathon-korea-22
qiskit-community
from qiskit_nature.problems.sampling.protein_folding.interactions.random_interaction import ( RandomInteraction, ) from qiskit_nature.problems.sampling.protein_folding.interactions.miyazawa_jernigan_interaction import ( MiyazawaJerniganInteraction, ) from qiskit_nature.problems.sampling.protein_folding.peptide.peptide import Peptide from qiskit_nature.problems.sampling.protein_folding.protein_folding_problem import ( ProteinFoldingProblem, ) from qiskit_nature.problems.sampling.protein_folding.penalty_parameters import PenaltyParameters from qiskit.utils import algorithm_globals, QuantumInstance algorithm_globals.random_seed = 23 main_chain = "APRLRFY" side_chains = [""] * 7 random_interaction = RandomInteraction() mj_interaction = MiyazawaJerniganInteraction() penalty_back = 10 penalty_chiral = 10 penalty_1 = 10 penalty_terms = PenaltyParameters(penalty_chiral, penalty_back, penalty_1) peptide = Peptide(main_chain, side_chains) protein_folding_problem = ProteinFoldingProblem(peptide, mj_interaction, penalty_terms) qubit_op = protein_folding_problem.qubit_op() from qiskit.circuit.library import RealAmplitudes from qiskit.algorithms.optimizers import COBYLA from qiskit.algorithms import NumPyMinimumEigensolver, VQE from qiskit.opflow import PauliExpectation, CVaRExpectation from qiskit import execute, Aer # set classical optimizer optimizer = COBYLA(maxiter=50) # set variational ansatz ansatz = RealAmplitudes(reps=1) # set the backend backend_name = "aer_simulator" backend = QuantumInstance( Aer.get_backend(backend_name), shots=8192, seed_transpiler=algorithm_globals.random_seed, seed_simulator=algorithm_globals.random_seed, ) counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) # initialize CVaR_alpha objective with alpha = 0.1 cvar_exp = CVaRExpectation(0.1, PauliExpectation()) # initialize VQE using CVaR vqe = VQE( expectation=cvar_exp, optimizer=optimizer, ansatz=ansatz, quantum_instance=backend, callback=store_intermediate_result, ) result = vqe.compute_minimum_eigenvalue(qubit_op) print(result) import matplotlib.pyplot as plt fig = plt.figure() plt.plot(counts, values) plt.ylabel("Conformation Energy") plt.xlabel("VQE Iterations") fig.add_axes([0.44, 0.51, 0.44, 0.32]) plt.plot(counts[40:], values[40:]) plt.ylabel("Conformation Energy") plt.xlabel("VQE Iterations") plt.show() main_chain = "APRLRFDR" side_chains = [""] * 8 random_interaction = RandomInteraction() mj_interaction = MiyazawaJerniganInteraction() penalty_back = 10 penalty_chiral = 10 penalty_1 = 10 penalty_terms = PenaltyParameters(penalty_chiral, penalty_back, penalty_1) peptide = Peptide(main_chain, side_chains) protein_folding_problem = ProteinFoldingProblem(peptide, mj_interaction, penalty_terms) qubit_op = protein_folding_problem.qubit_op() "from qiskit.circuit.library import [INSERT YOUR OWN ANSATZ]" from qiskit.circuit.library import RealAmplitudes "from qiskit.algorithms.optimizers import [INSERT YOUR OWN OPTIMIZER]" from qiskit.algorithms.optimizers import COBYLA from qiskit.algorithms import NumPyMinimumEigensolver, VQE from qiskit.opflow import PauliExpectation, CVaRExpectation from qiskit import execute, Aer # set classical optimizer start """ 1. Choose your optimizer Note that you have to import optimizer. """ "optimizer = [INSERT YOUR OWN OPTIMIZER]" optimizer = COBYLA(maxiter=100) # set classical optimizer end # set variational ansatz start """ 2. Choose your ansatz Note that you have to import ansatz. """ "ansatz = [INSERT YOUR OWN ANSATZ]" ansatz = RealAmplitudes(reps=1) # set variational ansatz end # set the backend backend_name = "aer_simulator" backend = QuantumInstance( Aer.get_backend(backend_name), shots=8192, seed_transpiler=algorithm_globals.random_seed, seed_simulator=algorithm_globals.random_seed, ) counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) # initialize CVaR_alpha objective with alpha = 0.1 cvar_exp = CVaRExpectation(0.1, PauliExpectation()) # initialize VQE using CVaR vqe = VQE( expectation=cvar_exp, optimizer=optimizer, ansatz=ansatz, quantum_instance=backend, callback=store_intermediate_result, ) result = vqe.compute_minimum_eigenvalue(qubit_op) print(result) import matplotlib.pyplot as plt fig = plt.figure() plt.plot(counts, values) plt.ylabel("Conformation Energy") plt.xlabel("VQE Iterations") fig.add_axes([0.44, 0.51, 0.44, 0.32]) plt.plot(counts[40:], values[40:]) plt.ylabel("Conformation Energy") plt.xlabel("VQE Iterations") plt.show() print( "Result:", values[-1] )
https://github.com/daimurat/qiskit-implementation
daimurat
import numpy as np import matplotlib.pyplot as plt %matplotlib notebook from qiskit import QuantumCircuit from qiskit.circuit import Parameter def generate_2qubit_qnn(label): circuit = QuantumCircuit(2) circuit.ry(np.pi / 4.0, 0) circuit.ry(np.pi / 4.0, 1) circuit.barrier() for i in range(2): if label[i] == 'x': circuit.rx(Parameter('theta'+str(i)), i) elif label[i] == 'y': circuit.ry(Parameter('theta'+str(i)), i) elif label[i] == 'z': circuit.rz(Parameter('theta'+str(i)), i) circuit.barrier() # Add CZ ladder. circuit.cz(0, 1) return circuit qc_test = generate_2qubit_qnn('xy') qc_test.draw('mpl') # 期待値の計算 from qiskit import Aer from qiskit.utils import QuantumInstance from qiskit.opflow import CircuitSampler, StateFn, PauliSumOp from qiskit.opflow.expectations import PauliExpectation hamiltonian = PauliSumOp.from_list([('X', 1.0)]) expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(qc_test) aerpauli_basis = PauliExpectation().convert(expectation) quantum_instance = QuantumInstance(Aer.get_backend('qasm_simulator'), shots = 32768) sampler = CircuitSampler(quantum_instance) # 期待値の評価 def calculate_exp_val(params): value_dict = dict(zip(qc_test.parameters, params)) result = sampler.convert(aerpauli_basis, params=value_dict).eval() return np.real(result) X = np.linspace(0, 2*np.pi, 30) Y = np.linspace(0, 2*np.pi, 30) Z = np.array([[calculate_exp_val([x, y]) for x in X] for y in Y]).reshape(len(Y), len(X)) xx, yy = np.meshgrid(X, Y) fig = plt.figure() ax = fig.add_subplot(projection="3d") ax.plot_surface(xx, yy, Z, cmap=plt.cm.jet) ax.set_xlabel('theta_1') ax.set_ylabel('theta_2') ax.set_zlabel('loss') plt.show() from qiskit.opflow import Gradient gradient = Gradient().convert(expectation) gradient_in_pauli_basis = PauliExpectation().convert(gradient) # 勾配の評価 def calculate_gradient(params): value_dict = dict(zip(qc_test.parameters, params)) result = sampler.convert(gradient_in_pauli_basis, params=value_dict).eval() return np.real(result) from qiskit.opflow import NaturalGradient ng = NaturalGradient().convert(expectation) ng_in_pauli_basis = PauliExpectation().convert(ng) def calculate_natural_gradient(params): value_dict = dict(zip(qc_test.parameters, params)) result = sampler.convert(ng_in_pauli_basis, params=value_dict).eval() return np.real(result) initial_point = np.array([np.pi, np.pi]) from qiskit.algorithms.optimizers import GradientDescent gd_loss= [] xx_op= [] yy_op= [] def gd_callback(nfevs, x, fx, stepsize): gd_loss.append(fx) xx_op.append(x[0]) yy_op.append(x[1]) gd = GradientDescent(maxiter=50,learning_rate=0.1, callback=gd_callback) x_opt, fx_opt, nfevs = ( gd.optimize(initial_point.size, calculate_exp_val, gradient_function=calculate_gradient, initial_point=initial_point) ) ngd_loss= [] xx_op_ng= [] yy_op_ng= [] def ngd_callback(nfevs, x, fx, stepsize): ngd_loss.append(fx) xx_op_ng.append(x[0]) yy_op_ng.append(x[1]) qng = GradientDescent(maxiter=50,learning_rate=0.1, callback=ngd_callback) x_opt_ng, fx_opt_ng, nfevs_ng = ( qng.optimize(initial_point.size, calculate_exp_val, gradient_function=calculate_natural_gradient, initial_point=initial_point) ) from matplotlib.animation import FuncAnimation fig = plt.figure() ax = fig.add_subplot(projection="3d") ax.plot_surface(xx, yy, Z, cmap=plt.cm.jet, alpha=0.6) gd, = ax.plot([], [], [], '.-k', label='vanilla gradient descent') ngd, = ax.plot([], [], [], '.-r', label='natural gradient descent') ax.set_xlabel('theta_1') ax.set_ylabel('theta_2') ax.set_zlabel('loss') def update(f): gd.set_data(xx_op[:f], yy_op[:f]) gd.set_3d_properties(gd_loss[:f]) ngd.set_data(xx_op_ng[:f], yy_op_ng[:f]) ngd.set_3d_properties(ngd_loss[:f]) anim = FuncAnimation(fig, update, interval=200) plt.legend(loc='upper left') plt.show() anim.save("ngd.gif") import qiskit.tools.jupyter %qiskit_version_table
https://github.com/Cryoris/surfer
Cryoris
"""The QFI interface. Avoids using the plain name QFI since that exists in Qiskit and I want to avoid conflicts. """ from typing import List, Optional from abc import ABC, abstractmethod import qiskit import numpy as np class QFICalculator(ABC): """The QFI interface.""" def __init__(self, do_checks: bool = True): """ Args: do_checks: Do some sanity checks on the inputs. Can be disabled for performance. """ self.do_checks = do_checks @abstractmethod def compute( self, circuit: qiskit.QuantumCircuit, values: np.ndarray, parameters: Optional[List[qiskit.circuit.Parameter]] = None, ) -> np.ndarray: """Compute the QFI for the given circuit. The initial state is assumed to be the all-zero state. Args: circuit: A parameterized unitary circuit preparing the quantum state of which we compute the QFI. values: The parameter values. """ raise NotImplementedError @staticmethod def check_inputs( circuit: qiskit.QuantumCircuit, values: np.ndarray, ) -> None: """Check the circuit and values. Args: circuit: A parameterized unitary circuit preparing the quantum state of which we compute the QFI. values: The parameter values. Raises: ValueError: If the circuit is invalid (non unitary or gates with more than 1 parameter). ValueError: If the number of values doesn't match the parameters. NotImplementedError: If the circuit has repeated parameters. """ _check_circuit_is_unitay(circuit) # _check_1_parameter_per_gate(circuit) # check the number of parameters if circuit.num_parameters != values.size: raise ValueError( f"Mismatching number of parameters ({circuit.num_parameters}) " f"and values ({values.size})." ) # _check_no_duplicate_params(circuit) def _check_circuit_is_unitay(circuit): try: _ = circuit.to_gate() except qiskit.circuit.exceptions.CircuitError: # pylint: disable=raise-missing-from raise ValueError("The circuit is not unitary.") def _check_1_parameter_per_gate(circuit): for inst, _, _ in circuit.data: params = inst.params if ( any( isinstance(param, qiskit.circuit.ParameterExpression) for param in params ) and len(params) > 1 ): raise ValueError( "If a gate is parameterized, it can only have 1 parameter." ) def _check_no_duplicate_params(circuit): # pylint: disable=protected-access for _, gates in circuit._parameter_table.items(): if len(gates) > 1: raise NotImplementedError( "The product rule is currently not implemented, parameters must be unique." )
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/quantum-kittens/quantum-computing-basics
quantum-kittens
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Additional libraries from qiskit import QuantumRegister, ClassicalRegister from qiskit.providers.ibmq import least_busy from qiskit.tools import job_monitor from qiskit import execute # Loading your IBM Quantum account(s) provider = IBMQ.load_account() #code taken from https://qiskit.org/documentation/intro_tutorial1.html # Identify backend: Use Aer's qasm_simulator simulator = QasmSimulator() # Create a quantum circuit with 2 qubits and 2 classical bits circuit = QuantumCircuit(2, 2) # Add a H gate on qubit 0 circuit.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1 circuit.cx(0, 1) # Map the quantum measurements to the classical bits circuit.measure([0,1], [0,1]) # compile the circuit down to low-level QASM instructions # supported by the backend (not needed for simple circuits) compiled_circuit = transpile(circuit, simulator) # Execute the circuit on the qasm simulator job = simulator.run(compiled_circuit, shots=1000) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(compiled_circuit) print("\nTotal count for 00 and 11 are:",counts) # Draw the circuit circuit.draw() # See what providers are available to you IBMQ.providers() # Get your provider and see which backends are available to you provider = IBMQ.get_provider('ibm-q-internal') # comment this if you don't have access to internal systems #provider = IBMQ.get_provider('ibm-q') # publically accessible provider, open-access for backend in provider.backends(): print(backend) # Find which real devices are eligible to run your circuit eligible_devices = provider.backends(filters=lambda x:x.configuration().n_qubits>1 and not x.configuration().simulator) for backend in eligible_devices: print(backend) # Select the least busy backend chosen_backend = least_busy(eligible_devices) print(chosen_backend.name()) # Run and monitor the job compiled_circuit = transpile(circuit, chosen_backend) job = chosen_backend.run(compiled_circuit, shots = 1000) job_monitor(job) # Check the results job_id = job.job_id() retrieved_job = chosen_backend.retrieve_job(job_id) result = retrieved_job.result() counts_real = result.get_counts() # If currently unable to run, can use the following result from real devices # counts_real = {'00': 476, '01': 15, '10': 18, '11': 491} # example result from a real quantum computer # Print both real and sim results print("Your backend is:") print(chosen_backend) print("Your job ID is:") print(job_id) print() print("The counts from the real device are:") print(counts_real) print() print("The counts from the simulator are:") print(counts) # Plot the results title = 'Real vs. Simulated' legend = ['Real Counts', 'Sim Counts'] plot_histogram([counts_real, counts], legend = legend, title = title, color = ['teal', 'purple'], bar_labels = False) # NOT operation using the simulator simulator = QasmSimulator() for i in ['0','1']: # Prepare circuit qreg = QuantumRegister(1, name = 'q_reg') creg = ClassicalRegister(1, name = 'c_reg') not_circ = QuantumCircuit(qreg,creg) # Initialize qubit state if i == '1': not_circ.x(0) not_circ.barrier() # Apply NOT operation not_circ.x(qreg[0]) # this is where you replace 'which' not_circ.barrier() # Measure not_circ.measure(qreg[0],creg[0]) display(not_circ.draw('mpl')) job = simulator.run(not_circ, shots=1000) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(not_circ) print('The result when the qubit is initialized in state ', i,' is:', max(counts))
https://github.com/xtophe388/QISKIT
xtophe388
import qiskit qiskit.__qiskit_version__ # useful additional packages import numpy as np import matplotlib.pyplot as plt %matplotlib inline # importing Qiskit from qiskit import BasicAer, IBMQ from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.compiler import transpile from qiskit.tools.monitor import job_monitor # import basic plot tools from qiskit.tools.visualization import plot_histogram # Load our saved IBMQ accounts IBMQ.load_account() n = 13 # the length of the first register for querying the oracle # Choose a type of oracle at random. With probability half it is constant, # and with the same probability it is balanced oracleType, oracleValue = np.random.randint(2), np.random.randint(2) if oracleType == 0: print("The oracle returns a constant value ", oracleValue) else: print("The oracle returns a balanced function") a = np.random.randint(1,2**n) # this is a hidden parameter for balanced oracle. # Creating registers # n qubits for querying the oracle and one qubit for storing the answer qr = QuantumRegister(n+1) #all qubits are initialized to zero # for recording the measurement on the first register cr = ClassicalRegister(n) circuitName = "DeutschJozsa" djCircuit = QuantumCircuit(qr, cr) # Create the superposition of all input queries in the first register by applying the Hadamard gate to each qubit. for i in range(n): djCircuit.h(qr[i]) # Flip the second register and apply the Hadamard gate. djCircuit.x(qr[n]) djCircuit.h(qr[n]) # Apply barrier to mark the beginning of the oracle djCircuit.barrier() if oracleType == 0:#If the oracleType is "0", the oracle returns oracleValue for all input. if oracleValue == 1: djCircuit.x(qr[n]) else: djCircuit.iden(qr[n]) else: # Otherwise, it returns the inner product of the input with a (non-zero bitstring) for i in range(n): if (a & (1 << i)): djCircuit.cx(qr[i], qr[n]) # Apply barrier to mark the end of the oracle djCircuit.barrier() # Apply Hadamard gates after querying the oracle for i in range(n): djCircuit.h(qr[i]) # Measurement djCircuit.barrier() for i in range(n): djCircuit.measure(qr[i], cr[i]) #draw the circuit djCircuit.draw(output='mpl',scale=0.5) backend = BasicAer.get_backend('qasm_simulator') shots = 1000 job = execute(djCircuit, backend=backend, shots=shots) results = job.result() answer = results.get_counts() plot_histogram(answer) backend = IBMQ.get_backend('ibmq_16_melbourne') djCompiled = transpile(djCircuit, backend=backend, optimization_level=1) djCompiled.draw(output='mpl',scale=0.5) job = execute(djCompiled, backend=backend, shots=1024) job_monitor(job) results = job.result() answer = results.get_counts() threshold = int(0.01 * shots) # the threshold of plotting significant measurements filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} # filter the answer for better view of plots removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) # number of counts removed filteredAnswer['other_bitstrings'] = removedCounts # the removed counts are assigned to a new index plot_histogram(filteredAnswer) print(filteredAnswer)
https://github.com/sayana25/IQCQ-UPES-2023
sayana25
pip install qiskit pip install qiskit-ibm-runtime pip install pylatexenc import qiskit from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister,execute,IBMQ, assemble, Aer from qiskit.visualization import plot_histogram, plot_bloch_vector from math import sqrt, pi #qc = QuantumCircuit(1) # Create a quantum circuit with one qubit qc = QuantumCircuit(1) # Create a quantum circuit with one qubit initial_state = [0,1] # Define initial_state as |1> qc.initialize(initial_state, 0) # Apply initialisation operation to the 0th qubit qc.draw() # Let's view our circuit qc = QuantumCircuit(3,3) # Create a quantum circuit with 3 qubits, like in python qc.h(0) #hadamard gate qc.x(1) #Pauli-X gate qc.y(2) #Pauli-Y gate qc.draw() # Let's view our circuit
https://github.com/nahumsa/volta
nahumsa
# 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 qiskit from qiskit import QuantumCircuit, execute from qiskit.utils import QuantumInstance from qiskit.providers import BaseBackend from typing import Union import textwrap def swap_test_circuit(qc1: QuantumCircuit, qc2: QuantumCircuit) -> QuantumCircuit: """Construct the SWAP test circuit given two circuits. Args: qc1(qiskit.QuantumCircuit): Quantum circuit for the first state. qc2(qiskit.QuantumCircuit): Quantum circuit for the second state. Output: (qiskit.QuantumCircuit): swap test circuit. """ # Helper variables n_total = qc1.num_qubits + qc2.num_qubits range_qc1 = [i + 1 for i in range(qc1.num_qubits)] range_qc2 = [i + qc1.num_qubits + 1 for i in range(qc2.num_qubits)] # Constructing the SWAP test circuit qc_swap = QuantumCircuit(n_total + 1, 1) qc_swap.append(qc1, range_qc1) qc_swap.append(qc2, range_qc2) # Swap Test qc_swap.h(0) for index, qubit in enumerate(range_qc1): qc_swap.cswap(0, qubit, range_qc2[index]) qc_swap.h(0) # Measurement on the auxiliary qubit qc_swap.measure(0, 0) return qc_swap def measure_swap_test( qc1: QuantumCircuit, qc2: QuantumCircuit, backend: Union[BaseBackend, QuantumInstance], num_shots: int = 10000, ) -> float: """Returns the fidelity from a SWAP test. Args: qc1 (QuantumCircuit): Quantum Circuit for the first state. qc2 (QuantumCircuit): Quantum Circuit for the second state. backend (Union[BaseBackend,QuantumInstance]): Backend. num_shots (int, optional): Number of shots. Defaults to 10000. Returns: float: result of the overlap betweeen the first and second state. """ swap_circuit = swap_test_circuit(qc1, qc2) # Check if the backend is a quantum instance. if qiskit.utils.quantum_instance.QuantumInstance == type(backend): count = backend.execute(swap_circuit).get_counts() else: count = ( execute(swap_circuit, backend=backend, shots=num_shots) .result() .get_counts() ) if "0" not in count: count["0"] = 0 if "1" not in count: count["1"] = 0 total_counts = count["0"] + count["1"] fid_meas = count["0"] p_0 = fid_meas / total_counts return 2 * (p_0 - 1 / 2) def dswap_test_circuit(qc1: QuantumCircuit, qc2: QuantumCircuit) -> QuantumCircuit: """Construct the destructive SWAP test circuit given two circuits. Args: qc1(qiskit.QuantumCircuit): Quantum circuit for the first state. qc2(qiskit.QuantumCircuit): Quantum circuit for the second state. Output: (qiskit.QuantumCircuit): swap test circuit. """ # Helper variables n_total = qc1.num_qubits + qc2.num_qubits range_qc1 = [i for i in range(qc1.num_qubits)] range_qc2 = [i + qc1.num_qubits for i in range(qc2.num_qubits)] # Constructing the SWAP test circuit qc_swap = QuantumCircuit(n_total, n_total) qc_swap.append(qc1, range_qc1) qc_swap.append(qc2, range_qc2) for index, qubit in enumerate(range_qc1): qc_swap.cx(qubit, range_qc2[index]) qc_swap.h(qubit) for index, qubit in enumerate(range_qc1): qc_swap.measure(qubit, 2 * index) for index, qubit in enumerate(range_qc2): qc_swap.measure(range_qc2[index], 2 * index + 1) return qc_swap def measure_dswap_test( qc1: QuantumCircuit, qc2: QuantumCircuit, backend: Union[BaseBackend, QuantumInstance], num_shots: int = 10000, ) -> float: """Returns the fidelity from a destructive SWAP test. Args: qc1 (QuantumCircuit): Quantum Circuit for the first state. qc2 (QuantumCircuit): Quantum Circuit for the second state. backend (Union[BaseBackend,QuantumInstance]): Backend. num_shots (int, optional): Number of shots. Defaults to 10000. Returns: float: result of the overlap betweeen the first and second state. """ n = qc1.num_qubits swap_circuit = dswap_test_circuit(qc1, qc2) # Check if the backend is a quantum instance. if qiskit.utils.quantum_instance.QuantumInstance == type(backend): count = backend.execute(swap_circuit).get_counts() else: count = ( execute(swap_circuit, backend=backend, shots=num_shots) .result() .get_counts() ) result = 0 for meas, counts in count.items(): split_meas = textwrap.wrap(meas, 2) for m in split_meas: if m == "11": result -= counts else: result += counts total = sum(count.values()) return result / (n * total) def amplitude_transition_test_circuit( qc1: QuantumCircuit, qc2: QuantumCircuit ) -> QuantumCircuit: """Construct the SWAP test circuit given two circuits using amplitude transition. Args: qc1(qiskit.QuantumCircuit): Quantum circuit for the first state. qc2(qiskit.QuantumCircuit): Quantum circuit for the second state. Output: (qiskit.QuantumCircuit): swap test circuit. """ # Constructing the SWAP test circuit n_qubits = qc1.num_qubits qc_swap = QuantumCircuit(n_qubits) qc_swap.append(qc1, range(n_qubits)) qc_swap.append(qc2.inverse(), range(n_qubits)) # Measurement on the auxiliary qubit qc_swap.measure_all() return qc_swap def measure_amplitude_transition_test( qc1: QuantumCircuit, qc2: QuantumCircuit, backend, num_shots: int = 10000, ) -> float: """Returns the fidelity from a SWAP test using amplitude transition. Args: qc1 (QuantumCircuit): Quantum Circuit for the first state. qc2 (QuantumCircuit): Quantum Circuit for the second state. backend (Union[BaseBackend,QuantumInstance]): Backend. num_shots (int, optional): Number of shots. Defaults to 10000. Returns: float: result of the overlap betweeen the first and second state. """ swap_circuit = amplitude_transition_test_circuit(qc1, qc2) # Check if the backend is a quantum instance. if qiskit.utils.quantum_instance.QuantumInstance == type(backend): count = backend.execute(swap_circuit).get_counts() else: count = ( execute(swap_circuit, backend=backend, shots=num_shots) .result() .get_counts() ) if "0" * qc1.num_qubits not in count: count["0" * qc1.num_qubits] = 0 total_counts = sum(count.values()) fid_meas = count["0" * qc1.num_qubits] p_0 = fid_meas / total_counts return p_0
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit_aer import AerSimulator from qiskit.tools.visualization import plot_histogram import random circ = QuantumCircuit(40, 40) # Initialize with a Hadamard layer circ.h(range(40)) # Apply some random CNOT and T gates qubit_indices = [i for i in range(40)] for i in range(10): control, target, t = random.sample(qubit_indices, 3) circ.cx(control, target) circ.t(t) circ.measure(range(40), range(40)) # Create statevector method simulator statevector_simulator = AerSimulator(method='statevector') # Transpile circuit for backend tcirc = transpile(circ, statevector_simulator) # Try and run circuit statevector_result = statevector_simulator.run(tcirc, shots=1).result() print('This succeeded?: {}'.format(statevector_result.success)) print('Why not? {}'.format(statevector_result.status)) # Create extended stabilizer method simulator extended_stabilizer_simulator = AerSimulator(method='extended_stabilizer') # Transpile circuit for backend tcirc = transpile(circ, extended_stabilizer_simulator) extended_stabilizer_result = extended_stabilizer_simulator.run(tcirc, shots=1).result() print('This succeeded?: {}'.format(extended_stabilizer_result.success)) small_circ = QuantumCircuit(2, 2) small_circ.h(0) small_circ.cx(0, 1) small_circ.t(0) small_circ.measure([0, 1], [0, 1]) # This circuit should give 00 or 11 with equal probability... expected_results ={'00': 50, '11': 50} tsmall_circ = transpile(small_circ, extended_stabilizer_simulator) result = extended_stabilizer_simulator.run( tsmall_circ, shots=100).result() counts = result.get_counts(0) print('100 shots in {}s'.format(result.time_taken)) plot_histogram([expected_results, counts], legend=['Expected', 'Extended Stabilizer']) # Add runtime options for extended stabilizer simulator opts = {'extended_stabilizer_approximation_error': 0.03} reduced_error = extended_stabilizer_simulator.run( tsmall_circ, shots=100, **opts).result() reduced_error_counts = reduced_error.get_counts(0) print('100 shots in {}s'.format(reduced_error.time_taken)) plot_histogram([expected_results, reduced_error_counts], legend=['Expected', 'Extended Stabilizer']) print("The circuit above, with 100 shots at precision 0.03 " "and default mixing time, needed {}s".format(int(reduced_error.time_taken))) opts = { 'extended_stabilizer_approximation_error': 0.03, 'extended_stabilizer_mixing_time': 100 } optimized = extended_stabilizer_simulator.run( tsmall_circ, shots=100, **opts).result() print('Dialing down the mixing time, we completed in just {}s'.format(optimized.time_taken)) # We set these options here only to make the example run more quickly. opts = {'extended_stabilizer_mixing_time': 100} multishot = extended_stabilizer_simulator.run( tcirc, shots=100, **opts).result() print("100 shots took {} s".format(multishot.time_taken)) opts = { 'extended_stabilizer_measure_sampling': True, 'extended_stabilizer_mixing_time': 100 } measure_sampling = extended_stabilizer_simulator.run( circ, shots=100, **opts).result() print("With the optimization, 100 shots took {} s".format(result.time_taken)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/anpaschool/qiskit-toolkit
anpaschool
import numpy as np import IPython import ipywidgets as widgets import colorsys import matplotlib.pyplot as plt from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister from qiskit import execute, Aer, BasicAer from qiskit.visualization import plot_bloch_multivector from qiskit.tools.jupyter import * from qiskit.visualization import * import os import glob import moviepy.editor as mpy import seaborn as sns sns.set() '''========State Vector=======''' def getStateVector(qc): '''get state vector in row matrix form''' backend = BasicAer.get_backend('statevector_simulator') job = execute(qc,backend).result() vec = job.get_statevector(qc) return vec def vec_in_braket(vec: np.ndarray) -> str: '''get bra-ket notation of vector''' nqubits = int(np.log2(len(vec))) state = '' for i in range(len(vec)): rounded = round(vec[i], 3) if rounded != 0: basis = format(i, 'b').zfill(nqubits) state += np.str(rounded).replace('-0j', '+0j') state += '|' + basis + '\\rangle + ' state = state.replace("j", "i") return state[0:-2].strip() def vec_in_text_braket(vec): return '$$\\text{{State:\n $|\\Psi\\rangle = $}}{}$$'\ .format(vec_in_braket(vec)) def writeStateVector(vec): return widgets.HTMLMath(vec_in_text_braket(vec)) '''==========Bloch Sphere =========''' def getBlochSphere(qc): '''plot multi qubit bloch sphere''' vec = getStateVector(qc) return plot_bloch_multivector(vec) def getBlochSequence(path,figs): '''plot block sphere sequence and save it to a folder for gif movie creation''' try: os.mkdir(path) except: print('Directory already exist') for i,fig in enumerate(figs): fig.savefig(path+"/rot_"+str(i)+".png") return def getBlochGif(figs,path,fname,fps,remove = True): '''create gif movie from provided images''' file_list = glob.glob(path + "/*.png") list.sort(file_list, key=lambda x: int(x.split('_')[1].split('.png')[0])) clip = mpy.ImageSequenceClip(file_list, fps=fps) clip.write_gif('{}.gif'.format(fname), fps=fps) '''remove all image files after gif creation''' if remove: for file in file_list: os.remove(file) return '''=========Matrix=================''' def getMatrix(qc): '''get numpy matrix representing a circuit''' backend = BasicAer.get_backend('unitary_simulator') job = execute(qc, backend) ndArray = job.result().get_unitary(qc, decimals=3) Matrix = np.matrix(ndArray) return Matrix def plotMatrix(M): '''visualize a matrix using seaborn heatmap''' MD = [["0" for i in range(M.shape[0])] for j in range(M.shape[1])] for i in range(M.shape[0]): for j in range(M.shape[1]): r = M[i,j].real im = M[i,j].imag MD[i][j] = str(r)[0:4]+ " , " +str(im)[0:4] plt.figure(figsize = [2*M.shape[1],M.shape[0]]) sns.heatmap(np.abs(M),\ annot = np.array(MD),\ fmt = '',linewidths=.5,\ cmap='Blues') return '''=========Measurement========''' def getCount(qc): backend= Aer.get_backend('qasm_simulator') result = execute(qc,backend).result() counts = result.get_counts(qc) return counts def plotCount(counts,figsize): plot_histogram(counts) '''========Phase============''' def getPhaseCircle(vec): '''get phase color, angle and radious of phase circir''' Phase = [] for i in range(len(vec)): angles = (np.angle(vec[i]) + (np.pi * 4)) % (np.pi * 2) rgb = colorsys.hls_to_rgb(angles / (np.pi * 2), 0.5, 0.5) mag = np.abs(vec[i]) Phase.append({"rgb":rgb,"mag": mag,"ang":angles}) return Phase def getPhaseDict(QCs): '''get a dictionary of state vector phase circles for each quantum circuit and populate phaseDict list''' phaseDict = [] for qc in QCs: vec = getStateVector(qc) Phase = getPhaseCircle(vec) phaseDict.append(Phase) return phaseDict def plotiPhaseCircle(phaseDict,depth,path,show=False,save=False): '''plot any quantum circuit phase circle diagram from provided phase Dictionary''' r = 0.30 dx = 1.0 nqubit = len(phaseDict[0]) fig = plt.figure(figsize = [depth,nqubit]) for i in range(depth): x0 = i for j in range(nqubit): y0 = j+1 try: mag = phaseDict[i][j]['mag'] ang = phaseDict[i][j]['ang'] rgb = phaseDict[i][j]['rgb'] ax=plt.gca() circle1= plt.Circle((dx+x0,y0), radius = r, color = 'white') ax.add_patch(circle1) circle2= plt.Circle((dx+x0,y0), radius= r*mag, color = rgb) ax.add_patch(circle2) line = plt.plot((dx+x0,dx+x0+(r*mag*np.cos(ang))),\ (y0,y0+(r*mag*np.sin(ang))),color = "black") except: ax=plt.gca() circle1= plt.Circle((dx+x0,y0), radius = r, color = 'white') ax.add_patch(circle1) plt.ylim(nqubit+1,0) plt.yticks([y+1 for y in range(nqubit)]) plt.xticks([x for x in range(depth+2)]) plt.xlabel("Circuit Depth") plt.ylabel("Basis States") if show: plt.show() plt.savefig(path+".png") plt.close(fig) if save: plt.savefig(path +".png") plt.close(fig) return def plotiPhaseCircle_rotated(phaseDict,depth,path,show=False,save=False): '''plot any quantum circuit phase circle diagram from provided phase Dictionary''' r = 0.30 dy = 1.0 nqubit = len(phaseDict[0]) fig = plt.figure(figsize = [nqubit,depth]) for i in range(depth): y0 = i for j in range(nqubit): x0 = j+1 try: mag = phaseDict[i][j]['mag'] ang = phaseDict[i][j]['ang'] rgb = phaseDict[i][j]['rgb'] ax=plt.gca() circle1= plt.Circle((x0,dy+y0), radius = r, color = 'white') ax.add_patch(circle1) circle2= plt.Circle((x0,dy+y0), radius= r*mag, color = rgb) ax.add_patch(circle2) line = plt.plot((x0,x0+(r*mag*np.cos(ang))),\ (dy+y0,dy+y0+(r*mag*np.sin(ang))),color = "black") except: ax=plt.gca() circle1= plt.Circle((x0,dy+y0), radius = r, color = 'white') ax.add_patch(circle1) plt.ylim(0,depth+1) plt.yticks([x+1 for x in range(depth)]) plt.xticks([y for y in range(nqubit+2)]) plt.ylabel("Circuit Depth") plt.xlabel("Basis States") if show: plt.show() plt.savefig(path+".png") plt.close(fig) if save: plt.savefig(path +".png") plt.close(fig) return def getPhaseSequence(QCs,path,rotated=False): '''plot a sequence of phase circle diagram for a given sequence of quantum circuits''' try: os.mkdir(path) except: print("Directory already exist") depth = len(QCs) phaseDict =[] for i,qc in enumerate(QCs): vec = getStateVector(qc) Phase = getPhaseCircle(vec) phaseDict.append(Phase) ipath = path + "phase_" + str(i) if rotated: plotiPhaseCircle_rotated(phaseDict,depth,ipath,save=True,show=False) else: plotiPhaseCircle(phaseDict,depth,ipath,save=True,show=False) return def getPhaseGif(path,fname,fps,remove = True): '''create a gif movie file from phase circle figures''' file_list = glob.glob(path+ "/*.png") list.sort(file_list, key=lambda x: int(x.split('_')[1].split('.png')[0])) clip = mpy.ImageSequenceClip(file_list, fps=fps) clip.write_gif('{}.gif'.format(fname), fps=fps) '''remove all image files after gif creation''' if remove: for file in file_list: os.remove(file) return
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
from qiskit import QuantumCircuit from qiskit.primitives import Sampler, Estimator from qiskit.visualization import plot_histogram, plot_bloch_multivector qc = QuantumCircuit(3) # Apply H-gate to each qubit: for i in range(3): qc.h(i) # See the circuit: qc.draw('mpl') # Let's see the result from qiskit.quantum_info import Statevector state = Statevector.from_instruction(qc) plot_bloch_multivector(state) qc.draw('mpl') from qiskit.visualization import array_to_latex array_to_latex(state, prefix="\\text{Statevector} = ") qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.draw('mpl') # You can similar get a unitary matrix representing the circuit as an operator by passing it to the Operator default constructor from qiskit.quantum_info import Operator operator = Operator(qc) print(operator.data) # In Jupyter Notebooks we can display this nicely using Latex. # If not using Jupyter Notebooks you may need to remove the # array_to_latex function and use print(unitary) instead. from qiskit.visualization import array_to_latex array_to_latex(operator.data, prefix="\\text{Circuit = }\n") qc = QuantumCircuit(2) qc.x(1) qc.draw('mpl') # Simulate the unitary unitary = Operator(qc).data # Display the results: array_to_latex(unitary, prefix="\\text{Circuit = } ") qc = QuantumCircuit(2) # appkt the cnot gate qc.cx(0,1) # the first number represent the control qubit and the second qubit represent the target qubit # draw it qc.draw('mpl') # Simulate the unitary unitary = Operator(qc).data # Display the results: array_to_latex(unitary, prefix="\\text{Circuit = } ") qc = QuantumCircuit(2) # appkt the cnot gate qc.cx(1,0) # the first number represent the control qubit and the second qubit represent the target qubit # draw it qc.draw('mpl') # Simulate the unitary unitary = Operator(qc).data # Display the results: array_to_latex(unitary, prefix="\\text{Circuit = } ") qc = QuantumCircuit(2) # Apply H-gate to the first: qc.h(0) qc.draw('mpl') # Let's see the result: final_state = Statevector.from_instruction(qc) # Print the statevector neatly: array_to_latex(final_state, prefix="\\text{Statevector = }") qc = QuantumCircuit(2) # Apply H-gate to the first: qc.h(0) # Apply a CNOT: qc.cx(0,1) qc.draw('mpl') # Let's get the result:f final_state = Statevector.from_instruction(qc) array_to_latex(final_state, prefix="\\text{Statevector = }") qc.measure_all() qc.draw('mpl') result = sampler.run(qc).result() counts = result.quasi_dists[0] plot_histogram(counts) plot_bloch_multivector(final_state) from qiskit.visualization import plot_state_qsphere plot_state_qsphere(final_state)
https://github.com/qiskit-community/qiskit-device-benchmarking
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2024. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Analyze the fast_count results """ import argparse import numpy as np import qiskit_device_benchmarking.utilities.file_utils as fu import matplotlib.pyplot as plt def generate_plot(out_data, degree_data, args): """Generate a bar plot of the qubit numbers of each backend Generates a plot of the name count_plot_<XXX>.pdf where XXX is the current date and time Args: out_data: data from the run (count data) degree_data: average degree args: arguments passed to the parser Returns: None """ count_data = np.array([out_data[i] for i in out_data]) degree_data = np.array([degree_data[i] for i in out_data]) backend_lbls = np.array([i for i in out_data]) sortinds = np.argsort(count_data) plt.bar(backend_lbls[sortinds], count_data[sortinds]) plt.xticks(rotation=45, ha='right') ax1 = plt.gca() ax2 = ax1.twinx() ax2.plot(range(len(sortinds)),degree_data[sortinds],marker='x', color='black') plt.xlabel('Backend') plt.grid(axis='y') ax1.set_ylabel('Largest Connected Region') ax2.set_ylabel('Average Degree') plt.title('CHSH Test on Each Edge to Determine Qubit Count') plt.savefig('count_plot_%s.pdf'%fu.timestamp_name(),bbox_inches='tight') plt.close() return if __name__ == '__main__': """Analyze a benchmarking run from `fast_bench.py` Args: Call -h for arguments """ parser = argparse.ArgumentParser(description = 'Analyze the results of a ' + 'benchmarking run.') parser.add_argument('-f', '--files', help='Comma separated list of files') parser.add_argument('-b', '--backends', help='Comma separated list of ' + 'backends to plot. If empty plot all.') parser.add_argument('--plot', help='Generate a plot', action='store_true') args = parser.parse_args() #import from results files and concatenate into a larger results results_dict = {} for file in args.files.split(','): results_dict_new = fu.import_yaml(file) for backend in results_dict_new: if backend not in results_dict: results_dict[backend] = results_dict_new[backend] elif backend!='config': #backend in the results dict but maybe not that depth err_str = 'Backend %s already exists, duplicate results'%(backend) raise ValueError(err_str) if args.backends is not None: backends_filt = args.backends.split(',') else: backends_filt = [] count_data = {} degree_data = {} for backend in results_dict: if len(backends_filt)>0: if backend not in backends_filt: continue if backend=='config': continue count_data[backend] = results_dict[backend]['largest_region'] degree_data[backend] = results_dict[backend]['average_degree'] print('Backend %s, Largest Connected Region: %d'%(backend,count_data[backend])) print('Backend %s, Average Degree: %f'%(backend,degree_data[backend])) if args.plot: generate_plot(count_data, degree_data, args) elif args.plot: print('Need to run mean/max also')
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. # This file is part of QuTiP: Quantum Toolbox in Python. # # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names # of its contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ############################################################################### """ Routines for running Python functions in parallel using process pools from the multiprocessing library. """ import os from concurrent.futures import ProcessPoolExecutor import sys from qiskit.exceptions import QiskitError from qiskit.utils.multiprocessing import local_hardware_info from qiskit.tools.events.pubsub import Publisher from qiskit import user_config def get_platform_parallel_default(): """ Returns the default parallelism flag value for the current platform. Returns: parallel_default: The default parallelism flag value for the current platform. """ # Default False on Windows if sys.platform == "win32": parallel_default = False # On macOS default false on Python >=3.8 elif sys.platform == "darwin": parallel_default = False # On linux (and other OSes) default to True else: parallel_default = True return parallel_default CONFIG = user_config.get_config() if os.getenv("QISKIT_PARALLEL", None) is not None: PARALLEL_DEFAULT = os.getenv("QISKIT_PARALLEL", None).lower() == "true" else: PARALLEL_DEFAULT = get_platform_parallel_default() # Set parallel flag if os.getenv("QISKIT_IN_PARALLEL") is None: os.environ["QISKIT_IN_PARALLEL"] = "FALSE" if os.getenv("QISKIT_NUM_PROCS") is not None: CPU_COUNT = int(os.getenv("QISKIT_NUM_PROCS")) else: CPU_COUNT = CONFIG.get("num_process", local_hardware_info()["cpus"]) def _task_wrapper(param): (task, value, task_args, task_kwargs) = param return task(value, *task_args, **task_kwargs) def parallel_map( # pylint: disable=dangerous-default-value task, values, task_args=(), task_kwargs={}, num_processes=CPU_COUNT ): """ Parallel execution of a mapping of `values` to the function `task`. This is functionally equivalent to:: result = [task(value, *task_args, **task_kwargs) for value in values] On Windows this function defaults to a serial implementation to avoid the overhead from spawning processes in Windows. Args: task (func): Function that is to be called for each value in ``values``. values (array_like): List or array of values for which the ``task`` function is to be evaluated. task_args (list): Optional additional arguments to the ``task`` function. task_kwargs (dict): Optional additional keyword argument to the ``task`` function. num_processes (int): Number of processes to spawn. Returns: result: The result list contains the value of ``task(value, *task_args, **task_kwargs)`` for each value in ``values``. Raises: QiskitError: If user interrupts via keyboard. Events: terra.parallel.start: The collection of parallel tasks are about to start. terra.parallel.update: One of the parallel task has finished. terra.parallel.finish: All the parallel tasks have finished. Examples: .. code-block:: python import time from qiskit.tools.parallel import parallel_map def func(_): time.sleep(0.1) return 0 parallel_map(func, list(range(10))); """ if len(values) == 0: return [] if len(values) == 1: return [task(values[0], *task_args, **task_kwargs)] Publisher().publish("terra.parallel.start", len(values)) nfinished = [0] def _callback(_): nfinished[0] += 1 Publisher().publish("terra.parallel.done", nfinished[0]) # Run in parallel if not Win and not in parallel already if ( num_processes > 1 and os.getenv("QISKIT_IN_PARALLEL") == "FALSE" and CONFIG.get("parallel_enabled", PARALLEL_DEFAULT) ): os.environ["QISKIT_IN_PARALLEL"] = "TRUE" try: results = [] with ProcessPoolExecutor(max_workers=num_processes) as executor: param = ((task, value, task_args, task_kwargs) for value in values) future = executor.map(_task_wrapper, param) results = list(future) Publisher().publish("terra.parallel.done", len(results)) except (KeyboardInterrupt, Exception) as error: if isinstance(error, KeyboardInterrupt): Publisher().publish("terra.parallel.finish") os.environ["QISKIT_IN_PARALLEL"] = "FALSE" raise QiskitError("Keyboard interrupt in parallel_map.") from error # Otherwise just reset parallel flag and error os.environ["QISKIT_IN_PARALLEL"] = "FALSE" raise error Publisher().publish("terra.parallel.finish") os.environ["QISKIT_IN_PARALLEL"] = "FALSE" return results # Cannot do parallel on Windows , if another parallel_map is running in parallel, # or len(values) == 1. results = [] for _, value in enumerate(values): result = task(value, *task_args, **task_kwargs) results.append(result) _callback(0) Publisher().publish("terra.parallel.finish") return results
https://github.com/Qiskit/feedback
Qiskit
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.compiler import transpile from qiskit.circuit.random import random_circuit from qiskit_aer import AerSimulator qc = random_circuit(16, 3, measure=True) backend = AerSimulator() t_qc = transpile(qc, backend, optimization_level=3, init_method='qubit_reuse') t_qc_original = transpile(qc, backend, optimization_level=3) # For comparison later qc.draw('mpl', fold=-1) t_qc.draw('mpl', fold=-1) from qiskit.quantum_info import hellinger_fidelity counts_normal = backend.run(t_qc_original, shots=2**12).result().get_counts() counts_reduced = backend.run(t_qc, shots=2**12).result().get_counts() hellinger_fidelity(counts_normal, counts_reduced) def build_bv_circuit(secret_string): input_size = len(secret_string) num_qubits = input_size + 1 qr = QuantumRegister(num_qubits) cr = ClassicalRegister(input_size) qc = QuantumCircuit(qr, cr, name="main") qc.x(qr[input_size]) qc.h(qr) qc.barrier() for i_qubit in range(input_size): if secret_string[input_size - 1 - i_qubit] == "1": qc.cx(qr[i_qubit], qr[input_size]) qc.barrier() qc.h(qr) qc.x(qr[input_size]) qc.barrier() qc.measure(qr[:-1], cr) return qc secret = 5871 secret_string = format(secret, f"0b") qc = build_bv_circuit(secret_string=secret_string) qc.draw('mpl', fold=-1) t_qc = transpile(qc, backend, optimization_level=3, init_method='qubit_reuse') t_qc_original = transpile(qc, backend, optimization_level=3) # For comparison later t_qc.draw('mpl', fold=-1) counts_normal = backend.run(t_qc_original, shots=2**12).result().get_counts() counts_reduced = backend.run(t_qc, shots=2**12).result().get_counts() print(counts_normal, counts_reduced) hellinger_fidelity(counts_normal, counts_reduced) # Matrix Product State generator from qiskit.circuit.library import RealAmplitudes def MPS(num_qubits, **kwargs): """ Constructs a Matrix Product State (MPS) quantum circuit. Args: num_qubits (int): The number of qubits in the circuit. **kwargs: Additional keyword arguments to be passed to the RealAmplitudes. Returns: QuantumCircuit: The constructed MPS quantum circuit. """ qc = QuantumCircuit(num_qubits) qubits = range(num_qubits) print(len(list(zip(qubits[:-1], qubits[1:])))) # Iterate over adjacent qubit pairs for i, j in zip(qubits[:-1], qubits[1:]): qc.compose(RealAmplitudes(num_qubits=2, parameter_prefix=f'θ_{i},{j}', **kwargs), [i, j], inplace=True) qc.barrier( ) # Add a barrier after each block for clarity and separation return qc # Tree tuples generator def _generate_tree_tuples(n): """ Generate a list of tuples representing the tree structure of consecutive numbers up to n. Args: n (int): The number up to which the tuples are generated. Returns: list: A list of tuples representing the tree structure. """ tuples_list = [] indices = [] # Generate initial tuples with consecutive numbers up to n for i in range(0, n, 2): tuples_list.append((i, i + 1)) indices += [tuples_list] # Perform iterations until we reach a single tuple while len(tuples_list) > 1: new_tuples = [] # Generate new tuples by combining adjacent larger numbers for i in range(0, len(tuples_list), 2): new_tuples.append((tuples_list[i][1], tuples_list[i + 1][1])) tuples_list = new_tuples indices += [tuples_list] return indices # Tree Tensor Network Generator def TTN(num_qubits, **kwargs): """ Constructs a Tree Tensor Network (TTN) quantum circuit. Args: num_qubits (int): The number of qubits in the circuit. **kwargs: Additional keyword arguments to be passed to the RealAmplitudes. Returns: QuantumCircuit: The constructed TTN quantum circuit. Raises: AssertionError: If the number of qubits is not a power of 2 or zero. """ qc = QuantumCircuit(num_qubits) qubits = range(num_qubits) # Compute qubit indices assert num_qubits & ( num_qubits - 1) == 0 and num_qubits != 0, "Number of qubits must be a power of 2" indices = _generate_tree_tuples(num_qubits) # Iterate over each layer of TTN indices for layer_indices in indices: for i, j in layer_indices: qc.compose(RealAmplitudes(num_qubits=2, parameter_prefix=f'θ_{i},{j}', **kwargs), [i, j], inplace=True) qc.barrier( ) # Add a barrier after each layer for clarity and separation return qc import numpy as np qc = TTN(2**3) qc.measure_all() params = {param: np.pi/(2**((index%3)+1)) for index, param in enumerate(qc.parameters)} qc = qc.bind_parameters(params) qc.draw('mpl', fold=-1) t_qc = transpile(qc, backend, optimization_level=3, init_method='qubit_reuse') t_qc_original = transpile(qc, backend, optimization_level=3) # For comparison later t_qc = transpile(qc, backend, optimization_level=3, init_method='qubit_reuse') t_qc_original = transpile(qc, backend, optimization_level=3) # For comparison later t_qc.draw('mpl', fold=-1) counts_normal = backend.run(t_qc_original, shots=2**12).result().get_counts() counts_reduced = backend.run(t_qc, shots=2**12).result().get_counts() # print(counts_normal, counts_reduced) hellinger_fidelity(counts_normal, counts_reduced)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) depths = [] gate_counts = [] non_local_gate_counts = [] levels = [str(x) for x in range(4)] for level in range(4): circ = transpile(ghz, backend, optimization_level=level) depths.append(circ.depth()) gate_counts.append(sum(circ.count_ops().values())) non_local_gate_counts.append(circ.num_nonlocal_gates()) fig, (ax1, ax2) = plt.subplots(2, 1) ax1.bar(levels, depths, label='Depth') ax1.set_xlabel("Optimization Level") ax1.set_ylabel("Depth") ax1.set_title("Output Circuit Depth") ax2.bar(levels, gate_counts, label='Number of Circuit Operations') ax2.bar(levels, non_local_gate_counts, label='Number of non-local gates') ax2.set_xlabel("Optimization Level") ax2.set_ylabel("Number of gates") ax2.legend() ax2.set_title("Number of output circuit gates") fig.tight_layout() plt.show()
https://github.com/Victor1128/shor-qiskit
Victor1128
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/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import * from qiskit.quantum_info import Statevector from math import pi from qiskit.visualization import * qc=QuantumCircuit(1) qc.x(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Pauli-X gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.x(0) qc.x(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Pauli-X gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.y(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Pauli-Y gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.x(0) qc.y(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Pauli-Y gate print(result.get_unitary(qc, decimals=3)) state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(1) qc.z(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Pauli-Z gate print(result.get_unitary(qc, decimals=3)) state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(1) qc.z(0) qc.draw(output="mpl") qc=QuantumCircuit(1) qc.x(0) qc.z(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Pauli-Z gate print(result.get_unitary(qc, decimals=3)) state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(1) qc.h(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Hadamard gate print(result.get_unitary(qc, decimals=3)) state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(1) qc.x(0) qc.h(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Hadamard gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.s(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for S gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.x(0) qc.s(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for S gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.s(0) qc.s(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for S dagger gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.sdg(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Sdg gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.x(0) qc.sdg(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Sdg gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.sdg(0) qc.sdg(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Sdg gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.t(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for T gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.x(0) qc.t(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for T gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.tdg(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Tdg gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.x(0) qc.tdg(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Tdg gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.tdg(0) qc.tdg(0) qc.tdg(0) qc.tdg(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Tdg gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.z(0) backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Tdg gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.p(pi,0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for P gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.p(pi/2,0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for P gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.p(pi/4,0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for P gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.x(0) qc.p(pi,0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for P gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.x(0) qc.p(pi/2,0) qc.draw(output="mpl") qc=QuantumCircuit(1) qc.x(0) qc.p(pi/4,0) qc.draw(output="mpl") qc=QuantumCircuit(1) qc.p(0,0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for P gate print(result.get_unitary(qc, decimals=3)) I=result.get_unitary(qc, decimals=3) array_to_latex(I)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import math # importing Qiskit from qiskit import Aer, IBMQ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute from qiskit.backends.ibmq import least_busy # useful additional packages from qiskit.wrapper.jupyter import * from qiskit.tools.visualization import plot_histogram IBMQ.load_accounts() def input_state(circ, q, n): """n-qubit input state for QFT that produces output 1.""" for j in range(n): circ.h(q[j]) circ.u1(math.pi/float(2**(j)), q[j]).inverse() def qft(circ, q, n): """n-qubit QFT on q in circ.""" for j in range(n): for k in range(j): circ.cu1(math.pi/float(2**(j-k)), q[j], q[k]) circ.h(q[j]) q = QuantumRegister(3) c = ClassicalRegister(3) qft3 = QuantumCircuit(q, c) input_state(qft3, q, 3) qft(qft3, q, 3) for i in range(3): qft3.measure(q[i], c[i]) print(qft3.qasm()) # run on local simulator backend = Aer.get_backend("qasm_simulator") simulate = execute(qft3, backend=backend, shots=1024).result() simulate.get_counts() %%qiskit_job_status # Use the IBM Quantum Experience backend = least_busy(IBMQ.backends(simulator=False)) shots = 1024 job_exp = execute(qft3, backend=backend, shots=shots) results = job_exp.result() plot_histogram(results.get_counts())
https://github.com/conradhaupt/Qiskit-Bayesian-Inference-Module-QCA19-
conradhaupt
# Import major packages import qiskit as qk import qinfer as qf import numpy as np import matplotlib as mpl # Qiskit imports for IQPE from qiskit import IBMQ from qiskit.aqua.algorithms.single_sample import IQPE,QPE from qiskit.aqua.components import iqfts from qiskit.aqua.operators import WeightedPauliOperator from qiskit.aqua.algorithms import ExactEigensolver from qiskit.aqua.components.initial_states import Custom from qiskit import Aer,execute from qiskit.aqua import QuantumInstance from qiskit.providers.aer import noise # QInfer imports for modelling the IQPE algorithm from qinfer import distributions from qinfer.smc import SMCUpdater # The QInfer Sequantial Monte-Carlo Sampler from qinfer import FiniteOutcomeModel # Tertiary imports import matplotlib.pyplot as plt import time # Intial setup IBMQ.load_account() ibmqx_provider = IBMQ.get_provider(hub='ibm-q-wits', group='internal', project='default') mpl.rc('text', usetex=True) # Function definitions for the entire notebook EPS = 1e-15 def chop(value): if np.abs(value) <= EPS: return 0 else: return value def radiandiff(a,b): FULL_ROTATION = 2 * np.pi return np.min(np.abs([a - b, b - a, a - b + FULL_ROTATION, b - a + FULL_ROTATION])) def complexfromangle(angle): real = chop(np.real(np.exp(1.j * angle))) imag = chop(np.imag(np.exp(1.j * angle))) return real,imag # Set-up unitary with specified phase angle = 4 * np.pi / 5 real,imag = complexfromangle(angle) PAULI_DICT_ZZ = { 'paulis': [ {"coeff": {"imag": imag, "real": real}, "label": "ZZ"} ] } QUBIT_OP_ZZ = WeightedPauliOperator.from_dict(PAULI_DICT_ZZ) eigen_results = ExactEigensolver(QUBIT_OP_ZZ,4).run() eigen_value = eigen_results['eigvals'][0] eigen_vector = eigen_results['eigvecs'][0] print('Eigenvalues',eigen_results['eigvals']) print('Phase is %.4f radians' %(angle)) # Setup initial state as eigenvector state_in = Custom(QUBIT_OP_ZZ.num_qubits, state_vector=eigen_vector) # Use QASM Simulator for testing simulator = Aer.get_backend('qasm_simulator') # Construct IQPE circuit and simulate iqpe_builder = IQPE( QUBIT_OP_ZZ, state_in, num_iterations=1, num_time_slices=1, expansion_mode='suzuki', expansion_order=1, shallow_circuit_concat=True) # This is required to setup iqpe_builder so we can call construct_circuit() later on iqpe_results = iqpe_circ = iqpe_builder.run(simulator,shots=1) # Extend the QInfer FiniteOutcomeModel as IQPE has only one bit per measure class IQPEModel(FiniteOutcomeModel): def __init__(self): super(IQPEModel, self).__init__() # Number of parameters overwhich to conduct the Bayesian Inference @property def n_modelparams(self): # phi return 1 # Number of parameters that are needed for the simulation but are known. # i.e. do not need to be inferred @property def expparams_dtype(self): return [('theta','float64'), ('m','int64')] @property def is_n_outcomes_constant(self): return True # This function will verify whether the new inferred model parameters are valid for our model. @staticmethod def are_models_valid(modelparams): # NOTE: If T2 is included as a model parameter, restrict it to positive return np.logical_and(modelparams[:] >= -2*np.pi, modelparams[:]<=2*np.pi, modelparams[:] > 0).all(axis=1) def n_outcomes(self, expparams): return 2 # This function implements our probability for reading a 0 or 1 on our IQPE circuit. # These equations are taken from [1] and are used by the updater/sampler to modify the posterior def likelihood(self, outcomes, modelparams, expparams): super(IQPEModel, self).likelihood(outcomes, modelparams, expparams) # Probability of getting 0 for IQPE is # P(0) = (1 + cos(M(theta - phi)))/2 # P(1) = (1 - cos(M(theta - phi)))/2 # This is the probability of getting a 0 with T2 depolarisation noise from [1]. # Not currently used. # pr0 = np.exp(-expparams['m'] / expparams['T2']) * (1 + np.cos(expparams['m'] * (expparams['theta'] - modelparams[:]))) / 2 + (1 - np.exp(-expparams['m'] / expparams['T2']))/2 pr0 = (1 + np.cos(expparams['m'] * (expparams['theta'] - modelparams[:]))) / 2 return FiniteOutcomeModel.pr0_to_likelihood_array(outcomes, pr0) # As our model parameter is an angle, ensure we have the circular mean for the distribution so we allow # for wraparound. This is done by converting angles to x,y points on a unit circle, averaging over # x and y independently, and then combining the resulting average x and y values to create a new # vector. If the resulting magnitude is 0, there is no circular average as all points are equi-distant. # The resulting angle is approximately the circular average of the collection of angles/phases. class PhaseSMCUpdater(SMCUpdater): @staticmethod def particle_mean(weights,locations): locs = [complexfromangle(a) for a in locations.flatten()] loc_x = [] loc_y = [] for x,y in locs: loc_x.append(x) loc_y.append(y) avg_x = np.average(loc_x,weights=weights) avg_y = np.average(loc_y,weights=weights) avg_angle = np.angle(avg_x + 1.j*avg_y) avg_mag = np.sqrt(avg_x**2 + avg_y**2) return avg_angle # Bayesien Inference Parameters N_PARTICLES = 5000 # number of samples for PhaseSMCUpdater N_EXP = 25 # Number of times to choose a new theta USE_QISKIT_QASM_SIMULATOR = True # Toggle parameter if we don't want to run any circuit simulations SIM_N_SHOTS=1024 # number of shots for the circuit execution # DType list for experiment metric logging performance_dtype = [ ('outcome', 'i1'), ('est_mean', 'f8'), ('est_cov_mat', 'f8'), ('true_err', 'f8'), ('resample_count', 'i8'), ('elapsed_time', 'f8'), ('like_count', 'i8'), ('sim_count', 'i8'), ('bme', 'f8'), ('var', 'f8'), ('bme_err', 'f8') ] performance = np.empty((N_EXP), dtype=performance_dtype) # Set-up initial prior and QInfer model # prior = distributions.UniformDistribution([0, 2 * np.pi]) prior = distributions.NormalDistribution(angle,np.pi/4) model = IQPEModel() # Use IBMQX Rochester as the base device for the partially ideal noise-model. We backend_device = ibmqx_provider.get_backend('ibmq_rochester') partially_ideal_model = noise.device.basic_device_noise_model( backend_device.properties(),gate_error=False,readout_error=False, thermal_relaxation=False,standard_gates=True) data_backend = Aer.get_backend('qasm_simulator') # Create a Bayesian Inference Updater updater = PhaseSMCUpdater(model, N_PARTICLES, prior,zero_weight_policy='skip') # Set-up initial experimental parameters THETA = prior.sample()[0][0] M = 1 T2 = 100 posterior_marginal = [] memory_list = [] theta_list = [] ############################################## # Run for each experiment we defined earlier # ############################################## for idx_exp in range(N_EXP): # Define experimental parameters expparams = np.array([(M,THETA)], dtype=model.expparams_dtype) # Simulate IQPE circuit and get results for inference circuit = iqpe_builder.construct_circuit(k=M,omega=THETA,measurement=True) results = execute(circuit,simulator,shots=SIM_N_SHOTS,memory=True,noise_model=ideal_model) counts = results.result().get_counts() memory = results.result().get_memory() memory_list.append(memory) theta_list.append(THETA.flatten()) # Start by simulating and recording the data. # # Retrieve the outcome of the simulation either from the circuit simulation or a model simulation if USE_QISKIT_QASM_SIMULATOR: outcomes = np.array([[int(m) for m in memory]]) else: outcomes = model.simulate_experiment(np.array([[angle]]),expparams,repeat=SIM_N_SHOTS) outcomes = outcomes.reshape((1,outcomes.shape[0])) model._sim_count = 0 model._call_count = 0 # Time the update process # tic = toc = None # tic = time.time() # Update the posterior particles using the result of the circuit simulation updater.batch_update(outcomes, expparams) # performance[idx_exp]['elapsed_time'] = time.time() - tic # Record the performance of this updater. est_mean = updater.est_mean() performance[idx_exp]['est_mean'] = est_mean performance[idx_exp]['true_err'] = radiandiff(est_mean,angle) ** 2 performance[idx_exp]['est_cov_mat'] = updater.est_covariance_mtx() performance[idx_exp]['resample_count'] = updater.resample_count performance[idx_exp]['like_count'] = model.call_count performance[idx_exp]['sim_count'] = model.sim_count # Log print(idx_exp,'/',N_EXP,'[',M,THETA,est_mean,']') # Re-evaluate experiment parameters uniform_draw_01 = np.random.uniform(low=0.05,high=0.95) # uniform_draw_01 = np.random.uniform() cumsum_particles = np.cumsum(updater.particle_weights) draw_index = (cumsum_particles<= uniform_draw_01).argmin() THETA = updater.particle_locations[draw_index] # current_variance = updater.est_covariance_mtx()[0][0] # M=idx_exp % 6 + 1 posterior_marginal.append((updater.posterior_marginal())) print('Inference completed') # Plot for each iteration print(angle) fig_iter = plt.figure() ax_iter = plt.subplot(111) for x in posterior_marginal: # print(x[0],x[1]) _ = ax_iter.plot(x[0],x[1]) ax_iter.vlines(angle,ymin=0,ymax=2) _ = ax_iter.legend(['Iter ' + str(x) for x in range(len(posterior_marginal[0:10]))]) _ = plt.grid() _ = plt.ylabel('Posterior') _ = plt.xlabel(r'$\phi$') _ = plt.title('Posterior Marginal for some iterations') plt.savefig('iterative_posterior.png',dpi=300) ax_qinfer = updater.plot_posterior_marginal(smoothing=0) plt.vlines(angle,ymin=0,ymax=3) plt.grid() _ = plt.ylabel('Posterior') _ = plt.xlabel(r'$\phi$') _ = plt.title('IQPE Posterior') plt.savefig('final_posterior.png',dpi=300) fig_true_err = plt.figure() ax_true_err = plt.subplot(111) ax_true_err.semilogy(performance['true_err']) ax_true_err.grid() _ = plt.xlabel('Iteration count') _ = plt.ylabel('True Error') _ = plt.title('True Error over each Iteration') plt.savefig('true_error.png',dpi=300) fig_est_mean = plt.figure() ax_est_mean = plt.subplot(111) ax_est_mean.plot(performance['est_mean']) ax_est_mean.grid() ax_est_mean.hlines(angle,xmin=0,xmax=N_EXP) _ = plt.xlabel('Iteration count') _ = plt.ylabel('Estimated $\phi$ (mean)') _ = plt.title('Estimated Mean for each Iteration') plt.savefig('mean.png',dpi=300) # Calculate the naive prediction of the IQPE phase, phi E_i = memory_list # Convert to integers theta_i = theta_list phi_i = [] for i,E in enumerate(E_i): # print(i,E) e = [int(v) for v in E] # Naive sum sum = 0 for v in e: sum += v p_i = sum / len(E) # Inverse naive phi approximation using expected value from experimental results phi = theta_i[i][0] - (np.arccos(1 - (2 * p_i))) / M phi_i.append(phi) # Plot the naive phi estimate plt.plot(phi_i) plt.grid() plt.hlines(angle,xmin=0,xmax=25) _ = plt.xlabel('Iteration Count') _ = plt.ylabel(r'$\phi$') _ = plt.title('Naive $\phi$ estimation using expectation values of experimental runs') plt.savefig('naive.png',dpi=300) # Disable TeX text rendering mpl.rc('text', usetex=False) # Render the IQPE circuit for M=1 and the last Theta used circuit = iqpe_builder.construct_circuit(k=1,omega=THETA,measurement=True) circ_fig = circuit.draw(output='mpl') circ_fig.savefig('iqpe_1.png',dpi=300) # Render the IQPE circuit for M=2 and the last Theta used circuit = iqpe_builder.construct_circuit(k=2,omega=THETA,measurement=True) circ_fig = circuit.draw(output='mpl') circ_fig.savefig('iqpe_2.png',dpi=300)
https://github.com/qiskit-community/prototype-qrao
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test QRAO steps on various hardware and simulator backends""" import pytest from docplex.mp.model import Model from qiskit.utils import QuantumInstance from qiskit.algorithms.minimum_eigen_solvers import VQE from qiskit.circuit.library import RealAmplitudes from qiskit.algorithms.optimizers import SPSA from qiskit import BasicAer from qiskit_aer import Aer from qiskit_optimization.algorithms import OptimizationResultStatus from qiskit_optimization.translators import from_docplex_mp from qiskit_ibm_provider import IBMProvider, least_busy, IBMAccountError from qrao import ( QuantumRandomAccessOptimizer, QuantumRandomAccessEncoding, MagicRounding, ) # pylint: disable=redefined-outer-name # TODO: # - update these tests to include solution checking once behavior can be made # - deterministic. # - This might just require us to set seeds in the QuantumInstance and # - remove that as an argument altogether. backends = [ (BasicAer.get_backend, "qasm_simulator"), (Aer.get_backend, "qasm_simulator"), (Aer.get_backend, "statevector_simulator"), (Aer.get_backend, "aer_simulator"), (Aer.get_backend, "aer_simulator_statevector"), (Aer.get_backend, "aer_simulator_density_matrix"), (Aer.get_backend, "aer_simulator_matrix_product_state"), # The following takes forever, haven't yet waited long enough to know the # real timescale # (Aer.get_backend, "aer_simulator_extended_stabilizer"), ] @pytest.fixture(scope="module") def my_encoding(): """Fixture to construct ``my_encoding`` for use in this file""" # Load small reference problem elist = [(0, 1), (0, 4), (0, 3), (1, 2), (1, 5), (2, 3), (2, 4), (4, 5), (5, 3)] num_nodes = 6 mod = Model("maxcut") nodes = list(range(num_nodes)) var = [mod.binary_var(name="x" + str(i)) for i in nodes] mod.maximize(mod.sum((var[i] + var[j] - 2 * var[i] * var[j]) for i, j in elist)) problem = from_docplex_mp(mod) encoding = QuantumRandomAccessEncoding(max_vars_per_qubit=3) encoding.encode(problem) return encoding @pytest.fixture(scope="module") def my_ansatz(my_encoding): """Fixture to construct ``my_ansatz`` for use in this file""" return RealAmplitudes(my_encoding.num_qubits) @pytest.mark.parametrize("relaxed_backend", backends) @pytest.mark.parametrize("rounding_backend", backends) @pytest.mark.filterwarnings("ignore::PendingDeprecationWarning") @pytest.mark.filterwarnings( "ignore:.*statevector_simulator.*:UserWarning" ) # ignore magic rounding's UserWarning when using statevector_simulator @pytest.mark.backend def test_backend(relaxed_backend, rounding_backend, my_encoding, my_ansatz, shots=3): """Smoke test of each backend combination""" def cb(f, *args): "Construct backend" return f(*args) relaxed_qi = QuantumInstance(backend=cb(*relaxed_backend), shots=shots) rounding_qi = QuantumInstance(backend=cb(*rounding_backend), shots=shots) vqe = VQE( ansatz=my_ansatz, optimizer=SPSA(maxiter=1, learning_rate=0.01, perturbation=0.1), quantum_instance=relaxed_qi, ) rounding_scheme = MagicRounding(rounding_qi) qrao = QuantumRandomAccessOptimizer( encoding=my_encoding, min_eigen_solver=vqe, rounding_scheme=rounding_scheme ) result = qrao.solve() assert result.status == OptimizationResultStatus.SUCCESS @pytest.mark.backend def test_magic_rounding_on_hardware_backend(my_encoding, my_ansatz): """Test *magic rounding* on a hardware backend, if available.""" try: provider = IBMProvider() except IBMAccountError: pytest.skip("No hardware backend available") print(f"Encoding requires {my_encoding.num_qubits} qubits") backend = least_busy( provider.backends( min_num_qubits=my_encoding.num_qubits, simulator=False, operational=True, ) ) print(f"Using backend: {backend}") relaxed_qi = QuantumInstance(backend=Aer.get_backend("aer_simulator"), shots=100) rounding_qi = QuantumInstance(backend=backend, shots=32) vqe = VQE( ansatz=my_ansatz, optimizer=SPSA(maxiter=1, learning_rate=0.01, perturbation=0.1), quantum_instance=relaxed_qi, ) rounding_scheme = MagicRounding(quantum_instance=rounding_qi) qrao = QuantumRandomAccessOptimizer( encoding=my_encoding, min_eigen_solver=vqe, rounding_scheme=rounding_scheme ) result = qrao.solve() assert result.status == OptimizationResultStatus.SUCCESS
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import json from qiskit import Aer from qiskit_aqua import run_algorithm from qiskit_aqua.input import EnergyInput from qiskit_aqua.translators.ising import setpacking from qiskit_aqua.algorithms import ExactEigensolver input_file = 'sample.setpacking' with open(input_file) as f: list_of_subsets = json.load(f) print(list_of_subsets) qubitOp, offset = setpacking.get_setpacking_qubitops(list_of_subsets) algo_input = EnergyInput(qubitOp) def brute_force(): # brute-force way: try every possible assignment! def bitfield(n, L): result = np.binary_repr(n, L) return [int(digit) for digit in result] # [2:] to chop off the "0b" part L = len(list_of_subsets) max = 2**L max_v = -np.inf for i in range(max): cur = bitfield(i, L) cur_v = setpacking.check_disjoint(cur, list_of_subsets) if cur_v: if np.count_nonzero(cur) > max_v: max_v = np.count_nonzero(cur) return max_v size = brute_force() print("size of set packing", size) params = { 'problem': {'name': 'ising'}, 'algorithm': {'name': 'ExactEigensolver'} } result = run_algorithm(params, algo_input) x = setpacking.sample_most_likely(len(list_of_subsets), result['eigvecs'][0]) ising_sol = setpacking.get_solution(x) np.testing.assert_array_equal(ising_sol, [0, 1, 1]) print("size of set packing", np.count_nonzero(ising_sol)) algo = ExactEigensolver(algo_input.qubit_op, k=1, aux_operators=[]) result = algo.run() x = setpacking.sample_most_likely(len(list_of_subsets), result['eigvecs'][0]) ising_sol = setpacking.get_solution(x) np.testing.assert_array_equal(ising_sol, [0, 1, 1]) oracle = brute_force() print("size of set packing", np.count_nonzero(ising_sol)) algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'paulis' } optimizer_cfg = { 'name': 'SPSA', 'max_trials': 200 } var_form_cfg = { 'name': 'RY', 'depth': 5, 'entanglement': 'linear' } params = { 'problem': {'name': 'ising', 'random_seed': 100}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = Aer.get_backend('qasm_simulator') result = run_algorithm(params, algo_input, backend=backend) x = setpacking.sample_most_likely(len(list_of_subsets), result['eigvecs'][0]) ising_sol = setpacking.get_solution(x) print("size of set packing", np.count_nonzero(ising_sol))
https://github.com/ionq-samples/qiskit-getting-started
ionq-samples
# general imports import math import time import pickle import random import numpy as np import matplotlib.pyplot as plt from scipy.optimize import minimize from datetime import datetime # Noisy optimization package — you could also use scipy's optimization functions, # but this is a little better suited to the noisy output of NISQ devices. %pip install noisyopt import noisyopt # magic invocation for producing visualizations in notebook %matplotlib inline # Qiskit imports from qiskit import Aer from qiskit_ionq import IonQProvider #Call provider and set token value provider = IonQProvider(token='My token') provider.backends() # fix random seed for reproducibility — this allows us to re-run the process and get the same results seed = 42 np.random.seed(seed) random.seed(a=seed) #Generate BAS, only one bar or stripe allowed def generate_target_distribution(rows, columns): #Stripes states=[] for i in range(rows): s=['0']*rows*columns for j in range(columns): s[j+columns*i]='1' states.append(''.join(s)) #Bars for j in range(columns): s=['0']*rows*columns for i in range(rows): s[j+columns*i]='1' states.append(''.join(s)) return states #Parameters for driver def generate_beta(ansatz_type,random_init): if ansatz_type[0]==0: #No driver beta=[] elif ansatz_type[0]==1: #Rz(t1)Rx(t2)Rz(t3), angles different for each qubit beta=( [random.uniform(0.0,2.*math.pi) for i in range(3*n*(layers-1))] if random_init else [0]*3*n*(layers-1) ) elif ansatz_type[0]==2: #Rz(t1)Rx(t2)Rz(t3), angles same for all qubits beta=( [random.uniform(0.0,2.*math.pi) for i in range(3*(layers-1))] if random_init else [0]*3*(layers-1) ) elif ansatz_type[0]==3: #Rz(t1), angles different for each qubit beta=( [random.uniform(0.0,2.*math.pi) for i in range(n*(layers-1))] if random_init else [0]*n*(layers-1) ) else: raise Exception("Undefined driver type") return beta #Parameters for entangler def generate_gamma(ansatz_type,random_init, n, conn): length_gamma=int(n*conn-conn*(conn+1)/2.) if ansatz_type[1]==0: #No entangler gamma=[] elif ansatz_type[1]==1: #XX(t1), angles different for each qubit gamma=( [random.uniform(0.0,2.*math.pi) for i in range(length_gamma*layers)] if random_init else [0]*length_gamma*layers ) elif ansatz_type[1]==2: #XX(t1), angles same for all qubits gamma=( [random.uniform(0.0,2.*math.pi) for i in range(layers)] if random_init else gamma[0]*layers ) else: raise Exception("Undefined entangler type") return gamma from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit import Gate def driver(circ,qr,beta,n,ansatz_type): #qr=QuantumRegister(n) #circ = QuantumCircuit(qr) if ansatz_type==0: pass elif ansatz_type==1: for i_q in range(n): circ.rz(beta[3*i_q], qr[i_q]) circ.rx(beta[3*i_q+1], qr[i_q]) circ.rz(beta[3*i_q+2], qr[i_q]) elif ansatz_type==2: for i_q in range(n): circ.rz(beta[0], qr[i_q]) circ.rx(beta[1], qr[i_q]) circ.rz(beta[2], qr[i_q]) elif ansatz_type==3: for i_q in range(n): circ.rz(beta[i_q], qr[i_q]) return def entangler(circ,qr,gamma,n,conn,ansatz_type): #qr=QuantumRegister(n) #cr=ClassicalRegister(n) #circ = QuantumCircuit(qr) if ansatz_type==0: pass elif ansatz_type==1: i_gamma=0 for i_conn in range(1,conn+1): for i_q in range(0,n-i_conn): circ.cx(qr[i_q],qr[i_q+i_conn]) circ.rx(gamma[i_gamma],qr[i_q]) circ.cx(qr[i_q],qr[i_q+i_conn]) #circ.rxx(gamma[i_gamma], qr[i_q], qr[i_q+i_conn]) i_gamma+=1 elif ansatz_type==2: for i_conn in range(1,conn+1): for i_q in range(0,n-i_conn): circ.cx(qr[i_q],qr[i_q+i_conn]) circ.rx(gamma[0],qr[i_q]) circ.cx(qr[i_q],qr[i_q+i_conn]) #circ.rxx(gamma[0], qr[i_q], qr[i_q+i_conn]) #circ.measure(qr,cr) return #Define circuit ansatz def circuit_ansatz(n,params,conn=1, layers=1, ansatz_type=[1,1]): qr=QuantumRegister(n) cr=ClassicalRegister(n) circ = QuantumCircuit(qr,cr) if ansatz_type[0]==0: length_beta=0 elif ansatz_type[0]==1: length_beta=3*n elif ansatz_type[0]==2: length_beta=3 elif ansatz_type[0]==3: length_beta=n if ansatz_type[1]==0: length_gamma=0 elif ansatz_type[1]==1: length_gamma=int(n*conn-conn*(conn+1)/2.) elif ansatz_type[1]==2: length_gamma=1 for i_layer in range(layers-1): beta=params[(length_beta+length_gamma)*i_layer:(length_beta+length_gamma)*i_layer+length_beta] gamma=params[(length_beta+length_gamma)*i_layer+length_beta:(length_beta+length_gamma)*(i_layer+1)] entangler(circ,qr,gamma,n,conn,ansatz_type[1]) driver(circ,qr,beta,n,ansatz_type[0]) gamma=params[(length_beta+length_gamma)*(layers-1):] entangler(circ,qr,gamma,n,conn,ansatz_type[1]) circ.measure(qr, cr) return circ def cost(counts, shots, target_states,tol=0.0001): cost=0 for state in target_states: if state in counts: cost-=1./len(target_states)*np.log2(max(tol,counts[state]/shots)) else: cost-=1./len(target_states)*np.log2(tol) return cost from qiskit.providers.jobstatus import JobStatus def run_iteration(circ, num_qubits, shots=100): # submit task: define task (asynchronous) task_status='' while task_status != JobStatus.DONE: task = backend.run(circ, shots=shots) #print("Job submitted") # Get ID of submitted task task_id = task.job_id() #print('Task ID :', task_id) while (task_status == JobStatus.INITIALIZING) or (task_status == JobStatus.QUEUED) or (task_status == JobStatus.VALIDATING) or (task_status == JobStatus.RUNNING) or (task_status==''): time.sleep(1) try: task_status=task.status() except: print("Error querying status. Trying again.") pass #print('Task status is', task_status) # get result counts = task.result().get_counts() return counts #Run an iteration of the circuit and calculate its cost def run_circuit_and_calc_cost(params, *args): n, conn, layers, ansatz_type, target_states, shots = args circ=circuit_ansatz(n, params, conn, layers,ansatz_type) counts=run_iteration(circ, n, shots=shots) iter_cost=cost(counts, shots, target_states) cost_history.append(iter_cost) print("Current cost:", iter_cost) return iter_cost backend = provider.get_backend("ionq_simulator") #Set problem parameters r=2 #Number of rows — make sure r*c is less than qubit count c=2 #Number of columns — make sure r*c is less than qubit count n=r*c #Qubits needed conn=2 #Connectivity of the entangler. #Check on qubit count if n>backend.configuration().n_qubits: raise Exception("Too many qubits") #Check on conn if conn>(n-1): raise Exception("Connectivity is too large") target_states=generate_target_distribution(r,c) # Check expected output print('Bitstrings that should be generated by trained circuit are', target_states, 'corresponding to the following BAS patterns:\n') for state in target_states: for i in range(r): print(state[c*i:][:c].replace('0','□ ').replace('1','■ ')) print('') # Choose entangler and driver type layers=1 # Number of layers in each circuit shots=100 # Number of shots per iteration ansatz_type=[1,1] random_init=False # Set to true for random initialization; will be slower to converge # Set up args beta=generate_beta(ansatz_type, random_init) gamma=generate_gamma(ansatz_type, random_init, n, conn) params=beta+gamma base_bounds=(0,2.*math.pi) bnds=((base_bounds , ) * len(params)) #Set up list to track cost history cost_history=[] max_iter=100 # max number of optimizer iterations args=(n, conn, layers, ansatz_type, target_states, shots) opts = {'disp': True, 'maxiter': max_iter, 'maxfev': max_iter, 'return_all': True} #Visualize the circuit circ=circuit_ansatz(n, params, conn,layers,ansatz_type) circ.draw() from qiskit.visualization import plot_histogram #Train Circuit result=noisyopt.minimizeSPSA(run_circuit_and_calc_cost, params, args=args, bounds=bnds, niter=max_iter, disp=False, paired=False) print("Success: ", result.success) print(result.message) print("Final cost function is ", result.fun) print("Min possible cost function is ", np.log2(len(target_states))) print("Number of iterations is ", result.nit) print("Number of function evaluations is ", result.nfev) print("Number of parameters was ", len(params)) print("Approximate cost on hardware: $", 0.01*len(cost_history)*shots) #Plot the evolution of the cost function plt.figure() plt.plot(cost_history) plt.ylabel('Cost') plt.xlabel('Iteration') #Visualize the result result_final=run_iteration(circuit_ansatz(n, result.x, conn,layers,ansatz_type), shots) plot_histogram(result_final) #Train Circuit backend = provider.get_backend("ionq_qpu") result=noisyopt.minimizeSPSA(run_circuit_and_calc_cost, params, args=args, bounds=bnds, niter=max_iter, disp=False, paired=False) print("Success: ", result.success) print(result.message) print("Final cost function is ", result.fun) print("Min possible cost function is ", np.log2(len(target_states))) print("Number of iterations is ", result.nit) print("Number of function evaluations is ", result.nfev) print("Number of parameters was ", len(params)) print("Approximate cost on hardware: $", 0.01*len(cost_history)*shots) #Plot the evolution of the cost function plt.figure() plt.plot(cost_history) plt.ylabel('Cost') plt.xlabel('Iteration') #Visualize the result result_final=run_iteration(circuit_ansatz(n, result.x, conn,layers,ansatz_type), shots) plot_histogram(result_final)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. r""" =================== Overview of Sampler =================== Sampler class calculates probabilities or quasi-probabilities of bitstrings from quantum circuits. A sampler is initialized with an empty parameter set. The sampler is used to create a :class:`~qiskit.providers.JobV1`, via the :meth:`qiskit.primitives.Sampler.run()` method. This method is called with the following parameters * quantum circuits (:math:`\psi_i(\theta)`): list of (parameterized) quantum circuits. (a list of :class:`~qiskit.circuit.QuantumCircuit` objects) * parameter values (:math:`\theta_k`): list of sets of parameter values to be bound to the parameters of the quantum circuits. (list of list of float) The method returns a :class:`~qiskit.providers.JobV1` object, calling :meth:`qiskit.providers.JobV1.result()` yields a :class:`~qiskit.primitives.SamplerResult` object, which contains probabilities or quasi-probabilities of bitstrings, plus optional metadata like error bars in the samples. Here is an example of how sampler is used. .. code-block:: python from qiskit.primitives import Sampler from qiskit import QuantumCircuit from qiskit.circuit.library import RealAmplitudes # a Bell circuit bell = QuantumCircuit(2) bell.h(0) bell.cx(0, 1) bell.measure_all() # two parameterized circuits pqc = RealAmplitudes(num_qubits=2, reps=2) pqc.measure_all() pqc2 = RealAmplitudes(num_qubits=2, reps=3) pqc2.measure_all() theta1 = [0, 1, 1, 2, 3, 5] theta2 = [0, 1, 2, 3, 4, 5, 6, 7] # initialization of the sampler sampler = Sampler() # Sampler runs a job on the Bell circuit job = sampler.run(circuits=[bell], parameter_values=[[]], parameters=[[]]) job_result = job.result() print([q.binary_probabilities() for q in job_result.quasi_dists]) # Sampler runs a job on the parameterized circuits job2 = sampler.run( circuits=[pqc, pqc2], parameter_values=[theta1, theta2], parameters=[pqc.parameters, pqc2.parameters]) job_result = job2.result() print([q.binary_probabilities() for q in job_result.quasi_dists]) """ from __future__ import annotations from abc import abstractmethod from collections.abc import Sequence from copy import copy from typing import Generic, TypeVar from qiskit.circuit import QuantumCircuit from qiskit.circuit.parametertable import ParameterView from qiskit.providers import JobV1 as Job from .base_primitive import BasePrimitive T = TypeVar("T", bound=Job) class BaseSampler(BasePrimitive, Generic[T]): """Sampler base class Base class of Sampler that calculates quasi-probabilities of bitstrings from quantum circuits. """ __hash__ = None def __init__( self, *, options: dict | None = None, ): """ Args: options: Default options. """ self._circuits = [] self._parameters = [] super().__init__(options) def run( self, circuits: QuantumCircuit | Sequence[QuantumCircuit], parameter_values: Sequence[float] | Sequence[Sequence[float]] | None = None, **run_options, ) -> T: """Run the job of the sampling of bitstrings. Args: circuits: One of more circuit objects. parameter_values: Parameters to be bound to the circuit. run_options: Backend runtime options used for circuit execution. Returns: The job object of the result of the sampler. The i-th result corresponds to ``circuits[i]`` evaluated with parameters bound as ``parameter_values[i]``. Raises: ValueError: Invalid arguments are given. """ # Singular validation circuits = self._validate_circuits(circuits) parameter_values = self._validate_parameter_values( parameter_values, default=[()] * len(circuits), ) # Cross-validation self._cross_validate_circuits_parameter_values(circuits, parameter_values) # Options run_opts = copy(self.options) run_opts.update_options(**run_options) return self._run( circuits, parameter_values, **run_opts.__dict__, ) @abstractmethod def _run( self, circuits: tuple[QuantumCircuit, ...], parameter_values: tuple[tuple[float, ...], ...], **run_options, ) -> T: raise NotImplementedError("The subclass of BaseSampler must implment `_run` method.") # TODO: validate measurement gates are present @classmethod def _validate_circuits( cls, circuits: Sequence[QuantumCircuit] | QuantumCircuit, ) -> tuple[QuantumCircuit, ...]: circuits = super()._validate_circuits(circuits) for i, circuit in enumerate(circuits): if circuit.num_clbits == 0: raise ValueError( f"The {i}-th circuit does not have any classical bit. " "Sampler requires classical bits, plus measurements " "on the desired qubits." ) return circuits @property def circuits(self) -> tuple[QuantumCircuit, ...]: """Quantum circuits to be sampled. Returns: The quantum circuits to be sampled. """ return tuple(self._circuits) @property def parameters(self) -> tuple[ParameterView, ...]: """Parameters of quantum circuits. Returns: List of the parameters in each quantum circuit. """ return tuple(self._parameters)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.second_q.drivers import GaussianForcesDriver # if you ran Gaussian elsewhere and already have the output file driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") # if you want to run the Gaussian job from Qiskit # driver = GaussianForcesDriver( # ['#p B3LYP/6-31g Freq=(Anharm) Int=Ultrafine SCF=VeryTight', # '', # 'CO2 geometry optimization B3LYP/6-31g', # '', # '0 1', # 'C -0.848629 2.067624 0.160992', # 'O 0.098816 2.655801 -0.159738', # 'O -1.796073 1.479446 0.481721', # '', # '' from qiskit_nature.second_q.problems import HarmonicBasis basis = HarmonicBasis([2, 2, 2, 2]) from qiskit_nature.second_q.problems import VibrationalStructureProblem from qiskit_nature.second_q.mappers import DirectMapper vibrational_problem = driver.run(basis=basis) vibrational_problem.hamiltonian.truncation_order = 2 main_op, aux_ops = vibrational_problem.second_q_ops() print(main_op) qubit_mapper = DirectMapper() qubit_op = qubit_mapper.map(main_op) print(qubit_op) basis = HarmonicBasis([3, 3, 3, 3]) vibrational_problem = driver.run(basis=basis) vibrational_problem.hamiltonian.truncation_order = 2 main_op, aux_ops = vibrational_problem.second_q_ops() qubit_mapper = DirectMapper() qubit_op = qubit_mapper.map(main_op) print(qubit_op) # for simplicity, we will use the smaller basis again vibrational_problem = driver.run(basis=HarmonicBasis([2, 2, 2, 2])) vibrational_problem.hamiltonian.truncation_order = 2 from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms import GroundStateEigensolver solver = GroundStateEigensolver( qubit_mapper, NumPyMinimumEigensolver(filter_criterion=vibrational_problem.get_default_filter_criterion()), ) result = solver.solve(vibrational_problem) print(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
from qiskit import * import numpy as np import math import qiskit nshots = 8192 IBMQ.load_account() #provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibmq_belem') simulator = Aer.get_backend('qasm_simulator') from qiskit.tools.monitor import job_monitor from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter dth = math.pi/10 th = np.arange(0,math.pi+dth,dth) ph = 0; lb = 0 N = len(th) F_the = np.zeros(N); F_sim = np.zeros(N); F_exp = np.zeros(N) for j in range(0,N): F_the[j] = math.cos(th[j]/2)**2 qr = QuantumRegister(3) cr = ClassicalRegister(1) qc = QuantumCircuit(qr,cr) qc.u(th[j],ph,lb,qr[2]) qc.h(qr[0]) qc.cswap(qr[0],qr[1],qr[2]) qc.h(qr[0]) qc.measure(qr[0],cr[0]) job_sim = execute(qc, backend=simulator, shots=nshots) counts = job_sim.result().get_counts(qc) if '0' in counts: F_sim[j] = 2*counts['0']/nshots - 1 job_exp = execute(qc, backend=device, shots=nshots) print(job_exp.job_id()) job_monitor(job_exp) counts = job_exp.result().get_counts(qc) if '0' in counts: F_exp[j] = 2*counts['0']/nshots - 1 qc.draw('mpl') qc.decompose().decompose().draw('mpl') # o circuito é "profundo" por causa da swap controlada F_the, F_sim, F_exp from matplotlib import pyplot as plt plt.plot(th, F_the, label=r'$F_{the}$') plt.plot(th, F_sim, '*', label=r'$F_{sim}$') plt.plot(th, F_exp, 'o', label=r'$F_{exp}$') plt.xlabel(r'$\theta$') plt.legend() plt.show()
https://github.com/daimurat/qiskit-implementation
daimurat
import matplotlib.pyplot as plt import numpy as np # ランダムシードの指定 np.random.seed(1) # 標準正規分布に従う乱数の生成 X_xor = np.random.randn(200, 2) y_xor = np.logical_xor(X_xor[:, 0] > 0, X_xor[:, 1] > 0) # 真の場合は1、偽の場合は-1 y_xor = np.where(y_xor, 1, -1) #データのプロット plt.scatter(X_xor[y_xor==1, 0], X_xor[y_xor==1, 1], c='b', marker='x', label='1') plt.scatter(X_xor[y_xor==-1, 0], X_xor[y_xor==-1, 1], c='r', marker='s', label='-1') plt.xlim([-3, 3]) plt.ylim([-3, 3]) plt.legend(loc='best') plt.tight_layout() plt.show() from qiskit.circuit.library import ZZFeatureMap map_zz = ZZFeatureMap(feature_dimension=2, reps=2) ## カーネルの定義(手組) from qiskit import BasicAer from qiskit_machine_learning.kernels import QuantumKernel from sklearn.svm import SVC # Create the quantum feature map map_zz = ZZFeatureMap(feature_dimension=2, reps=2, entanglement='linear') # Create the quantum kernel adhoc_kernel = QuantumKernel(feature_map=map_zz, quantum_instance=BasicAer.get_backend('statevector_simulator')) # Set the SVC algorithm to use our custom kernel model = SVC(kernel=adhoc_kernel.evaluate) model.fit(X_xor, y_xor) # 決定境界の可視化 from matplotlib.colors import ListedColormap def plot_decision_regisons(X, y, classifier, resolution=0.2): markers = ('s', 'x', 'o', '^', 'v') colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') cmap = ListedColormap(colors[:len(np.unique(y))]) # 決定境界のプロット x1_min, x1_max = X[:, 0].min() - 1 , X[:, 0].max() + 1 x2_min, x2_max = X[:, 1].min() - 1 , X[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) # 各特徴量を1次元配列に変換して予測を実行 Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T) Z = Z.reshape(xx1.shape) # グリッドポイントの等高線プロット plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap) plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y==cl, 0], y=X[y==cl, 1], alpha=0.8, c=colors[idx], marker=markers[idx], label=cl, edgecolors='black') plot_decision_regisons(X_xor, y_xor, classifier=model) plt.legend(loc='upper left') plt.tight_layout() plt.show()
https://github.com/AnshDabkara/Qiskit_Algorithm
AnshDabkara
from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile, assemble from qiskit.tools.monitor import job_monitor import matplotlib as mpl # import basic plot tools from qiskit.visualization import plot_histogram bv_circuit=QuantumCircuit(4,3) #bv_circuit.clear() bit_string=('111') bv_circuit.x(3) bv_circuit.h([0,1,2,3]) bv_circuit.barrier() bv_circuit.cx(0,3) bv_circuit.cx(1,3) bv_circuit.cx(2,3) bv_circuit.barrier() bv_circuit.h([0,1,2,3]) bv_circuit.measure([0,1,2],[0,1,2]) bv_circuit.draw('mpl') aer_sim = Aer.get_backend('aer_simulator') #Local Simulator shots = 1024 #No. of times the circuit is running qobj = assemble(bv_circuit, shots = shots) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) #Plotting the result bit_string=('1010') bv_circuit=QuantumCircuit(len(bit_string)+1,len(bit_string)) bv_circuit.clear() #bv_circuit.x(len(bit_string)) bv_circuit.h(range(len(bit_string))) bv_circuit.x(len(bit_string)) bv_circuit.h(len(bit_string)) bv_circuit.barrier() for i, yes in enumerate(reversed(bit_string)): if yes=='1': bv_circuit.cx(i,len(bit_string)) bv_circuit.barrier() bv_circuit.h(range(len(bit_string))) bv_circuit.h(len(bit_string)) bv_circuit.measure(range(len(bit_string)),range(len(bit_string))) bv_circuit.draw('mpl') aer_sim = Aer.get_backend('aer_simulator') #Local Simulator shots = 1024 #No. of times the circuit is running qobj = assemble(bv_circuit, shots = shots) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) #Plotting the result
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test functionality to collect, split and consolidate blocks from DAGCircuits.""" import unittest from qiskit import QuantumRegister, ClassicalRegister from qiskit.converters import ( circuit_to_dag, circuit_to_dagdependency, circuit_to_instruction, dag_to_circuit, dagdependency_to_circuit, ) from qiskit.test import QiskitTestCase from qiskit.circuit import QuantumCircuit, Measure, Clbit from qiskit.dagcircuit.collect_blocks import BlockCollector, BlockSplitter, BlockCollapser class TestCollectBlocks(QiskitTestCase): """Tests to verify correctness of collecting, splitting, and consolidating blocks from DAGCircuit and DAGDependency. Additional tests appear as a part of CollectLinearFunctions and CollectCliffords passes. """ def test_collect_gates_from_dagcircuit_1(self): """Test collecting CX gates from DAGCircuits.""" qc = QuantumCircuit(5) qc.cx(0, 1) qc.cx(0, 2) qc.z(0) qc.cx(0, 3) qc.cx(0, 4) block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=2, ) # The middle z-gate leads to two blocks of size 2 each self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 2) self.assertEqual(len(blocks[1]), 2) def test_collect_gates_from_dagcircuit_2(self): """Test collecting both CX and Z gates from DAGCircuits.""" qc = QuantumCircuit(5) qc.cx(0, 1) qc.cx(0, 2) qc.z(0) qc.cx(0, 3) qc.cx(0, 4) block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "z"], split_blocks=False, min_block_size=1, ) # All of the gates are part of a single block self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 5) def test_collect_gates_from_dagcircuit_3(self): """Test collecting CX gates from DAGCircuits.""" qc = QuantumCircuit(5) qc.cx(0, 1) qc.cx(0, 2) qc.z(0) qc.cx(1, 3) qc.cx(0, 3) qc.cx(0, 4) block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx"], split_blocks=False, min_block_size=1, ) # We should end up with two CX blocks: even though there is "a path # around z(0)", without commutativity analysis z(0) prevents from # including all CX-gates into the same block self.assertEqual(len(blocks), 2) def test_collect_gates_from_dagdependency_1(self): """Test collecting CX gates from DAGDependency.""" qc = QuantumCircuit(5) qc.cx(0, 1) qc.cx(0, 2) qc.z(0) qc.cx(0, 3) qc.cx(0, 4) block_collector = BlockCollector(circuit_to_dagdependency(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1, ) # The middle z-gate commutes with CX-gates, which leads to a single block of length 4 self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 4) def test_collect_gates_from_dagdependency_2(self): """Test collecting both CX and Z gates from DAGDependency.""" qc = QuantumCircuit(5) qc.cx(0, 1) qc.cx(0, 2) qc.z(0) qc.cx(0, 3) qc.cx(0, 4) block_collector = BlockCollector(circuit_to_dagdependency(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "z"], split_blocks=False, min_block_size=1, ) # All the gates are part of a single block self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 5) def test_collect_and_split_gates_from_dagcircuit(self): """Test collecting and splitting blocks from DAGCircuit.""" qc = QuantumCircuit(6) qc.cx(0, 1) qc.cx(3, 5) qc.cx(2, 4) qc.swap(1, 0) qc.cz(5, 3) block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: True, split_blocks=False, min_block_size=1, ) # All the gates are part of a single block self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 5) # Split the first block into sub-blocks over disjoint qubit sets # We should get 3 sub-blocks split_blocks = BlockSplitter().run(blocks[0]) self.assertEqual(len(split_blocks), 3) def test_collect_and_split_gates_from_dagdependency(self): """Test collecting and splitting blocks from DAGDependecy.""" qc = QuantumCircuit(6) qc.cx(0, 1) qc.cx(3, 5) qc.cx(2, 4) qc.swap(1, 0) qc.cz(5, 3) block_collector = BlockCollector(circuit_to_dagdependency(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: True, split_blocks=False, min_block_size=1, ) # All the gates are part of a single block self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 5) # Split the first block into sub-blocks over disjoint qubit sets # We should get 3 sub-blocks split_blocks = BlockSplitter().run(blocks[0]) self.assertEqual(len(split_blocks), 3) def test_circuit_has_measure(self): """Test that block collection works properly when there is a measure in the middle of the circuit.""" qc = QuantumCircuit(2, 1) qc.cx(1, 0) qc.x(0) qc.x(1) qc.measure(0, 0) qc.x(0) qc.cx(1, 0) block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["x", "cx"], split_blocks=False, min_block_size=1, ) # measure prevents combining the two blocks self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 3) self.assertEqual(len(blocks[1]), 2) def test_circuit_has_measure_dagdependency(self): """Test that block collection works properly when there is a measure in the middle of the circuit.""" qc = QuantumCircuit(2, 1) qc.cx(1, 0) qc.x(0) qc.x(1) qc.measure(0, 0) qc.x(0) qc.cx(1, 0) block_collector = BlockCollector(circuit_to_dagdependency(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["x", "cx"], split_blocks=False, min_block_size=1, ) # measure prevents combining the two blocks self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 3) self.assertEqual(len(blocks[1]), 2) def test_circuit_has_conditional_gates(self): """Test that block collection works properly when there the circuit contains conditional gates.""" qc = QuantumCircuit(2, 1) qc.x(0) qc.x(1) qc.cx(1, 0) qc.x(1).c_if(0, 1) qc.x(0) qc.x(1) qc.cx(0, 1) # If the filter_function does not look at conditions, we should collect all # gates into the block. block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["x", "cx"], split_blocks=False, min_block_size=1, ) self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 7) # If the filter_function does look at conditions, we should not collect the middle # conditional gate (note that x(1) following the measure is collected into the first # block). block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["x", "cx"] and not getattr(node.op, "condition", None), split_blocks=False, min_block_size=1, ) self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 4) self.assertEqual(len(blocks[1]), 2) def test_circuit_has_conditional_gates_dagdependency(self): """Test that block collection works properly when there the circuit contains conditional gates.""" qc = QuantumCircuit(2, 1) qc.x(0) qc.x(1) qc.cx(1, 0) qc.x(1).c_if(0, 1) qc.x(0) qc.x(1) qc.cx(0, 1) # If the filter_function does not look at conditions, we should collect all # gates into the block. block_collector = BlockCollector(circuit_to_dagdependency(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["x", "cx"], split_blocks=False, min_block_size=1, ) self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 7) # If the filter_function does look at conditions, we should not collect the middle # conditional gate (note that x(1) following the measure is collected into the first # block). block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["x", "cx"] and not getattr(node.op, "condition", None), split_blocks=False, min_block_size=1, ) self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 4) self.assertEqual(len(blocks[1]), 2) def test_multiple_collection_methods(self): """Test that block collection allows to collect blocks using several different filter functions.""" qc = QuantumCircuit(5) qc.cx(0, 1) qc.cx(0, 2) qc.swap(1, 4) qc.swap(4, 3) qc.z(0) qc.z(1) qc.z(2) qc.z(3) qc.z(4) qc.swap(3, 4) qc.cx(0, 3) qc.cx(0, 4) block_collector = BlockCollector(circuit_to_dag(qc)) linear_blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=1, ) cx_blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx"], split_blocks=False, min_block_size=1, ) swapz_blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["swap", "z"], split_blocks=False, min_block_size=1, ) # We should end up with two linear blocks self.assertEqual(len(linear_blocks), 2) self.assertEqual(len(linear_blocks[0]), 4) self.assertEqual(len(linear_blocks[1]), 3) # We should end up with two cx blocks self.assertEqual(len(cx_blocks), 2) self.assertEqual(len(cx_blocks[0]), 2) self.assertEqual(len(cx_blocks[1]), 2) # We should end up with one swap,z blocks self.assertEqual(len(swapz_blocks), 1) self.assertEqual(len(swapz_blocks[0]), 8) def test_min_block_size(self): """Test that the option min_block_size for collecting blocks works correctly.""" # original circuit circuit = QuantumCircuit(2) circuit.cx(0, 1) circuit.h(0) circuit.cx(0, 1) circuit.cx(1, 0) circuit.h(0) circuit.cx(0, 1) circuit.cx(1, 0) circuit.cx(0, 1) block_collector = BlockCollector(circuit_to_dag(circuit)) # When min_block_size = 1, we should obtain 3 linear blocks blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=1, ) self.assertEqual(len(blocks), 3) # When min_block_size = 2, we should obtain 2 linear blocks blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=2, ) self.assertEqual(len(blocks), 2) # When min_block_size = 3, we should obtain 1 linear block blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=3, ) self.assertEqual(len(blocks), 1) # When min_block_size = 4, we should obtain no linear blocks blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=4, ) self.assertEqual(len(blocks), 0) def test_split_blocks(self): """Test that splitting blocks of nodes into sub-blocks works correctly.""" # original circuit is linear circuit = QuantumCircuit(5) circuit.cx(0, 2) circuit.cx(1, 4) circuit.cx(2, 0) circuit.cx(0, 3) circuit.swap(3, 2) circuit.swap(4, 1) block_collector = BlockCollector(circuit_to_dag(circuit)) # If we do not split block into sub-blocks, we expect a single linear block. blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=2, ) self.assertEqual(len(blocks), 1) # If we do split block into sub-blocks, we expect two linear blocks: # one over qubits {0, 2, 3}, and another over qubits {1, 4}. blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=True, min_block_size=2, ) self.assertEqual(len(blocks), 2) def test_do_not_split_blocks(self): """Test that splitting blocks of nodes into sub-blocks works correctly.""" # original circuit is linear circuit = QuantumCircuit(5) circuit.cx(0, 3) circuit.cx(0, 2) circuit.cx(1, 4) circuit.swap(4, 2) block_collector = BlockCollector(circuit_to_dagdependency(circuit)) # Check that we have a single linear block blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=True, min_block_size=1, ) self.assertEqual(len(blocks), 1) def test_collect_blocks_with_cargs(self): """Test collecting and collapsing blocks with classical bits appearing as cargs.""" qc = QuantumCircuit(3) qc.h(0) qc.h(1) qc.h(2) qc.measure_all() dag = circuit_to_dag(qc) # Collect all measure instructions blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: isinstance(node.op, Measure), split_blocks=False, min_block_size=1 ) # We should have a single block consisting of 3 measures self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 3) self.assertEqual(blocks[0][0].op, Measure()) self.assertEqual(blocks[0][1].op, Measure()) self.assertEqual(blocks[0][2].op, Measure()) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dag_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 5) self.assertEqual(collapsed_qc.data[0].operation.name, "h") self.assertEqual(collapsed_qc.data[1].operation.name, "h") self.assertEqual(collapsed_qc.data[2].operation.name, "h") self.assertEqual(collapsed_qc.data[3].operation.name, "barrier") self.assertEqual(collapsed_qc.data[4].operation.name, "COLLAPSED") self.assertEqual(collapsed_qc.data[4].operation.definition.num_qubits, 3) self.assertEqual(collapsed_qc.data[4].operation.definition.num_clbits, 3) def test_collect_blocks_with_cargs_dagdependency(self): """Test collecting and collapsing blocks with classical bits appearing as cargs, using DAGDependency.""" qc = QuantumCircuit(3) qc.h(0) qc.h(1) qc.h(2) qc.measure_all() dag = circuit_to_dagdependency(qc) # Collect all measure instructions blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: isinstance(node.op, Measure), split_blocks=False, min_block_size=1 ) # We should have a single block consisting of 3 measures self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 3) self.assertEqual(blocks[0][0].op, Measure()) self.assertEqual(blocks[0][1].op, Measure()) self.assertEqual(blocks[0][2].op, Measure()) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dagdependency_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 5) self.assertEqual(collapsed_qc.data[0].operation.name, "h") self.assertEqual(collapsed_qc.data[1].operation.name, "h") self.assertEqual(collapsed_qc.data[2].operation.name, "h") self.assertEqual(collapsed_qc.data[3].operation.name, "barrier") self.assertEqual(collapsed_qc.data[4].operation.name, "COLLAPSED") self.assertEqual(collapsed_qc.data[4].operation.definition.num_qubits, 3) self.assertEqual(collapsed_qc.data[4].operation.definition.num_clbits, 3) def test_collect_blocks_with_clbits(self): """Test collecting and collapsing blocks with classical bits appearing under condition.""" qc = QuantumCircuit(4, 3) qc.cx(0, 1).c_if(0, 1) qc.cx(2, 3) qc.cx(1, 2) qc.cx(0, 1) qc.cx(2, 3).c_if(1, 0) dag = circuit_to_dag(qc) # Collect all cx gates (including the conditional ones) blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1 ) # We should have a single block consisting of all CX nodes self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 5) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dag_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 1) self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED") self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 4) self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 2) def test_collect_blocks_with_clbits_dagdependency(self): """Test collecting and collapsing blocks with classical bits appearing under conditions, using DAGDependency.""" qc = QuantumCircuit(4, 3) qc.cx(0, 1).c_if(0, 1) qc.cx(2, 3) qc.cx(1, 2) qc.cx(0, 1) qc.cx(2, 3).c_if(1, 0) dag = circuit_to_dagdependency(qc) # Collect all cx gates (including the conditional ones) blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1 ) # We should have a single block consisting of all CX nodes self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 5) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dagdependency_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 1) self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED") self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 4) self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 2) def test_collect_blocks_with_clbits2(self): """Test collecting and collapsing blocks with classical bits appearing under condition.""" qreg = QuantumRegister(4, "qr") creg = ClassicalRegister(3, "cr") cbit = Clbit() qc = QuantumCircuit(qreg, creg, [cbit]) qc.cx(0, 1).c_if(creg[1], 1) qc.cx(2, 3).c_if(cbit, 0) qc.cx(1, 2) qc.cx(0, 1).c_if(creg[2], 1) dag = circuit_to_dag(qc) # Collect all cx gates (including the conditional ones) blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1 ) # We should have a single block consisting of all CX nodes self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 4) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dag_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 1) self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED") self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 4) self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 3) def test_collect_blocks_with_clbits2_dagdependency(self): """Test collecting and collapsing blocks with classical bits appearing under condition, using DAGDependency.""" qreg = QuantumRegister(4, "qr") creg = ClassicalRegister(3, "cr") cbit = Clbit() qc = QuantumCircuit(qreg, creg, [cbit]) qc.cx(0, 1).c_if(creg[1], 1) qc.cx(2, 3).c_if(cbit, 0) qc.cx(1, 2) qc.cx(0, 1).c_if(creg[2], 1) dag = circuit_to_dag(qc) # Collect all cx gates (including the conditional ones) blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1 ) # We should have a single block consisting of all CX nodes self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 4) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dag_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 1) self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED") self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 4) self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 3) def test_collect_blocks_with_cregs(self): """Test collecting and collapsing blocks with classical registers appearing under condition.""" qreg = QuantumRegister(4, "qr") creg = ClassicalRegister(3, "cr") creg2 = ClassicalRegister(2, "cr2") qc = QuantumCircuit(qreg, creg, creg2) qc.cx(0, 1).c_if(creg, 3) qc.cx(1, 2) qc.cx(0, 1).c_if(creg[2], 1) dag = circuit_to_dag(qc) # Collect all cx gates (including the conditional ones) blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1 ) # We should have a single block consisting of all CX nodes self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 3) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dag_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 1) self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED") self.assertEqual(len(collapsed_qc.data[0].operation.definition.cregs), 1) self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 3) self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 3) def test_collect_blocks_with_cregs_dagdependency(self): """Test collecting and collapsing blocks with classical registers appearing under condition, using DAGDependency.""" qreg = QuantumRegister(4, "qr") creg = ClassicalRegister(3, "cr") creg2 = ClassicalRegister(2, "cr2") qc = QuantumCircuit(qreg, creg, creg2) qc.cx(0, 1).c_if(creg, 3) qc.cx(1, 2) qc.cx(0, 1).c_if(creg[2], 1) dag = circuit_to_dagdependency(qc) # Collect all cx gates (including the conditional ones) blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1 ) # We should have a single block consisting of all CX nodes self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 3) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dagdependency_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 1) self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED") self.assertEqual(len(collapsed_qc.data[0].operation.definition.cregs), 1) self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 3) self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 3) def test_collect_blocks_backwards_dagcircuit(self): """Test collecting H gates from DAGCircuit in the forward vs. the reverse directions.""" qc = QuantumCircuit(4) qc.h(0) qc.h(1) qc.h(2) qc.h(3) qc.cx(1, 2) qc.z(0) qc.z(1) qc.z(2) qc.z(3) block_collector = BlockCollector(circuit_to_dag(qc)) # When collecting in the forward direction, there are two blocks of # single-qubit gates: the first of size 6, and the second of size 2. blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["h", "z"], split_blocks=False, min_block_size=1, collect_from_back=False, ) self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 6) self.assertEqual(len(blocks[1]), 2) # When collecting in the backward direction, there are also two blocks of # single-qubit ates: but now the first is of size 2, and the second is of size 6. blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["h", "z"], split_blocks=False, min_block_size=1, collect_from_back=True, ) self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 2) self.assertEqual(len(blocks[1]), 6) def test_collect_blocks_backwards_dagdependency(self): """Test collecting H gates from DAGDependency in the forward vs. the reverse directions.""" qc = QuantumCircuit(4) qc.z(0) qc.z(1) qc.z(2) qc.z(3) qc.cx(1, 2) qc.h(0) qc.h(1) qc.h(2) qc.h(3) block_collector = BlockCollector(circuit_to_dagdependency(qc)) # When collecting in the forward direction, there are two blocks of # single-qubit gates: the first of size 6, and the second of size 2. blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["h", "z"], split_blocks=False, min_block_size=1, collect_from_back=False, ) self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 6) self.assertEqual(len(blocks[1]), 2) # When collecting in the backward direction, there are also two blocks of # single-qubit ates: but now the first is of size 1, and the second is of size 7 # (note that z(1) and CX(1, 2) commute). blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["h", "z"], split_blocks=False, min_block_size=1, collect_from_back=True, ) self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 1) self.assertEqual(len(blocks[1]), 7) def test_split_layers_dagcircuit(self): """Test that splitting blocks of nodes into layers works correctly.""" # original circuit is linear circuit = QuantumCircuit(5) circuit.cx(0, 2) circuit.cx(1, 4) circuit.cx(2, 0) circuit.cx(0, 3) circuit.swap(3, 2) circuit.swap(4, 1) block_collector = BlockCollector(circuit_to_dag(circuit)) # If we split the gates into depth-1 layers, we expect four linear blocks: # CX(0, 2), CX(1, 4) # CX(2, 0), CX(4, 1) # CX(0, 3) # CX(3, 2) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=1, split_layers=True, ) self.assertEqual(len(blocks), 4) self.assertEqual(len(blocks[0]), 2) self.assertEqual(len(blocks[1]), 2) self.assertEqual(len(blocks[2]), 1) self.assertEqual(len(blocks[3]), 1) def test_split_layers_dagdependency(self): """Test that splitting blocks of nodes into layers works correctly.""" # original circuit is linear circuit = QuantumCircuit(5) circuit.cx(0, 2) circuit.cx(1, 4) circuit.cx(2, 0) circuit.cx(0, 3) circuit.swap(3, 2) circuit.swap(4, 1) block_collector = BlockCollector(circuit_to_dagdependency(circuit)) # If we split the gates into depth-1 layers, we expect four linear blocks: # CX(0, 2), CX(1, 4) # CX(2, 0), CX(4, 1) # CX(0, 3) # CX(3, 2) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=1, split_layers=True, ) self.assertEqual(len(blocks), 4) self.assertEqual(len(blocks[0]), 2) self.assertEqual(len(blocks[1]), 2) self.assertEqual(len(blocks[2]), 1) self.assertEqual(len(blocks[3]), 1) if __name__ == "__main__": unittest.main()
https://github.com/MuhammadMiqdadKhan/Solution-of-IBM-s-Global-Quantum-Challenge-2020
MuhammadMiqdadKhan
#initialization %matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import IBMQ from qiskit.compiler import transpile, assemble from qiskit.providers.ibmq import least_busy from qiskit.tools.jupyter import * from qiskit.tools.monitor import job_monitor from qiskit.visualization import * from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter provider = IBMQ.load_account() # load your IBM Quantum Experience account # If you are a member of the IBM Q Network, fill your hub, group, and project information to # get access to your premium devices. # provider = IBMQ.get_provider(hub='', group='', project='') from may4_challenge.ex2 import get_counts, show_final_answer num_qubits = 5 meas_calibs, state_labels = complete_meas_cal(range(num_qubits), circlabel='mcal') # find the least busy device that has at least 5 qubits backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= num_qubits and not x.configuration().simulator and x.status().operational==True)) backend # run experiments on a real device shots = 8192 experiments = transpile(meas_calibs, backend=backend, optimization_level=3) job = backend.run(assemble(experiments, shots=shots)) print(job.job_id()) %qiskit_job_watcher # get measurement filter cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') meas_filter = meas_fitter.filter #print(meas_fitter.cal_matrix) meas_fitter.plot_calibration() # get noisy counts noisy_counts = get_counts(backend) plot_histogram(noisy_counts[0]) # apply measurement error mitigation and plot the mitigated counts mitigated_counts_0 = meas_filter.apply(noisy_counts[0]) plot_histogram([mitigated_counts_0, noisy_counts[0]]) # uncomment whatever answer you think is correct #answer1 = 'a' #answer1 = 'b' answer1 = 'c' #answer1 = 'd' # plot noisy counts plot_histogram(noisy_counts[1]) # apply measurement error mitigation # insert your code here to do measurement error mitigation on noisy_counts[1] plot_histogram([mitigated_counts_1, noisy_counts[1]]) # uncomment whatever answer you think is correct #answer2 = 'a' #answer2 = 'b' #answer2 = 'c' answer2 = 'd' # plot noisy counts plot_histogram(noisy_counts[2]) # apply measurement error mitigation # insert your code here to do measurement error mitigation on noisy_counts[2] plot_histogram([mitigated_counts_2, noisy_counts[2]]) # uncomment whatever answer you think is correct #answer3 = 'a' answer3 = 'b' #answer3 = 'c' #answer3 = 'd' # plot noisy counts plot_histogram(noisy_counts[3]) # apply measurement error mitigation # insert your code here to do measurement error mitigation on noisy_counts[3] plot_histogram([mitigated_counts_3, noisy_counts[3]]) # uncomment whatever answer you think is correct #answer4 = 'a' answer4 = 'b' #answer4 = 'c' #answer4 = 'd' # answer string show_final_answer(answer1, answer2, answer3, answer4)
https://github.com/quantumyatra/quantum_computing
quantumyatra
from jupyter_widget_engine import jupyter_widget_engine def start(engine): # set text under screen engine.screen['text'].description = 'Press any button to begin...' # set some parameters engine.started = False engine.pos = (8,8) engine.f = 0 def next_frame (engine): if not engine.started: # record that the game has started engine.started = True # change text under screen engine.screen['text'].description = 'The game is afoot!' # set initial player position (x,y) = engine.pos engine.screen[x,y].button_style = 'info' else: # display frame number in top left corner engine.f += 1 engine.screen[0,0].description = str(engine.f) # get current position (x,y) = engine.pos # removed player from current position engine.screen[x,y].button_style = '' # update based on controller input if engine.controller['up'].value: y -= 1 if engine.controller['down'].value: y += 1 if engine.controller['left'].value: x -= 1 if engine.controller['right'].value: x += 1 # put player at new position engine.screen[x,y].button_style = 'info' # store new position engine.pos = (x,y) engine = jupyter_widget_engine(start,next_frame,L=16)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# import common packages import itertools import logging import numpy as np from qiskit import Aer from qiskit_aqua import Operator, set_aqua_logging, QuantumInstance from qiskit_aqua.algorithms.adaptive import VQE from qiskit_aqua.algorithms.classical import ExactEigensolver from qiskit_aqua.components.optimizers import COBYLA from qiskit_chemistry.drivers import PySCFDriver, UnitsType from qiskit_chemistry.core import Hamiltonian, TransformationType, QubitMappingType from qiskit_chemistry.aqua_extensions.components.variational_forms import UCCSD from qiskit_chemistry.aqua_extensions.components.initial_states import HartreeFock # set_aqua_logging(logging.INFO) # using driver to get fermionic Hamiltonian driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0 1.6', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=True) algo_input = core.run(molecule) qubit_op = algo_input.qubit_op print("Originally requires {} qubits".format(qubit_op.num_qubits)) print(qubit_op) [symmetries, sq_paulis, cliffords, sq_list] = qubit_op.find_Z2_symmetries() print('Z2 symmetries found:') for symm in symmetries: print(symm.to_label()) print('single qubit operators found:') for sq in sq_paulis: print(sq.to_label()) print('cliffords found:') for clifford in cliffords: print(clifford.print_operators()) print('single-qubit list: {}'.format(sq_list)) tapered_ops = [] for coeff in itertools.product([1, -1], repeat=len(sq_list)): tapered_op = Operator.qubit_tapering(qubit_op, cliffords, sq_list, list(coeff)) tapered_ops.append((list(coeff), tapered_op)) print("Number of qubits of tapered qubit operator: {}".format(tapered_op.num_qubits)) ee = ExactEigensolver(qubit_op, k=1) result = core.process_algorithm_result(ee.run()) for line in result[0]: print(line) smallest_eig_value = 99999999999999 smallest_idx = -1 for idx in range(len(tapered_ops)): ee = ExactEigensolver(tapered_ops[idx][1], k=1) curr_value = ee.run()['energy'] if curr_value < smallest_eig_value: smallest_eig_value = curr_value smallest_idx = idx print("Lowest eigenvalue of the {}-th tapered operator (computed part) is {:.12f}".format(idx, curr_value)) the_tapered_op = tapered_ops[smallest_idx][1] the_coeff = tapered_ops[smallest_idx][0] print("The {}-th tapered operator matches original ground state energy, with corresponding symmetry sector of {}".format(smallest_idx, the_coeff)) # setup initial state init_state = HartreeFock(num_qubits=the_tapered_op.num_qubits, num_orbitals=core._molecule_info['num_orbitals'], qubit_mapping=core._qubit_mapping, two_qubit_reduction=core._two_qubit_reduction, num_particles=core._molecule_info['num_particles'], sq_list=sq_list) # setup variationl form var_form = UCCSD(num_qubits=the_tapered_op.num_qubits, depth=1, num_orbitals=core._molecule_info['num_orbitals'], num_particles=core._molecule_info['num_particles'], active_occupied=None, active_unoccupied=None, initial_state=init_state, qubit_mapping=core._qubit_mapping, two_qubit_reduction=core._two_qubit_reduction, num_time_slices=1, cliffords=cliffords, sq_list=sq_list, tapering_values=the_coeff, symmetries=symmetries) # setup optimizer optimizer = COBYLA(maxiter=1000) # set vqe algo = VQE(the_tapered_op, var_form, optimizer, 'matrix') # setup backend backend = Aer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend=backend) algo_result = algo.run(quantum_instance) result = core.process_algorithm_result(algo_result) for line in result[0]: print(line) print("The parameters for UCCSD are:\n{}".format(algo_result['opt_params']))
https://github.com/ctuning/ck-qiskit
ctuning
import numpy as np import IPython import ipywidgets as widgets import colorsys import matplotlib.pyplot as plt from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister from qiskit import execute, Aer, BasicAer from qiskit.visualization import plot_bloch_multivector from qiskit.tools.jupyter import * from qiskit.visualization import * import os import glob import moviepy.editor as mpy import seaborn as sns sns.set() '''========State Vector=======''' def getStateVector(qc): '''get state vector in row matrix form''' backend = BasicAer.get_backend('statevector_simulator') job = execute(qc,backend).result() vec = job.get_statevector(qc) return vec def vec_in_braket(vec: np.ndarray) -> str: '''get bra-ket notation of vector''' nqubits = int(np.log2(len(vec))) state = '' for i in range(len(vec)): rounded = round(vec[i], 3) if rounded != 0: basis = format(i, 'b').zfill(nqubits) state += np.str(rounded).replace('-0j', '+0j') state += '|' + basis + '\\rangle + ' state = state.replace("j", "i") return state[0:-2].strip() def vec_in_text_braket(vec): return '$$\\text{{State:\n $|\\Psi\\rangle = $}}{}$$'\ .format(vec_in_braket(vec)) def writeStateVector(vec): return widgets.HTMLMath(vec_in_text_braket(vec)) '''==========Bloch Sphere =========''' def getBlochSphere(qc): '''plot multi qubit bloch sphere''' vec = getStateVector(qc) return plot_bloch_multivector(vec) def getBlochSequence(path,figs): '''plot block sphere sequence and save it to a folder for gif movie creation''' try: os.mkdir(path) except: print('Directory already exist') for i,fig in enumerate(figs): fig.savefig(path+"/rot_"+str(i)+".png") return def getBlochGif(figs,path,fname,fps,remove = True): '''create gif movie from provided images''' file_list = glob.glob(path + "/*.png") list.sort(file_list, key=lambda x: int(x.split('_')[1].split('.png')[0])) clip = mpy.ImageSequenceClip(file_list, fps=fps) clip.write_gif('{}.gif'.format(fname), fps=fps) '''remove all image files after gif creation''' if remove: for file in file_list: os.remove(file) return '''=========Matrix=================''' def getMatrix(qc): '''get numpy matrix representing a circuit''' backend = BasicAer.get_backend('unitary_simulator') job = execute(qc, backend) ndArray = job.result().get_unitary(qc, decimals=3) Matrix = np.matrix(ndArray) return Matrix def plotMatrix(M): '''visualize a matrix using seaborn heatmap''' MD = [["0" for i in range(M.shape[0])] for j in range(M.shape[1])] for i in range(M.shape[0]): for j in range(M.shape[1]): r = M[i,j].real im = M[i,j].imag MD[i][j] = str(r)[0:4]+ " , " +str(im)[0:4] plt.figure(figsize = [2*M.shape[1],M.shape[0]]) sns.heatmap(np.abs(M),\ annot = np.array(MD),\ fmt = '',linewidths=.5,\ cmap='Blues') return '''=========Measurement========''' def getCount(qc): backend= Aer.get_backend('qasm_simulator') result = execute(qc,backend).result() counts = result.get_counts(qc) return counts def plotCount(counts,figsize): plot_histogram(counts) '''========Phase============''' def getPhaseCircle(vec): '''get phase color, angle and radious of phase circir''' Phase = [] for i in range(len(vec)): angles = (np.angle(vec[i]) + (np.pi * 4)) % (np.pi * 2) rgb = colorsys.hls_to_rgb(angles / (np.pi * 2), 0.5, 0.5) mag = np.abs(vec[i]) Phase.append({"rgb":rgb,"mag": mag,"ang":angles}) return Phase def getPhaseDict(QCs): '''get a dictionary of state vector phase circles for each quantum circuit and populate phaseDict list''' phaseDict = [] for qc in QCs: vec = getStateVector(qc) Phase = getPhaseCircle(vec) phaseDict.append(Phase) return phaseDict def plotiPhaseCircle(phaseDict,depth,path,show=False,save=False): '''plot any quantum circuit phase circle diagram from provided phase Dictionary''' r = 0.30 dx = 1.0 nqubit = len(phaseDict[0]) fig = plt.figure(figsize = [depth,nqubit]) for i in range(depth): x0 = i for j in range(nqubit): y0 = j+1 try: mag = phaseDict[i][j]['mag'] ang = phaseDict[i][j]['ang'] rgb = phaseDict[i][j]['rgb'] ax=plt.gca() circle1= plt.Circle((dx+x0,y0), radius = r, color = 'white') ax.add_patch(circle1) circle2= plt.Circle((dx+x0,y0), radius= r*mag, color = rgb) ax.add_patch(circle2) line = plt.plot((dx+x0,dx+x0+(r*mag*np.cos(ang))),\ (y0,y0+(r*mag*np.sin(ang))),color = "black") except: ax=plt.gca() circle1= plt.Circle((dx+x0,y0), radius = r, color = 'white') ax.add_patch(circle1) plt.ylim(nqubit+1,0) plt.yticks([y+1 for y in range(nqubit)]) plt.xticks([x for x in range(depth+2)]) plt.xlabel("Circuit Depth") plt.ylabel("Basis States") if show: plt.show() plt.savefig(path+".png") plt.close(fig) if save: plt.savefig(path +".png") plt.close(fig) return def plotiPhaseCircle_rotated(phaseDict,depth,path,show=False,save=False): '''plot any quantum circuit phase circle diagram from provided phase Dictionary''' r = 0.30 dy = 1.0 nqubit = len(phaseDict[0]) fig = plt.figure(figsize = [nqubit,depth]) for i in range(depth): y0 = i for j in range(nqubit): x0 = j+1 try: mag = phaseDict[i][j]['mag'] ang = phaseDict[i][j]['ang'] rgb = phaseDict[i][j]['rgb'] ax=plt.gca() circle1= plt.Circle((x0,dy+y0), radius = r, color = 'white') ax.add_patch(circle1) circle2= plt.Circle((x0,dy+y0), radius= r*mag, color = rgb) ax.add_patch(circle2) line = plt.plot((x0,x0+(r*mag*np.cos(ang))),\ (dy+y0,dy+y0+(r*mag*np.sin(ang))),color = "black") except: ax=plt.gca() circle1= plt.Circle((x0,dy+y0), radius = r, color = 'white') ax.add_patch(circle1) plt.ylim(0,depth+1) plt.yticks([x+1 for x in range(depth)]) plt.xticks([y for y in range(nqubit+2)]) plt.ylabel("Circuit Depth") plt.xlabel("Basis States") if show: plt.show() plt.savefig(path+".png") plt.close(fig) if save: plt.savefig(path +".png") plt.close(fig) return def getPhaseSequence(QCs,path,rotated=False): '''plot a sequence of phase circle diagram for a given sequence of quantum circuits''' try: os.mkdir(path) except: print("Directory already exist") depth = len(QCs) phaseDict =[] for i,qc in enumerate(QCs): vec = getStateVector(qc) Phase = getPhaseCircle(vec) phaseDict.append(Phase) ipath = path + "phase_" + str(i) if rotated: plotiPhaseCircle_rotated(phaseDict,depth,ipath,save=True,show=False) else: plotiPhaseCircle(phaseDict,depth,ipath,save=True,show=False) return def getPhaseGif(path,fname,fps,remove = True): '''create a gif movie file from phase circle figures''' file_list = glob.glob(path+ "/*.png") list.sort(file_list, key=lambda x: int(x.split('_')[1].split('.png')[0])) clip = mpy.ImageSequenceClip(file_list, fps=fps) clip.write_gif('{}.gif'.format(fname), fps=fps) '''remove all image files after gif creation''' if remove: for file in file_list: os.remove(file) return
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/JanLahmann/RasQberry
JanLahmann
import numpy as np import networkx as nx import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize import matplotlib.pyplot as plt LAMBDA = 10 SEED = 10 SHOTS = 10000 # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') # function f costo def f(theta): beta = theta[:p] gamma = theta[p:] # Anzats qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): cost = tsp_obj_2(state, G, LAMBDA) expected_value += cost*probability counts = result.get_counts() mean = compute_tsp_energy_2(invert_counts(counts),G) return mean return f def crear_grafo(cantidad_ciudades): pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) return G, mejor_costo, mejor_camino def run_QAOA(p,ciudades, grafo): if grafo == None: G, mejor_costo, mejor_camino = crear_grafo(ciudades) print("Mejor Costo") print(mejor_costo) print("Mejor Camino") print(mejor_camino) print("Bordes del grafo") print(G.edges()) print("Nodos") print(G.nodes()) print("Pesos") labels = nx.get_edge_attributes(G,'weight') print(labels) else: G = grafo intial_random = [] # beta, mixer Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,np.pi)) # gamma, cost Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) if __name__ == '__main__': # Run QAOA parametros: profundidad p, numero d ciudades, run_QAOA(5, 3, None)
https://github.com/andre-juan/dicke_states_preparation
andre-juan
import numpy as np import matplotlib.pyplot as plt import scipy # main classes and functions from qiskit import QuantumRegister, QuantumCircuit, Aer, execute # gates from qiskit.circuit.library import RYGate # visualization stuff from qiskit.visualization import plot_histogram ################################################################## ################################################################## # auxiliary functions ################################################################## ################################################################## def show_figure(fig): ''' auxiliar function to display plot even if it's not the last command of the cell from: https://github.com/Qiskit/qiskit-terra/issues/1682 ''' new_fig = plt.figure() new_mngr = new_fig.canvas.manager new_mngr.canvas.figure = fig fig.set_canvas(new_mngr.canvas) plt.show(fig) # =============================================== def test_circuit_qasm(qc, figsize=(12, 4)): ''' auxiliar function to simulate the execution of a quantum circuit using the qasm simulator. the quantum circuit to be simulates (qc) must have no measurements or classical registers. ''' # meausring qc.measure_all() ################################# backend = Aer.get_backend("qasm_simulator") job = execute(qc, backend, shots=1e5, seed_simulator=42) results = job.result() counts = results.get_counts() print(f"\nNumber of elements in result superposition: {len(counts)}\n") return plot_histogram(counts, title="Results", figsize=figsize) # =============================================== def test_circuit_sv(qc, print_stuff=False, figsize=(12, 4)): ''' auxiliar function to simulate the execution of a quantum circuit using the state vector simulator. optionally, prints the statevector components as well as the probabilities. ''' backend = Aer.get_backend("statevector_simulator") job = execute(qc, backend, seed_simulator=42) results = job.result() counts = results.get_counts() if print_stuff: sv = results.data(0)['statevector'] probs = sv**2 print(f"Statevector:\t{sv}\n") print(f"Probabilities:\t{probs}") print(f"\nNumber of elements in result superposition: {len(counts)}\n") return plot_histogram(counts, title="Results", figsize=figsize) ################################################################## ################################################################## # quantum circuit ################################################################## ################################################################## def gate_i(n, draw=False): ''' returns the 2-qubit gate (i), introduced in Sec. 2.2 this gate is simply a cR_y between 2 CNOTs, with rotation angle given by 2*np.arccos(np.sqrt(1/n)) args: - `n`: int, defining the rotation angle; - `draw` : bool, determines if the circuit is drawn. ''' qc_i = QuantumCircuit(2) qc_i.cnot(0, 1) theta = 2*np.arccos(np.sqrt(1/n)) cry = RYGate(theta).control(ctrl_state="1") qc_i.append(cry, [1, 0]) qc_i.cnot(0, 1) #################################### gate_i = qc_i.to_gate() gate_i.name = "$(i)$" #################################### if draw: show_figure(qc_i.draw("mpl")) return gate_i # =============================================== def gate_ii_l(l, n, draw=False): ''' returns the 2-qubit gate (ii)_l, introduced in Sec. 2.2 this gate is simply a ccR_y between 2 CNOTs, with rotation angle given by 2*np.arccos(np.sqrt(l/n)) args: - `l`: int, defining the rotation angle; - `n`: int, defining the rotation angle; - `draw` : bool, determines if the circuit is drawn. ''' qc_ii = QuantumCircuit(3) qc_ii.cnot(0, 2) theta = 2*np.arccos(np.sqrt(l/n)) ccry = RYGate(theta).control(num_ctrl_qubits = 2, ctrl_state="11") qc_ii.append(ccry, [2, 1, 0]) qc_ii.cnot(0, 2) #################################### gate_ii = qc_ii.to_gate() gate_ii.name = f"$(ii)_{l}$" #################################### if draw: show_figure(qc_ii.draw("mpl")) return gate_ii # =============================================== def gate_scs_nk(n, k, draw=False): ''' returns the SCS_{n,k} gate, which is introduced in Definition 3 and if built of one 2-qubits (i) gate and k+1 3-qubits gates (ii)_l args: - `n`: int, used as argument of `gate_i()` and `gate_ii_l()`; - `k`: int, defines the size of the gate, as well as its topology; - `draw` : bool, determines if the circuit is drawn. ''' qc_scs = QuantumCircuit(k+1) qc_scs.append(gate_i(n), [k-1, k]) for l in range(2, k+1): qc_scs.append(gate_ii_l(l, n), [k-l, k-l+1, k]) #################################### gate_scs = qc_scs.to_gate() gate_scs.name = "SCS$_{" + f"{n},{k}" + "}$" #################################### if draw: show_figure(qc_scs.decompose().draw("mpl")) return gate_scs # =============================================== def first_block(n, k, l, draw=False): ''' returns the first block of unitaries products in Lemma 2. args: - `n`: int, used to calculate indices and as argument of `gate_scs_nk()`; - `k`: int, used to calculate indices and as argument of `gate_scs_nk()`; - `l`: int, used to calculate indices and as argument of `gate_scs_nk()`; - `draw` : bool, determines if the circuit is drawn. ''' qr = QuantumRegister(n) qc_first_block = QuantumCircuit(qr) # indices of qubits to which we append identities. n_first = l-k-1 n_last = n-l # this will be a list with the qubits indices to which # we append the SCS_{n,k} gate. idxs_scs = list(range(n)) # only if ther is an identity to append to first registers if n_first != 0: # correcting the qubits indices to which we apply SCS_{n, k} idxs_scs = idxs_scs[n_first:] # applying identity to first qubits qc_first_block.i(qr[:n_first]) if n_last !=0: idxs_scs = idxs_scs[:-n_last] # appending SCS_{n, k} to appropriate indices qc_first_block.append(gate_scs_nk(l, k), idxs_scs) # applying identity to last qubits qc_first_block.i(qr[-n_last:]) else: # appending SCS_{n, k} to appropriate indices qc_first_block.append(gate_scs_nk(l, k), idxs_scs) # string with the operator, to be used as gate label str_operator = "$1^{\otimes " + f'{n_first}' + "} \otimes$ SCS$_{" + f"{l},{k}" + "} \otimes 1^{\otimes " + f"{n_last}" + "}$" #################################### gate_first_block = qc_first_block.to_gate() gate_first_block.name = str_operator #################################### if draw: show_figure(qc_first_block.decompose().draw("mpl")) return gate_first_block # =============================================== def second_block(n, k, l, draw=False): ''' returns the second block of unitaries products in Lemma 2. args: - `n`: int, used to calculate indices and as argument of `gate_scs_nk()`; - `k`: int, used to calculate indices and as argument of `gate_scs_nk()`; - `l`: int, used to calculate indices and as argument of `gate_scs_nk()`; - `draw` : bool, determines if the circuit is drawn. ''' qr = QuantumRegister(n) qc_second_block = QuantumCircuit(qr) # here we only have identities added to last registers, so it's a bit simpler n_last = n-l idxs_scs = list(range(n)) if n_last !=0: idxs_scs = idxs_scs[:-n_last] # appending SCS_{n, k} to appropriate indices qc_second_block.append(gate_scs_nk(l, l-1), idxs_scs) qc_second_block.i(qr[-n_last:]) else: # appending SCS_{n, k} to appropriate indices qc_second_block.append(gate_scs_nk(l, l-1), idxs_scs) str_operator = "SCS$_{" + f"{l},{l-1}" + "} \otimes 1^{\otimes " + f"{n_last}" + "}$" #################################### gate_second_block = qc_second_block.to_gate() gate_second_block.name = str_operator #################################### if draw: show_figure(qc_second_block.decompose().draw("mpl")) return gate_second_block # =============================================== def dicke_state(n, k, draw=False, barrier=False, only_decomposed=False): ''' returns a quantum circuit with to prepare a Dicke state with arbitrary n, k this function essentially calls previous functions, wrapping the products in Lemma 2 within the appropriate for loops for the construction of U_{n, k}, which is applied to the initial state as prescribed. args: - `n`: int, number of qubits for the Dicke state; - `k`: int, hamming weight of states to be included in the superposition; - `draw` : bool, determines if the circuit is drawn; - `barrier` : bool, determines if barriers are added to the circuit; - `only_decomposed` : bool, determines if only the 3-fold decomposed circuit is drawn. ''' qr = QuantumRegister(n) qc = QuantumCircuit(qr) ######################################## # initial state qc.x(qr[-k:]) if barrier: qc.barrier() ######################################## # applying U_{n, k} # I didn't create a function to generate a U_{n, k} gate # because I wanted to keep the possibility of adding barriers, # which are quite nice for visualizing the circuit and its elements. # apply first term in Lemma 2 # notice how this range captures exactly the product bounds. # also, it's very important to invert the range, for the gates # to be applied in the correct order!! for l in range(k+1, n+1)[::-1]: qc.append(first_block(n, k, l), range(n)) if barrier: qc.barrier() # apply second term in Lemma 2 for l in range(2, k+1)[::-1]: qc.append(second_block(n, k, l), range(n)) if barrier: qc.barrier() ######################################## # drawing if draw: # draws only the 3-fold decomposed circuit. # this opens up to (i) and (ii)_l into its components. if only_decomposed: show_figure(qc.decompose().decompose().decompose().draw("mpl")) else: show_figure(qc.draw("mpl")) print() show_figure(qc.decompose().draw("mpl")) print() show_figure(qc.decompose().decompose().draw("mpl")) print() show_figure(qc.decompose().decompose().decompose().draw("mpl")) return qc
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.compiler import transpile from qiskit.transpiler import PassManager circ = QuantumCircuit(3) circ.ccx(0, 1, 2) circ.draw(output='mpl') from qiskit.transpiler.passes import Unroller pass_ = Unroller(['u1', 'u2', 'u3', 'cx']) pm = PassManager(pass_) new_circ = pm.run(circ) new_circ.draw(output='mpl') from qiskit.transpiler import passes [pass_ for pass_ in dir(passes) if pass_[0].isupper()] from qiskit.transpiler import CouplingMap, Layout from qiskit.transpiler.passes import BasicSwap, LookaheadSwap, StochasticSwap coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]] circuit = QuantumCircuit(7) circuit.h(3) circuit.cx(0, 6) circuit.cx(6, 0) circuit.cx(0, 1) circuit.cx(3, 1) circuit.cx(3, 0) coupling_map = CouplingMap(couplinglist=coupling) bs = BasicSwap(coupling_map=coupling_map) pass_manager = PassManager(bs) basic_circ = pass_manager.run(circuit) ls = LookaheadSwap(coupling_map=coupling_map) pass_manager = PassManager(ls) lookahead_circ = pass_manager.run(circuit) ss = StochasticSwap(coupling_map=coupling_map) pass_manager = PassManager(ss) stochastic_circ = pass_manager.run(circuit) circuit.draw(output='mpl') basic_circ.draw(output='mpl') lookahead_circ.draw(output='mpl') stochastic_circ.draw(output='mpl') import math from qiskit.providers.fake_provider import FakeTokyo backend = FakeTokyo() # mimics the tokyo device in terms of coupling map and basis gates qc = QuantumCircuit(10) random_state = [ 1 / math.sqrt(4) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 0, 0, 0, 1 / math.sqrt(4) * complex(1, 0), 1 / math.sqrt(8) * complex(1, 0)] qc.initialize(random_state, range(4)) qc.draw() optimized_0 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=0) print('gates = ', optimized_0.count_ops()) print('depth = ', optimized_0.depth()) optimized_1 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=1) print('gates = ', optimized_1.count_ops()) print('depth = ', optimized_1.depth()) optimized_2 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=2) print('gates = ', optimized_2.count_ops()) print('depth = ', optimized_2.depth()) optimized_3 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=3) print('gates = ', optimized_3.count_ops()) print('depth = ', optimized_3.depth()) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit 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) circ.draw(output='mpl') from qiskit.converters import circuit_to_dag from qiskit.tools.visualization import dag_drawer dag = circuit_to_dag(circ) dag_drawer(dag) dag.op_nodes() node = dag.op_nodes()[3] print("node name: ", node.name) print("node op: ", node.op) print("node qargs: ", node.qargs) print("node cargs: ", node.cargs) print("node condition: ", node.op.condition) from qiskit.circuit.library import HGate dag.apply_operation_back(HGate(), qargs=[q[0]]) dag_drawer(dag) from qiskit.circuit.library import CCXGate dag.apply_operation_front(CCXGate(), qargs=[q[0], q[1], q[2]], cargs=[]) dag_drawer(dag) from qiskit.circuit.library import CHGate, U2Gate, CXGate mini_dag = DAGCircuit() p = QuantumRegister(2, "p") mini_dag.add_qreg(p) mini_dag.apply_operation_back(CHGate(), qargs=[p[1], p[0]]) mini_dag.apply_operation_back(U2Gate(0.1, 0.2), qargs=[p[1]]) # substitute the cx node with the above mini-dag cx_node = dag.op_nodes(op=CXGate).pop() dag.substitute_node_with_dag(node=cx_node, input_dag=mini_dag, wires=[p[0], p[1]]) dag_drawer(dag) from qiskit.converters import dag_to_circuit circuit = dag_to_circuit(dag) circuit.draw(output='mpl') from copy import copy from qiskit.transpiler.basepasses import TransformationPass from qiskit.transpiler import Layout from qiskit.circuit.library import SwapGate class BasicSwap(TransformationPass): """Maps (with minimum effort) a DAGCircuit onto a `coupling_map` adding swap gates.""" def __init__(self, coupling_map, initial_layout=None): """Maps a DAGCircuit onto a `coupling_map` using swap gates. Args: coupling_map (CouplingMap): Directed graph represented a coupling map. initial_layout (Layout): initial layout of qubits in mapping """ super().__init__() self.coupling_map = coupling_map self.initial_layout = initial_layout def run(self, dag): """Runs the BasicSwap pass on `dag`. Args: dag (DAGCircuit): DAG to map. Returns: DAGCircuit: A mapped DAG. Raises: TranspilerError: if the coupling map or the layout are not compatible with the DAG. """ new_dag = DAGCircuit() for qreg in dag.qregs.values(): new_dag.add_qreg(qreg) for creg in dag.cregs.values(): new_dag.add_creg(creg) if self.initial_layout is None: if self.property_set["layout"]: self.initial_layout = self.property_set["layout"] else: self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values()) if len(dag.qubits) != len(self.initial_layout): raise TranspilerError('The layout does not match the amount of qubits in the DAG') if len(self.coupling_map.physical_qubits) != len(self.initial_layout): raise TranspilerError( "Mappers require to have the layout to be the same size as the coupling map") canonical_register = dag.qregs['q'] trivial_layout = Layout.generate_trivial_layout(canonical_register) current_layout = trivial_layout.copy() for layer in dag.serial_layers(): subdag = layer['graph'] for gate in subdag.two_qubit_ops(): physical_q0 = current_layout[gate.qargs[0]] physical_q1 = current_layout[gate.qargs[1]] if self.coupling_map.distance(physical_q0, physical_q1) != 1: # Insert a new layer with the SWAP(s). swap_layer = DAGCircuit() swap_layer.add_qreg(canonical_register) path = self.coupling_map.shortest_undirected_path(physical_q0, physical_q1) for swap in range(len(path) - 2): connected_wire_1 = path[swap] connected_wire_2 = path[swap + 1] qubit_1 = current_layout[connected_wire_1] qubit_2 = current_layout[connected_wire_2] # create the swap operation swap_layer.apply_operation_back(SwapGate(), qargs=[qubit_1, qubit_2], cargs=[]) # layer insertion order = current_layout.reorder_bits(new_dag.qubits) new_dag.compose(swap_layer, qubits=order) # update current_layout for swap in range(len(path) - 2): current_layout.swap(path[swap], path[swap + 1]) order = current_layout.reorder_bits(new_dag.qubits) new_dag.compose(subdag, qubits=order) return new_dag q = QuantumRegister(7, 'q') in_circ = QuantumCircuit(q) in_circ.h(q[0]) in_circ.cx(q[0], q[4]) in_circ.cx(q[2], q[3]) in_circ.cx(q[6], q[1]) in_circ.cx(q[5], q[0]) in_circ.rz(0.1, q[2]) in_circ.cx(q[5], q[0]) from qiskit.transpiler import PassManager from qiskit.transpiler import CouplingMap from qiskit import BasicAer pm = PassManager() coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]] coupling_map = CouplingMap(couplinglist=coupling) pm.append([BasicSwap(coupling_map)]) out_circ = pm.run(in_circ) in_circ.draw(output='mpl') out_circ.draw(output='mpl') import logging logging.basicConfig(level='DEBUG') from qiskit.providers.fake_provider import FakeTenerife log_circ = QuantumCircuit(2, 2) log_circ.h(0) log_circ.h(1) log_circ.h(1) log_circ.x(1) log_circ.cx(0, 1) log_circ.measure([0,1], [0,1]) backend = FakeTenerife() transpile(log_circ, backend); logging.getLogger('qiskit.transpiler').setLevel('INFO') transpile(log_circ, backend); # Change log level back to DEBUG logging.getLogger('qiskit.transpiler').setLevel('DEBUG') # Transpile multiple circuits circuits = [log_circ, log_circ] transpile(circuits, backend); formatter = logging.Formatter('%(name)s - %(processName)-10s - %(levelname)s: %(message)s') handler = logging.getLogger().handlers[0] handler.setFormatter(formatter) transpile(circuits, backend); import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/arnavdas88/QuGlassyIsing
arnavdas88
!pip install qiskit J = 4.0 B_x = 2.0 B_z = 0.0 import numpy as np from qiskit.providers.aer import AerSimulator, QasmSimulator from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.aqua.operators import * from qiskit.aqua import set_qiskit_aqua_logging, QuantumInstance from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE, NumPyEigensolver from qiskit.circuit import QuantumCircuit, ParameterVector from qiskit.visualization import plot_histogram Hamiltonian = J * (Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z) - B_z * (( Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ) ) - B_x * ( ( X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X )) ansatz = TwoLocal(num_qubits=36, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True) print(ansatz) backend = AerSimulator(method='matrix_product_state') quantum_instance = QuantumInstance(backend, shots = 8192, initial_layout = None, optimization_level = 3) optimizer = COBYLA(maxiter=10000, tol=0.000000001) vqe = VQE(Hamiltonian, ansatz, optimizer, include_custom = False) print('We are using:', quantum_instance.backend) vqe_result = vqe.run(quantum_instance) print(vqe['result']) plot_histogram(vqe_result['eigenstate']) import pickle filename = "2D_Ising_Model_CountsDIS1.pkl" a = {'vqe_result': vqe_result} #This saves the data with open(filename, 'wb') as handle: pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL) # This loads the data with open(filename, 'rb') as handle: b = pickle.load(handle)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors=scale_factors) print("created zne_qcs (length:", len(zne_qcs), ")") t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 1 # unused # Number of trotter steps print("trotter step: ", num_steps) # execute: reps = 1 job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
# Import helper module from local folder import sys import os sys.path.append(os.getcwd()) from resources import helper # Numerical and plotting tools import numpy as np import matplotlib.pyplot as plt # Import SI unit conversion factors from resources.helper import GHz, MHz, kHz, us, ns # Importing standard Qiskit libraries from qiskit import IBMQ from qiskit.tools.jupyter import * # Loading your IBM Quantum account IBMQ.load_account() # IBMQ.providers() # see a list of providers you have access to # Get the special provider assigned to you using information from the output above hub_name = 'iqc2021-1' # e.g. 'iqc2021-1' group_name = 'challenge-159' # e.g. 'challenge-1' project_name = 'ex4' # Your project name should be 'ex4' provider = IBMQ.get_provider(hub=hub_name, group=group_name, project=project_name) # Get `ibmq_jakarta` backend from the provider backend_name = 'ibmq_jakarta' backend = provider.get_backend(backend_name) backend # See details of the `ibmq_jakarta` quantum system from qiskit import pulse from qiskit.pulse import Play, Schedule, DriveChannel # Please use qubit 0 throughout the notebook qubit = 0 backend_config = backend.configuration() exc_chans = helper.get_exc_chans(globals()) dt = backend_config.dt print(f"Sampling time: {dt*1e9} ns") backend_defaults = backend.defaults() center_frequency = backend_defaults.qubit_freq_est inst_sched_map = backend_defaults.instruction_schedule_map inst_sched_map.instructions # Retrieve calibrated measurement pulse from backend meas = inst_sched_map.get('measure', qubits=[qubit]) meas.exclude(channels=exc_chans).draw(time_range=[0,1000]) from qiskit.pulse import DriveChannel, Gaussian # The same spec pulse for both 01 and 12 spec drive_amp = 0.25 drive_duration = inst_sched_map.get('x', qubits=[qubit]).duration # Calibrated backend pulse use advanced DRAG pulse to reduce leakage to the |2> state. # Here we will use simple Gaussian pulse drive_sigma = drive_duration // 4 # DRAG pulses typically 4*sigma long. spec_pulse = Gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma, name=f"Spec drive amplitude = {drive_amp}") # Construct an np array of the frequencies for our experiment spec_freqs_GHz = helper.get_spec01_freqs(center_frequency, qubit) # Create the base schedule # Start with drive pulse acting on the drive channel spec01_scheds = [] for freq in spec_freqs_GHz: with pulse.build(name="Spec Pulse at %.3f GHz" % freq) as spec01_sched: with pulse.align_sequential(): # Pay close attention to this part to solve the problem at the end pulse.set_frequency(freq*GHz, DriveChannel(qubit)) pulse.play(spec_pulse, DriveChannel(qubit)) pulse.call(meas) spec01_scheds.append(spec01_sched) # Draw spec01 schedule spec01_scheds[-1].exclude(channels=exc_chans).draw(time_range=[0,1000]) from qiskit.tools.monitor import job_monitor # Run the job on a real backend spec01_job = backend.run(spec01_scheds, job_name="Spec 01", **helper.job_params) print(spec01_job.job_id()) job_monitor(spec01_job) # If the queuing time is too long, you can save the job id # And retrieve the job after it's done # Replace 'JOB_ID' with the the your job id and uncomment to line below #spec01_job = backend.retrieve_job('JOB_ID') from resources.helper import SpecFitter amp_guess = 5e6 f01_guess = 5 B = 1 C = 0 fit_guess = [amp_guess, f01_guess, B, C] fit = SpecFitter(spec01_job.result(), spec_freqs_GHz, qubits=[qubit], fit_p0=fit_guess) fit.plot(0, series='z') f01 = fit.spec_freq(0, series='z') print("Spec01 frequency is %.6f GHz" % f01) # Retrieve qubit frequency from backend properties f01_calibrated = backend.properties().frequency(qubit) / GHz f01_error = abs(f01-f01_calibrated) * 1000 # error in MHz print("Qubit frequency error is %.6f MHz" % f01_error) max_rabi_amp = 0.75 rabi_amps = helper.get_rabi_amps(max_rabi_amp) rabi_scheds = [] for ridx, amp in enumerate(rabi_amps): with pulse.build(name="rabisched_%d_0" % ridx) as sched: # '0' corresponds to Rabi with pulse.align_sequential(): pulse.set_frequency(f01*GHz, DriveChannel(qubit)) rabi_pulse = Gaussian(duration=drive_duration, amp=amp, \ sigma=drive_sigma, name=f"Rabi drive amplitude = {amp}") pulse.play(rabi_pulse, DriveChannel(qubit)) pulse.call(meas) rabi_scheds.append(sched) # Draw rabi schedule rabi_scheds[-1].exclude(channels=exc_chans).draw(time_range=[0,1000]) # Run the job on a real device rabi_job = backend.run(rabi_scheds, job_name="Rabi", **helper.job_params) print(rabi_job.job_id()) job_monitor(rabi_job) # If the queuing time is too long, you can save the job id # And retrieve the job after it's done # Replace 'JOB_ID' with the the your job id and uncomment to line below #rabi_job = backend.retrieve_job('JOB_ID') from qiskit.ignis.characterization.calibrations.fitters import RabiFitter amp_guess = 5e7 fRabi_guess = 2 phi_guess = 0.5 c_guess = 0 fit_guess = [amp_guess, fRabi_guess, phi_guess, c_guess] fit = RabiFitter(rabi_job.result(), rabi_amps, qubits=[qubit], fit_p0=fit_guess) fit.plot(qind=0, series='0') x180_amp = fit.pi_amplitude() print("Pi amplitude is %.3f" % x180_amp) # Define pi pulse x_pulse = Gaussian(duration=drive_duration, amp=x180_amp, sigma=drive_sigma, name='x_pulse') def build_spec12_pulse_schedule(freq, anharm_guess_GHz): with pulse.build(name="Spec Pulse at %.3f GHz" % (freq+anharm_guess_GHz)) as spec12_schedule: with pulse.align_sequential(): # WRITE YOUR CODE BETWEEN THESE LINES - START # X Pulse pulse.set_frequency(f01*GHz, DriveChannel(qubit)) pulse.play(x_pulse, DriveChannel(qubit)) # 0-2 Spec Pulse pulse.set_frequency((freq+anharm_guess_GHz)*GHz, DriveChannel(qubit)) pulse.play(spec_pulse, DriveChannel(qubit)) pulse.call(meas) # WRITE YOUR CODE BETWEEN THESE LINES - END return spec12_schedule anharmonicity_guess_GHz = -0.3 # your anharmonicity guess freqs_GHz = helper.get_spec12_freqs(f01, qubit) # Now vary the sideband frequency for each spec pulse spec12_scheds = [] for freq in freqs_GHz: spec12_scheds.append(build_spec12_pulse_schedule(freq, anharmonicity_guess_GHz)) # Draw spec12 schedule spec12_scheds[-1].exclude(channels=exc_chans).draw(time_range=[0,1000]) spec12_scheds[1].exclude(channels=exc_chans).draw(time_range=[0,1000]) # Run the job on a real device spec12_job = backend.run(spec12_scheds, job_name="Spec 12", **helper.job_params) print(spec12_job.job_id()) job_monitor(spec12_job) # If the queuing time is too long, you can save the job id # And retrieve the job after it's done # Replace 'JOB_ID' with the the your job id and uncomment to line below #spec12_job = backend.retrieve_job('JOB_ID') amp_guess = 2e7 f12_guess = f01 - 0.3 B = .1 C = 0 fit_guess = [amp_guess, f12_guess, B, C] fit = SpecFitter(spec12_job.result(), freqs_GHz+anharmonicity_guess_GHz, qubits=[qubit], fit_p0=fit_guess) fit.plot(0, series='z') f12 = fit.spec_freq(0, series='z') print("Spec12 frequency is %.6f GHz" % f12) # Check your answer using following code from qc_grader import grade_ex4 grade_ex4(f12,qubit,backend_name) # Submit your answer. You can re-submit at any time. from qc_grader import submit_ex4 submit_ex4(f12,qubit,backend_name) Ec = f01 - f12 Ej = (2*f01-f12)**2/(8*(f01-f12)) print(f"Ej/Ec: {Ej/Ec:.2f}") # This value is typically ~ 30
https://github.com/dukeskardashian/encryptedConnQ
dukeskardashian
from qiskit import QuantumCircuit, Aer, execute # Erstellen eines Quanten-Schaltkreises qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) # Simulation der Quantenverschlüsselung simulator = Aer.get_backend('qasm_simulator') job = execute(qc, simulator, shots=1) result = job.result() counts = result.get_counts(qc) # Ausgabe der verschlüsselten Bits print('Ergebnis:', counts) #Allgemeines Beispiel für den Aufbau einer verschlüsselten Verbindung mit einer #simulierten Quantenverschlüsselung unter Verwendung des Qiskit-Frameworks von IBM Quantum.
https://github.com/FilipeChagasDev/register-by-constant-qft-adder
FilipeChagasDev
import qiskit from qiskit_reg_by_const_qft_adder import reg_by_const_qft_adder from numeric_systems import * from typing import * from test_tools import * for a in range(-4, 3): for c in range(-4, 3): #Create the quantum circuit my_circuit = qiskit.QuantumCircuit(4) #Initialize register with $a$ a_binary = integer_to_binary(a, 4) for i in range(4): if a_binary[i] == True: my_circuit.x(i) #Create gate g = reg_by_const_qft_adder(4, c) #Append gate to the circuit my_circuit.append(g, list(range(4))) #Append measurements my_circuit.measure_all() #Simulation result_binary = one_shot_simulation(my_circuit) result_integer = binary_to_integer(result_binary) print(f'a={a}, c={c}, result={result_integer}')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw, IQXSimple 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=IQXSimple())
https://github.com/yaelbh/qiskit-sympy-provider
yaelbh
# -*- coding: utf-8 -*- # Copyright 2018, 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. """ Exception for errors raised by Sympy simulators. """ from qiskit import QISKitError class SympySimulatorError(QISKitError): """Class for errors raised by the Sympy simulators.""" def __init__(self, *message): """Set the error message.""" super().__init__(*message) self.message = ' '.join(message) def __str__(self): """Return the message.""" return repr(self.message)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# load necessary Runtime libraries from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session backend = "ibmq_qasm_simulator" # use the simulator from qiskit.circuit import Parameter from qiskit.opflow import I, X, Z mu = Parameter('$\\mu$') ham_pauli = mu * X cc = Parameter('$c$') ww = Parameter('$\\omega$') ham_res = -(1/2)*ww*(I^Z) + cc*(X^X) + (ham_pauli^I) tt = Parameter('$t$') U_ham = (tt*ham_res).exp_i() from qiskit import transpile from qiskit.circuit import ClassicalRegister from qiskit.opflow import PauliTrotterEvolution, Suzuki import numpy as np num_trot_steps = 5 total_time = 10 cr = ClassicalRegister(1, 'c') spec_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=2, reps=num_trot_steps)).convert(U_ham) spec_circ = spec_op.to_circuit() spec_circ_t = transpile(spec_circ, basis_gates=['sx', 'rz', 'cx']) spec_circ_t.add_register(cr) spec_circ_t.measure(0, cr[0]) spec_circ_t.draw('mpl') # fixed Parameters fixed_params = { cc: 0.3, mu: 0.7, tt: total_time } # Parameter value for single circuit param_keys = list(spec_circ_t.parameters) # run through all the ww values to create a List of Lists of Parameter value num_pts = 101 wvals = np.linspace(-2, 2, num_pts) param_vals = [] for wval in wvals: all_params = {**fixed_params, **{ww: wval}} param_vals.append([all_params[key] for key in param_keys]) with Session(backend=backend): sampler = Sampler() job = sampler.run( circuits=[spec_circ_t]*num_pts, parameter_values=param_vals, shots=1e5 ) result = job.result() Zexps = [] for dist in result.quasi_dists: if 1 in dist: Zexps.append(1 - 2*dist[1]) else: Zexps.append(1) from qiskit.opflow import PauliExpectation, Zero param_bind = { cc: 0.3, mu: 0.7, tt: total_time } init_state = Zero^2 obsv = I^Z Zexp_exact = (U_ham @ init_state).adjoint() @ obsv @ (U_ham @ init_state) diag_meas_op = PauliExpectation().convert(Zexp_exact) Zexact_values = [] for w_set in wvals: param_bind[ww] = w_set Zexact_values.append(np.real(diag_meas_op.bind_parameters(param_bind).eval())) import matplotlib.pyplot as plt plt.style.use('dark_background') fig, ax = plt.subplots(dpi=100) ax.plot([-param_bind[mu], -param_bind[mu]], [0, 1], ls='--', color='purple') ax.plot([param_bind[mu], param_bind[mu]], [0, 1], ls='--', color='purple') ax.plot(wvals, Zexact_values, label='Exact') ax.plot(wvals, Zexps, label=f"{backend}") ax.set_xlabel(r'$\omega$ (arb)') ax.set_ylabel(r'$\langle Z \rangle$ Expectation') ax.legend() import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() from qiskit.tools.jupyter import * %qiskit_version_table
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/arian-code/nptel_quantum_assignments
arian-code
from sympy import * import numpy as np from sympy.physics.quantum import TensorProduct from sympy import Matrix, I from sympy.physics.quantum.dagger import Dagger init_printing(use_unicode=True) H=Matrix([[1/sqrt(2), 1/sqrt(2)],[1/sqrt(2), -1/sqrt(2)]]) lhs=H lhs bra_0=Matrix([[1],[0]]) ket_0=Dagger(bra_0) bra_1=Matrix([[0],[1]]) ket_1=Dagger(bra_1) bra_plus=(1/sqrt(2))*Matrix([[1],[1]]) ket_plus=Dagger(bra_plus) bra_minus=(1/sqrt(2))*Matrix([[1],[-1]]) ket_minus=Dagger(bra_minus) bra_0, ket_0, bra_1, ket_1, bra_plus, bra_minus, ket_plus, ket_minus #Test 1/sqrt(2)*(TensorProduct(bra_0, ket_0)+TensorProduct(bra_1, ket_1)) #option A rhs=1/sqrt(2)*(TensorProduct(bra_0, ket_0)+TensorProduct(bra_1, ket_1)) print (lhs) print (rhs) if (lhs==rhs): print ("It is true") else: print ("It is false") #option B rhs=(TensorProduct(bra_0, ket_plus)+TensorProduct(bra_1, ket_minus)) print (lhs) print (rhs) if (lhs==rhs): print ("It is true") else: print ("It is false") #option C rhs=1/sqrt(2)*(TensorProduct(bra_0, ket_0)+ TensorProduct(bra_0, ket_1)+ TensorProduct(bra_1, ket_0)- TensorProduct(bra_1, ket_1)) print (lhs) print (rhs) if (lhs==rhs): print ("It is true") else: print ("It is false") #option C rhs=1/sqrt(2)*(TensorProduct(bra_plus, ket_0)+ TensorProduct(bra_minus, ket_1)) print (lhs) print (rhs) if (lhs==rhs): print ("It is true") else: print ("It is false")
https://github.com/noamsgl/IBMAscolaChallenge
noamsgl
from qiskit import Aer from qiskit import execute from qiskit.test.mock import FakeVigo from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from sklearn.preprocessing import OneHotEncoder class QuantumNoiseEstimator: def __init__(self, dataset=None, classifier=RandomForestClassifier()): """ Initialize the class :param dataset: the dataset (QuantumNoiseDataset) :param classifier: the classifier to use todo: generalize classifier to an estimator (regression etc.) """ self.dataset = dataset assert self.dataset is not None, "dataset is empty" self.classifier = classifier self.encoder_decoder = QuantumDatasetEncoder(classifier) encoded_features = self.encoder_decoder.encode_features(self.dataset) encoded_labels = self.encoder_decoder.encode_labels(self.dataset) self.X_train, self.X_test, self.Y_train, self.Y_test = train_test_split(encoded_features, encoded_labels, test_size=0.33) def fit(self): """ Fit the model to the dataset :return: """ self.classifier.fit(self.X_train, self.Y_train) def predict(self, feature): encoded_feature = self.encoder_decoder.encode_feature(feature) encoded_label = self.classifier.predict(encoded_feature) decoded_label = self.encoder_decoder.decode_label(encoded_label) return decoded_label def __repr__(self): return "I am a Quantum Noise Estimator" class DatasetGenerator: def __init__(self, shots=1000): """ Initialize this class :param shots: number of times to measure each circuit """ self.shots = shots self.observations = [] self.features = [] self.labels = [] self.dataset = QuantumNoiseDataset() # Device Model self.device_backend = FakeVigo() self.coupling_map = self.device_backend.configuration().coupling_map self.simulator = Aer.get_backend('qasm simulator') def add_observation(self, circuit, noise_model): """ Add a new data point - (feature, label) -to the dataset. Blocking method (until counts are calculated) :param circuit: :param noise_model: :return: none """ feature = (circuit, noise_model) label = self.get_counts(circuit, noise_model) self.dataset.add_data_point(feature, label) def get_counts(self, circuit, noise_model): """ Simulate a circuit with a noise_model and return measurement counts :param circuit: :param noise_model: :return: measurement counts (dict) """ result = execute(circuit, self.simulator, noise_model=noise_model, coupling_map=self.coupling_map, basis_gates=noise_model.basis_gates, shots=self.shots).result() counts = result.get_counts() return counts def get_dataset(self): """ :return: the dataset (QuantumNoiseDataset) """ return self.dataset def __repr__(self): return "I am a dataset generator for quantum noise estimation" def mock_dataset(self): """ Generate a mock dataset :return: the dataset (QuantumNoiseDataset) """ raise NotImplementedError class QuantumNoiseDataset: def __init__(self): self.data_points = [] def add_data_point(self, feature, label): dp = (feature, label) self.data_points.append(dp) class QuantumDatasetEncoder: def __init__(self, classifier): """ Initialize the class :param classifier: the classifier (might be useful later) Encodes and Decodes dataset for sklearn classifier """ self.classifier = classifier self.features_encoder = OneHotEncoder() self.labels_encoder = None def encode_features(self, dataset): raise NotImplementedError def encode_labels(self, dataset): raise NotImplementedError def decode_labels(self, labels): raise NotImplementedError def decode_label(self, encoded_label): raise NotImplementedError def encode_feature(self, feature): raise NotImplementedError
https://github.com/dnnagy/qintro
dnnagy
import math import numpy as np import matplotlib as mpl from matplotlib import pyplot as plt import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute from qiskit.visualization import plot_bloch_multivector from qiskit.visualization import plot_bloch_vector from qiskit.visualization import plot_histogram qbackend = Aer.get_backend('qasm_simulator') sbackend = Aer.get_backend('statevector_simulator') ubackend = Aer.get_backend('unitary_simulator') qiskit.__version__ import torch torch.__version__ import strawberryfields as sf sf.__version__ help(sf) import cirq cirq.__version__
https://github.com/conradhaupt/Qiskit-Bayesian-Inference-Module-QCA19-
conradhaupt
import qiskit as qk import qinfer as qf from qiskit.aqua.algorithms.single_sample import IQPE,QPE from qiskit.aqua.components import iqfts from qiskit.aqua.operators import WeightedPauliOperator from qiskit.aqua.algorithms import ExactEigensolver from qiskit.aqua.components.initial_states import Custom import numpy as np from qiskit import Aer,execute from qiskit.aqua import QuantumInstance # We need distributions to model priors. from qinfer import distributions # The noisy coin model has already been implmented, so let's import it here. from qinfer.test_models import NoisyCoinModel # Next, we need to import the sequential Monte Carlo updater class. from qinfer.smc import SMCUpdater # We'll be demonstrating approximate likelihood evaluation (ALE) as well. from qinfer import ale from qinfer import FiniteOutcomeModel import matplotlib.pyplot as plt from scipy.stats import circmean import time EPS = 1e-15 def chop(value): if np.abs(value) <= EPS: return 0 else: return value def radiandiff(a,b): FULL_ROTATION = 2 * np.pi return np.min(np.abs([a - b, b - a, a - b + FULL_ROTATION, b - a + FULL_ROTATION])) # Set-up unitary with specified phase angle = np.pi / 3 real = chop(np.real(np.exp(1.j * angle))) imag = chop(np.imag(np.exp(1.j * angle))) PAULI_DICT_ZZ = { 'paulis': [ {"coeff": {"imag": imag, "real": real}, "label": "ZZ"} ] } QUBIT_OP_ZZ = WeightedPauliOperator.from_dict(PAULI_DICT_ZZ) eigen_results = ExactEigensolver(QUBIT_OP_ZZ,4).run() eigen_value = eigen_results['eigvals'][0] eigen_vector = eigen_results['eigvecs'][0] print('Eigenvalues',eigen_results['eigvals']) print('Phase is %.4f radians' %(angle)) # Setup initial state as eigenvector state_in = Custom(QUBIT_OP_ZZ.num_qubits, state_vector=eigen_vector) # Use QASM Simulator for testing simulator = Aer.get_backend('qasm_simulator') # Construct IQPE circuit and simulate iqpe_builder = IQPE( QUBIT_OP_ZZ, state_in, num_iterations=1, num_time_slices=1, expansion_mode='suzuki', expansion_order=1, shallow_circuit_concat=True) # This is required to setup iqpe_builder so we can call construct_circuit() later on iqpe_results = iqpe_circ = iqpe_builder.run(simulator,shots=1) class IQPEModel(FiniteOutcomeModel): def __init__(self): super(IQPEModel, self).__init__() ## PROPERTIES ## @property def n_modelparams(self): # phi return 1 # one for just phi, two for phi and T2 @property def expparams_dtype(self): return [('theta','float64'), ('m','int64')] @property def is_n_outcomes_constant(self): return True ## METHODS ## @staticmethod def are_models_valid(modelparams): # NOTE: If T2 is included as a model parameter, restrict it to positive return np.logical_and(modelparams[:] >= 0, modelparams[:]<=2*np.pi).all(axis=1) def n_outcomes(self, expparams): return 2 def likelihood(self, outcomes, modelparams, expparams): # We first call the superclass method, which basically # just makes sure that call count diagnostics are properly # logged. super(IQPEModel, self).likelihood(outcomes, modelparams, expparams) # Probability of getting 0 for IQPE is # P(0) = (1 + cos(M(theta - phi)))/2 # pr0 = np.exp(-expparams['m'] / expparams['T2']) * (1 + np.cos(expparams['m'] * (expparams['theta'] - modelparams[:]))) / 2 + (1 - np.exp(-expparams['m'] / expparams['T2']))/2 pr0 = (1 + np.cos(expparams['m'] * (expparams['theta'] - modelparams[:]))) / 2 # Concatenate over outcomes. return FiniteOutcomeModel.pr0_to_likelihood_array(outcomes, pr0) class PhaseSMCUpdater(SMCUpdater): @staticmethod def particle_mean(weights,locations): weighted_values = np.multiply(weights, locations) return circmean(weighted_values) N_PARTICLES = 5000 N_EXP = 20 USE_QISKIT_QASM_SIMULATOR = False SIM_N_SHOTS=4096 performance_dtype = [ ('outcome', 'i1'), ('est_mean', 'f8'), ('est_cov_mat', 'f8'), ('true_err', 'f8'), ('resample_count', 'i8'), ('elapsed_time', 'f8'), ('like_count', 'i8'), ('sim_count', 'i8'), ('bme', 'f8'), ('var', 'f8'), ('bme_err', 'f8') ] performance = np.empty((N_EXP), dtype=performance_dtype) # Set-up initial prior and QInfer model prior = distributions.UniformDistribution([0, 2 * np.pi]) # prior = distributions.NormalDistribution(np.pi,0.5) model = IQPEModel() # Set-up initial experimental parameters THETA = prior.sample()[0][0] M = 3 data_backend = Aer.get_backend('qasm_simulator') # Create a Bayesian Inference Updater updater = PhaseSMCUpdater(model, N_PARTICLES, prior) # For each experiment we defined earlier for idx_exp in range(N_EXP): # Define experimental parameters expparams = np.array([(M,THETA)], dtype=model.expparams_dtype) # Simulate IQPE circuit and get results for inference circuit = iqpe_builder.construct_circuit(k=M,omega=THETA,measurement=True) results = execute(circuit,simulator,shots=SIM_N_SHOTS,memory=True) counts = results.result().get_counts() memory = results.result().get_memory() # Start by simulating and recording the data. # Retrieve the outcome of the simulation either from the circuit simulation or a model simulation if USE_QISKIT_QASM_SIMULATOR: outcomes = np.array([[int(m) for m in memory]]) else: outcomes = model.simulate_experiment(np.array([[angle]]),expparams,repeat=SIM_N_SHOTS) outcomes = outcomes.reshape((1,outcomes.shape[0])) # performance['outcome'][idx_exp] = [outcomes] # Reset the like_count and sim_count # properties so that we can count how many were used # by this update. Note that this is a hack; # an appropriate method should be added to # Simulatable. model._sim_count = 0 model._call_count = 0 # Time the update process # tic = toc = None # tic = time.time() # Update the posterior particles using the result of the circuit simulation updater.batch_update(outcomes, expparams) # performance[idx_exp]['elapsed_time'] = time.time() - tic # Record the performance of this updater. est_mean = updater.est_mean() performance[idx_exp]['est_mean'] = est_mean performance[idx_exp]['true_err'] = radiandiff(est_mean,angle) ** 2 performance[idx_exp]['est_cov_mat'] = updater.est_covariance_mtx() performance[idx_exp]['resample_count'] = updater.resample_count performance[idx_exp]['like_count'] = model.call_count performance[idx_exp]['sim_count'] = model.sim_count # Re-evaluate experiment parameters uniform_draw_01 = np.random.uniform() cumsum_particles = np.cumsum(updater.particle_weights) draw_index = (cumsum_particles<= uniform_draw_01).argmin() THETA = updater.particle_locations[draw_index] current_variance = updater.est_covariance_mtx()[0][0] # M modification scheme min_M = 8 - int(np.mod(idx_exp,10)/2) # min_M = 4 M = int(np.max([min_M,np.ceil(1.25/np.sqrt(current_variance))])) print(min_M,M,THETA) print('Inference completed') plot = updater.plot_posterior_marginal()
https://github.com/Pitt-JonesLab/slam_decomposition
Pitt-JonesLab
from __future__ import annotations import logging from typing import TYPE_CHECKING # using this to avoid a circular import if TYPE_CHECKING: from slam.basis import CircuitTemplate from fractions import Fraction from sys import stdout from typing import List import numpy as np from monodromy.coordinates import unitary_to_monodromy_coordinate from monodromy.coverage import ( CircuitPolytope, build_coverage_set, deduce_qlr_consequences, print_coverage_set, ) from monodromy.haar import expected_cost from monodromy.polytopes import ConvexPolytope from monodromy.static.examples import everything_polytope, exactly, identity_polytope from qiskit.converters import circuit_to_dag from qiskit.quantum_info import Operator from slam.utils.gates.custom_gates import CustomCostGate MAX_ITERS = 10 """Helper function for monodromy polytope package.""" # NOTE I'm not sure the best way to do this or if there is a more direct way already in the monodromy package somewhere # references: # https://github.com/Qiskit/qiskit-terra/blob/main/qiskit/quantum_info/synthesis/xx_decompose/decomposer.py # https://github.com/evmckinney9/monodromy/blob/main/scripts/single_circuit.py def monodromy_range_from_target(basis: CircuitTemplate, target_u) -> range: # NOTE, depending on whether using precomputed coverages, # both return a range element, because this is value is used by the optimizer to call build # in order to bind the precomputed circuit polytope, we use a set method on basis if basis.n_qubits != 2: raise ValueError("monodromy only for 2Q templates") target_coords = unitary_to_monodromy_coordinate(target_u) # XXX if the code was working everywhere this extra case would not be needed # for some reason in the custom built circuit polytope sets we built using parallel_drive_volume.py # the base case identity polytope has some broken attributes # e.g. basis.coverage[0].has_element(target_coords) throws error # so we need to check for this case and return a range of 0 manually if target_coords == [0.0, 0.0, 0.0, 0.0]: return range(0, 1) # old method when polytopes not precomputed # NOTE possible deprecated not sure when this would ever be none if basis.coverage is None: raise ValueError("Deprecated method, use precomputed coverages") iters = 0 while ( iters == 0 or not circuit_polytope.has_element(target_coords) ) and iters < MAX_ITERS: iters += 1 basis.build(iters) circuit_polytope = get_polytope_from_circuit(basis) if iters == MAX_ITERS and not circuit_polytope.has_element(target_coords): raise ValueError( "Monodromy did not find a polytope containing U, may need better gate or adjust MAX_ITERS" ) logging.info(f"Monodromy found needs {iters} basis applications") return range(iters, iters + 1) else: # new method, now we can iterate over precomputed polytopes # we want to find the first polytoped (when sorted by cost) that contains target # this sorting might be redundant but we will do it just in case found_cover = -1 sorted_polytopes = sorted(basis.coverage, key=lambda k: k.cost) for i, circuit_polytope in enumerate(sorted_polytopes): # XXX skip the identity polytope, see above if circuit_polytope.cost == 0: continue if circuit_polytope.has_element(target_coords): # set polytope basis.set_polytope(circuit_polytope) # return a default range found_cover = i break if found_cover == -1: raise ValueError("Monodromy did not find a polytope containing U") return range(found_cover, found_cover + 1) def get_polytope_from_circuit(basis: CircuitTemplate) -> ConvexPolytope: from qiskit import QuantumCircuit if isinstance(basis, QuantumCircuit): if basis.num_qubits != 2: raise ValueError("monodromy only for 2Q templates") dag = circuit_to_dag(basis) else: # if isinstance(basis, CircuitTemplate): #XXX not imported for preventing circular import if basis.n_qubits != 2: raise ValueError("monodromy only for 2Q templates") dag = circuit_to_dag(basis.circuit) circuit_polytope = identity_polytope for gate in dag.two_qubit_ops(): gd = Operator(gate.op).data b_polytope = exactly( *( Fraction(x).limit_denominator(10_000) for x in unitary_to_monodromy_coordinate(gd)[:-1] ) ) circuit_polytope = deduce_qlr_consequences( target="c", a_polytope=circuit_polytope, b_polytope=b_polytope, c_polytope=everything_polytope, ) return circuit_polytope # reference: monodromy/demo.py def gate_set_to_haar_expectation(*basis_gates: List[CustomCostGate], chatty=True): coverage_set, basis_gate_hash_dict = gate_set_to_coverage( *basis_gates, chatty=chatty ) return coverage_to_haar_expectation(coverage_set, chatty=chatty) def gate_set_to_coverage( *basis_gates: List[CustomCostGate], chatty=True, cost_1q=0, bare_cost=False ): # first converts all individal gates to circuitpolytope objeect operations = [] basis_gate_hash_dict = {} for gate in basis_gates: # this is an ugly solution, but not sure a more direct way # when we see the circuit polytope later in the basis build method, # we need to reconstruct it as a variational circuit, and need a reference to the gates # the circuitpolytopes need a hashable object so we use string # this dict looks up string->gate object if str(gate) in basis_gate_hash_dict.keys(): raise ValueError("need unique gate strings for hashing to work") basis_gate_hash_dict[str(gate)] = gate circuit_polytope = identity_polytope b_polytope = exactly( *( Fraction(x).limit_denominator(10_000) for x in unitary_to_monodromy_coordinate( np.matrix(gate, dtype=complex) )[:-1] ) ) circuit_polytope = deduce_qlr_consequences( target="c", a_polytope=circuit_polytope, b_polytope=b_polytope, c_polytope=everything_polytope, ) # use bare_cost to get cost in terms of number of gates - will be scaled by costs later # idea is we don't need to recompute everytime we change costs for speed limits or 2Q gates # this idea can't be used if using mixed basis gate sets because we need to know relative costs if bare_cost and len(basis_gates) != 1: raise ValueError("bare_cost only works for single 2Q gate sets") if hasattr(gate, "cost"): op_cost = gate.cost() + cost_1q elif bare_cost: op_cost = 1 else: op_cost = 1 operations.append( CircuitPolytope( operations=[str(gate)], cost=op_cost, convex_subpolytopes=circuit_polytope.convex_subpolytopes, ) ) # second build coverage set which finds the necessary permutations to do a complete span if chatty: logging.info("==== Working to build a set of covering polytopes ====") coverage_set = build_coverage_set(operations, chatty=chatty) # TODO: add some warning or fail condition if the coverage set fails to coverage # one way, (but there may be a more direct way) is to check if expected haar == 0 if chatty: logging.info("==== Done. Here's what we found: ====") logging.info(print_coverage_set(coverage_set)) # return circuit_polytope # return operations return coverage_set, basis_gate_hash_dict def coverage_to_haar_expectation(coverage_set, chatty=True): # finally, return the expected haar coverage if chatty: logging.info("==== Haar volumes ====") cost = expected_cost(coverage_set, chatty=chatty) stdout.flush() # fix out of order logging if chatty: logging.info(f"Haar-expectation cost: {cost}") return cost # In-house rendering, also see utils.visualize.py """ import matplotlib.pyplot as plt plt.close() fig = plt.figure() ax = fig.add_subplot(111, projection="3d") from weylchamber import WeylChamber w = WeylChamber(); total_coord_list = [] for subpoly in reduced_vertices: subpoly_coords = [[float(x) for x in coord] for coord in subpoly] total_coord_list += subpoly_coords w.scatter(*zip(*subpoly_coords)) from scipy.spatial import ConvexHull pts = np.array(total_coord_list) hull = ConvexHull(pts) for s in hull.simplices: s = np.append(s, s[0]) # Here we cycle back to the first coordinate ax.plot(pts[s, 0], pts[s, 1], pts[s, 2], "r-") w.render(ax) """
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # 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(qc, targets=[0,1,2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs) print("created zne_qcs (length:", len(zne_qcs), ")") t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") # QREM shots = 1 << 13 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()) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) jobs.append(job) dt_now = datetime.datetime.now() import pickle with open("jobs_jakarta_100step_" + 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_100step_" + 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) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) # Compute tomography fidelities for each repetition raw_fids = [] for result in results: fid = state_tomo(result, st_qcs) raw_fids.append(fid) # print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) # 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))) plt.clf() plt.style.use('ggplot') plt.figure(dpi=200) plt.title("state fidelity from Trotter step 1 to "+str(trotter_steps)) plt.plot(trotter_steps, raw_fids, label="raw fidelity") plt.plot(trotter_steps, fids, label="fidelity after QREM") plt.xlabel("number of trotter steps") plt.ylabel("fidelity") plt.grid(linestyle='dotted') for step, fid in zip(trotter_steps, raw_fids): print(step, fid) for step, fid in zip(trotter_steps, fids): print(step, fid)
https://github.com/hamburgerguy/Quantum-Algorithm-Implementations
hamburgerguy
"""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/qiskit-community/qiskit-translations-staging
qiskit-community
%matplotlib inline from qiskit_finance import QiskitFinanceError from qiskit_finance.data_providers import * import datetime import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() data = RandomDataProvider( tickers=["TICKER1", "TICKER2"], start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=1, ) data.run() means = data.get_mean_vector() print("Means:") print(means) rho = data.get_similarity_matrix() print("A time-series similarity measure:") print(rho) plt.imshow(rho) plt.show() cov = data.get_covariance_matrix() print("A covariance matrix:") print(cov) plt.imshow(cov) plt.show() print("The underlying evolution of stock prices:") for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() for (cnt, s) in enumerate(data._tickers): print(s) print(data._data[cnt]) data = RandomDataProvider( tickers=["CompanyA", "CompanyB", "CompanyC"], start=datetime.datetime(2015, 1, 1), end=datetime.datetime(2016, 1, 30), seed=1, ) data.run() for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() stocks = ["GOOG", "AAPL"] token = "REPLACE-ME" if token != "REPLACE-ME": try: wiki = WikipediaDataProvider( token=token, tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), ) wiki.run() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") if token != "REPLACE-ME": if wiki._data: if wiki._n <= 1: print( "Not enough wiki data to plot covariance or time-series similarity. Please use at least two tickers." ) else: rho = wiki.get_similarity_matrix() print("A time-series similarity measure:") print(rho) plt.imshow(rho) plt.show() cov = wiki.get_covariance_matrix() print("A covariance matrix:") print(cov) plt.imshow(cov) plt.show() else: print("No wiki data loaded.") if token != "REPLACE-ME": if wiki._data: print("The underlying evolution of stock prices:") for (cnt, s) in enumerate(stocks): plt.plot(wiki._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() for (cnt, s) in enumerate(stocks): print(s) print(wiki._data[cnt]) else: print("No wiki data loaded.") token = "REPLACE-ME" if token != "REPLACE-ME": try: nasdaq = DataOnDemandProvider( token=token, tickers=["GOOG", "AAPL"], start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 2), ) nasdaq.run() for (cnt, s) in enumerate(nasdaq._tickers): plt.plot(nasdaq._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") token = "REPLACE-ME" if token != "REPLACE-ME": try: lse = ExchangeDataProvider( token=token, tickers=["AEO", "ABBY", "ADIG", "ABF", "AEP", "AAL", "AGK", "AFN", "AAS", "AEFS"], stockmarket=StockMarket.LONDON, start=datetime.datetime(2018, 1, 1), end=datetime.datetime(2018, 12, 31), ) lse.run() for (cnt, s) in enumerate(lse._tickers): plt.plot(lse._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") try: data = YahooDataProvider( tickers=["MSFT", "AAPL", "GOOG"], start=datetime.datetime(2021, 1, 1), end=datetime.datetime(2021, 12, 31), ) data.run() for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend(loc="upper center", bbox_to_anchor=(0.5, 1.1), ncol=3) plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: data = None print(ex) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright