repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/ctuning/ck-qiskit
ctuning
#!/usr/bin/env python3 """ Example used in the readme. In this example a Bell state is made and then measured. ## Running this script using the "lightweight" CK infrastructure to import QISKit library... # 1) on local simulator: ck virtual env --tags=lib,qiskit --shell_cmd=quantum_coin_flip.py # 2) on remote simulator (need the API Token from IBM QuantumExperience) : CK_IBM_BACKEND=ibmq_qasm_simulator ck virtual `ck search env:* --tags=qiskit,lib` `ck search env:* --tags=ibmqx,login` --shell_cmd=quantum_coin_flip.py # 3) on remote quantum hardware (need the API Token from IBM QuantumExperience) : CK_IBM_BACKEND=ibmqx4 ck virtual `ck search env:* --tags=qiskit,lib` `ck search env:* --tags=ibmqx,login` --shell_cmd=quantum_coin_flip.py """ import sys import os # We don't know from where the user is running the example, # so we need a relative position from this file path. # TODO: Relative imports for intra-package imports are highly discouraged. # http://stackoverflow.com/a/7506006 sys.path.append(os.path.join(os.path.dirname(__file__), '../..')) from qiskit import QuantumProgram, QISKitError, available_backends, register try: import Qconfig register(Qconfig.APItoken, Qconfig.config["url"], verify=False, hub=Qconfig.config["hub"], group=Qconfig.config["group"], project=Qconfig.config["project"]) except: print(""" WARNING: There's no connection with IBMQuantumExperience servers. cannot test I/O intesive tasks, will only test CPU intensive tasks running the jobs in the local simulator """) available_backends = available_backends() print("The backends available for use are: {}\n".format(available_backends)) backend = os.environ.get('CK_IBM_BACKEND', 'local_qasm_simulator') email = os.environ.get('CK_IBM_API_EMAIL', 'N/A') print("User email: {}\n".format(email)) timeout = int( os.environ.get('CK_IBM_TIMEOUT', 120) ) shots = int( os.environ.get('CK_IBM_REPETITION', 10) ) # Create a QuantumProgram object instance. Q_program = QuantumProgram() try: # Create a Quantum Register called "qr" with 2 qubits. qr = Q_program.create_quantum_register("qr", 2) # Create a Classical Register called "cr" with 2 bits. cr = Q_program.create_classical_register("cr", 2) # Create a Quantum Circuit called "qc" with the Quantum Register "qr" # and the Classical Register "cr". qc = Q_program.create_circuit("bell", [qr], [cr]) # Add an H gate to qubit 0, putting this qubit in superposition. qc.h(qr[0]) # Add a CX gate to control qubit 0 and target qubit 1, putting # the qubits in a Bell state. qc.cx(qr[0], qr[1]) # Add a Measure gate to observe the state. qc.measure(qr, cr) # Compile and execute the Quantum Program using the given backend. result = Q_program.execute(["bell"], backend=backend, shots=shots, seed=1, timeout=timeout) # Show the results. print(result) # 'COMPLETED' q_execution_time = result.get_data().get('time') if q_execution_time: print("Quantum execution time: {} sec".format(q_execution_time) ) print(result.get_data("bell")) except QISKitError as ex: print('Error in the circuit! {}'.format(ex)) ########################### Save output to CK format. ############################## import json import numpy as np # See https://stackoverflow.com/questions/26646362/numpy-array-is-not-json-serializable # class NumpyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.ndarray): return obj.tolist() elif isinstance(obj, np.bool_): return bool(obj) elif isinstance(obj, np.complex): return obj.real # if you care about the imaginary part, try (obj.real, obj.imag) return json.JSONEncoder.default(self, obj) output_dict = { 'backends': available_backends, 'email': email, 'result': result.get_data("bell"), } formatted_json = json.dumps(output_dict, cls=NumpyEncoder, sort_keys = True, indent = 4) #print(formatted_json) with open('tmp-ck-timer.json', 'w') as json_file: json_file.write( formatted_json )
https://github.com/ctuning/ck-qiskit
ctuning
# 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. """ Quantum teleportation example. Note: if you have only cloned the Qiskit repository but not used `pip install`, the examples only work from the root directory. """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import BasicAer from qiskit import execute ############################################################### # Set the backend name and coupling map. ############################################################### coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]] backend = BasicAer.get_backend("qasm_simulator") ############################################################### # Make a quantum program for quantum teleportation. ############################################################### q = QuantumRegister(3, "q") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c0, c1, c2, name="teleport") # Prepare an initial state qc.u(0.3, 0.2, 0.1, q[0]) # Prepare a Bell pair qc.h(q[1]) qc.cx(q[1], q[2]) # Barrier following state preparation qc.barrier(q) # Measure in the Bell basis qc.cx(q[0], q[1]) qc.h(q[0]) qc.measure(q[0], c0[0]) qc.measure(q[1], c1[0]) # Apply a correction qc.barrier(q) qc.z(q[2]).c_if(c0, 1) qc.x(q[2]).c_if(c1, 1) qc.measure(q[2], c2[0]) ############################################################### # Execute. # Experiment does not support feedback, so we use the simulator ############################################################### # First version: not mapped initial_layout = {q[0]: 0, q[1]: 1, q[2]: 2} job = execute(qc, backend=backend, coupling_map=None, shots=1024, initial_layout=initial_layout) result = job.result() print(result.get_counts(qc)) # Second version: mapped to 2x8 array coupling graph job = execute( qc, backend=backend, coupling_map=coupling_map, shots=1024, initial_layout=initial_layout ) result = job.result() print(result.get_counts(qc)) # Both versions should give the same distribution
https://github.com/ctuning/ck-qiskit
ctuning
# -*- coding: utf-8 -*- # Copyright 2017, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. """ The eval_hamiltonian function has been borrowed from QISKit's tools/apps/optimization.py and slightly modified by dividiti to fit our benchmarking needs. """ import uuid import copy import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.extensions.standard import h, x, y, z from qiskit.tools.apps.optimization import make_Hamiltonian, group_paulis, measure_pauli_z def eval_hamiltonian(Q_program, hamiltonian, input_circuit, shots, device, timeout=60): """Calculates the average value of a Hamiltonian on a state created by the input circuit Args: Q_program (QuantumProgram): QuantumProgram object used to run the input circuit. hamiltonian (array or matrix or list): a representation of the Hamiltonian or observables to be measured. If it is a list, it is a list of Pauli operators grouped into tpb sets. input_circuit (QuantumCircuit): input circuit. shots (int): number of shots considered in the averaging. If 1 the averaging is exact. device (str): the backend used to run the simulation. Returns: float: Average value of the Hamiltonian or observable. """ energy = 0 q_execution_times = [] if 'statevector' in device: # Hamiltonian is not a pauli_list grouped into tpb sets if not isinstance(hamiltonian, list): circuit = ['c' + str(uuid.uuid4())] # unique random circuit for no collision Q_program.add_circuit(circuit[0], input_circuit) result = Q_program.execute(circuit, device, shots=shots, timeout=timeout, config={"data": ["statevector"]}) statevector = result.get_data(circuit[0]).get('statevector') if statevector is None: statevector = result.get_data( circuit[0]).get('statevector') if statevector: statevector = statevector[0] # Diagonal Hamiltonian represented by 1D array if (hamiltonian.shape[0] == 1 or np.shape(np.shape(np.array(hamiltonian))) == (1,)): energy = np.sum(hamiltonian * np.absolute(statevector) ** 2) # Hamiltonian represented by square matrix elif hamiltonian.shape[0] == hamiltonian.shape[1]: energy = np.inner(np.conjugate(statevector), np.dot(hamiltonian, statevector)) # Hamiltonian represented by a Pauli list else: circuits = [] circuits_labels = [] circuits.append(input_circuit) # Trial circuit w/o the final rotations circuits_labels.append('circuit_label0' + str(uuid.uuid4())) Q_program.add_circuit(circuits_labels[0], circuits[0]) # Execute trial circuit with final rotations for each Pauli in # hamiltonian and store from circuits[1] on n_qubits = input_circuit.regs['q'].size q = QuantumRegister(n_qubits, "q") i = 1 for p in hamiltonian: circuits.append(copy.deepcopy(input_circuit)) for j in range(n_qubits): if p[1].v[j] == 0 and p[1].w[j] == 1: circuits[i].x(q[j]) elif p[1].v[j] == 1 and p[1].w[j] == 0: circuits[i].z(q[j]) elif p[1].v[j] == 1 and p[1].w[j] == 1: circuits[i].y(q[j]) circuits_labels.append('circuit_label' + str(i) + str(uuid.uuid4())) Q_program.add_circuit(circuits_labels[i], circuits[i]) i += 1 result = Q_program.execute(circuits_labels, device, shots=shots, timeout=timeout) # no Pauli final rotations statevector_0 = result.get_data( circuits_labels[0])['statevector'] i = 1 for p in hamiltonian: statevector_i = result.get_data( circuits_labels[i])['statevector'] # inner product with final rotations of (i-1)-th Pauli energy += p[0] * np.inner(np.conjugate(statevector_0), statevector_i) i += 1 # finite number of shots and hamiltonian grouped in tpb sets else: circuits = [] circuits_labels = [] n = int(len(hamiltonian[0][0][1].v)) q = QuantumRegister(n, "q") c = ClassicalRegister(n, "c") i = 0 for tpb_set in hamiltonian: circuits.append(copy.deepcopy(input_circuit)) circuits_labels.append('tpb_circuit_' + str(i) + str(uuid.uuid4())) for j in range(n): # Measure X if tpb_set[0][1].v[j] == 0 and tpb_set[0][1].w[j] == 1: circuits[i].h(q[j]) # Measure Y elif tpb_set[0][1].v[j] == 1 and tpb_set[0][1].w[j] == 1: circuits[i].s(q[j]).inverse() circuits[i].h(q[j]) circuits[i].measure(q[j], c[j]) Q_program.add_circuit(circuits_labels[i], circuits[i]) i += 1 result = Q_program.execute(circuits_labels, device, shots=shots, timeout=timeout) for j, _ in enumerate(hamiltonian): # print( "Q execution data [{}] = {}".format(j, result.get_data(circuits_labels[j]))) q_execution_time = result.get_data(circuits_labels[j]).get('time') if q_execution_time: q_execution_times.append( q_execution_time ) for k, _ in enumerate(hamiltonian[j]): energy += hamiltonian[j][k][0] *\ measure_pauli_z(result.get_counts( circuits_labels[j]), hamiltonian[j][k][1]) return energy, q_execution_times
https://github.com/ctuning/ck-qiskit
ctuning
#!/usr/bin/env python3 """ This script runs Variational-Quantum-Eigensolver using Qiskit library Example running it partially using CK infrastructure: ck virtual env --tag_groups='compiler,python qiskit,lib vqe,utils vqe,hamiltonian deployed,ansatz deployed,optimizer' \ --shell_cmd="$HOME/CK/ck-qiskit/program/qiskit-vqe/qiskit_vqe_common.py --start_param_value=0.5" """ import os import json import time import inspect import numpy as np from scipy import linalg as la from qiskit import QuantumProgram, register, QISKitError from qiskit.tools.apps.optimization import make_Hamiltonian, group_paulis from qiskit.tools.qi.pauli import Pauli, label_to_pauli from eval_hamiltonian import eval_hamiltonian from vqe_utils import cmdline_parse_and_report, get_first_callable, NumpyEncoder from vqe_hamiltonian import label_to_hamiltonian_coeff # the file contents will be different depending on the plugin choice import custom_ansatz # the file contents will be different depending on the plugin choice fun_evaluation_counter = 0 # global def vqe_for_qiskit(sample_number, pauli_list, timeout_seconds, json_stream_file): def expectation_estimation(current_params, report): timestamp_before_ee = time.time() timestamp_before_q_run = timestamp_before_ee # no point in taking consecutive timestamps ansatz_circuit = ansatz_function(current_params) global fun_evaluation_counter # Trying to recover from a timed-out run assuming it to be a temporary glitch: # for attempt in range(1,8): try: complex_energy, q_run_seconds = eval_hamiltonian(Q_program, pauli_list_grouped, ansatz_circuit, sample_number, q_device_name, timeout=timeout_seconds) energy = complex_energy.real break except QISKitError as e: print("{}, trying again -- attempt number {}, timeout: {} seconds".format(e, attempt, timeout_seconds)) if len(q_run_seconds)>0: # got the real measured q time total_q_run_seconds = sum( q_run_seconds ) else: # have to assume total_q_run_seconds = time.time() - timestamp_before_q_run q_run_seconds = [ total_q_run_seconds ] q_runs = len(q_run_seconds) total_q_run_shots = sample_number * q_runs q_run_shots = [sample_number] * q_runs report_this_iteration = { 'total_q_seconds_per_c_iteration' : total_q_run_seconds, 'seconds_per_individual_q_run' : q_run_seconds, 'total_q_shots_per_c_iteration' : total_q_run_shots, 'shots_per_individual_q_run' : q_run_shots, 'energy' : energy, } if report != 'TestMode': report['iterations'].append( report_this_iteration ) report['total_q_seconds'] += report_this_iteration['total_q_seconds_per_c_iteration'] # total_q_time += total report['total_q_shots'] += report_this_iteration['total_q_shots_per_c_iteration'] fun_evaluation_counter += 1 report_this_iteration['total_seconds_per_c_iteration'] = time.time() - timestamp_before_ee print(report_this_iteration, "\n") json_stream_file.write( json.dumps(report_this_iteration, cls=NumpyEncoder)+"\n" ) json_stream_file.flush() return energy # Initialise quantum program Q_program = QuantumProgram() # Groups a list of (coeff,Pauli) tuples into tensor product basis (tpb) sets pauli_list_grouped = group_paulis(pauli_list) report = { 'total_q_seconds': 0, 'total_q_shots':0, 'iterations' : [] } # Initial objective function value fun_initial = expectation_estimation(start_params, 'TestMode') print('Initial guess at start_params is: {:.4f}'.format(fun_initial)) timestamp_before_optimizer = time.time() optimizer_output = minimizer_function(expectation_estimation, start_params, my_args=(report), my_options = minimizer_options) report['total_seconds'] = time.time() - timestamp_before_optimizer # Also generate and provide a validated function value at the optimal point fun_validated = expectation_estimation(optimizer_output['x'], 'TestMode') print('Validated value at solution is: {:.4f}'.format(fun_validated)) # Exact (noiseless) calculation of the energy at the given point: complex_energy, _ = eval_hamiltonian(Q_program, pauli_list, ansatz_function(optimizer_output['x']), 1, 'local_statevector_simulator') optimizer_output['fun_exact'] = complex_energy.real optimizer_output['fun_validated'] = fun_validated print('Total Q seconds = %f' % report['total_q_seconds']) print('Total Q shots = %d' % report['total_q_shots']) print('Total seconds = %f' % report['total_seconds']) return (optimizer_output, report) if __name__ == '__main__': start_params, sample_number, q_device_name, minimizer_method, minimizer_options, minimizer_function = cmdline_parse_and_report( num_params = custom_ansatz.num_params, q_device_name_default = 'local_qasm_simulator', q_device_name_help = "Real devices: 'ibmqx4' or 'ibmqx5'. Use 'ibmq_qasm_simulator' for remote simulator or 'local_qasm_simulator' for local", minimizer_options_default = '{"maxfev":200, "xatol": 0.001, "fatol": 0.001}', start_param_value_default = 0.0 ) # q_device_name = os.environ.get('VQE_QUANTUM_BACKEND', 'local_qasm_simulator') # try 'local_qasm_simulator', 'ibmq_qasm_simulator', 'ibmqx4', 'ibmqx5' try: import Qconfig register(Qconfig.APItoken, Qconfig.config["url"], verify=False, hub=Qconfig.config["hub"], group=Qconfig.config["group"], project=Qconfig.config["project"]) except: print(""" WARNING: There's no connection with IBMQuantumExperience servers. cannot test I/O intesive tasks, will only test CPU intensive tasks running the jobs in the local simulator """) # Ignore warnings due to chopping of small imaginary part of the energy #import warnings #warnings.filterwarnings('ignore') # Load the Hamiltonian into Qiskit-friendly format: pauli_list = [ [label_to_hamiltonian_coeff[label], label_to_pauli(label)] for label in label_to_hamiltonian_coeff ] # Calculate Exact Energy classically, to compare with quantum solution: # H = make_Hamiltonian(pauli_list) classical_energy = np.amin(la.eigh(H)[0]) print('The exact ground state energy (the smallest eigenvalue of the Hamiltonian) is: {:.4f}'.format(classical_energy)) # Load the ansatz function from the plug-in ansatz_method = get_first_callable( custom_ansatz ) ansatz_function = getattr(custom_ansatz, ansatz_method) # ansatz_method is a string/name, ansatz_function is an imported callable timeout_seconds = int( os.environ.get('VQE_QUANTUM_TIMEOUT', '120') ) json_stream_file = open('vqe_stream.json', 'a') # ---------------------------------------- run VQE: -------------------------------------------------- (vqe_output, report) = vqe_for_qiskit(sample_number, pauli_list, timeout_seconds, json_stream_file) # ---------------------------------------- store the results: ---------------------------------------- json_stream_file.write( '# Experiment finished\n' ) json_stream_file.close() minimizer_src = inspect.getsource( minimizer_function ) ansatz_src = inspect.getsource( ansatz_function ) vqe_input = { "q_device_name" : q_device_name, "minimizer_method" : minimizer_method, "minimizer_src" : minimizer_src, "minimizer_options" : minimizer_options, "ansatz_method" : ansatz_method, "ansatz_src" : ansatz_src, "sample_number" : sample_number, "classical_energy" : classical_energy } output_dict = { "vqe_input" : vqe_input, "vqe_output" : vqe_output, "report" : report } formatted_json = json.dumps(output_dict, cls=NumpyEncoder, sort_keys = True, indent = 4) # print(formatted_json) with open('ibm_vqe_report.json', 'w') as json_file: json_file.write( formatted_json )
https://github.com/ctuning/ck-qiskit
ctuning
from qiskit import IBMQ from qiskit import BasicAer as Aer from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit import execute import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Circle, Rectangle import copy from ipywidgets import widgets from IPython.display import display, clear_output try: IBMQ.load_accounts() except: pass class run_game(): # Implements a puzzle, which is defined by the given inputs. def __init__(self,initialize, success_condition, allowed_gates, vi, qubit_names, eps=0.1, backend=Aer.get_backend('qasm_simulator'), shots=1024,mode='circle',verbose=False): """ initialize List of gates applied to the initial 00 state to get the starting state of the puzzle. Supported single qubit gates (applied to qubit '0' or '1') are 'x', 'y', 'z', 'h', 'ry(pi/4)'. Supported two qubit gates are 'cz' and 'cx'. Specify only the target qubit. success_condition Values for pauli observables that must be obtained for the puzzle to declare success. allowed_gates For each qubit, specify which operations are allowed in this puzzle. 'both' should be used only for operations that don't need a qubit to be specified ('cz' and 'unbloch'). Gates are expressed as a dict with an int as value. If this is non-zero, it specifies the number of times the gate is must be used (no more or less) for the puzzle to be successfully solved. If the value is zero, the player can use the gate any number of times. vi Some visualization information as a three element list. These specify: * which qubits are hidden (empty list if both shown). * whether both circles shown for each qubit (use True for qubit puzzles and False for bit puzzles). * whether the correlation circles (the four in the middle) are shown. qubit_names The two qubits are always called '0' and '1' from the programming side. But for the player, we can display different names. eps=0.1 How close the expectation values need to be to the targets for success to be declared. backend=Aer.get_backend('qasm_simulator') Backend to be used by Qiskit to calculate expectation values (defaults to local simulator). shots=1024 Number of shots used to to calculate expectation values. mode='circle' Either the standard 'Hello Quantum' visualization can be used (with mode='circle') or the alternative line based one (mode='line'). verbose=False """ def get_total_gate_list(): # Get a text block describing allowed gates. total_gate_list = "" for qubit in allowed_gates: gate_list = "" for gate in allowed_gates[qubit]: if required_gates[qubit][gate] > 0 : gate_list += ' ' + gate+" (use "+str(required_gates[qubit][gate])+" time"+"s"*(required_gates[qubit][gate]>1)+")" elif allowed_gates[qubit][gate]==0: gate_list += ' '+gate + ' ' if gate_list!="": if qubit=="both" : gate_list = "\nAllowed symmetric operations:" + gate_list else : gate_list = "\nAllowed operations for " + qubit_names[qubit] + ":\n" + " "*10 + gate_list total_gate_list += gate_list +"\n" return total_gate_list def get_success(required_gates): # Determine whether the success conditions are satisfied, both for expectation values, and the number of gates to be used. success = True grid.get_rho() if verbose: print(grid.rho) for pauli in success_condition: success = success and (abs(success_condition[pauli] - grid.rho[pauli])<eps) for qubit in required_gates: for gate in required_gates[qubit]: success = success and (required_gates[qubit][gate]==0) return success def get_command(gate,qubit): # For a given gate and qubit, return the string describing the corresoinding Qiskit string. if qubit=='both': qubit = '1' qubit_name = qubit_names[qubit] for name in qubit_names.values(): if name!=qubit_name: other_name = name # then make the command (both for the grid, and for printing to screen) if gate in ['x','y','z','h']: real_command = 'grid.qc.'+gate+'(grid.qr['+qubit+'])' clean_command = 'qc.'+gate+'('+qubit_name+')' elif gate in ['ry(pi/4)','ry(-pi/4)']: real_command = 'grid.qc.ry('+'-'*(gate=='ry(-pi/4)')+'np.pi/4,grid.qr['+qubit+'])' clean_command = 'qc.ry('+'-'*(gate=='ry(-pi/4)')+'np.pi/4,'+qubit_name+')' elif gate in ['cz','cx','swap']: real_command = 'grid.qc.'+gate+'(grid.qr['+'0'*(qubit=='1')+'1'*(qubit=='0')+'],grid.qr['+qubit+'])' clean_command = 'qc.'+gate+'('+other_name+','+qubit_name+')' return [real_command,clean_command] clear_output() bloch = [None] # set up initial state and figure grid = pauli_grid(backend=backend,shots=shots,mode=mode) for gate in initialize: eval( get_command(gate[0],gate[1])[0] ) required_gates = copy.deepcopy(allowed_gates) # determine which qubits to show in figure if allowed_gates['0']=={} : # if no gates are allowed for qubit 0, we know to only show qubit 1 shown_qubit = 1 elif allowed_gates['1']=={} : # and vice versa shown_qubit = 0 else : shown_qubit = 2 # show figure grid.update_grid(bloch=bloch[0],hidden=vi[0],qubit=vi[1],corr=vi[2],message=get_total_gate_list()) description = {'gate':['Choose gate'],'qubit':['Choose '+'qu'*vi[1]+'bit'],'action':['Make it happen!']} all_allowed_gates_raw = [] for q in ['0','1','both']: all_allowed_gates_raw += list(allowed_gates[q]) all_allowed_gates_raw = list(set(all_allowed_gates_raw)) all_allowed_gates = [] for g in ['bloch','unbloch']: if g in all_allowed_gates_raw: all_allowed_gates.append( g ) for g in ['x','y','z','h','cz','cx']: if g in all_allowed_gates_raw: all_allowed_gates.append( g ) for g in all_allowed_gates_raw: if g not in all_allowed_gates: all_allowed_gates.append( g ) gate = widgets.ToggleButtons(options=description['gate']+all_allowed_gates) qubit = widgets.ToggleButtons(options=['']) action = widgets.ToggleButtons(options=['']) boxes = widgets.VBox([gate,qubit,action]) display(boxes) if vi[1]: print('\nYour quantum program so far\n') self.program = [] def given_gate(a): # Action to be taken when gate is chosen. This sets up the system to choose a qubit. if gate.value: if gate.value in allowed_gates['both']: qubit.options = description['qubit'] + ["not required"] qubit.value = "not required" else: allowed_qubits = [] for q in ['0','1']: if (gate.value in allowed_gates[q]) or (gate.value in allowed_gates['both']): allowed_qubits.append(q) allowed_qubit_names = [] for q in allowed_qubits: allowed_qubit_names += [qubit_names[q]] qubit.options = description['qubit'] + allowed_qubit_names def given_qubit(b): # Action to be taken when qubit is chosen. This sets up the system to choose an action. if qubit.value not in ['',description['qubit'][0],'Success!']: action.options = description['action']+['Apply operation'] def given_action(c): # Action to be taken when user confirms their choice of gate and qubit. # This applied the command, updates the visualization and checks whether the puzzle is solved. if action.value not in ['',description['action'][0]]: # apply operation if action.value=='Apply operation': if qubit.value not in ['',description['qubit'][0],'Success!']: # translate bit gates to qubit gates if gate.value=='NOT': q_gate = 'x' elif gate.value=='CNOT': q_gate = 'cx' else: q_gate = gate.value if qubit.value=="not required": q = qubit_names['1'] else: q = qubit.value q01 = '0'*(qubit.value==qubit_names['0']) + '1'*(qubit.value==qubit_names['1']) + 'both'*(qubit.value=="not required") if q_gate in ['bloch','unbloch']: if q_gate=='bloch': bloch[0] = q01 else: bloch[0] = None else: command = get_command(q_gate,q01) eval(command[0]) if vi[1]: print(command[1]) self.program.append( command[1] ) if required_gates[q01][gate.value]>0: required_gates[q01][gate.value] -= 1 grid.update_grid(bloch=bloch[0],hidden=vi[0],qubit=vi[1],corr=vi[2],message=get_total_gate_list()) success = get_success(required_gates) if success: gate.options = ['Success!'] qubit.options = ['Success!'] action.options = ['Success!'] plt.close(grid.fig) else: gate.value = description['gate'][0] qubit.options = [''] action.options = [''] gate.observe(given_gate) qubit.observe(given_qubit) action.observe(given_action) class pauli_grid(): # Allows a quantum circuit to be created, modified and implemented, and visualizes the output in the style of 'Hello Quantum'. def __init__(self,backend=Aer.get_backend('qasm_simulator'),shots=1024,mode='circle'): """ backend=Aer.get_backend('qasm_simulator') Backend to be used by Qiskit to calculate expectation values (defaults to local simulator). shots=1024 Number of shots used to to calculate expectation values. mode='circle' Either the standard 'Hello Quantum' visualization can be used (with mode='circle') or the alternative line based one (mode='line'). """ self.backend = backend self.shots = shots self.box = {'ZI':(-1, 2),'XI':(-2, 3),'IZ':( 1, 2),'IX':( 2, 3),'ZZ':( 0, 3),'ZX':( 1, 4),'XZ':(-1, 4),'XX':( 0, 5)} self.rho = {} for pauli in self.box: self.rho[pauli] = 0.0 for pauli in ['ZI','IZ','ZZ']: self.rho[pauli] = 1.0 self.qr = QuantumRegister(2) self.cr = ClassicalRegister(2) self.qc = QuantumCircuit(self.qr, self.cr) self.mode = mode # colors are background, qubit circles and correlation circles, respectively if self.mode=='line': self.colors = [(1.6/255,72/255,138/255),(132/255,177/255,236/255),(33/255,114/255,216/255)] else: self.colors = [(1.6/255,72/255,138/255),(132/255,177/255,236/255),(33/255,114/255,216/255)] self.fig = plt.figure(figsize=(5,5),facecolor=self.colors[0]) self.ax = self.fig.add_subplot(111) plt.axis('off') self.bottom = self.ax.text(-3,1,"",size=9,va='top',color='w') self.lines = {} for pauli in self.box: w = plt.plot( [self.box[pauli][0],self.box[pauli][0]], [self.box[pauli][1],self.box[pauli][1]], color=(1.0,1.0,1.0), lw=0 ) b = plt.plot( [self.box[pauli][0],self.box[pauli][0]], [self.box[pauli][1],self.box[pauli][1]], color=(0.0,0.0,0.0), lw=0 ) c = {} c['w'] = self.ax.add_patch( Circle(self.box[pauli], 0.0, color=(0,0,0), zorder=10) ) c['b'] = self.ax.add_patch( Circle(self.box[pauli], 0.0, color=(1,1,1), zorder=10) ) self.lines[pauli] = {'w':w,'b':b,'c':c} def get_rho(self): # Runs the circuit specified by self.qc and determines the expectation values for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ'. bases = ['ZZ','ZX','XZ','XX'] results = {} for basis in bases: temp_qc = copy.deepcopy(self.qc) for j in range(2): if basis[j]=='X': temp_qc.h(self.qr[j]) temp_qc.barrier(self.qr) temp_qc.measure(self.qr,self.cr) job = execute(temp_qc, backend=self.backend, shots=self.shots) results[basis] = job.result().get_counts() for string in results[basis]: results[basis][string] = results[basis][string]/self.shots prob = {} # prob of expectation value -1 for single qubit observables for j in range(2): for p in ['X','Z']: pauli = {} for pp in 'IXZ': pauli[pp] = (j==1)*pp + p + (j==0)*pp prob[pauli['I']] = 0 for basis in [pauli['X'],pauli['Z']]: for string in results[basis]: if string[(j+1)%2]=='1': prob[pauli['I']] += results[basis][string]/2 # prob of expectation value -1 for two qubit observables for basis in ['ZZ','ZX','XZ','XX']: prob[basis] = 0 for string in results[basis]: if string[0]!=string[1]: prob[basis] += results[basis][string] for pauli in prob: self.rho[pauli] = 1-2*prob[pauli] def update_grid(self,rho=None,labels=False,bloch=None,hidden=[],qubit=True,corr=True,message=""): """ rho = None Dictionary of expectation values for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ'. If supplied, this will be visualized instead of the results of running self.qc. labels = None Dictionary of strings for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ' that are printed in the corresponding boxes. bloch = None If a qubit name is supplied, and if mode='line', Bloch circles are displayed for this qubit hidden = [] Which qubits have their circles hidden (empty list if both shown). qubit = True Whether both circles shown for each qubit (use True for qubit puzzles and False for bit puzzles). corr = True Whether the correlation circles (the four in the middle) are shown. message A string of text that is displayed below the grid. """ def see_if_unhidden(pauli): # For a given Pauli, see whether its circle should be shown. unhidden = True # first: does it act non-trivially on a qubit in `hidden` for j in hidden: unhidden = unhidden and (pauli[j]=='I') # second: does it contain something other than 'I' or 'Z' when only bits are shown if qubit==False: for j in range(2): unhidden = unhidden and (pauli[j] in ['I','Z']) # third: is it a correlation pauli when these are not allowed if corr==False: unhidden = unhidden and ((pauli[0]=='I') or (pauli[1]=='I')) return unhidden def add_line(line,pauli_pos,pauli): """ For mode='line', add in the line. line = the type of line to be drawn (X, Z or the other one) pauli = the box where the line is to be drawn expect = the expectation value that determines its length """ unhidden = see_if_unhidden(pauli) coord = None p = (1-self.rho[pauli])/2 # prob of 1 output # in the following, white lines goes from a to b, and black from b to c if unhidden: if line=='Z': a = ( self.box[pauli_pos][0], self.box[pauli_pos][1]+l/2 ) c = ( self.box[pauli_pos][0], self.box[pauli_pos][1]-l/2 ) b = ( (1-p)*a[0] + p*c[0] , (1-p)*a[1] + p*c[1] ) lw = 8 coord = (b[1] - (a[1]+c[1])/2)*1.2 + (a[1]+c[1])/2 elif line=='X': a = ( self.box[pauli_pos][0]+l/2, self.box[pauli_pos][1] ) c = ( self.box[pauli_pos][0]-l/2, self.box[pauli_pos][1] ) b = ( (1-p)*a[0] + p*c[0] , (1-p)*a[1] + p*c[1] ) lw = 9 coord = (b[0] - (a[0]+c[0])/2)*1.1 + (a[0]+c[0])/2 else: a = ( self.box[pauli_pos][0]+l/(2*np.sqrt(2)), self.box[pauli_pos][1]+l/(2*np.sqrt(2)) ) c = ( self.box[pauli_pos][0]-l/(2*np.sqrt(2)), self.box[pauli_pos][1]-l/(2*np.sqrt(2)) ) b = ( (1-p)*a[0] + p*c[0] , (1-p)*a[1] + p*c[1] ) lw = 9 self.lines[pauli]['w'].pop(0).remove() self.lines[pauli]['b'].pop(0).remove() self.lines[pauli]['w'] = plt.plot( [a[0],b[0]], [a[1],b[1]], color=(1.0,1.0,1.0), lw=lw ) self.lines[pauli]['b'] = plt.plot( [b[0],c[0]], [b[1],c[1]], color=(0.0,0.0,0.0), lw=lw ) return coord l = 0.9 # line length r = 0.6 # circle radius L = 0.98*np.sqrt(2) # box height and width if rho==None: self.get_rho() # draw boxes for pauli in self.box: if 'I' in pauli: color = self.colors[1] else: color = self.colors[2] self.ax.add_patch( Rectangle( (self.box[pauli][0],self.box[pauli][1]-1), L, L, angle=45, color=color) ) # draw circles for pauli in self.box: unhidden = see_if_unhidden(pauli) if unhidden: if self.mode=='line': self.ax.add_patch( Circle(self.box[pauli], r, color=(0.5,0.5,0.5)) ) else: prob = (1-self.rho[pauli])/2 self.ax.add_patch( Circle(self.box[pauli], r, color=(prob,prob,prob)) ) # update bars if required if self.mode=='line': if bloch in ['0','1']: for other in 'IXZ': px = other*(bloch=='1') + 'X' + other*(bloch=='0') pz = other*(bloch=='1') + 'Z' + other*(bloch=='0') z_coord = add_line('Z',pz,pz) x_coord = add_line('X',pz,px) for j in self.lines[pz]['c']: self.lines[pz]['c'][j].center = (x_coord,z_coord) self.lines[pz]['c'][j].radius = (j=='w')*0.05 + (j=='b')*0.04 px = 'I'*(bloch=='0') + 'X' + 'I'*(bloch=='1') pz = 'I'*(bloch=='0') + 'Z' + 'I'*(bloch=='1') add_line('Z',pz,pz) add_line('X',px,px) else: for pauli in self.box: for j in self.lines[pauli]['c']: self.lines[pauli]['c'][j].radius = 0.0 if pauli in ['ZI','IZ','ZZ']: add_line('Z',pauli,pauli) if pauli in ['XI','IX','XX']: add_line('X',pauli,pauli) if pauli in ['XZ','ZX']: add_line('ZX',pauli,pauli) self.bottom.set_text(message) if labels: for pauli in box: plt.text(self.box[pauli][0]-0.05,self.box[pauli][1]-0.85, pauli) self.ax.set_xlim([-3,3]) self.ax.set_ylim([0,6]) self.fig.canvas.draw()
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/ctuning/ck-qiskit
ctuning
# 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. """ Example use of the initialize gate to prepare arbitrary pure states. """ import math from qiskit import QuantumCircuit, execute, BasicAer ############################################################### # Make a quantum circuit for state initialization. ############################################################### circuit = QuantumCircuit(4, 4, name="initializer_circ") desired_vector = [ 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), ] circuit.initialize(desired_vector, [0, 1, 2, 3]) circuit.measure([0, 1, 2, 3], [0, 1, 2, 3]) print(circuit) ############################################################### # Execute on a simulator backend. ############################################################### shots = 10000 # Desired vector print("Desired probabilities: ") print([format(abs(x * x), ".3f") for x in desired_vector]) # Initialize on local simulator sim_backend = BasicAer.get_backend("qasm_simulator") job = execute(circuit, sim_backend, shots=shots) result = job.result() counts = result.get_counts(circuit) qubit_strings = [format(i, "04b") for i in range(2**4)] print("Probabilities from simulator: ") print([format(counts.get(s, 0) / shots, ".3f") for s in qubit_strings])
https://github.com/ctuning/ck-qiskit
ctuning
#!/usr/bin/env python3 """ Example used in the readme. In this example a Bell state is made and then measured. ## Running this script using the "lightweight" CK infrastructure to import QISKit library... # 1) on local simulator: ck virtual env --tags=lib,qiskit --shell_cmd=quantum_coin_flip.py # 2) on remote simulator (need the API Token from IBM QuantumExperience) : CK_IBM_BACKEND=ibmq_qasm_simulator ck virtual `ck search env:* --tags=qiskit,lib` `ck search env:* --tags=ibmqx,login` --shell_cmd=quantum_coin_flip.py # 3) on remote quantum hardware (need the API Token from IBM QuantumExperience) : CK_IBM_BACKEND=ibmqx4 ck virtual `ck search env:* --tags=qiskit,lib` `ck search env:* --tags=ibmqx,login` --shell_cmd=quantum_coin_flip.py """ import sys import os # We don't know from where the user is running the example, # so we need a relative position from this file path. # TODO: Relative imports for intra-package imports are highly discouraged. # http://stackoverflow.com/a/7506006 sys.path.append(os.path.join(os.path.dirname(__file__), '../..')) from qiskit import QuantumProgram, QISKitError, available_backends, register try: import Qconfig register(Qconfig.APItoken, Qconfig.config["url"], verify=False, hub=Qconfig.config["hub"], group=Qconfig.config["group"], project=Qconfig.config["project"]) except: print(""" WARNING: There's no connection with IBMQuantumExperience servers. cannot test I/O intesive tasks, will only test CPU intensive tasks running the jobs in the local simulator """) available_backends = available_backends() print("The backends available for use are: {}\n".format(available_backends)) backend = os.environ.get('CK_IBM_BACKEND', 'local_qasm_simulator') email = os.environ.get('CK_IBM_API_EMAIL', 'N/A') print("User email: {}\n".format(email)) timeout = int( os.environ.get('CK_IBM_TIMEOUT', 120) ) shots = int( os.environ.get('CK_IBM_REPETITION', 10) ) # Create a QuantumProgram object instance. Q_program = QuantumProgram() try: # Create a Quantum Register called "qr" with 2 qubits. qr = Q_program.create_quantum_register("qr", 2) # Create a Classical Register called "cr" with 2 bits. cr = Q_program.create_classical_register("cr", 2) # Create a Quantum Circuit called "qc" with the Quantum Register "qr" # and the Classical Register "cr". qc = Q_program.create_circuit("bell", [qr], [cr]) # Add an H gate to qubit 0, putting this qubit in superposition. qc.h(qr[0]) # Add a CX gate to control qubit 0 and target qubit 1, putting # the qubits in a Bell state. qc.cx(qr[0], qr[1]) # Add a Measure gate to observe the state. qc.measure(qr, cr) # Compile and execute the Quantum Program using the given backend. result = Q_program.execute(["bell"], backend=backend, shots=shots, seed=1, timeout=timeout) # Show the results. print(result) # 'COMPLETED' q_execution_time = result.get_data().get('time') if q_execution_time: print("Quantum execution time: {} sec".format(q_execution_time) ) print(result.get_data("bell")) except QISKitError as ex: print('Error in the circuit! {}'.format(ex)) ########################### Save output to CK format. ############################## import json import numpy as np # See https://stackoverflow.com/questions/26646362/numpy-array-is-not-json-serializable # class NumpyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.ndarray): return obj.tolist() elif isinstance(obj, np.bool_): return bool(obj) elif isinstance(obj, np.complex): return obj.real # if you care about the imaginary part, try (obj.real, obj.imag) return json.JSONEncoder.default(self, obj) output_dict = { 'backends': available_backends, 'email': email, 'result': result.get_data("bell"), } formatted_json = json.dumps(output_dict, cls=NumpyEncoder, sort_keys = True, indent = 4) #print(formatted_json) with open('tmp-ck-timer.json', 'w') as json_file: json_file.write( formatted_json )
https://github.com/ctuning/ck-qiskit
ctuning
# 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. """ Quantum teleportation example. Note: if you have only cloned the Qiskit repository but not used `pip install`, the examples only work from the root directory. """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import BasicAer from qiskit import execute ############################################################### # Set the backend name and coupling map. ############################################################### coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]] backend = BasicAer.get_backend("qasm_simulator") ############################################################### # Make a quantum program for quantum teleportation. ############################################################### q = QuantumRegister(3, "q") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c0, c1, c2, name="teleport") # Prepare an initial state qc.u(0.3, 0.2, 0.1, q[0]) # Prepare a Bell pair qc.h(q[1]) qc.cx(q[1], q[2]) # Barrier following state preparation qc.barrier(q) # Measure in the Bell basis qc.cx(q[0], q[1]) qc.h(q[0]) qc.measure(q[0], c0[0]) qc.measure(q[1], c1[0]) # Apply a correction qc.barrier(q) qc.z(q[2]).c_if(c0, 1) qc.x(q[2]).c_if(c1, 1) qc.measure(q[2], c2[0]) ############################################################### # Execute. # Experiment does not support feedback, so we use the simulator ############################################################### # First version: not mapped initial_layout = {q[0]: 0, q[1]: 1, q[2]: 2} job = execute(qc, backend=backend, coupling_map=None, shots=1024, initial_layout=initial_layout) result = job.result() print(result.get_counts(qc)) # Second version: mapped to 2x8 array coupling graph job = execute( qc, backend=backend, coupling_map=coupling_map, shots=1024, initial_layout=initial_layout ) result = job.result() print(result.get_counts(qc)) # Both versions should give the same distribution
https://github.com/ctuning/ck-qiskit
ctuning
#-------------------------------------------------------------------------------------------------------------- # This module contains basic gates that can be used while developing circuits on IBM QExperience #-------------------------------------------------------------------------------------------------------------- #-------------------------------------------------------------------------------------------------------------- # Import necessary modules #-------------------------------------------------------------------------------------------------------------- from qiskit import QuantumProgram import Qconfig #-------------------------------------------------------------------------------------------------------------- # The CSWAP gate # Input : Quantum program object, the Circuit name, the quantum register name, control bit number and target # bit numbers. # Output : Quantum_program_object with the relevant connections # Circuit implemented - CSWAP #-------------------------------------------------------------------------------------------------------------- def CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,Target_bit_numbers): # Get the circuit and the quantum register by name qc = Quantum_program_object.get_circuit(Circuit_name) qr = Quantum_program_object.get_quantum_register(Quantum_register_name) # Get control bit numbers and the target bit number for the addressing the qubits Control = Control_bit_number Target_1 = Target_bit_numbers[0] Target_2 = Target_bit_numbers[1] # Implement CSWAP using 3 CCNOT implementations # Implement CCNOT on Control,Target_1 and Target_2 using decomposition given by Nelson and Chuang qc.h(qr[Target_2]) qc.cx(qr[Target_1],qr[Target_2]) qc.tdg(qr[Target_2]) qc.cx(qr[Control],qr[Target_2]) qc.t(qr[Target_2]) qc.cx(qr[Target_1],qr[Target_2]) qc.tdg(qr[Target_2]) qc.cx(qr[Control],qr[Target_2]) qc.tdg(qr[Target_1]) qc.t(qr[Target_2]) qc.h(qr[Target_2]) qc.cx(qr[Control],qr[Target_1]) qc.tdg(qr[Target_1]) qc.cx(qr[Control],qr[Target_1]) qc.t(qr[Control]) qc.s(qr[Target_1]) # Implement CCNOT on Control,Target_2 and Target_1 using decomposition given by Nelson and Chuang qc.h(qr[Target_1]) qc.cx(qr[Target_2],qr[Target_1]) qc.tdg(qr[Target_1]) qc.cx(qr[Control],qr[Target_1]) qc.t(qr[Target_1]) qc.cx(qr[Target_2],qr[Target_1]) qc.tdg(qr[Target_1]) qc.cx(qr[Control],qr[Target_1]) qc.tdg(qr[Target_2]) qc.t(qr[Target_1]) qc.h(qr[Target_1]) qc.cx(qr[Control],qr[Target_2]) qc.tdg(qr[Target_2]) qc.cx(qr[Control],qr[Target_2]) qc.t(qr[Control]) qc.s(qr[Target_2]) # Implement CCNOT on Control,Target_1 and Target_2 using decomposition given by Nelson and Chuang qc.h(qr[Target_2]) qc.cx(qr[Target_1],qr[Target_2]) qc.tdg(qr[Target_2]) qc.cx(qr[Control],qr[Target_2]) qc.t(qr[Target_2]) qc.cx(qr[Target_1],qr[Target_2]) qc.tdg(qr[Target_2]) qc.cx(qr[Control],qr[Target_2]) qc.tdg(qr[Target_1]) qc.t(qr[Target_2]) qc.h(qr[Target_2]) qc.cx(qr[Control],qr[Target_1]) qc.tdg(qr[Target_1]) qc.cx(qr[Control],qr[Target_1]) qc.t(qr[Control]) qc.s(qr[Target_1]) # Return the program object return Quantum_program_object #-------------------------------------------------------------------------------------------------------------- # The CCNOT gate # Input : Quantum program object, the Circuit name, the quantum register name, control bit numbers and target # bit number. # Output : Quantum_program_object with the relevant connections # Circuit implemented - CCNOT #-------------------------------------------------------------------------------------------------------------- def CCNOT(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_numbers,Target_bit_number): # Get the circuit and the quantum register by name qc = Quantum_program_object.get_circuit(Circuit_name) qr = Quantum_program_object.get_quantum_register(Quantum_register_name) # Get control bit numbers and the target bit number for the addressing the qubits Control_1 = Control_bit_numbers[0] Control_2 = Control_bit_numbers[1] Target = Target_bit_number # Implement Hadamard on target qubits qc.h(qr[Target]) # Implement CNOT between Control_2 and Target qc.cx(qr[Control_2],qr[Target]) # Implement T (dagger) on target qubits qc.tdg(qr[Target]) # Implement CNOT between Control_1 and Target qc.cx(qr[Control_1],qr[Target]) # Implement T on target qubits qc.t(qr[Target]) # Implement CNOT between Control_2 and Target qc.cx(qr[Control_2],qr[Target]) # Implement T (dagger) on target qubits qc.tdg(qr[Target]) # Implement CNOT between Control_1 and Target qc.cx(qr[Control_1],qr[Target]) # Implement T (dagger) on Control_2, T and H on Target qc.tdg(qr[Control_2]) qc.t(qr[Target]) qc.h(qr[Target]) # Implement CNOT from Control_1 to Control_2 followed by T (dagger) on Control_2 qc.cx(qr[Control_1],qr[Control_2]) qc.tdg(qr[Control_2]) # Implement CNOT from Control_1 to Control_2 followed by T on Control_1 and S on Control_2 qc.cx(qr[Control_1],qr[Control_2]) qc.t(qr[Control_1]) qc.s(qr[Control_2]) # Return the program object return Quantum_program_object
https://github.com/ctuning/ck-qiskit
ctuning
#-------------------------------------------------------------------------------------------------------------- # This module contains control unitaries that can be used while developing circuits on IBM QExperience #-------------------------------------------------------------------------------------------------------------- #-------------------------------------------------------------------------------------------------------------- # Import necessary modules #-------------------------------------------------------------------------------------------------------------- from qiskit import QuantumProgram import Qconfig import Basic_gates # TODO make it more generalized #-------------------------------------------------------------------------------------------------------------- # The control unitary for 2mod15 on 4 quantum qubits # Input : Quantum program object, the Circuit name and the quantum register name, and the # control bit number where the connections are supposed to be made # Output : Quantum_program_object with the relevant connections # Circuit implemented - CSwap(Q[3],Q[2])->CSwap(Q[2],Q[1])->CSwap(Q[1],Q[0]) #-------------------------------------------------------------------------------------------------------------- def C_2mod15(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number): # Get the circuit and the quantum register by name qc = Quantum_program_object.get_circuit(Circuit_name) qr = Quantum_program_object.get_quantum_register(Quantum_register_name) Control_bit_number = Control_bit_number # Implement controlled swap on qr[3] and qr[2] Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[3,2]) # Implement controlled swap on qr[2] and qr[1] Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[2,1]) # Implement controlled swap on qr[1] and qr[0] Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[1,0]) # Return the program object return Quantum_program_object #-------------------------------------------------------------------------------------------------------------- # The control unitary for 7mod15 on 4 quantum qubits # Input : Quantum program object, the Circuit name and the quantum register name, and the # control bit number where the connections are supposed to be made # Output : Quantum_program_object with the relevant connections # Circuit implemented - CSwap(Q[1],Q[0])->CSwap(Q[1],Q[2])->CSwap(Q[2],Q[3])->CX on all 4 qubits #-------------------------------------------------------------------------------------------------------------- def C_7mod15(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number): # Get the circuit and the quantum register by name qc = Quantum_program_object.get_circuit(Circuit_name) qr = Quantum_program_object.get_quantum_register(Quantum_register_name) Control_bit_number = Control_bit_number # Implement controlled swap on qr[1] and qr[0] Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[1,0]) # Implement controlled swap on qr[2] and qr[1] Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[2,1]) # Implement controlled swap on qr[3] and qr[2] Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[3,2]) # Implement CX on all four qubits qc.cx(Control_bit_number,qr[3]) qc.cx(Control_bit_number,qr[2]) qc.cx(Control_bit_number,qr[1]) qc.cx(Control_bit_number,qr[0]) # Return the program object return Quantum_program_object #-------------------------------------------------------------------------------------------------------------- # The control unitary for 8mod15 on 4 quantum qubits # Input : Quantum program object, the Circuit name and the quantum register name, and the # control bit number where the connections are supposed to be made # Output : Quantum_program_object with the relevant connections # Circuit implemented - CSwap(Q[1],Q[0])->CSwap(Q[1],Q[2])->CSwap(Q[2],Q[3]) #-------------------------------------------------------------------------------------------------------------- def C_8mod15(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number): # Get the circuit and the quantum register by name qc = Quantum_program_object.get_circuit(Circuit_name) qr = Quantum_program_object.get_quantum_register(Quantum_register_name) Control_bit_number = Control_bit_number # Implement controlled swap on qr[1] and qr[0] Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[1,0]) # Implement controlled swap on qr[2] and qr[1] Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[2,1]) # Implement controlled swap on qr[3] and qr[2] Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[3,2]) # Return the program object return Quantum_program_object #-------------------------------------------------------------------------------------------------------------- # The control unitary for 11mod15 on 4 quantum qubits # Input : Quantum program object, the Circuit name and the quantum register name, and the # control bit number where the connections are supposed to be made # Output : Quantum_program_object with the relevant connections # Circuit implemented - CSwap(Q[2],Q[0])->CSwap(Q[3],Q[1])->CX on all 4 qubits #-------------------------------------------------------------------------------------------------------------- def C_11mod15(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number): # Get the circuit and the quantum register by name qc = Quantum_program_object.get_circuit(Circuit_name) qr = Quantum_program_object.get_quantum_register(Quantum_register_name) Control_bit_number = Control_bit_number # Implement controlled swap on qr[2] and qr[0] Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[2,0]) # Implement controlled swap on qr[3] and qr[1] Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[3,1]) # Implement CX on all four qubits qc.cx(Control_bit_number,qr[3]) qc.cx(Control_bit_number,qr[2]) qc.cx(Control_bit_number,qr[1]) qc.cx(Control_bit_number,qr[0]) # Return the program object return Quantum_program_object #-------------------------------------------------------------------------------------------------------------- # The control unitary for 13mod15 on 4 quantum qubits # Input : Quantum program object, the Circuit name and the quantum register name, and the # control bit number where the connections are supposed to be made # Output : Quantum_program_object with the relevant connections # Circuit implemented - CSwap(Q[3],Q[2])->CSwap(Q[2],Q[1])->CSwap(Q[1],Q[0])->CX on all 4 qubits #-------------------------------------------------------------------------------------------------------------- def C_13mod15(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number): # Get the circuit and the quantum register by name qc = Quantum_program_object.get_circuit(Circuit_name) qr = Quantum_program_object.get_quantum_register(Quantum_register_name) Control_bit_number = Control_bit_number # Implement controlled swap on qr[3] and qr[2] Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[3,2]) # Implement controlled swap on qr[2] and qr[1] Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[2,1]) # Implement controlled swap on qr[1] and qr[0] Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[1,0]) # Implement CX on all four qubits qc.cx(Control_bit_number,qr[3]) qc.cx(Control_bit_number,qr[2]) qc.cx(Control_bit_number,qr[1]) qc.cx(Control_bit_number,qr[0]) # Return the program object return Quantum_program_object
https://github.com/ctuning/ck-qiskit
ctuning
"""The following is python code utilizing the qiskit library that can be run on extant quantum hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding, for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1, results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>). To find the factor, use the equivalence a^r mod 15. From this: (a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15 Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients, gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15, so the result of running shors algorithm to find the prime factors of an integer using quantum hardware are demonstrated. Note, this is not the same as the technical implementation of shor's algorithm described in this section for breaking the discrete log hardness assumption, though the proof of concept remains.""" # Import libraries from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from numpy import pi from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.visualization import plot_histogram # Initialize qubit registers qreg_q = QuantumRegister(5, 'q') creg_c = ClassicalRegister(5, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.reset(qreg_q[0]) circuit.reset(qreg_q[1]) circuit.reset(qreg_q[2]) circuit.reset(qreg_q[3]) circuit.reset(qreg_q[4]) # Apply Hadamard transformations to qubit registers circuit.h(qreg_q[0]) circuit.h(qreg_q[1]) circuit.h(qreg_q[2]) # Apply first QFT, modular exponentiation, and another QFT circuit.h(qreg_q[1]) circuit.cx(qreg_q[2], qreg_q[3]) circuit.crx(pi/2, qreg_q[0], qreg_q[1]) circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4]) circuit.h(qreg_q[0]) circuit.rx(pi/2, qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) # Measure the qubit registers 0-2 circuit.measure(qreg_q[2], creg_c[2]) circuit.measure(qreg_q[1], creg_c[1]) circuit.measure(qreg_q[0], creg_c[0]) # Get least busy quantum hardware backend to run on 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) # Run the circuit on available quantum hardware and plot histogram from qiskit.tools.monitor import job_monitor job = execute(circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(circuit) plot_histogram(answer) #largest amplitude results correspond with r values used to find the prime factor of N.
https://github.com/ctuning/ck-qiskit
ctuning
# -*- coding: utf-8 -*- # Copyright 2017, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. """ The eval_hamiltonian function has been borrowed from QISKit's tools/apps/optimization.py and slightly modified by dividiti to fit our benchmarking needs. """ import uuid import copy import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.extensions.standard import h, x, y, z from qiskit.tools.apps.optimization import make_Hamiltonian, group_paulis, measure_pauli_z def eval_hamiltonian(Q_program, hamiltonian, input_circuit, shots, device, timeout=60): """Calculates the average value of a Hamiltonian on a state created by the input circuit Args: Q_program (QuantumProgram): QuantumProgram object used to run the input circuit. hamiltonian (array or matrix or list): a representation of the Hamiltonian or observables to be measured. If it is a list, it is a list of Pauli operators grouped into tpb sets. input_circuit (QuantumCircuit): input circuit. shots (int): number of shots considered in the averaging. If 1 the averaging is exact. device (str): the backend used to run the simulation. Returns: float: Average value of the Hamiltonian or observable. """ energy = 0 q_execution_times = [] if 'statevector' in device: # Hamiltonian is not a pauli_list grouped into tpb sets if not isinstance(hamiltonian, list): circuit = ['c' + str(uuid.uuid4())] # unique random circuit for no collision Q_program.add_circuit(circuit[0], input_circuit) result = Q_program.execute(circuit, device, shots=shots, timeout=timeout, config={"data": ["statevector"]}) statevector = result.get_data(circuit[0]).get('statevector') if statevector is None: statevector = result.get_data( circuit[0]).get('statevector') if statevector: statevector = statevector[0] # Diagonal Hamiltonian represented by 1D array if (hamiltonian.shape[0] == 1 or np.shape(np.shape(np.array(hamiltonian))) == (1,)): energy = np.sum(hamiltonian * np.absolute(statevector) ** 2) # Hamiltonian represented by square matrix elif hamiltonian.shape[0] == hamiltonian.shape[1]: energy = np.inner(np.conjugate(statevector), np.dot(hamiltonian, statevector)) # Hamiltonian represented by a Pauli list else: circuits = [] circuits_labels = [] circuits.append(input_circuit) # Trial circuit w/o the final rotations circuits_labels.append('circuit_label0' + str(uuid.uuid4())) Q_program.add_circuit(circuits_labels[0], circuits[0]) # Execute trial circuit with final rotations for each Pauli in # hamiltonian and store from circuits[1] on n_qubits = input_circuit.regs['q'].size q = QuantumRegister(n_qubits, "q") i = 1 for p in hamiltonian: circuits.append(copy.deepcopy(input_circuit)) for j in range(n_qubits): if p[1].v[j] == 0 and p[1].w[j] == 1: circuits[i].x(q[j]) elif p[1].v[j] == 1 and p[1].w[j] == 0: circuits[i].z(q[j]) elif p[1].v[j] == 1 and p[1].w[j] == 1: circuits[i].y(q[j]) circuits_labels.append('circuit_label' + str(i) + str(uuid.uuid4())) Q_program.add_circuit(circuits_labels[i], circuits[i]) i += 1 result = Q_program.execute(circuits_labels, device, shots=shots, timeout=timeout) # no Pauli final rotations statevector_0 = result.get_data( circuits_labels[0])['statevector'] i = 1 for p in hamiltonian: statevector_i = result.get_data( circuits_labels[i])['statevector'] # inner product with final rotations of (i-1)-th Pauli energy += p[0] * np.inner(np.conjugate(statevector_0), statevector_i) i += 1 # finite number of shots and hamiltonian grouped in tpb sets else: circuits = [] circuits_labels = [] n = int(len(hamiltonian[0][0][1].v)) q = QuantumRegister(n, "q") c = ClassicalRegister(n, "c") i = 0 for tpb_set in hamiltonian: circuits.append(copy.deepcopy(input_circuit)) circuits_labels.append('tpb_circuit_' + str(i) + str(uuid.uuid4())) for j in range(n): # Measure X if tpb_set[0][1].v[j] == 0 and tpb_set[0][1].w[j] == 1: circuits[i].h(q[j]) # Measure Y elif tpb_set[0][1].v[j] == 1 and tpb_set[0][1].w[j] == 1: circuits[i].s(q[j]).inverse() circuits[i].h(q[j]) circuits[i].measure(q[j], c[j]) Q_program.add_circuit(circuits_labels[i], circuits[i]) i += 1 result = Q_program.execute(circuits_labels, device, shots=shots, timeout=timeout) for j, _ in enumerate(hamiltonian): # print( "Q execution data [{}] = {}".format(j, result.get_data(circuits_labels[j]))) q_execution_time = result.get_data(circuits_labels[j]).get('time') if q_execution_time: q_execution_times.append( q_execution_time ) for k, _ in enumerate(hamiltonian[j]): energy += hamiltonian[j][k][0] *\ measure_pauli_z(result.get_counts( circuits_labels[j]), hamiltonian[j][k][1]) return energy, q_execution_times
https://github.com/ctuning/ck-qiskit
ctuning
#!/usr/bin/env python3 """ This script runs Variational-Quantum-Eigensolver using Qiskit library Example running it partially using CK infrastructure: ck virtual env --tag_groups='compiler,python qiskit,lib vqe,utils vqe,hamiltonian deployed,ansatz deployed,optimizer' \ --shell_cmd="$HOME/CK/ck-qiskit/program/qiskit-vqe/qiskit_vqe_common.py --start_param_value=0.5" """ import os import json import time import inspect import numpy as np from scipy import linalg as la from qiskit import QuantumProgram, register, QISKitError from qiskit.tools.apps.optimization import make_Hamiltonian, group_paulis from qiskit.tools.qi.pauli import Pauli, label_to_pauli from eval_hamiltonian import eval_hamiltonian from vqe_utils import cmdline_parse_and_report, get_first_callable, NumpyEncoder from vqe_hamiltonian import label_to_hamiltonian_coeff # the file contents will be different depending on the plugin choice import custom_ansatz # the file contents will be different depending on the plugin choice fun_evaluation_counter = 0 # global def vqe_for_qiskit(sample_number, pauli_list, timeout_seconds, json_stream_file): def expectation_estimation(current_params, report): timestamp_before_ee = time.time() timestamp_before_q_run = timestamp_before_ee # no point in taking consecutive timestamps ansatz_circuit = ansatz_function(current_params) global fun_evaluation_counter # Trying to recover from a timed-out run assuming it to be a temporary glitch: # for attempt in range(1,8): try: complex_energy, q_run_seconds = eval_hamiltonian(Q_program, pauli_list_grouped, ansatz_circuit, sample_number, q_device_name, timeout=timeout_seconds) energy = complex_energy.real break except QISKitError as e: print("{}, trying again -- attempt number {}, timeout: {} seconds".format(e, attempt, timeout_seconds)) if len(q_run_seconds)>0: # got the real measured q time total_q_run_seconds = sum( q_run_seconds ) else: # have to assume total_q_run_seconds = time.time() - timestamp_before_q_run q_run_seconds = [ total_q_run_seconds ] q_runs = len(q_run_seconds) total_q_run_shots = sample_number * q_runs q_run_shots = [sample_number] * q_runs report_this_iteration = { 'total_q_seconds_per_c_iteration' : total_q_run_seconds, 'seconds_per_individual_q_run' : q_run_seconds, 'total_q_shots_per_c_iteration' : total_q_run_shots, 'shots_per_individual_q_run' : q_run_shots, 'energy' : energy, } if report != 'TestMode': report['iterations'].append( report_this_iteration ) report['total_q_seconds'] += report_this_iteration['total_q_seconds_per_c_iteration'] # total_q_time += total report['total_q_shots'] += report_this_iteration['total_q_shots_per_c_iteration'] fun_evaluation_counter += 1 report_this_iteration['total_seconds_per_c_iteration'] = time.time() - timestamp_before_ee print(report_this_iteration, "\n") json_stream_file.write( json.dumps(report_this_iteration, cls=NumpyEncoder)+"\n" ) json_stream_file.flush() return energy # Initialise quantum program Q_program = QuantumProgram() # Groups a list of (coeff,Pauli) tuples into tensor product basis (tpb) sets pauli_list_grouped = group_paulis(pauli_list) report = { 'total_q_seconds': 0, 'total_q_shots':0, 'iterations' : [] } # Initial objective function value fun_initial = expectation_estimation(start_params, 'TestMode') print('Initial guess at start_params is: {:.4f}'.format(fun_initial)) timestamp_before_optimizer = time.time() optimizer_output = minimizer_function(expectation_estimation, start_params, my_args=(report), my_options = minimizer_options) report['total_seconds'] = time.time() - timestamp_before_optimizer # Also generate and provide a validated function value at the optimal point fun_validated = expectation_estimation(optimizer_output['x'], 'TestMode') print('Validated value at solution is: {:.4f}'.format(fun_validated)) # Exact (noiseless) calculation of the energy at the given point: complex_energy, _ = eval_hamiltonian(Q_program, pauli_list, ansatz_function(optimizer_output['x']), 1, 'local_statevector_simulator') optimizer_output['fun_exact'] = complex_energy.real optimizer_output['fun_validated'] = fun_validated print('Total Q seconds = %f' % report['total_q_seconds']) print('Total Q shots = %d' % report['total_q_shots']) print('Total seconds = %f' % report['total_seconds']) return (optimizer_output, report) if __name__ == '__main__': start_params, sample_number, q_device_name, minimizer_method, minimizer_options, minimizer_function = cmdline_parse_and_report( num_params = custom_ansatz.num_params, q_device_name_default = 'local_qasm_simulator', q_device_name_help = "Real devices: 'ibmqx4' or 'ibmqx5'. Use 'ibmq_qasm_simulator' for remote simulator or 'local_qasm_simulator' for local", minimizer_options_default = '{"maxfev":200, "xatol": 0.001, "fatol": 0.001}', start_param_value_default = 0.0 ) # q_device_name = os.environ.get('VQE_QUANTUM_BACKEND', 'local_qasm_simulator') # try 'local_qasm_simulator', 'ibmq_qasm_simulator', 'ibmqx4', 'ibmqx5' try: import Qconfig register(Qconfig.APItoken, Qconfig.config["url"], verify=False, hub=Qconfig.config["hub"], group=Qconfig.config["group"], project=Qconfig.config["project"]) except: print(""" WARNING: There's no connection with IBMQuantumExperience servers. cannot test I/O intesive tasks, will only test CPU intensive tasks running the jobs in the local simulator """) # Ignore warnings due to chopping of small imaginary part of the energy #import warnings #warnings.filterwarnings('ignore') # Load the Hamiltonian into Qiskit-friendly format: pauli_list = [ [label_to_hamiltonian_coeff[label], label_to_pauli(label)] for label in label_to_hamiltonian_coeff ] # Calculate Exact Energy classically, to compare with quantum solution: # H = make_Hamiltonian(pauli_list) classical_energy = np.amin(la.eigh(H)[0]) print('The exact ground state energy (the smallest eigenvalue of the Hamiltonian) is: {:.4f}'.format(classical_energy)) # Load the ansatz function from the plug-in ansatz_method = get_first_callable( custom_ansatz ) ansatz_function = getattr(custom_ansatz, ansatz_method) # ansatz_method is a string/name, ansatz_function is an imported callable timeout_seconds = int( os.environ.get('VQE_QUANTUM_TIMEOUT', '120') ) json_stream_file = open('vqe_stream.json', 'a') # ---------------------------------------- run VQE: -------------------------------------------------- (vqe_output, report) = vqe_for_qiskit(sample_number, pauli_list, timeout_seconds, json_stream_file) # ---------------------------------------- store the results: ---------------------------------------- json_stream_file.write( '# Experiment finished\n' ) json_stream_file.close() minimizer_src = inspect.getsource( minimizer_function ) ansatz_src = inspect.getsource( ansatz_function ) vqe_input = { "q_device_name" : q_device_name, "minimizer_method" : minimizer_method, "minimizer_src" : minimizer_src, "minimizer_options" : minimizer_options, "ansatz_method" : ansatz_method, "ansatz_src" : ansatz_src, "sample_number" : sample_number, "classical_energy" : classical_energy } output_dict = { "vqe_input" : vqe_input, "vqe_output" : vqe_output, "report" : report } formatted_json = json.dumps(output_dict, cls=NumpyEncoder, sort_keys = True, indent = 4) # print(formatted_json) with open('ibm_vqe_report.json', 'w') as json_file: json_file.write( formatted_json )
https://github.com/ctuning/ck-qiskit
ctuning
#!/usr/bin/env python3 import qiskit.tools.apps.optimization num_of_qubits = 2 circuit_depth = 6 num_params = 2 * num_of_qubits * circuit_depth # make sure you set this correctly to the number of parameters used by the ansatz ## Previously used for Hydrogen VQE in QISKit implementation # def universal_ansatz(current_params, entangler_map=None): if entangler_map==None: # Which qubits to use (0 to 1 best to avoid qiskit bugs) entangler_map = {1: [0]} return qiskit.tools.apps.optimization.trial_circuit_ryrz(num_of_qubits, circuit_depth, current_params, entangler_map, None, False)
https://github.com/ctuning/ck-qiskit
ctuning
#!/usr/bin/env python3 import qiskit.tools.apps.optimization num_of_qubits = 2 circuit_depth = 6 num_params = 2 * num_of_qubits * circuit_depth # make sure you set this correctly to the number of parameters used by the ansatz ## Previously used for Hydrogen VQE in QISKit implementation # def universal_ansatz(current_params, entangler_map=None): if entangler_map==None: # Which qubits to use (0 to 1 best to avoid qiskit bugs) entangler_map = {1: [0]} return qiskit.tools.apps.optimization.trial_circuit_ryrz(num_of_qubits, circuit_depth, current_params, entangler_map, None, False)
https://github.com/ctuning/ck-qiskit
ctuning
#!/usr/bin/env python3 import qiskit.tools.apps.optimization num_of_qubits = 2 circuit_depth = 6 num_params = 2 * num_of_qubits * circuit_depth # make sure you set this correctly to the number of parameters used by the ansatz ## Previously used for Hydrogen VQE in QISKit implementation # def universal_ansatz(current_params, entangler_map=None): if entangler_map==None: # Which qubits to use (0 to 1 best to avoid qiskit bugs) entangler_map = {1: [0]} return qiskit.tools.apps.optimization.trial_circuit_ryrz(num_of_qubits, circuit_depth, current_params, entangler_map, None, False)
https://github.com/ctuning/ck-qiskit
ctuning
#!/usr/bin/env python3 import qiskit.tools.apps.optimization num_of_qubits = 2 circuit_depth = 6 num_params = 2 * num_of_qubits * circuit_depth # make sure you set this correctly to the number of parameters used by the ansatz ## Previously used for Hydrogen VQE in QISKit implementation # def universal_ansatz(current_params, entangler_map=None): if entangler_map==None: # Which qubits to use (0 to 1 best to avoid qiskit bugs) entangler_map = {1: [0]} return qiskit.tools.apps.optimization.trial_circuit_ryrz(num_of_qubits, circuit_depth, current_params, entangler_map, None, False)
https://github.com/ctuning/ck-qiskit
ctuning
#!/usr/bin/env python3 import qiskit.tools.apps.optimization num_of_qubits = 2 circuit_depth = 6 num_params = 2 * num_of_qubits * circuit_depth # make sure you set this correctly to the number of parameters used by the ansatz ## Previously used for Hydrogen VQE in QISKit implementation # def universal_ansatz(current_params, entangler_map=None): if entangler_map==None: # Which qubits to use (0 to 1 best to avoid qiskit bugs) entangler_map = {1: [0]} return qiskit.tools.apps.optimization.trial_circuit_ryrz(num_of_qubits, circuit_depth, current_params, entangler_map, None, False)
https://github.com/ctuning/ck-qiskit
ctuning
#!/usr/bin/env python3 import qiskit.tools.apps.optimization num_of_qubits = 2 circuit_depth = 6 num_params = 2 * num_of_qubits * circuit_depth # make sure you set this correctly to the number of parameters used by the ansatz ## Previously used for Hydrogen VQE in QISKit implementation # def universal_ansatz(current_params, entangler_map=None): if entangler_map==None: # Which qubits to use (0 to 1 best to avoid qiskit bugs) entangler_map = {1: [0]} return qiskit.tools.apps.optimization.trial_circuit_ryrz(num_of_qubits, circuit_depth, current_params, entangler_map, None, False)
https://github.com/gatchan00/QPlex
gatchan00
%config IPCompleter.greedy=True # 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 Operator, 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 # set_qiskit_aqua_logging(logging.DEBUG) # choose INFO, DEBUG to see the log a = -5 b = -3 #xRaw = 4 #yRaw = 5 def getBit(number,precision,posicion): return int(format(number,'b').rjust(precision,'0')[precision-1-i]) n = 3 from docplex.mp.model import Model from qiskit.aqua.translators.ising import docplex # Create an instance of a model and variables. mdl = Model(name='max_cut') x = {i: mdl.binary_var(name='x_{0}'.format(i)) for i in range(n)} y = {i: mdl.binary_var(name='y_{0}'.format(i)) for i in range(n)} # Object function precision = 4 max_cut_func = mdl.sum(a*2**i*x[i]+b*2**i*y[i] for i in range(n)) mdl.maximize(max_cut_func) qubitOp_docplex, offset_docplex = docplex.get_qubitops(mdl) seed = 10598 spsa = SPSA(max_trials=300) ry = RY(qubitOp_docplex.num_qubits, depth=4, entanglement='linear') vqe = VQE(qubitOp_docplex, ry, spsa, 'matrix') backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, seed=seed, seed_transpiler=seed) result = vqe.run(quantum_instance) x = max_cut.sample_most_likely(result['eigvecs'][0]) print('solution:', max_cut.get_graph_solution(x)) #print('solution objective:', max_cut.max_cut_value(x, w))
https://github.com/gatchan00/QPlex
gatchan00
import matplotlib.pyplot as plt import matplotlib.axes as axes import numpy as np import networkx as nx from qiskit import BasicAer from qiskit.tools.visualization import plot_histogram from qiskit.aqua import Operator, 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 # set_qiskit_aqua_logging(logging.DEBUG) # choose INFO, DEBUG to see the log from docplex.mp.model import Model from qiskit.aqua.translators.ising import docplex def createMatrixRestrictionDefaultOrig(qbits_code, input_vars, input_rest, beta): num_vars = len(input_vars) tamMatrix = num_vars * qbits_code # matrix is num_vars * qbits used for each var p = 1000 # very high number matrix = np.zeros([tamMatrix, tamMatrix]) for row in range(tamMatrix): for col in range(row, tamMatrix): dom_row = row // qbits_code dom_col = col // qbits_code if row == col: matrix[row, col] = -input_vars[dom_row] * 2 ** (row % qbits_code) else: if dom_row == dom_col: # Si estamos en un X0 X1 o X0 X2... no hay relación, se pone 0 matrix[row, col] = 0 matrix[col, row] = 0 else: r = p / beta * (input_rest[dom_row] * input_rest[dom_col]) matrix[row, col] = r matrix[col, row] = r return matrix def wrapper(qbits_encode, input_vars, options): if options['restriction'] == 'default': matrix = createMatrixRestrictionDefault(qbits_encode, input_vars, options['input_rest'], options['beta']) return matrix def createMatrixSinRestrictionDefault(qbits_code, input_vars, input_rest, beta): num_vars = len(input_vars) tamMatrix = num_vars * qbits_code # matrix is num_vars * qbits used for each var p = 1000 # very high number matrix = np.zeros([tamMatrix, tamMatrix]) for row in range(tamMatrix): for col in range(row, tamMatrix): dom_row = row // qbits_code dom_col = col // qbits_code if row == col: matrix[row, col] = 1#-input_vars[dom_row] * 2 ** (row % qbits_code) else: if dom_row == dom_col: # Si estamos en un X0 X1 o X0 X2... no hay relación, se pone 0 matrix[row, col] = 0 matrix[col, row] = 0 else: r = -p / beta * (input_rest[dom_row] * input_rest[dom_col]) matrix[row, col] = r matrix[col, row] = r #print(matrix) for row in range(tamMatrix): acu = 0. for col in range(row+1, tamMatrix): acu += matrix[row, col] matrix[row, row] = (matrix[row, row]/2) + (acu/4) return matrix def createMatrixRestrictionDefaultOrig2(qbits_code, input_vars, input_rest, beta): num_vars = len(input_vars) tamMatrix = num_vars * qbits_code # matrix is num_vars * qbits used for each var p = 1000 # very high number matrix = np.zeros([tamMatrix, tamMatrix]) for row in range(tamMatrix): for col in range(row, tamMatrix): dom_row = row // qbits_code dom_col = col // qbits_code if row == col: matrix[row, col] = input_vars[dom_row] * 2 ** (row % qbits_code) else: if dom_row == dom_col: # Si estamos en un X0 X1 o X0 X2... no hay relación, se pone 0 matrix[row, col] = 0 matrix[col, row] = 0 else: r = p / beta * (input_rest[dom_row] * input_rest[dom_col]) matrix[row, col] = r matrix[col, row] = r for row in range(tamMatrix): acu = 0. for col in range(row+1, tamMatrix): acu += matrix[row, col] matrix[row, row] = (matrix[row, row]/2) + (acu/4) return matrix def createMatrixRestrictionDefault(qbits_code, input_vars, input_rest, beta): num_vars = len(input_vars) tamMatrix = num_vars * qbits_code # matrix is num_vars * qbits used for each var p = 1000 # very high number matrix = np.zeros([tamMatrix, tamMatrix]) for row in range(tamMatrix): for col in range(row, tamMatrix): dom_row = row // qbits_code dom_col = col // qbits_code if row == col: matrix[row, col] = -input_vars[dom_row] * 2 ** (row % qbits_code) else: if dom_row == dom_col: # Si estamos en un X0 X1 o X0 X2... no hay relación, se pone 0 matrix[row, col] = 0 matrix[col, row] = 0 else: r = -p / beta * (input_rest[dom_row] * input_rest[dom_col]) matrix[row, col] = -r matrix[col, row] = -r #print(matrix) for row in range(tamMatrix): acu = 0. for col in range(row+1, tamMatrix): acu += matrix[row, col] matrix[row, row] = (matrix[row, row]/2) + (acu/4) return matrix def createMatrixRestrictionBackup1(qbits_code, input_vars, input_rest, beta): num_vars = len(input_vars) tamMatrix = num_vars * qbits_code # matrix is num_vars * qbits used for each var p = 1 # very high number matrix = np.zeros([tamMatrix, tamMatrix]) for row in range(tamMatrix): for col in range(row, tamMatrix): dom_row = row // qbits_code dom_col = col // qbits_code if row == col: matrix[row, col] = -input_vars[dom_row] * 2 ** (row % qbits_code) else: if dom_row == dom_col: # Si estamos en un X0 X1 o X0 X2... no hay relación, se pone 0 matrix[row, col] = 0 matrix[col, row] = 0 else: r = -p / beta * (input_rest[dom_row] * input_rest[dom_col]) matrix[row, col] = -r matrix[col, row] = -r #print(matrix) for row in range(tamMatrix): acu = 0. for col in range(row+1, tamMatrix): acu += matrix[row, col] matrix[row, row] = (matrix[row, row]/2) + (acu/4) return matrix def getPauliMatrix(matrix): rows = matrix.shape[0] paulis = [] for row_pos in range(rows): for col_pos in range(matrix.shape[1]): temp = {} temp["imag"] = 0.0 temp["real"] = matrix[row_pos, col_pos] label_pauli = ["I" for _ in range(rows)] if row_pos != col_pos: label_pauli[row_pos] = 'Z' label_pauli[col_pos] = 'Z' label_pauli = "".join(label_pauli) paulis.append({"coeff": temp, "label": label_pauli}) paulis_dict = {"paulis": paulis} for i in paulis_dict["paulis"]: print(i) pauli_matrix = Operator.load_from_dict(paulis_dict) return pauli_matrix def dameInversoBinario(target, precision, num_vars): contador = {} for i in range(precision): contador[i] = 0 while target > 0: for i in range(precision-1, -1, -1): while target >= 2**i: target -= 2**i contador[i] += 1 print(contador) #Invertir bits long_buscada = num_vars * precision array = np.zeros(long_buscada) for i in range(precision): for j in range(contador[i]): array[j*num_vars + (i)] = 1 invert_array = ['0' if x == 1 else '1' for x in array] arrays = np.array_split(np.array(invert_array), 3) acu = 0 for i in arrays: en_binario = "".join(list(np.flip(i))) acu += int(en_binario, 2) return acu def optimize_f(precision, coefs_param, beta): coefs = coefs_param.copy() coefs.append(0) coefs_restr = (1, 1, 1) lista_vars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] mdl = Model() variables = [] for num_var in range(len(coefs)): tmp = {i: mdl.binary_var(name=(lista_vars[num_var] + '_{0}').format(i)) for i in range(precision)} variables.append(tmp) # x = {i: mdl.binary_var(name='x_{0}'.format(i)) for i in range(precision)} # y = {i: mdl.binary_var(name='y_{0}'.format(i)) for i in range(precision)} # z = {i: mdl.binary_var(name='z_{0}'.format(i)) for i in range(precision)} #print(variables) # Object function # my_func = mdl.sum(coefs[0]*(2**i)*x[i]+coefs[1]*(2**i)*y[i]+(2**i)*coefs[2]*z[i] for i in range(precision)) # my_func = mdl.sum(coefs[j]*(2**i)*vars[j][i] for j in range(len(coefs)) for i in range(precision)) my_func = mdl.sum(coefs[j] * (2 ** i) * variables[j][i] for j in range(len(coefs)) for i in range(precision)) # (x[i] for i in range(precision)), (y[i] for i in range(precision)), (z[i] for i in range(precision) # tmp = {0:{'var':x,'coef':coefs_restr[0]}, # 1:{'var':y,'coef':coefs_restr[1]}, # 2:{'var':z,'coef':coefs_restr[2]}} mdl.maximize(my_func) inverted_beta = dameInversoBinario(beta, precision, len(coefs)) # mdl.add_constraint(mdl.sum( tmp[v]['var'][i]*(2**i)*tmp[v]['coef'] for v in range(len(coefs)) for i in range(precision)) == beta) # mdl.add_constraint(mdl.sum( x[0] + x[1]*(2) + x[2]*(4) + y[0] + y[1]*(2) + y[2]*(4) + z[0] + z[1]*(2) + z[2]*(4) ) == inverted_beta) # mdl.add_constraint(mdl.sum( variables[0][0] + variables[0][1]*(2) + variables[0][2]*(4) + variables[1][0] + variables[1][1] # *(2) + variables[1][2]*(4) + variables[2][0] + variables[2][1]*(2) + variables[2][2]*(4) ) == inverted_beta) mdl.add_constraint( mdl.sum(variables[v][i] * 2 ** i for v in range(len(coefs)) for i in range(precision)) == inverted_beta) # mdl.add_constraint(mdl.sum( -x[0] - x[1]*(2) - x[2]*(4) - y[0] - y[1]*(2) - y[2]*(4) - z[0] - z[1]*(2) - z[2]*(4) ) == 6) # mdl.add_constraint(mdl.sum( -1*tmp[v]['var'][i]*(2**i)*tmp[v]['coef'] for v in range(len(coefs)) for i in range(precision)) == -beta) qubitOp_docplex, offset_docplex = docplex.get_qubitops(mdl) #print(qubitOp_docplex) # algo_input = EnergyInput(qubitOp_docplex) # print(algo_input.) # ee = VQE(qubitOp_docplex) # ee.run() ee = ExactEigensolver(qubitOp_docplex, k=1) result_ee = ee.run() x_ee = max_cut.sample_most_likely(result_ee['eigvecs'][0]) print('solution:', max_cut.get_graph_solution(x_ee)) solucion_ee = max_cut.get_graph_solution(x_ee) return (solucion_ee, None) """ algorithm_cfg = { 'name': 'ExactEigensolver', } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params,algo_input) """ # x = max_cut.sample_most_likely(result['eigvecs'][0]) # print('energy:', result['energy']) # print('max-cut objective:', result['energy'] + offset_docplex) # print('solution:', max_cut.get_graph_solution(x)) # print('solution objective:', max_cut.max_cut_value(x, w)) seed = 10598 # change optimizer(spsa), change ry (riyc) spsa = SPSA(max_trials=300) ry = RY(qubitOp_docplex.num_qubits, depth=6, entanglement='linear') vqe = VQE(qubitOp_docplex, ry, spsa, 'matrix') backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, seed=seed, seed_transpiler=seed) result = vqe.run(quantum_instance) x = max_cut.sample_most_likely(result['eigvecs'][0]) print('solution:', max_cut.get_graph_solution(x)) return (solucion_ee, max_cut.get_graph_solution(x)) def wrapper_optimiza_f(precision, coefs_param, beta): r = optimize_f(precision, coefs_param, beta) r_ee = r[0] vars = np.array_split(r_ee, 3) tam = len(vars) answer = {} for i in range(tam): curr = vars[i] curr_i = np.flip(curr) curr_i = [str(int(k)) for k in curr_i] en_binario = "".join(list(curr_i)) curr_var = int(en_binario, 2) if i != tam - 1: answer[i]=curr_var return answer if __name__ == '__main__': precision = 6 coefs_param = [2, -3] beta = 7 a = wrapper_optimiza_f(precision, coefs_param, beta) print(a) exit() dameInversoBinario(6, 3, 3) exit() qbits_encode = 2 # Max number of qubits for coding a number input_vars = [2, -3] # 2*x + 4*y +6*z # basic restriction options = {} options['restriction'] = 'default' # a*x+b*y+c*z <= beta (que puede ser 1) options['input_rest'] = [1, 1] options['beta'] = 2 matrix = wrapper(qbits_encode, input_vars, options) print(matrix) pauli_matrix = getPauliMatrix(matrix) print(pauli_matrix) from docplex.mp.model import Model mdl = Model() mdl.add_constraint
https://github.com/gatchan00/QPlex
gatchan00
%config IPCompleter.greedy=True %matplotlib inline from qplex_core import * precision = 6 coefs_param = [2, -3] beta = 7 a = wrapper_optimiza_f(precision, coefs_param, beta) print(a) #tú mandas la función 2*X-3*Y, #La precisión para representar enteros es de 6 qbits por número (usamos los X e Y y le añadimos un Z) #como restricción se manda X*y<=6 #El resultado es {0: 0, 1: 7}, que quiere decir, que X vale 0 e Y vale 7 # useful additional packages import matplotlib.pyplot as plt import matplotlib.axes as axes import numpy as np import networkx as nx from qiskit import BasicAer from qiskit.tools.visualization import plot_histogram from qiskit.aqua import Operator, 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 # set_qiskit_aqua_logging(logging.DEBUG) # choose INFO, DEBUG to see the log from docplex.mp.model import Model from qiskit.aqua.translators.ising import docplex from qplex_core import * def mainJGOS(): precision = 6 coefs_param = [2, -3 ] coefs = coefs_param.copy() coefs.append(0) coefs_restr = (1, 1, 1) beta = 7 lista_vars = ['a', 'b', 'c', 'd', 'e','f','g','h'] mdl = Model() variables = [] for num_var in range(len(coefs)): tmp ={i: mdl.binary_var(name=(lista_vars[num_var]+'_{0}').format(i)) for i in range(precision)} variables.append(tmp) #x = {i: mdl.binary_var(name='x_{0}'.format(i)) for i in range(precision)} #y = {i: mdl.binary_var(name='y_{0}'.format(i)) for i in range(precision)} #z = {i: mdl.binary_var(name='z_{0}'.format(i)) for i in range(precision)} print(variables) # Object function #my_func = mdl.sum(coefs[0]*(2**i)*x[i]+coefs[1]*(2**i)*y[i]+(2**i)*coefs[2]*z[i] for i in range(precision)) #my_func = mdl.sum(coefs[j]*(2**i)*vars[j][i] for j in range(len(coefs)) for i in range(precision)) my_func = mdl.sum(coefs[j]*(2**i)*variables[j][i] for j in range(len(coefs)) for i in range(precision)) #(x[i] for i in range(precision)), (y[i] for i in range(precision)), (z[i] for i in range(precision) #tmp = {0:{'var':x,'coef':coefs_restr[0]}, # 1:{'var':y,'coef':coefs_restr[1]}, # 2:{'var':z,'coef':coefs_restr[2]}} mdl.maximize(my_func) inverted_beta = dameInversoBinario(beta, precision, len(coefs)) #mdl.add_constraint(mdl.sum( tmp[v]['var'][i]*(2**i)*tmp[v]['coef'] for v in range(len(coefs)) for i in range(precision)) == beta) #mdl.add_constraint(mdl.sum( x[0] + x[1]*(2) + x[2]*(4) + y[0] + y[1]*(2) + y[2]*(4) + z[0] + z[1]*(2) + z[2]*(4) ) == inverted_beta) #mdl.add_constraint(mdl.sum( variables[0][0] + variables[0][1]*(2) + variables[0][2]*(4) + variables[1][0] + variables[1][1] #*(2) + variables[1][2]*(4) + variables[2][0] + variables[2][1]*(2) + variables[2][2]*(4) ) == inverted_beta) mdl.add_constraint(mdl.sum(variables[v][i]*2**i for v in range(len(coefs)) for i in range(precision)) == inverted_beta) #mdl.add_constraint(mdl.sum( -x[0] - x[1]*(2) - x[2]*(4) - y[0] - y[1]*(2) - y[2]*(4) - z[0] - z[1]*(2) - z[2]*(4) ) == 6) #mdl.add_constraint(mdl.sum( -1*tmp[v]['var'][i]*(2**i)*tmp[v]['coef'] for v in range(len(coefs)) for i in range(precision)) == -beta) qubitOp_docplex, offset_docplex = docplex.get_qubitops(mdl) print(qubitOp_docplex) #algo_input = EnergyInput(qubitOp_docplex) #print(algo_input.) #ee = VQE(qubitOp_docplex) #ee.run() ee = ExactEigensolver(qubitOp_docplex, k=1) result_ee = ee.run() x_ee = max_cut.sample_most_likely(result_ee['eigvecs'][0]) print('solution:', max_cut.get_graph_solution(x_ee)) solucion_ee = max_cut.get_graph_solution(x_ee) return (solucion_ee, None) """ algorithm_cfg = { 'name': 'ExactEigensolver', } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params,algo_input) """ #x = max_cut.sample_most_likely(result['eigvecs'][0]) #print('energy:', result['energy']) #print('max-cut objective:', result['energy'] + offset_docplex) #print('solution:', max_cut.get_graph_solution(x)) #print('solution objective:', max_cut.max_cut_value(x, w)) seed = 10598 #change optimizer(spsa), change ry (riyc) spsa = SPSA(max_trials=300) ry = RY(qubitOp_docplex.num_qubits, depth=6, entanglement='linear') vqe = VQE(qubitOp_docplex, ry, spsa, 'matrix') backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, seed=seed, seed_transpiler=seed) result = vqe.run(quantum_instance) x = max_cut.sample_most_likely(result['eigvecs'][0]) print('solution:', max_cut.get_graph_solution(x)) return (solucion_ee, max_cut.get_graph_solution(x)) resultado = mainJGOS() r_ee = resultado[0] vars = np.array_split(r_ee, 3) tam = len(vars) for i in range(tam): curr = vars[i] curr_i = np.flip(curr) curr_i = [ str(int(k)) for k in curr_i ] en_binario = "".join(list(curr_i)) curr_var = int(en_binario, 2) if i != tam-1: print("Var %d = %d" %(i,curr_var))
https://github.com/dv-gorasiya/quantum-machine-learning
dv-gorasiya
import numpy as np from matplotlib import pyplot as plt from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from matplotlib.colors import ListedColormap seed = 12345 def plot_dataset(X, y, ax, axes=[-1, 1, -1, 1], marker='o', size=50, alpha=1.0, stepsize=0.5, grid=False, cmap=ListedColormap(['#FF0000', '#0000FF'])): """Simple routine to visualize a 2D dataset""" ax.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap, edgecolors='k', marker=marker, s=size, alpha=alpha) ax.axis(axes) ax.grid(grid, which='both') ax.set_xlabel(r"$x_1$", fontsize=24) ax.set_ylabel(r"$x_2$", fontsize=24, rotation=0) ax.xaxis.set_ticks(np.arange(axes[0], axes[1]+0.01, stepsize)) ax.yaxis.set_ticks(np.arange(axes[2], axes[3]+0.01, stepsize)) def visualize_dataset(): fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(18, 6)) ax1.set_title("Total", fontsize=24) plot_dataset(X, y, ax1) ax1.grid() ax2.set_title("Train", fontsize=24) plot_dataset(X_train, y_train, ax2, marker='s', size=80) ax2.grid() ax3.set_title("Test", fontsize=22) plot_dataset(X_test, y_test, ax3, marker='^', size=100) ax3.grid() plt.rcParams['font.size'] = 15 plt.tight_layout() plt.show() from sklearn.datasets import load_iris iris = load_iris() pair = [0, 2] X = iris.data[:, pair] y = iris.target # Data rescaling xmin = -1; xmax = 1 X = MinMaxScaler(feature_range=(xmin, xmax), copy=False).fit_transform(X) # Train/Test subdivision train_size = 20; test_size = 20 X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=train_size, test_size=test_size, stratify=y, random_state=seed ) def iris_visualize_dataset(X, y, ax, marker='o'): n_classes = 3 plot_colors = ['#FF0000', '#0000FF', '#00FF00'] cmap = ListedColormap(plot_colors) for i, color in zip(range(n_classes), plot_colors): idx = np.where(y == i) ax.scatter( X[idx, 0], X[idx, 1], c=color, label=iris.target_names[i], edgecolor="black", s=50, marker=marker ) fig, axs = plt.subplots(1, 3, figsize=(18, 6)) iris_visualize_dataset(X, y, axs[0]) iris_visualize_dataset(X_train, y_train, axs[1], marker='s') iris_visualize_dataset(X_test, y_test, axs[2], marker='^') for ax in axs: ax.set_xlim(xmin, xmax) ax.set_ylim(xmin, xmax) ax.set_xlabel(iris.feature_names[pair[0]]) ax.set_ylabel(iris.feature_names[pair[1]]) plt.rcParams['font.size'] = 20 plt.suptitle("Iris dataset") plt.legend(loc="lower right") plt.tight_layout() plt.show() from sklearn.datasets import make_blobs from sklearn.preprocessing import MinMaxScaler n_samples = 400 X, y = make_blobs(n_samples=n_samples, n_features=2, centers=2, random_state=110, shuffle=True, cluster_std=1.2) y[y%2 == 0] = -1 y[y > 0] = 1 xmin = -1; xmax = 1 X = MinMaxScaler(feature_range=(xmin, xmax)).fit_transform(X) train_size = 20 test_size = 20 X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=train_size, test_size=test_size, random_state=seed ) visualize_dataset() from sklearn.datasets import make_circles n_samples = 200 X, y = make_circles(n_samples, noise=0.1, factor=0.4, random_state=0) y[y%2 == 0] = -1 y[y > 0] = 1 xmin = -1; xmax = 1 X = MinMaxScaler(feature_range=(xmin, xmax)).fit_transform(X) train_size = 20 test_size = 20 X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=train_size, test_size=test_size, random_state=seed ) visualize_dataset() from sklearn.datasets import make_gaussian_quantiles n_samples = 200 X, y = make_gaussian_quantiles(n_samples=n_samples, n_features=2, n_classes=2, shuffle=True, random_state=10) y = 2*y-1 # Data rescaling xmin = -1; xmax = 1 X = MinMaxScaler(feature_range=(xmin, xmax), copy=False).fit_transform(X) train_size = 20 test_size = 20 X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=train_size, test_size=test_size, stratify=y, random_state=seed ) visualize_dataset() from sklearn.datasets import make_moons n_samples = 100 X, y = make_moons(n_samples=n_samples, noise=0.2, random_state=32345) y = 2*y-1 # Data rescaling xmin = -1; xmax = 1 X = MinMaxScaler(feature_range=(xmin, xmax), copy=False).fit_transform(X) train_size = 20 test_size = 20 X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=train_size, test_size=test_size, stratify=y, random_state=seed ) visualize_dataset()
https://github.com/dv-gorasiya/quantum-machine-learning
dv-gorasiya
from datasets import * from qiskit import BasicAer from qiskit.aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name from qiskit.aqua.input import ClassificationInput from qiskit.aqua import run_algorithm, QuantumInstance from qiskit.aqua.algorithms import QSVM from qiskit.aqua.components.feature_maps import SecondOrderExpansion # setup aqua logging import logging from qiskit.aqua import set_qiskit_aqua_logging set_qiskit_aqua_logging(logging.DEBUG) from qiskit import IBMQ IBMQ.save_account('2670c486a8792dff6c5327a9729c669ffe3fe33b5970cb3b5c1fd8662121db289092e7eb6d2525215d9d0e17808cf25599b7da660807e30e2c3409e302bfb2f5', 'https://api.quantum-computing.ibm.com/api/Hubs/ibm-q/Groups/open/Projects/main') IBMQ.load_accounts(overwrite=True) feature_dim=5 # we support feature_dim 2 or 3 sample_Total, training_input, test_input, class_labels = ad_hoc_data( training_size=20, test_size=10, n=feature_dim, gap=0.3, PLOT_DATA=True ) extra_test_data = sample_ad_hoc_data(sample_Total, 10, n=feature_dim) datapoints, class_to_label = split_dataset_to_data_and_labels(extra_test_data) print(class_to_label) seed = 10598 feature_map = SecondOrderExpansion(feature_dimension=feature_dim, depth=2, entanglement='linear') qsvm = QSVM(feature_map, training_input, test_input, datapoints[0]) #backend = BasicAer.get_backend('qasm_simulator') backend = IBMQ.get_backend('ibmq_16_melbourne') quantum_instance = QuantumInstance(backend, shots=1024, seed=seed, seed_transpiler=seed) result = qsvm.run(quantum_instance) """declarative approach params = { 'problem': {'name': 'classification', 'random_seed': 10598}, 'algorithm': { 'name': 'QSVM' }, 'backend': {'provider': 'qiskit.BasicAer', 'name': 'qasm_simulator', 'shots': 1024}, 'feature_map': {'name': 'SecondOrderExpansion', 'depth': 2, 'entanglement': 'linear'} } algo_input = ClassificationInput(training_input, test_input, datapoints[0]) result = run_algorithm(params, algo_input) """ print("testing success ratio: {}".format(result['testing_accuracy'])) print("preduction of datapoints:") print("ground truth: {}".format(map_label_to_class_name(datapoints[1], qsvm.label_to_class))) print("prediction: {}".format(result['predicted_classes'])) print("kernel matrix during the training:") kernel_matrix = result['kernel_matrix_training'] img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r') plt.show() sample_Total, training_input, test_input, class_labels = Breast_cancer( training_size=20, test_size=10, n=2, PLOT_DATA=True ) seed = 10598 feature_map = SecondOrderExpansion(feature_dimension=feature_dim, depth=2, entanglement='linear') qsvm = QSVM(feature_map, training_input, test_input) backend = BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1024, seed=seed, seed_transpiler=seed) result = qsvm.run(quantum_instance) """declarative approach, re-use the params above algo_input = ClassificationInput(training_input, test_input) result = run_algorithm(params, algo_input) """ print("testing success ratio: ", result['testing_accuracy']) result print("kernel matrix during the training:") kernel_matrix = result['kernel_matrix_training'] img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r') plt.show() sample_Total.shape
https://github.com/tanishabassan/QAOA-Maxcut
tanishabassan
import numpy as np from matplotlib import pyplot as plt from qiskit import Aer from qiskit.visualization import plot_histogram from scipy.optimize import minimize from VehicleRouting.standard.factories.MaxCutFactories import TwoConnectedMaxCutFactory from VehicleRouting.standard.problems.MaxCutProblem import MaxCutProblem from VehicleRouting.functions.functionsMaxCut import get_expectation, get_execute_circuit, create_qaoa_circuit from VehicleRouting.standard.plotter.GraphPlotter import GraphPlotter number_of_vertices = 4 problem_factory = TwoConnectedMaxCutFactory() problem = MaxCutProblem(problem_factory) plotter = GraphPlotter(problem) plotter.plot_problem() graph = problem.get_graph() expectation = get_expectation(graph, p=1) # Returns a function to be optimized p = 4 expectation = get_execute_circuit(graph) # Optimize initial_parameter = np.ones(2 * p) optimization_method = 'COBYLA' optimization_object = minimize(expectation, initial_parameter, method=optimization_method) print(optimization_object) backend = Aer.get_backend('aer_simulator') backend.shots = 2 ^ 12 # Create Circuit with Optimized Parameters optimized_parameters = optimization_object.x qc_res = create_qaoa_circuit(graph, optimized_parameters) qc_res.draw(output="mpl") counts = backend.run(qc_res, seed_simulator=10).result().get_counts() print(counts) plot_histogram(counts) plt.show()
https://github.com/tanishabassan/QAOA-Maxcut
tanishabassan
import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import matplotlib.axes as axes import numpy as np from scipy import linalg as la from itertools import permutations from functools import partial import networkx as nx # importing the QISKit from qiskit import QuantumCircuit, QuantumProgram import Qconfig # import basic plot tools from qiskit.tools.visualization import plot_histogram # import optimization tools from qiskit.tools.apps.optimization import trial_circuit_ry, SPSA_optimization, SPSA_calibration from qiskit.tools.apps.optimization import Energy_Estimate, make_Hamiltonian, eval_hamiltonian, group_paulis from qiskit.tools.qi.pauli import Pauli # Random choice of the cities/nodes N = 4 xc = (np.random.rand(N)-0.5)*10 yc = (np.random.rand(N)-0.5)*10 plt.scatter(xc, yc, s=200) for i in range(len(xc)): plt.annotate(i,(xc[i]+0.15,yc[i]),size=16,color='r') plt.show() # Getting the distances w = np.zeros([N,N]) for i in range(N): for j in range(N): w[i,j]= np.sqrt((xc[i]-xc[j])**2+(yc[i]-yc[j])**2) a=list(permutations(range(1,N))) last_best_distance = 10000000 for i in a: distance = 0 pre_j = 0 for j in i: distance = distance + w[j,pre_j] pre_j = j distance = distance + w[0,pre_j] order = (0,) + i if distance < last_best_distance: best_order = order last_best_distance = distance print('order = ' + str(order) + ' Distance = ' + str(distance)) best_distance_brute = last_best_distance best_order_brute = best_order plt.scatter(xc, yc) xbest = np.array([xc[i] for i in best_order_brute]) xbest = np.append(xbest,xbest[0]) ybest = np.array([yc[i] for i in best_order_brute]) ybest = np.append(ybest,ybest[0]) plt.plot(xbest, ybest, 'b.-', ms = 40) plt.plot(xc[0], yc[0], 'r*', ms = 20) for i in range(len(xc)): plt.annotate(i,(xc[i]+0.2,yc[i]),size=16,color='r') plt.show() print('Best order from brute force = ' + str(best_order_brute) + ' with total distance = ' + str(best_distance_brute)) n=(N-1)**2 # number of qubits A = np.max(w)*100 # A parameter of cost function # takes the part of w matrix excluding the 0-th point, which is the starting one wsave = w[1:N,1:N] # nearest-neighbor interaction matrix for the prospective cycle (p,p+1 interaction) shift = np.zeros([N-1,N-1]) shift = la.toeplitz([0,1,0], [0,1,0])/2 # the first and last point of the TSP problem are fixed by initial and final conditions firststep = np.zeros([N-1]) firststep[0] = 1; laststep = np.zeros([N-1]) laststep[N-2] = 1; # The binary variables that define a path live in a tensor product space of position and ordering indices # Q defines the interactions between variables Q = np.kron(shift,wsave) + np.kron(A*np.ones((N-1, N-1)), np.identity(N-1)) + np.kron(np.identity(N-1),A*np.ones((N-1, N-1))) # G defines the contribution from the individual variables G = np.kron(firststep,w[0,1:N]) + np.kron(laststep,w[1:N,0]) - 4*A*np.kron(np.ones(N-1),np.ones(N-1)) # M is the constant offset M = 2*A*(N-1) # Evaluates the cost distance from a binary representation of a path fun = lambda x: np.dot(np.around(x),np.dot(Q,np.around(x)))+np.dot(G,np.around(x))+M def get_order_tsp(x): # This function takes in a TSP state, an array of (N-1)^2 binary variables, and returns the # corresponding travelling path associated to it order = [0] for p in range(N-1): for j in range(N-1): if x[(N-1)*p+j]==1: order.append(j+1) return order def get_x_tsp(order): # This function takes in a traveling path and returns a TSP state, in the form of an array of (N-1)^2 # binary variables x = np.zeros((len(order)-1)**2) for j in range(1,len(order)): p=order[j] x[(N-1)*(j-1)+(p-1)]=1 return x # Checking if the best results from the brute force approach are correct for the mapped system of binary variables # Conversion from a path to a binary variable array xopt_brute = get_x_tsp(best_order_brute) print('Best path from brute force mapped to binary variables: \n') print(xopt_brute) flag = False for i in range(100000): rd = np.random.randint(2, size=n) if fun(rd) < (best_distance_brute - 0.0001): print('\n A random solution is better than the brute-force one. The path measures') print(fun(rd)) flag = True if flag == False: print('\nCheck with 10^5 random solutions: the brute-force solution mapped to binary variables is correct.\n') print('Shortest path evaluated with binary variables: ') print(fun(xopt_brute)) # Optimization with simulated annealing initial_x = np.random.randint(2, size=n) cost = fun(initial_x) x = np.copy(initial_x) alpha = 0.999 temp = 10 for j in range(10000): # pick a random index and flip the bit associated with it flip = np.random.randint(len(x)) new_x = np.copy(x) new_x[flip] = (x[flip] + 1) % 2 # compute cost function with flipped bit new_cost = fun(new_x) if np.exp(-(new_cost - cost) / temp) > np.random.rand(): x = np.copy(new_x) cost = new_cost temp = temp * alpha print('distance = ' + str(cost) + ' x_solution = ' + str(x) + ', final temperature= ' + str(temp)) best_order_sim_ann = get_order_tsp(x) plt.scatter(xc, yc) xbest = np.array([xc[i] for i in best_order_sim_ann]) xbest = np.append(xbest, xbest[0]) ybest = np.array([yc[i] for i in best_order_sim_ann]) ybest = np.append(ybest, ybest[0]) plt.plot(xbest, ybest, 'b.-', ms=40) plt.plot(xc[0], yc[0], 'r*', ms=20) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.15, yc[i]), size=16, color='r') plt.show() print('Best order from simulated annealing = ' + str(best_order_sim_ann) + ' with total distance = ' + str(cost)) # Defining the new matrices in the Z-basis Iv=np.ones((N-1)**2) Qz = (Q/4) Gz =( -G/2-np.dot(Iv,Q/4)-np.dot(Q/4,Iv)) Mz = (M+np.dot(G/2,Iv)+np.dot(Iv,np.dot(Q/4,Iv))) Mz = Mz + np.trace(Qz) Qz = Qz - np.diag(np.diag(Qz)) # Recall the change of variables is # x = (1-z)/2 # z = -2x+1 z= -(2*xopt_brute)+Iv for i in range(1000): rd = 1-2*np.random.randint(2, size=n) if np.dot(rd,np.dot(Qz,rd))+np.dot(Gz,rd)+Mz < (best_distance_brute-0.0001): print(np.dot(rd,np.dot(Qz,rd))+np.dot(Gz,rd)+Mz) # Getting the Hamiltonian in the form of a list of Pauli terms pauli_list = [] for i in range(n): if Gz[i] != 0: wp = np.zeros(n) vp = np.zeros(n) vp[i] = 1 pauli_list.append((Gz[i], Pauli(vp, wp))) for i in range(n): for j in range(i): if Qz[i, j] != 0: wp = np.zeros(n) vp = np.zeros(n) vp[i] = 1 vp[j] = 1 pauli_list.append((2 * Qz[i, j], Pauli(vp, wp))) pauli_list.append((Mz, Pauli(np.zeros(n), np.zeros(n)))) # Making the Hamiltonian as a full matrix and finding its lowest eigenvalue H = make_Hamiltonian(pauli_list) we, v = la.eigh(H, eigvals=(0, 0)) exact = we[0] print(exact) H = np.diag(H) # Setting up a quantum program and connecting to the Quantum Experience API Q_program = QuantumProgram() # set the APIToken and API url Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) # Optimization of the TSP using a quantum computer # Quantum circuit parameters # the entangler step is made of two-qubit gates between a control and target qubit, control: [target] coupling_map = None # the coupling_maps gates allowed on the device entangler_map = {0: [1], 1: [2], 2: [3], 3: [4], 4: [5], 5: [6], 6: [7], 7: [8]} # the layout of the qubits initial_layout = None # the backend used for the quantum computation backend = 'local_qasm_simulator' # Total number of trial steps used in the optimization max_trials = 1500; n = 9 # the number of qubits # Depth of the quantum circuit that prepares the trial state m = 5 # initial starting point for the control angles initial_theta = np.random.randn(m * n) # number of shots for each evaluation of the cost function (shots=1 corresponds to perfect evaluation, # only available on the simulator) shots = 1 # choose to plot the results of the optimizations every save_steps save_step = 1 """ ########################## RUN OPTIMIZATION ####################### if shots == 1: obj_funct_partial = partial(obj_funct, Q_program, pauli_list, entangler_map, coupling_map, initial_layout, n, m, backend, shots) initial_c=0.01 else: obj_funct_partial = partial(obj_funct, Q_program, pauli_list, entangler_map, coupling_map, initial_layout, n, m, backenddevice, shots) initial_c=0.1 target_update=2*np.pi*0.1 SPSA_parameters=SPSA_calibration(obj_funct_partial,initial_theta,initial_c,target_update,25) print ('SPSA parameters = ' + str(SPSA_parameters)) best_distance_quantum, best_theta, cost_plus, cost_minus,_,_ = SPSA_optimization(obj_funct_partial, initial_theta, SPSA_parameters, max_trials, save_step) """ def cost_function(Q_program, H, n, m, entangler_map, shots, device, theta): return eval_hamiltonian(Q_program, H, trial_circuit_ry(n, m, theta, entangler_map, None, False), shots, device).real initial_c = 0.1 target_update = 2 * np.pi * 0.1 save_step = 1 if shots != 1: H = group_paulis(pauli_list) SPSA_params = SPSA_calibration(partial(cost_function, Q_program, H, n, m, entangler_map, shots, backend), initial_theta, initial_c, target_update, 25) best_distance_quantum, best_theta, cost_plus, cost_minus, _, _ = SPSA_optimization( partial(cost_function, Q_program, H, n, m, entangler_map, shots, backend), initial_theta, SPSA_params, max_trials, save_step,1); """ ########################## PLOT RESULTS #######################""" plt.plot(np.arange(0, max_trials,save_step),cost_plus,label='C(theta_plus)') plt.plot(np.arange(0, max_trials,save_step),cost_minus,label='C(theta_minus)') plt.plot(np.arange(0, max_trials,save_step),(np.ones(max_trials//save_step)*best_distance_quantum), label='Final Cost') plt.plot(np.arange(0, max_trials,save_step),np.ones(max_trials//save_step)*exact, label='Exact Cost') plt.legend() plt.xlabel('Number of trials') plt.ylabel('Cost') # Sampling from the quantum state generated with the optimal angles from the quantum optimization shots = 100 circuits = ['final_circuit'] Q_program.add_circuit('final_circuit', trial_circuit_ry(n, m, best_theta, entangler_map,None,True)) result = Q_program.execute(circuits, backend=backend, shots=shots, coupling_map=coupling_map, initial_layout=initial_layout) data = result.get_counts('final_circuit') plot_histogram(data,5) # Getting path and total distance from the largest component of the quantum state max_value = max(data.values()) # maximum value max_keys = [k for k, v in data.items() if v == max_value] # getting all keys containing the `maximum` x_quantum = np.zeros(n) for bit in range(n): if max_keys[0][bit] == '1': x_quantum[bit] = 1 quantum_order = get_order_tsp(list(map(int, x_quantum))) best_distance_quantum_amp = fun(x_quantum) plt.scatter(xc, yc) xbest = np.array([xc[i] for i in quantum_order]) xbest = np.append(xbest, xbest[0]) ybest = np.array([yc[i] for i in quantum_order]) ybest = np.append(ybest, ybest[0]) plt.plot(xbest, ybest, 'b.-', ms=40) plt.plot(xc[0], yc[0], 'r*', ms=20) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.15, yc[i]), size=14, color='r') plt.show() print('Best order from quantum optimization is = ' + str(quantum_order) + ' with total distance = ' + str( best_distance_quantum_amp))
https://github.com/Raijeku/qmeans
Raijeku
!pip install qmeans import numpy as np import pandas as pd from qmeans.qmeans import QuantumKMeans from qiskit import Aer from sklearn.datasets import load_iris import matplotlib.pyplot as plt backend = Aer.get_backend("aer_simulator_statevector") X,y = load_iris(return_X_y=True) print('Data is: ',X) print('Labels are: ',y) qk_means = QuantumKMeans(backend, n_clusters=3, verbose=True, map_type='probability', init='random', shots=10000) qk_means.fit(X) print(qk_means.labels_) plt.scatter(X[:,0], X[:,1], c=qk_means.labels_) qk_means.get_params() !pip list import numpy as np import pandas as pd from qmeans.qmeans import QuantumKMeans, AerSimulator from sklearn.datasets import load_iris import matplotlib.pyplot as plt backend = AerSimulator() X,y = load_iris(return_X_y=True) print('Data is: ',X) print('Labels are: ',y) qk_means = QuantumKMeans(backend, n_clusters=3, verbose=True, map_type='probability', init='random', shots=10000) qk_means.fit(X) print(qk_means.labels_) plt.scatter(X[:,0], X[:,1], c=qk_means.labels_) qk_means.get_params() !pip list
https://github.com/Raijeku/qmeans
Raijeku
"""Module for quantum k-means algorithm with a class containing sk-learn style functions resembling the k-means algorithm. This module contains the QuantumKMeans class for clustering according to euclidian distances calculated by running quantum circuits. Typical usage example:: import numpy as np import pandas as pd from qmeans.qmeans import * backend = AerSimulator() X = pd.DataFrame(np.array([[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]])) q_means = QuantumKMeans(backend, n_clusters=2, verbose=True) q_means.fit(X) print(q_means.labels_) """ from typing import Tuple import numpy as np import pandas as pd from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, transpile from qiskit_aer import AerSimulator from qiskit.providers import Backend from sklearn.preprocessing import normalize, scale from sklearn.utils import check_random_state from sklearn.utils. extmath import stable_cumsum from sklearn.base import BaseEstimator from qiskit_aer.noise import NoiseModel def preprocess(points: np.ndarray, map_type: str ='angle', norm_relevance: bool = False): """Preprocesses data points according to a type criteria. The algorithm scales the data points if the type is 'angle' and normalizes the data points if the type is 'probability'. Args: points: The input data points. map_type: {'angle', 'probability'} Specifies the type of data encoding. 'angle': Uses U3 gates with its theta angle being the phase angle of the complex data point. 'probability': Relies on data normalization to preprocess the data to acquire a norm of 1. norm_relevance: If true, maps two-dimensional data onto 2 angles, one for the angle between both data points and another for the magnitude of the data points. Returns: p_points: Preprocessed points. """ if map_type == 'angle': p_points = scale(points[:]) a_points = points.copy() if norm_relevance is True: for i, point in enumerate(a_points): if np.array_equiv(point, np.zeros_like(point)): point = np.ones_like(point)*((1/a_points.shape[1])**(1/2)) a_points[i] = point _, norms = normalize(a_points[:], return_norm=True) #norms = np.sqrt(p_points[:,0]**2+p_points[:,1]**2) max_norm = np.max(norms) new_column = norms/max_norm new_column = new_column.reshape((new_column.size,1)) p_points = np.concatenate((p_points, new_column),axis=1) return p_points elif map_type == 'probability': """if len(points.shape) > 1: size = points.shape[1] else: size = points.shape[0]""" """print("pre points") print(points) print(type(points)) #i = 0 points = points.to_numpy() for i, point in enumerate(points): if np.array_equiv(point, np.zeros_like(point)): point = np.ones_like(point)*((1/points.shape[1])**(1/2)) points[i] = point print(point) #i += 1 print("post points") print(points) points = pd.DataFrame(points)""" p_points, norms = normalize(points[:], return_norm=True) return p_points, norms def distance(x: np.ndarray, y: np.ndarray, backend: Backend, map_type: str = 'probability', shots: int = 1024, norms: np.ndarray = np.array([1, 1]), norm_relevance: bool = False, noise_model: NoiseModel = None): """Finds the distance between two data points by mapping the data points onto qubits using amplitude or angle encoding and then using a swap test. The algorithm performs angle encoding if the type is 'angle' and amplitude encoding if the type is 'probability'. Args: x: The first data point. y: The second data point. backend: IBM quantum device to calculate the distance with. map_type: {'angle', 'probability'} Specify the type of data encoding. 'angle': Uses U3 gates with its theta angle being the phase angle of the complex data point. 'probability': Relies on data normalization to preprocess the data to acquire a norm of 1. shots: Number of repetitions of each circuit, for sampling. norm_relevance: If true, maps two-dimensional data onto 2 angles, one for the angle between both data points and another for the magnitude of the data points. noise_model: Noise model to use when runnings circuits on a simulator. Returns: distance: Distance between the two data points. """ if map_type == 'angle': if x.size == 2: qubits = int(np.ceil(np.log2(x.size))) #print("x is") #print(x) #x = x.values #print(x) #print("y is") #print(y) #y = y.values #print(y) complexes_x = x[0] + 1j*x[1] complexes_y= y[0] + 1j*y[1] theta_1 = np.angle(complexes_x) theta_2 = np.angle(complexes_y) qr = QuantumRegister(3, name="qr") cr = ClassicalRegister(3, name="cr") qc = QuantumCircuit(qr, cr, name="k_means") qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.u(theta_1, np.pi, np.pi, qr[1]) qc.u(theta_2, np.pi, np.pi, qr[2]) qc.cswap(qr[0], qr[1], qr[2]) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.reset(qr) qc = transpile(qc, backend) job = backend.run(qc, shots=shots, noise_model=noise_model) result = job.result() data = result.get_counts() if len(data)==1: return 0.0 else: return data['0'*(qubits*2)+'1']/shots elif x.size == 3 and norm_relevance is True: qubits = int(np.ceil(np.log2(x.size))) complexes_x = x[0] + 1j*x[1] complexes_y= y[0] + 1j*y[1] theta_1 = np.angle(complexes_x) theta_2 = np.angle(complexes_y) ro_1 = x[2]*np.pi ro_2 = y[2]*np.pi qr = QuantumRegister(3, name="qr") cr = ClassicalRegister(3, name="cr") qc = QuantumCircuit(qr, cr, name="k_means") qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.u(theta_1, np.pi, np.pi, qr[1]) qc.u(ro_1, 0, 0, qr[1]) qc.u(theta_2, np.pi, np.pi, qr[2]) qc.u(ro_2, 0, 0, qr[1]) qc.cswap(qr[0], qr[1], qr[2]) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.reset(qr) qc = transpile(qc, backend) job = backend.run(qc, shots=shots, noise_model=noise_model) result = job.result() data = result.get_counts() if len(data)==1: return 0.0 else: return data['0'*(qubits)+'1']/shots elif map_type == 'probability': if x.size > 1: qubits = int(np.ceil(np.log2(x.size))) else: qubits = 1 #print(y) n_x = np.zeros(2**qubits) n_x[:x.size] = x n_y = np.zeros(2**qubits) n_y[:y.size] = y qr = QuantumRegister(2*qubits + 1, name="qr") cr = ClassicalRegister(2*qubits + 1, name="cr") qc = QuantumCircuit(qr, cr, name="k_means") #print(n_x) #print((n_x**2).sum()) qc.initialize(n_x,[i+1 for i in range(qubits)]) # pylint: disable=no-member qc.initialize(n_y,[i+1+qubits for i in range(qubits)]) # pylint: disable=no-member qc.h(qr[0]) for i in range(qubits): qc.cswap(qr[0], qr[1+i], qr[qubits+1+i]) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.reset(qr) qc = transpile(qc, backend) job = backend.run(qc, shots=shots, noise_model=noise_model) result = job.result() data = result.get_counts() if len(data)==1: return 0.0 else: M = data['0'*(qubits*2)+'1']/shots return (norms[0]**2 + norms[1] ** 2 - 2*norms[0]*norms[1]*((1 - 2*M)**(1/2)))**(1/2) def batch_separate(X: np.ndarray, clusters: np.ndarray, max_experiments: int, norms: np.ndarray, cluster_norms: np.ndarray): """Creates batches of pairs of vectors. Separates data points X and cluster centers into a number of batches of elements for distance calculations in a single job. Each batch contains a set of data points and cluster centers, corresponding to the data for distance measurements in each batch. Args: X: Training instances to cluster. clusters: Cluster centers. max_experiments: The amount of distance measurements in each batch. Returns: B: Batches with pairs of data points and cluster centers. """ if X.shape[0] > clusters.shape[0]: if X.shape[0] % max_experiments == 0: batches_X = np.asarray(np.split(X,[i*max_experiments for i in range(1,X.shape[0]//max_experiments)])) batches_norms_X = np.asarray(np.split(norms, [i*max_experiments for i in range(1, norms.shape[0]//max_experiments)])) else: batches_X = np.asarray(np.split(X,[i*max_experiments for i in range(1,X.shape[0]//max_experiments + 1)])) batches_norms_X = np.asarray(np.split(norms, [i*max_experiments for i in range(1, norms.shape[0]//max_experiments + 1)])) #print("batches_X:",batches_X) #print(batches_X.shape) #print("clusters:",clusters) #print(clusters.shape) if X.shape[0] % max_experiments == 0: batches_clusters = np.empty([(X.shape[0]//max_experiments)*clusters.shape[0],clusters.shape[1]], dtype=clusters.dtype) batches_norms_clusters = np.empty([(X.shape[0]//max_experiments)*cluster_norms.shape[0],1], dtype=cluster_norms.dtype) else: batches_clusters = np.empty([(X.shape[0]//max_experiments + 1)*clusters.shape[0],clusters.shape[1]], dtype=clusters.dtype) batches_norms_clusters = np.empty([(X.shape[0]//max_experiments + 1)*cluster_norms.shape[0],1], dtype=cluster_norms.dtype) for i in range(clusters.shape[0]): batches_clusters[i::clusters.shape[0]] = clusters[i] batches_norms_clusters[i::cluster_norms.shape[0]] = cluster_norms[i] #print("batches_clusters:",batches_clusters) #print(batches_clusters.shape) batches_X = np.asarray(np.repeat(batches_X,clusters.shape[0],axis=0)) batches_norms_X = np.asarray(np.repeat(batches_norms_X,cluster_norms.shape[0],axis=0)) #print("batches_X:",batches_X) #print(batches_X.shape) batches = ([(batches_X[i], batches_clusters[i]) for i in range(batches_clusters.shape[0])], [(batches_norms_X[i], batches_norms_clusters[i]) for i in range(batches_norms_clusters.shape[0])]) return batches else: raise NotImplementedError def batch_distance(B: Tuple[np.ndarray, np.ndarray], backend: Backend, norm_B: np.ndarray, map_type: str = 'angle', shots: int = 1024): """Finds the distance between pairs of data points and cluster centers inside a batch by mapping the data points onto qubits using amplitude or angle encoding and then using a swap test. The algorithm performs angle encoding if the type is 'angle' and amplitude encoding if the type is 'probability'. Args: B: The batch of X data points and y cluster centers. backend: IBM quantum device to calculate the distance with. map_type: {'angle', 'probability'} Specifies the type of data encoding. 'angle': Uses U3 gates with its theta angle being the phase angle of the complex data point. 'probability': Relies on data normalization to preprocess the data to acquire a norm of 1. shots: Number of repetitions of each circuit, for sampling. Returns: distance: Distance between the data points and cluster centers of the batch. """ if B[0].shape[1] == 2: if map_type == 'angle': qcs = [] for point in B[0]: x = point y = B[1] complexes_x = x[0] + 1j*x[1] complexes_y= y[0] + 1j*y[1] theta_1 = np.angle(complexes_x) theta_2 = np.angle(complexes_y) qr = QuantumRegister(3, name="qr") cr = ClassicalRegister(3, name="cr") qc = QuantumCircuit(qr, cr, name="k_means") qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.u(theta_1, np.pi, np.pi, qr[1]) qc.u(theta_2, np.pi, np.pi, qr[2]) qc.cswap(qr[0], qr[1], qr[2]) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.reset(qr) qcs.append(qc) qcs = transpile(qcs, backend) job = backend.run(qcs, shots=shots) result = job.result() data = result.get_counts() return [batch_data['001']/shots if len(batch_data)!=1 else 0.0 for batch_data in data] elif map_type == 'probability': qcs = [] for point in B[0]: x = point y = B[1] qr = QuantumRegister(3, name="qr") cr = ClassicalRegister(3, name="cr") qc = QuantumCircuit(qr, cr, name="k_means") qc.initialize(x,1) # pylint: disable=no-member qc.initialize(y,2) # pylint: disable=no-member qc.h(qr[0]) qc.cswap(qr[0], qr[1], qr[2]) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.reset(qr) qcs.append(qc) qcs = transpile(qcs, backend) job = backend.run(qcs, shots=shots) result = job.result() data = result.get_counts() contained = ['0'*2+'1' in batch_data for batch_data in data] M = [data[i]['0'*2+'1']/shots if contained[i] is True else 0.0 for i in range(len(contained))] return [(norm_B[0][i]**2 + norm_B[1]**2 -2*norm_B[0][i]*norm_B[1]*((1 - 2*M_i)**(1/2)))**(1/2) for i, M_i in enumerate(M)] elif B[0].shape[1] == 3: if map_type == 'angle': qcs = [] for point in B[0]: x = point y = B[1] complexes_x = x[0] + 1j*x[1] complexes_y= y[0] + 1j*y[1] theta_1 = np.angle(complexes_x) theta_2 = np.angle(complexes_y) ro_1 = x[2]*np.pi/2 ro_2 = y[2]*np.pi/2 qr = QuantumRegister(3, name="qr") cr = ClassicalRegister(3, name="cr") qc = QuantumCircuit(qr, cr, name="k_means") qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.u(theta_1, np.pi, np.pi, qr[1]) qc.u(ro_1, 0, 0, qr[1]) qc.u(theta_2, np.pi, np.pi, qr[2]) qc.u(ro_2, 0, 0, qr[2]) qc.cswap(qr[0], qr[1], qr[2]) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.reset(qr) qcs.append(qc) qcs = transpile(qcs, backend) job = backend.run(qcs, shots=shots) result = job.result() data = result.get_counts() return [batch_data['001']/shots if len(batch_data)!=1 else 0.0 for batch_data in data] elif np.log2(B[0].shape[1]).is_integer(): if map_type == 'angle': qcs = [] for point in B[0]: x = point y = B[1] complexes_x = x[0] + 1j*x[1] complexes_y= y[0] + 1j*y[1] theta_1 = np.angle(complexes_x) theta_2 = np.angle(complexes_y) qr = QuantumRegister(3, name="qr") cr = ClassicalRegister(3, name="cr") qc = QuantumCircuit(qr, cr, name="k_means") qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.u(theta_1, np.pi, np.pi, qr[1]) qc.u(theta_2, np.pi, np.pi, qr[2]) qc.cswap(qr[0], qr[1], qr[2]) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.reset(qr) qcs.append(qc) qcs = transpile(qcs, backend) job = backend.run(qcs, shots=shots) result = job.result() data = result.get_counts() return [batch_data['001']/shots if len(batch_data)!=1 else 0.0 for batch_data in data] elif map_type == 'probability': qcs = [] for point in B[0]: x = point y = B[1] qr = QuantumRegister(int(np.log2(B[0].shape[1]))*2+1, name="qr") cr = ClassicalRegister(int(np.log2(B[0].shape[1]))*2+1, name="cr") qc = QuantumCircuit(qr, cr, name="k_means") qc.initialize(x,[i+1 for i in range(int(np.log2(B[0].shape[1])))]) # pylint: disable=no-member qc.initialize(y,[i+1+int(np.log2(B[0].shape[1])) for i in range(int(np.log2(B[0].shape[1])))]) # pylint: disable=no-member qc.h(qr[0]) for i in range(int(np.log2(B[0].shape[1]))): qc.cswap(qr[0], qr[1+i], qr[int(np.log2(B[0].shape[1])+1)+i]) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.reset(qr) qcs.append(qc) qcs = transpile(qcs, backend) job = backend.run(qcs, shots=shots) result = job.result() data = result.get_counts() contained = ['0'*int(np.log2(B[0].shape[1]))*2+'1' in batch_data for batch_data in data] M = [data[i]['0'*int(np.log2(B[0].shape[1]))*2+'1']/shots if contained[i] is True else 0.0 for i in range(len(contained))] #print('norm_B is', norm_B) #print('M is', M) return [(norm_B[0][i]**2 + norm_B[1]**2 -2*norm_B[0][i]*norm_B[1]*((1 - 2*M_i)**(1/2)))**(1/2) for i, M_i in enumerate(M)] else: if map_type == 'angle': qcs = [] for point in B[0]: x = point y = B[1] complexes_x = x[0] + 1j*x[1] complexes_y= y[0] + 1j*y[1] theta_1 = np.angle(complexes_x) theta_2 = np.angle(complexes_y) qr = QuantumRegister(3, name="qr") cr = ClassicalRegister(3, name="cr") qc = QuantumCircuit(qr, cr, name="k_means") qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.u(theta_1, np.pi, np.pi, qr[1]) qc.u(theta_2, np.pi, np.pi, qr[2]) qc.cswap(qr[0], qr[1], qr[2]) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.reset(qr) qcs.append(qc) qcs = transpile(qcs, backend) job = backend.run(qcs, shots=shots) result = job.result() data = result.get_counts() return [batch_data['001']/shots if len(batch_data)!=1 else 0.0 for batch_data in data] elif map_type == 'probability': qcs = [] for point in B[0]: if np.log2(B[0].shape[1]).is_integer(): qubits = int(np.log2(B[0].shape[1])) else: qubits = int(np.log2(B[0].shape[1])) + 1 x = np.zeros(2**qubits) x[:point.shape[0]] = point y = np.zeros(2**qubits) y[:B[1].shape[0]] = B[1] qr = QuantumRegister(qubits*2+1, name="qr") cr = ClassicalRegister(qubits*2+1, name="cr") qc = QuantumCircuit(qr, cr, name="k_means") qc.initialize(x,[i+1 for i in range(qubits)]) # pylint: disable=no-member qc.initialize(y,[i+1+qubits for i in range(qubits)]) # pylint: disable=no-member qc.h(qr[0]) for i in qubits: qc.cswap(qr[0], qr[1+i], qr[qubits+1+i]) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.reset(qr) qcs.append(qc) qcs = transpile(qcs, backend) job = backend.run(qcs, shots=shots) result = job.result() data = result.get_counts() contained = ['0'*qubits*2+'1' in batch_data for batch_data in data] M = [data[i]['0'*qubits*2+'1']/shots if contained[i]==True else 0.0 for i in range(len(contained))] return [(norm_B[0][i]**2 + norm_B[1]**2 -2*norm_B[0][i]*norm_B[1]*((1 - 2*M_i)**(1/2)))**(1/2) for i, M_i in enumerate(M)] def batch_collect(batch_d: np.ndarray, desired_shape: Tuple[int, int]): """Collects batches of distances. Retrieves batches of distances and transforms the shape of the data to a desired shape. Args: batch_d: Batches of distances. desired_shape: The shape of the collected distances. Returns: final_batch_d: Transformed distances. """ #print('Batch d is', batch_d) #print('Batch d shape is', batch_d.shape) #print('Desired shape is', desired_shape) final_batch_d = np.empty(batch_d.shape, dtype=batch_d.dtype) #print('Final Batch D is', final_batch_d) for i in range(batch_d.shape[0]//desired_shape[0]): final_batch_d[i] = batch_d[desired_shape[0]*i] #print('Final Batch D is', final_batch_d) #print(batch_d.shape[0]//desired_shape[0], batch_d.shape[0]) #print(batch_d.shape, desired_shape) if batch_d.squeeze(axis=-1).shape != desired_shape: for i in range(batch_d.shape[0]//desired_shape[0],batch_d.shape[0]): final_batch_d[i] = batch_d[desired_shape[0]*i-batch_d.shape[0]+1] #print('Final Batch D is', final_batch_d) return final_batch_d.reshape(desired_shape) def batch_distances(X: np.ndarray, cluster_centers: np.ndarray, backend: Backend, map_type: str, shots: int, verbose: bool, norms: np.ndarray, cluster_norms: np.ndarray): """Batches data and calculates and collects distances. Data is separated into batches, sent to the quantum device to calculate distances and the distances are then collected from the results. Args: X: Training instances to cluster. cluster_centers: Coordinates of cluster centers. backend: IBM quantum device to run the quantum k-means algorithm on. map_type: {'angle', 'probability'} Specifies the type of data encoding. 'angle': Uses U3 gates with its theta angle being the phase angle of the complex data point. 'probability': Relies on data normalization to preprocess the data to acquire a norm of 1. shots: Number of repetitions of each circuit, for sampling. verbose: Defines if verbosity is active for deeper insight into the class processes. Returns: distance: Distance between the data points and cluster centers. """ #print('LOOK HERE OMG ----------------------------------------------------------------') #print(norms) #print('LOOK HERE CLUSTERS ----------------------------------------------------------------') #print(cluster_norms) #print('LOOK HERE END ----------------------------------------------------------------') if isinstance(cluster_centers, pd.DataFrame): batches, norm_batches = batch_separate(X.to_numpy(), cluster_centers.to_numpy(),backend.configuration().max_experiments, norms, cluster_norms) else: batches, norm_batches = batch_separate(X.to_numpy(), cluster_centers,backend.configuration().max_experiments, norms, cluster_norms) #if verbose: print('Batches are', batches) #if verbose: print('Norm atches are', norm_batches) distance_list = np.asarray([batch_distance(B,backend,norm_batches[i],map_type,shots) for i, B in enumerate(batches)]) #if verbose: print('Distance list is', distance_list) distances = batch_collect(distance_list, (cluster_centers.shape[0],X.shape[0])) #if verbose: print('Distances are', distances) return distances def qmeans_plusplus(X: np.ndarray, n_clusters: int, backend: Backend, map_type: str, verbose: bool, initial_center: str, shots: int = 1024, norms: np.ndarray = np.array([1,1]), batch: bool = True, x_squared_norms: np.ndarray = None, n_local_trials: int = None, random_state: int = None, noise_model: NoiseModel = None): """Init n_clusters seeds according to q-means++. Selects initial cluster centers for q-mean clustering in a smart way to speed up convergence. Args: X: The data to pick seeds from. n_clusters: The number of centroids to initialize. backend: IBM quantum device to run the quantum k-means algorithm on. map_type: {'angle', 'probability'} Specifies the type of data encoding. 'angle': Uses U3 gates with its theta angle being the phase angle of the complex data point. 'probability': Relies on data normalization to preprocess the data to acquire a norm of 1. verbose: Defines if verbosity is active for deeper insight into the class processes. initial_center: {'random', 'far'} Speficies the strategy for setting the initial cluster center. 'random': Assigns a random initial center. 'far': Specifies the furthest point as the initial center. x_squared_norms: Squared Euclidean norm of each data point. n_local_trials: The number of seeding trials for each center (except the first), of which the one reducing inertia the most is greedily chosen. Set to None to make the number of trials depend logarithmically on the number of seeds (2+log(k)). random_state: Determines random number generation for centroid initialization. Pass an int for reproducible output across multiple function calls. noise_model: Noise model to use when runnings circuits on a simulator. Returns: centers: The initial centers for q-means. indices: The index location of the chosen centers in the data array X. For a given index and center, X[index] = center. """ if verbose: print('Started Qmeans++') random_state = check_random_state(random_state) n_samples, n_features = X.shape centers = np.empty((n_clusters, n_features), dtype= X.values.dtype) if n_local_trials is None: n_local_trials = 2 + int(np.log(n_clusters)) center_id = random_state.randint(n_samples) indices = np.full(n_clusters, -1, dtype=int) indices[0] = center_id centers[0] = X.values[center_id] if verbose: print('Centers are:', pd.DataFrame(centers)) if batch: closest_distances = batch_distances(X, centers[0, np.newaxis], backend, map_type, shots, verbose) else: if map_type == 'probability': closest_distances = np.asarray([[distance(point,centroid,backend,map_type,shots,np.array([norms[i],norms[j]]),noise_model=noise_model) for i, point in X.iterrows()] for j, centroid in pd.DataFrame(centers[0, np.newaxis]).iterrows()]) elif map_type == 'angle': closest_distances = np.asarray([[distance(point,centroid,backend,map_type,shots,noise_model=noise_model) for i, point in X.iterrows()] for j, centroid in pd.DataFrame(centers[0, np.newaxis]).iterrows()]) current_pot = closest_distances.sum() #if verbose: # print('Closest distances are:', closest_distances) for c in range(1, n_clusters): if verbose: print('Cluster center', c) rand_vals = random_state.random_sample(n_local_trials) * current_pot candidate_ids = np.searchsorted(stable_cumsum(closest_distances), rand_vals) np.clip(candidate_ids, None, closest_distances.size - 1, out=candidate_ids) if batch: distance_to_candidates = batch_distances(X, X.values[candidate_ids], backend, map_type, shots, verbose) else: if map_type == 'probability': distance_to_candidates = np.asarray([[distance(point,centroid,backend,map_type,shots,np.array([norms[i],norms[j]]),noise_model=noise_model) for i, point in X.iterrows()] for j, centroid in X.iloc[candidate_ids].iterrows()]) elif map_type == 'angle': distance_to_candidates = np.asarray([[distance(point,centroid,backend,map_type,shots,noise_model=noise_model) for i, point in X.iterrows()] for j, centroid in X.iloc[candidate_ids].iterrows()]) np.minimum(closest_distances, distance_to_candidates, out=distance_to_candidates) candidates_pot = distance_to_candidates.sum(axis=1) best_candidate = np.argmin(candidates_pot) current_pot = candidates_pot[best_candidate] closest_distances = distance_to_candidates[best_candidate] best_candidate = candidate_ids[best_candidate] centers[c] = X.values[best_candidate] indices[c] = best_candidate if verbose: print('Centers are:', pd.DataFrame(centers)) #if verbose: print('Closest distances are:', closest_distances) if c == 1 and initial_center == 'far': if batch: closest_distances = batch_distances(X, centers[1, np.newaxis], backend, map_type, shots, verbose) else: if map_type == 'probability': closest_distances = np.asarray([[distance(point,centroid,backend,map_type,shots,np.array([norms[i],norms[j]]),noise_model=noise_model) for i, point in X.iterrows()] for j, centroid in pd.DataFrame(centers[1, np.newaxis]).iterrows()]) elif map_type == 'angle': closest_distances = np.asarray([[distance(point,centroid,backend,map_type,shots,noise_model=noise_model) for i, point in X.iterrows()] for j, centroid in pd.DataFrame(centers[1, np.newaxis]).iterrows()]) current_pot = closest_distances.sum() rand_vals = random_state.random_sample(n_local_trials) * current_pot candidate_ids = np.searchsorted(stable_cumsum(closest_distances), rand_vals) np.clip(candidate_ids, None, closest_distances.size - 1, out=candidate_ids) if batch: distance_to_candidates = batch_distances(X, X.values[candidate_ids], backend, map_type, shots, verbose) else: if map_type == 'probability': distance_to_candidates = np.asarray([[distance(point,centroid,backend,map_type,shots,np.array([norms[i],norms[j]]),noise_model=noise_model) for i, point in X.iterrows()] for j, centroid in X.iloc[candidate_ids].iterrows()]) elif map_type == 'angle': distance_to_candidates = np.asarray([[distance(point,centroid,backend,map_type,shots,noise_model=noise_model) for i, point in X.iterrows()] for j, centroid in X.iloc[candidate_ids].iterrows()]) np.minimum(closest_distances, distance_to_candidates, out=distance_to_candidates) candidates_pot = distance_to_candidates.sum(axis=1) best_candidate = np.argmin(candidates_pot) current_pot = candidates_pot[best_candidate] closest_distances = distance_to_candidates[best_candidate] best_candidate = candidate_ids[best_candidate] centers[0] = X.values[best_candidate] indices[0] = best_candidate if verbose: print('Centers are:', pd.DataFrame(centers)) return centers, indices class QuantumKMeans(BaseEstimator): """Quantum k-means clustering algorithm. This k-means alternative implements quantum machine learning to calculate distances between data points and centroids using quantum circuits. Args: n_clusters: The number of clusters to use and the amount of centroids generated. init: {'q-means++, 'random'}, callable or array-like of shape (n_clusters, n_features) Method for initialization: 'q-means++' : selects initial cluster centers for q-mean clustering in a smart way to speed up convergence. 'random': choose n_clusters observations (rows) at random from data for the initial centroids. If an array is passed, it should be of shape (n_clusters, n_features) and gives the initial centers. If a callable is passed, it should take arguments X, n_clusters and a random state and return an initialization. tol: Relative tolerance with regards to Frobenius norm of the difference in the cluster centers of two consecutive iterations to declare convergence. verbose: Defines if verbosity is active for deeper insight into the class processes. max_iter: Maximum number of iterations of the quantum k-means algorithm for a single run. backend: IBM quantum device to run the quantum k-means algorithm on. map_type: {'angle', 'probability'} Specifies the type of data encoding. 'angle': Uses U3 gates with its theta angle being the phase angle of the complex data point. 'probability': Relies on data normalization to preprocess the data to acquire a norm of 1. shots: Number of repetitions of each circuit, for sampling. norm_relevance: If true, maps two-dimensional data onto 2 angles, one for the angle between both data points and another for the magnitude of the data points. initial_center: {'random', 'far'} Speficies the strategy for setting the initial cluster center. 'random': Assigns a random initial center. 'far': Specifies the furthest point as the initial center. noise_model: Noise model to use when runnings circuits on a simulator. Attributes: cluster_centers_: Coordinates of cluster centers. labels_: Centroid labels for each data point. n_iter_: Number of iterations run before convergence. """ def __init__(self, backend: Backend = AerSimulator(), n_clusters: int = 2, init: str = 'random', tol: float = 0.0001, max_iter: int = 300, verbose: bool = False, map_type: str = 'probability', shots: int = 1024, norm_relevance: bool = False, initial_center: str = 'random', noise_model: NoiseModel = None): """Initializes an instance of the quantum k-means algorithm.""" #self.cluster_centers_ = np.empty(0) #self.labels_ = np.empty(0) #self.n_iter_ = 0 self.n_clusters = n_clusters self.init = init self.tol = tol self.verbose = verbose self.max_iter = max_iter self.backend = backend self.map_type = map_type self.shots = shots self.norm_relevance = norm_relevance self.initial_center = initial_center self.noise_model = noise_model def fit(self, X: np.ndarray, y: np.ndarray = None, batch: bool = False): """Computes quantum k-means clustering. Args: X: Training instances to cluster. batch: Option for using batches to calculate distances. Returns: self: Fitted estimator. """ if self.verbose: print('Data is:',X) finished = False old_X = pd.DataFrame(X) if self.map_type == 'probability': X, norms = preprocess(X, self.map_type, self.norm_relevance) X = pd.DataFrame(X) else: X = pd.DataFrame(preprocess(X, self.map_type, self.norm_relevance)) if self.init == 'q-means++': if self.map_type == 'probability': self.cluster_centers_, _ = qmeans_plusplus(X, self.n_clusters, self.backend, self.map_type, self.verbose, self.initial_center, shots=self.shots, batch=batch, norms=norms) elif self.map_type == 'angle': self.cluster_centers_, _ = qmeans_plusplus(X, self.n_clusters, self.backend, self.map_type, self.verbose, self.initial_center, shots=self.shots, batch=batch) self.cluster_centers_ = pd.DataFrame(self.cluster_centers_)#.values elif self.init == 'random': self.cluster_centers_ = old_X.sample(n=self.n_clusters) self.n_iter_ = 0 while not finished and self.n_iter_ < self.max_iter: if self.verbose: print("Iteration",self.n_iter_) if self.map_type == 'probability': normalized_clusters, cluster_norms = preprocess(self.cluster_centers_.values, self.map_type, self.norm_relevance) elif self.map_type == 'angle': normalized_clusters = preprocess(self.cluster_centers_.values, self.map_type, self.norm_relevance) normalized_clusters = pd.DataFrame(normalized_clusters) if batch: distances = batch_distances(X, normalized_clusters, self.backend, self.map_type, self.shots, self.verbose, norms, cluster_norms) else: if self.map_type == 'probability': distances = np.asarray([[distance(point,centroid,self.backend,self.map_type,self.shots,np.array([norms[i],cluster_norms[j]]),noise_model=self.noise_model) for i, point in X.iterrows()] for j, centroid in normalized_clusters.iterrows()]) elif self.map_type == 'angle': distances = np.asarray([[distance(point,centroid,self.backend,self.map_type,self.shots,np.array([1,1]),self.norm_relevance,noise_model=self.noise_model) for i, point in X.iterrows()] for j, centroid in normalized_clusters.iterrows()]) self.labels_ = np.asarray([np.argmin(distances[:,i]) for i in range(distances.shape[1])]) new_centroids = old_X.groupby(self.labels_).mean() #Needs to be checked to see if less centers are an option if self.verbose: print("Old centroids are",self.cluster_centers_.values) if self.verbose: print("New centroids are",new_centroids.values) if abs((new_centroids.values - self.cluster_centers_.values).sum(axis=0).sum()) < self.tol: finished = True self.cluster_centers_ = new_centroids if self.verbose: print("Centers are", self.labels_) self.n_iter_ += 1 return self def predict(self, X: np.ndarray, sample_weight: np.ndarray = None, batch: bool = False): """Predict the closest cluster each sample in X belongs to. Args: X: New data points to predict. sample_weight: The weights for each observation in X. If None, all observations are assigned equal weight. batch: Option for using batches to calculate distances. Returns: labels: Centroid labels for each data point. """ if self.map_type == 'probability': X, norms = preprocess(X, self.map_type, self.norm_relevance) X = pd.DataFrame(X) else: X = pd.DataFrame(preprocess(X, self.map_type, self.norm_relevance)) if self.map_type == 'probability': normalized_clusters, cluster_norms = preprocess(self.cluster_centers_.values, self.map_type, self.norm_relevance) normalized_clusters = pd.DataFrame(normalized_clusters) else: normalized_clusters = pd.DataFrame(preprocess(self.cluster_centers_.values, self.map_type, self.norm_relevance)) if sample_weight is None: if batch: distances = batch_distances(X, self.cluster_centers_, self.backend, self.map_type, self.shots, self.verbose) else: if self.map_type == 'probability': distances = np.asarray([[distance(point,centroid,self.backend,self.map_type,self.shots,np.array([norms[i],cluster_norms[j]]),noise_model=self.noise_model) for i,point in X.iterrows()] for j,centroid in normalized_clusters.iterrows()]) elif self.map_type == 'angle': distances = np.asarray([[distance(point,centroid,self.backend,self.map_type,self.shots,np.array([1,1]),self.norm_relevance,noise_model=self.noise_model) for i,point in X.iterrows()] for j,centroid in normalized_clusters.iterrows()]) else: weight_X = X * sample_weight if batch: batch_distances(weight_X, self.cluster_centers_, self.backend, self.map_type, self.shots, self.verbose) else: if self.map_type == 'probability': distances = np.asarray([[distance(point,centroid,self.backend,self.map_type,self.shots,np.array([norms[i],cluster_norms[j]]),noise_model=self.noise_model) for i,point in weight_X.iterrows()] for j,centroid in normalized_clusters.iterrows()]) elif self.map_type == 'angle': distances = np.asarray([[distance(point,centroid,self.backend,self.map_type,self.shots,np.array([1,1]),self.norm_relevance,noise_model=self.noise_model) for i,point in weight_X.iterrows()] for j,centroid in normalized_clusters.iterrows()]) labels = np.asarray([np.argmin(distances[:,i]) for i in range(distances.shape[1])]) return labels def get_params(self, deep: bool = True): """Get parameters for this estimator. Args: deep: If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns: params: Parameter names mapped to their values. """ return {"n_clusters": self.n_clusters, "init": self.init, "tol": self.tol, "verbose": self.verbose, "max_iter": self.max_iter, "backend": self.backend, "map_type": self.map_type, "shots": self.shots, "norm_relevance": self.norm_relevance, "initial_center": self.initial_center } def set_params(self, **params): """Set the parameters of this estimator. Args: **params: Estimator parameters. Returns: self: Estimator instance. """ for parameter, value in params.items(): setattr(self, parameter, value) return self
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. """ Example showing how to use the Sympy Provider at level 0 (novice). This example shows the most basic way to user the Sympy Provider. It builds some circuits and runs them on both the statevector and unitary simulators. """ # Import the Qiskit modules from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute from qiskit_addon_sympy import SympyProvider SyQ = SympyProvider() # Create a Quantum and Classical Register. qubit_reg = QuantumRegister(2) clbit_reg = ClassicalRegister(2) # making first circuit: bell state qc1 = QuantumCircuit(qubit_reg, clbit_reg) qc1.h(qubit_reg[0]) qc1.cx(qubit_reg[0], qubit_reg[1]) # making another circuit: superpositions qc2 = QuantumCircuit(qubit_reg, clbit_reg) qc2.h(qubit_reg) # setting up the backend print("(Sympy Backends)") print(SyQ.backends()) # running the statevector simulator statevector_job = execute([qc1, qc2], SyQ.get_backend('statevector_simulator')) statevector_result = statevector_job.result() # show the results print("Stevector simulator: ", statevector_result) print(statevector_result.get_statevector(qc1)) print(statevector_result.get_statevector(qc2)) # running the unitary simulator unitary_job = execute([qc1, qc2], SyQ.get_backend('unitary_simulator')) unitary_result = unitary_job.result() # show the results print("Unitary simulator: ", unitary_result) print(unitary_result.get_unitary(qc1)) print(unitary_result.get_unitary(qc2))
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. """ Example showing how to use the Sympy Provider at level 1 (intermediate). This example shows how an intermediate user interacts with the Sympy Provider. It builds some circuits and compiles them. It makes a qobj object which is just a container to be run on a backend. The same qobj can run on many backends (as shown). It is the user responsibility to make sure it can be run. This is useful when you want to compare the same circuits on different backends or change the compile parameters. """ import time # Import the Qiskit modules from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import compile from qiskit_addon_sympy import SympyProvider SyQ = SympyProvider() # Create a quantum and classical register. qubit_reg = QuantumRegister(2, name='q') clbit_reg = ClassicalRegister(2, name='c') # Making first circuit: Bell state qc1 = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc1.h(qubit_reg[0]) qc1.cx(qubit_reg[0], qubit_reg[1]) # Making another circuit: superpositions qc2 = QuantumCircuit(qubit_reg, clbit_reg, name="superposition") qc2.h(qubit_reg) # Setting up the backend print("(Sympy Backends)") for backend in SyQ.backends(): print(backend.status()) statevector_backend = SyQ.get_backend('statevector_simulator') unitary_backend = SyQ.get_backend('unitary_simulator') # Compiling the qobj for the statevector backend qobj = compile([qc1, qc2], backend=statevector_backend) # Running the both backends on the same qobj statevector_job = statevector_backend.run(qobj) unitary_job = unitary_backend.run(qobj) lapse = 0 interval = 0.01 while statevector_job.status().name != 'DONE' or unitary_job.status().name != 'DONE': print('Status at {} milliseconds'.format(1000 * interval * lapse)) print("Stevector simulator: ", statevector_job.status()) print("Unitary simulator: ", unitary_job.status()) time.sleep(interval) lapse += 1 print(statevector_job.status()) print(unitary_job.status()) statevector_result = statevector_job.result() unitary_result = unitary_job.result() # Show the results print("Stevector simulator: ", statevector_result) print(statevector_result.get_statevector(qc1)) print(statevector_result.get_statevector(qc2)) print("Unitary simulator: ", unitary_result) print(unitary_result.get_unitary(qc1)) print(unitary_result.get_unitary(qc2))
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/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. # pylint: disable=invalid-name,missing-docstring from test.common import QiskitSympyTestCase import unittest from sympy import sqrt from qiskit import (load_qasm_file, execute, QuantumRegister, ClassicalRegister, QuantumCircuit, wrapper) from qiskit_addon_sympy import SympyProvider class SympyStatevectorSimulatorTest(QiskitSympyTestCase): """Test local statevector simulator.""" def setUp(self): self.qasm_filename = self._get_resource_path('simple.qasm') self.q_circuit = load_qasm_file(self.qasm_filename) def test_sympy_statevector_simulator(self): """Test final state vector for single circuit run.""" SyQ = SympyProvider() backend = SyQ.get_backend('statevector_simulator') result = execute(self.q_circuit, backend).result() actual = result.get_statevector(self.q_circuit) self.assertEqual(result.get_status(), 'COMPLETED') self.assertEqual(actual[0], sqrt(2)/2) self.assertEqual(actual[1], 0) self.assertEqual(actual[2], 0) self.assertEqual(actual[3], sqrt(2)/2) class TestQobj(QiskitSympyTestCase): """Check the objects compiled for this backend create names properly""" def setUp(self): qr = QuantumRegister(2, name="qr2") cr = ClassicalRegister(2, name=None) qc = QuantumCircuit(qr, cr, name="qc10") qc.h(qr[0]) qc.measure(qr[0], cr[0]) self.qr_name = qr.name self.cr_name = cr.name self.circuits = [qc] def test_qobj_sympy_statevector_simulator(self): SyQ = SympyProvider() backend = SyQ.get_backend('statevector_simulator') qobj = wrapper.compile(self.circuits, backend) cc = qobj.experiments[0].as_dict() ccq = qobj.experiments[0].header.compiled_circuit_qasm self.assertIn(self.qr_name, map(lambda x: x[0], cc['header']['qubit_labels'])) self.assertIn(self.qr_name, ccq) self.assertIn(self.cr_name, map(lambda x: x[0], cc['header']['clbit_labels'])) self.assertIn(self.cr_name, ccq) if __name__ == '__main__': unittest.main()
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. # pylint: disable=invalid-name,missing-docstring from test.common import QiskitSympyTestCase import unittest from sympy import sqrt from qiskit import (load_qasm_file, execute, QuantumRegister, ClassicalRegister, QuantumCircuit, wrapper) from qiskit_addon_sympy import SympyProvider class SympyUnitarySimulatorTest(QiskitSympyTestCase): """Test local unitary simulator sympy.""" def setUp(self): self.qasm_filename = self._get_resource_path('simple.qasm') self.q_circuit = load_qasm_file(self.qasm_filename) def test_unitary_simulator(self): """test generation of circuit unitary""" SyQ = SympyProvider() backend = SyQ.get_backend('unitary_simulator') result = execute(self.q_circuit, backend).result() actual = result.get_unitary(self.q_circuit) self.assertEqual(actual[0][0], sqrt(2)/2) self.assertEqual(actual[0][1], sqrt(2)/2) self.assertEqual(actual[0][2], 0) self.assertEqual(actual[0][3], 0) self.assertEqual(actual[1][0], 0) self.assertEqual(actual[1][1], 0) self.assertEqual(actual[1][2], sqrt(2)/2) self.assertEqual(actual[1][3], -sqrt(2)/2) self.assertEqual(actual[2][0], 0) self.assertEqual(actual[2][1], 0) self.assertEqual(actual[2][2], sqrt(2)/2) self.assertEqual(actual[2][3], sqrt(2)/2) self.assertEqual(actual[3][0], sqrt(2)/2) self.assertEqual(actual[3][1], -sqrt(2)/2) self.assertEqual(actual[3][2], 0) self.assertEqual(actual[3][3], 0) class TestQobj(QiskitSympyTestCase): """Check the objects compiled for this backend create names properly""" def setUp(self): qr = QuantumRegister(2, name="qr2") cr = ClassicalRegister(2, name=None) qc = QuantumCircuit(qr, cr, name="qc10") qc.h(qr[0]) qc.measure(qr[0], cr[0]) self.qr_name = qr.name self.cr_name = cr.name self.circuits = [qc] def test_qobj_sympy_unitary_simulator(self): SyQ = SympyProvider() backend = SyQ.get_backend('unitary_simulator') qobj = wrapper.compile(self.circuits, backend) cc = qobj.experiments[0].as_dict() ccq = qobj.experiments[0].header.compiled_circuit_qasm self.assertIn(self.qr_name, map(lambda x: x[0], cc['header']['qubit_labels'])) self.assertIn(self.qr_name, ccq) self.assertIn(self.cr_name, map(lambda x: x[0], cc['header']['clbit_labels'])) self.assertIn(self.cr_name, ccq) if __name__ == '__main__': unittest.main()
https://github.com/erinaldi/bmn2-qiskit
erinaldi
import pandas as pd import numpy as np import matplotlib.pyplot as plt import sys plt.style.use("../figures/paper.mplstyle") # parameters def read_data( optimizer: str, p: dict, ): """Read the VQE convergence data for the mini BMN model from disk Args: optimizer (str): The optimizer used. p (dict): The dictionary with the parameters for the filename. Returns: pandas.DataFrame: The dataframe collecting the results of the convergence """ filename = f"{p['f']}_l{p['l']}_convergence_{optimizer}_{p['v']}_depth{p['d']}_reps{p['n']}_max{p['m']}.h5" try: df = pd.read_hdf(filename, "vqe") except FileNotFoundError as e: print(f"{filename} not found. {e}") sys.exit() return df[df.counts<=p["s"]*p['m']] # only keep counts less than maxit # parameters def read_data_pickle( optimizer: str, p: dict, ): """Read the VQE convergence data for the mini BMN model from disk Args: optimizer (str): The optimizer used. p (dict): The dictionary with the parameters for the filename. Returns: pandas.DataFrame: The dataframe collecting the results of the convergence """ filename = f"{p['f']}_l{p['l']}_convergence_{optimizer}_{p['v']}_depth{p['d']}_reps{p['n']}_max{p['m']}.gz" try: df = pd.read_pickle(filename) except FileNotFoundError as e: print(f"{filename} not found. {e}") sys.exit() return df[df.counts<=p["s"]*p['m']] # only keep counts less than maxit def collect_data( optimizers: list, p: dict, h5: bool = True, ): """Read the VQE convergence data for the mini BMN model from disk Args: optimizer (str): The optimizer used. p (dict): The dictionary with the parameters for the filename. h5 (bool, optional): if the file to collect data from are in HDF5 format. Defaults to true Returns: pandas.DataFrame: The dataframe collecting the all the results of the convergence """ # concatenate the results from all files if h5: frames = [read_data(o, p) for o in optimizers] else: frames = [read_data_pickle(o, p) for o in optimizers] return pd.concat(frames, keys=optimizers, names=["Optimizer"]) depth = 9 g2N = 2.0 varform = ['ry','rz'] nrep = 100 maxit = 10000 datafolder = "../data/miniBMN_L2" params = dict() params["l"] = str(g2N).replace(".", "") params["d"] = depth params["v"] = "-".join(varform) params["m"] = maxit params["n"] = nrep params["f"] = datafolder params["s"] = 10.0 # factor to scale up maxit (works for SLSQP which does not care about maxit) df = read_data_pickle("SLSQP",params) df.plot.scatter(x='counts',y='energy',marker='.') # opt_label = ["COBYLA", "L-BFGS-B","SLSQP"]#,"NELDER-MEAD"] opt_label = ["COBYLA", "L-BFGS-B","SLSQP","NELDER-MEAD"] # opt_label = ["COBYLA"] result = collect_data(opt_label,params,h5=False) result.groupby('rep').apply(lambda x: x.sort_values(by='counts',ascending=False).iloc[:4][['counts','energy']]) result.groupby('Optimizer').apply(min).style.format(precision=5).hide_columns(['counts','casimir']) # change the precision of the output result.sort_values(by='energy').iloc[0] gs = dict() for r in opt_label: gs[r] = result.loc[r].groupby('rep').apply(min).energy gsdf = pd.DataFrame.from_dict(gs, dtype=float) gsdf gsdf.describe().T[["min","max","mean","std"]].style.format(precision=5) # change the precision of the output gsdf['SLSQP'].idxmin() gsdf.sort_values(by=['SLSQP'],ascending=True).plot.hist(y='SLSQP') result.loc['SLSQP',39].plot(x='counts',y='energy') ht = 0.003287 # select the best runs for each optimizer fig, ax = plt.subplots(figsize=(20,8)) for o in opt_label: result.loc[o,gsdf[o].idxmin()].plot(x='counts',y='energy', xlim=[0,10000],label=o, ax=ax) ax.axhline(ht,c="k",ls="--", lw="2",label="HT") ax.set_xlabel("iterations") ax.set_ylabel("VQE energy") ax.legend(loc="upper right") filename = f"../figures/miniBMN_L2_l{params['l']}_convergence_{params['v']}_depth{params['d']}_nr{params['n']}_max{params['m']}" plt.savefig(f"{filename}.pdf") plt.savefig(f"{filename}.png") plt.savefig(f"{filename}.svg") # select the best runs for each optimizer fig, ax = plt.subplots(figsize=(20,8)) for o in opt_label: result.loc[o,gsdf[o].idxmin()].plot(x='counts',y='energy', xlim=[0,50000],label=o, ax=ax) ax.axhline(ht,c="k",ls="--", lw="2",label="HT") # inset axes.... bounds are [x0, y0, width, height] for where to put it axins = ax.inset_axes([0.4, 0.4, 0.3, 0.5]) for o in opt_label: result.loc[o,gsdf[o].idxmin()].plot(x='counts',y='energy', xlim=[0,12000], legend=False, ax=axins) axins.axhline(ht,c="k",ls="--", lw="2") # sub region of the original image x1, x2, y1, y2 = 0, 12000, 0, 1 axins.set_xlim(x1, x2) axins.set_ylim(y1, y2) axins.set_xticklabels('') axins.set_yticklabels('') axins.set_ylabel('') axins.set_xlabel('') ax.indicate_inset_zoom(axins, edgecolor="black") ax.set_xlabel("iterations") ax.set_ylabel("VQE energy") ax.legend(loc="upper right") filename = f"../figures/miniBMN_L2_l{params['l']}_convergence_{params['v']}_depth{params['d']}_nr{params['n']}_max{params['m']}_zoom50000" plt.savefig(f"{filename}.pdf") plt.savefig(f"{filename}.png") plt.savefig(f"{filename}.svg") depths = [1,2,3,4,5,6,7,8,9] opts = ["COBYLA","L-BFGS-B","SLSQP","NELDER-MEAD"] # for d in depths: # params['d'] = d # print(f"Depth={params['d']} ---------------------") # res = collect_data(opts,params,h5=False) # gs = dict() # for r in opts: # gs[r] = res.loc[r].groupby('rep').apply(min).energy # gsdf = pd.DataFrame.from_dict(gs, dtype=float) # print(gsdf.describe().T[["min","max","mean","std"]]) ds = dict() for d in depths: params['d'] = d res = collect_data(opts,params,h5=False) ds[d] = res.groupby('Optimizer').apply(min).energy dfds = pd.DataFrame.from_dict(ds,orient='index',dtype=float).rename_axis("depth") dfds ht = 0.00328726 fig, ax = plt.subplots() dfds.plot(marker="o", ylim=[0,0.2], ax=ax) ax.axhline(ht,c="k",ls="--",lw="2",label="HT") ax.set_ylabel("VQE energy") ax.set_xlabel(r"$R_yR_z$"+" depth") ax.legend(loc="upper right") # plt.savefig("../figures/miniBMN_L2_l02_ry-rz_nr100_max10000_depths.pdf") # plt.savefig("../figures/miniBMN_L2_l02_ry-rz_nr100_max10000_depths.png") # plt.savefig("../figures/miniBMN_L2_l02_ry-rz_nr100_max10000_depths.svg") depth = 3 g2N = 2.0 varform = ['ry'] nrep = 100 maxit = 10000 dataprefix = "../data/bosBMN_L2" params = dict() params["l"] = str(g2N).replace(".", "") params["d"] = depth params["v"] = "-".join(varform) params["m"] = maxit params["n"] = nrep params["f"] = dataprefix params["s"] = 1.0 opt_label = ["COBYLA","L-BFGS-B","SLSQP","NELDER-MEAD"] result = collect_data(opt_label,params,False) result.groupby('Optimizer').apply(min) gs = dict() for r in opt_label: gs[r] = result.loc[r].groupby('rep').apply(min).energy gsdf = pd.DataFrame.from_dict(gs, dtype=float) gsdf.describe().T[["min","max","mean","std"]].style.format(precision=5) # change the precision of the output ht = 3.13406 # select the best runs for each optimizer fig, ax = plt.subplots(figsize=(20,8)) for o in opt_label: result.loc[o,gsdf[o].idxmin()].plot(x='counts',y='energy', xlim=[0,10000],label=o, ax=ax) ax.axhline(ht,c="k",ls="--", lw="2",label="HT") ax.set_xlabel("iterations") ax.set_ylabel("VQE energy") ax.legend(loc="upper right") # filename = f"../figures/miniBMN_l{params['l']}_convergence_{params['v']}_depth{params['d']}_nr{params['n']}_max{params['m']}" # plt.savefig(f"{filename}.pdf") # plt.savefig(f"{filename}.png") # select the best runs for each optimizer fig, ax = plt.subplots(figsize=(20,8)) for o in opt_label: result.loc[o,gsdf[o].idxmin()].plot(x='counts',y='energy', xlim=[0,10000],label=o, ax=ax) ax.axhline(ht,c="k",ls="--", lw="2",label="HT") # inset axes.... bounds are [x0, y0, width, height] for where to put it axins = ax.inset_axes([0.3, 0.4, 0.3, 0.5]) for o in opt_label: result.loc[o,gsdf[o].idxmin()].plot(x='counts',y='energy', xlim=[0,1000], legend=False, ax=axins) axins.axhline(ht,c="k",ls="--", lw="2") # sub region of the original image x1, x2, y1, y2 = 0, 1000, 3.1, 6 axins.set_xlim(x1, x2) axins.set_ylim(y1, y2) axins.set_xticklabels('') axins.set_yticklabels('') axins.set_ylabel('') axins.set_xlabel('') ax.indicate_inset_zoom(axins, edgecolor="black") ax.set_xlabel("iterations") ax.set_ylabel("VQE energy") ax.legend(loc="upper right") figprefix = dataprefix.replace("data","figures") filename = f"{figprefix}_l{params['l']}_convergence_{params['v']}_depth{params['d']}_nr{params['n']}_max{params['m']}_zoom" plt.savefig(f"{filename}.pdf") plt.savefig(f"{filename}.png") plt.savefig(f"{filename}.svg") # df = pd.read_csv("../data/bosBMN_L2_couplings_ry_depth3_reps100.csv", index_col='l', dtype=float) df = pd.read_csv("../data/bosBMN_L4_couplings_ry_depth3_reps100.csv", index_col='l', dtype=float) df df = df.assign(COBYLA_HT=df['COBYLA']-df['HT']) df = df.assign(L_BFGS_B_HT=df['L-BFGS-B']-df['HT']) df = df.assign(SLSQP_HT=df['SLSQP']-df['HT']) df = df.assign(NELDER_MEAD_HT=df['NELDER-MEAD']-df['HT']) fig, ax = plt.subplots() df.plot(y='HT', marker='o', ax=ax) df.plot(y='COBYLA', marker='o', ax=ax) ax.set_xlabel(r"$\lambda$") fig, ax = plt.subplots() df.plot.bar(y=['COBYLA_HT','L_BFGS_B_HT','SLSQP_HT','NELDER_MEAD_HT'],label=False,ax=ax) ax.tick_params(axis="x", rotation=0) ax.set_xlabel(r"$\lambda$") ax.set_ylabel("Energy difference") ax.legend(["COBYLA","L-BFGS-B","SLSQP","NELDER-MEAD"]) plt.savefig("../figures/bosBMN_L4_couplings_e-diff_ry_depth3_reps100_max10000.pdf") plt.savefig("../figures/bosBMN_L4_couplings_e-diff_ry_depth3_reps100_max10000.png") plt.savefig("../figures/bosBMN_L4_couplings_e-diff_ry_depth3_reps100_max10000.svg") df = pd.read_csv("../data/times_mini.csv", dtype=float) df.head() df.plot.hist() df['minutes'] = df['seconds']/60. df['hours'] = df['seconds']/3600. df.describe().T df.plot.hist(y='hours')
https://github.com/erinaldi/bmn2-qiskit
erinaldi
import numpy as np from scipy.sparse import diags L = 8 # cutoff for Fock space a = diags(np.sqrt(np.linspace(1,L-1,L-1)),offsets=1) print(a.toarray()) from qiskit.opflow import MatrixOp qubitOp = MatrixOp(primitive=a) print(qubitOp.num_qubits) type(qubitOp) print(qubitOp) a_pauli = qubitOp.to_pauli_op() print(a_pauli) type(a_pauli) a_pauli.to_matrix() from scipy.sparse import identity iden = identity(L) qubitOp = MatrixOp(primitive=iden) print(qubitOp.num_qubits) i_pauli = qubitOp.to_pauli_op() print(i_pauli) i_pauli.to_matrix() Nmat = 6 # BMN2 for SU(2) has 6 bosonic matrices from qiskit.opflow import ListOp, TensoredOp boson = ListOp([i_pauli]*6) print(boson) print(boson[0]) type(boson[0]) # generically speaking, we construct the list of bosons and then take the outer product a_list = [] # this will contain a1...a6 as a list of ListOp for i in np.arange(0,Nmat): # loop over all operators operator_list = [i_pauli] * Nmat # only the identity repeated Nmat times operator_list[i] = a_pauli # the i^th element is now the annihilation operator for a single boson a_list.append(ListOp(operator_list)) print(a_list[0]) type(a_list[0]) # here we create a list of operators which are the tensor products... a_tensor = [TensoredOp(x) for x in a_list] print(a_tensor[0]) print(a_tensor[0].to_pauli_op()) a_tensor[0].num_qubits sparse = a_tensor[0].to_spmatrix() type(sparse) sparse.shape # from qiskit.utils import algorithm_globals # algorithm_globals.massive=True # needed to big matrices... # full = a_tensor[0].to_matrix() # len(full) # full.shape i_tensor = TensoredOp(ListOp([i_pauli] * Nmat)) type(i_tensor) print(i_tensor) i_tensor.to_pauli_op() from qiskit.opflow import I I^Nmat i_tensor.num_qubits # full = i_tensor.to_matrix() # len(full) print(i_tensor.to_spmatrix()) # for each boson they are constructed using a and adag x_tensor = [1/np.sqrt(2)*(~x + x) for x in a_tensor] print(x_tensor[0]) print(x_tensor[0].to_pauli_op()) print(x_tensor[0].to_spmatrix()) from qiskit.opflow import SummedOp H_zero = 0.5*Nmat*i_tensor print(H_zero) H_zero_pauli = 0.5*Nmat*(I^Nmat) print(H_zero.to_pauli_op()) print(H_zero_pauli) H_zero.to_spmatrix() H_zero.to_pauli_op() ### Harmonic oscillator # this should be summed over all the bosons (Nmat) H_list = [H_zero] for op in a_tensor: H_list.append((~op @ op)) H_osc = SummedOp(H_list) print(H_osc) type(H_osc) H_osc_pauli = H_osc.to_pauli_op() type(H_osc_pauli) H_osc_pauli.num_qubits H_osc.to_spmatrix() quartic1 = SummedOp([x_tensor[2]@x_tensor[2]@x_tensor[3]@x_tensor[3], \ x_tensor[2]@x_tensor[2]@x_tensor[4]@x_tensor[4], \ x_tensor[1]@x_tensor[1]@x_tensor[3]@x_tensor[3], \ x_tensor[1]@x_tensor[1]@x_tensor[5]@x_tensor[5], \ x_tensor[0]@x_tensor[0]@x_tensor[4]@x_tensor[4], \ x_tensor[0]@x_tensor[0]@x_tensor[5]@x_tensor[5]]) print(quartic1.to_pauli_op()) quartic2 = SummedOp([x_tensor[0]@x_tensor[2]@x_tensor[3]@x_tensor[5],\ x_tensor[0]@x_tensor[1]@x_tensor[3]@x_tensor[4],\ x_tensor[1]@x_tensor[2]@x_tensor[4]@x_tensor[5]], coeff = -2.0) print(quartic2.to_pauli_op()) type(quartic2) ### Quartic Interaction V = quartic1 + quartic2 V.num_qubits V_pauli = V.to_pauli_op() g2N = 0.2 N = 2 ### Full Hamiltonian H = H_osc + g2N / N * V type(H) H.to_pauli_op() type(H.to_pauli_op()) H.num_qubits testH = H.to_matrix_op() testH Hpauli = H.to_pauli_op() # the line below is also fine... # Hpauli1 = H_osc.to_pauli_op() + g2N / N * V.to_pauli_op() # Hpauli print(Hpauli) type(Hpauli) print(f"Number of terms in H: {len(Hpauli.oplist)}") # write expression to disk with open('pauliH_L8_bos2.txt','w') as f: print(Hpauli,file=f) import sys print(sys.getsizeof(Hpauli)) from pympler import asizeof print(f"Size of Hpauli in MB: {asizeof.asizeof(Hpauli)/1024/1024}") # print(asizeof.asized(Hpauli, detail=1).format()) from qiskit.algorithms import NumPyMinimumEigensolver npme = NumPyMinimumEigensolver() # result = npme.compute_minimum_eigenvalue(operator=H_osc) # result = npme.compute_minimum_eigenvalue(operator=H) result = npme.compute_minimum_eigenvalue(operator=Hpauli) # result = npme.compute_minimum_eigenvalue(operator=testH) print(result) ref_value = result.eigenvalue.real print(f'Ground state energy value: {ref_value:.5f}') from scipy.sparse import kron def build_operators(L: int, N: int) -> list: """Generate all the annihilation operators needed to build the hamiltonian Args: L (int): the cutoff of the single site Fock space N (int): the number of colors of gauge group SU(N) Returns: list: a list of annihilation operators, length=N_bos """ # The annihilation operator for the single boson a_b = diags(np.sqrt(np.linspace(1, L - 1, L - 1)), offsets=1) # The identity operator of the Fock space of a single boson i_b = identity(L) # Bosonic Hilbert space N_bos = int(2 * (N ** 2 - 1)) # number of boson sites -> fixed for mini-BMN 2 product_list = [i_b] * N_bos # only the identity for bosons repeated N_bos times a_b_list = [] # this will contain a1...a6 for i in np.arange(0, N_bos): # loop over all bosonic operators operator_list = product_list.copy() # all elements are the identity operator operator_list[ i ] = a_b # the i^th element is now the annihilation operator for a single boson a_b_list.append( operator_list[0] ) # start taking tensor products from first element for a in operator_list[1:]: a_b_list[i] = kron( a_b_list[i], a ) # do the outer product between each operator_list element return a_b_list a_b_list = build_operators(L,N) # Build the Hamiltonian # Start piece by piece x_list = [] # only use the bosonic operators for op in a_b_list: x_list.append(1 / np.sqrt(2) * (op.conjugate().transpose() + op)) # Free Hamiltonian H_k = 0 for a in a_b_list: H_k = H_k + a.conjugate().transpose() * a # vacuum energy H_k = H_k + 0.5 * Nmat * identity(L ** Nmat) am = MatrixOp(a_b_list[0]) # this takes a really long time even for L=4 print(am.to_pauli_op()) xm = MatrixOp(x_list[0]) print(xm.to_pauli_op()) Hm = MatrixOp(H_k) result = npme.compute_minimum_eigenvalue(operator=Hm) ref_value = result.eigenvalue.real print(f'Ground state energy value: {ref_value:.5f}') v_b1 = ( x_list[2] * x_list[2] * x_list[3] * x_list[3] + x_list[2] * x_list[2] * x_list[4] * x_list[4] + x_list[1] * x_list[1] * x_list[3] * x_list[3] + x_list[1] * x_list[1] * x_list[5] * x_list[5] + x_list[0] * x_list[0] * x_list[4] * x_list[4] + x_list[0] * x_list[0] * x_list[5] * x_list[5] ) v_b2 = -2.0 * ( x_list[0] * x_list[2] * x_list[3] * x_list[5] + x_list[0] * x_list[1] * x_list[3] * x_list[4] + x_list[1] * x_list[2] * x_list[4] * x_list[5] ) V_b = v_b1 + v_b2 vm = MatrixOp(v_b1) vm.to_pauli_op() vm = MatrixOp(v_b2) vm.to_pauli_op() # full hamiltonian H_full = H_k + g2N / N * V_b Hm = MatrixOp(H_full) Hm.to_pauli_op() result = npme.compute_minimum_eigenvalue(operator=Hm) ref_value = result.eigenvalue.real print(f'Ground state energy value: {ref_value:.5f}') result = npme.compute_minimum_eigenvalue(operator=Hm.to_pauli_op()) ref_value = result.eigenvalue.real print(f'Ground state energy value: {ref_value:.5f}') print(result)
https://github.com/erinaldi/bmn2-qiskit
erinaldi
import sys import numpy as np N = 2 # cutoff for Fock space. The number of qubits used will be K = log2(N) annOp = np.array(np.diagflat(np.sqrt(np.linspace(1,N-1,N-1)),k=1)) with np.printoptions(precision=3, suppress=True, linewidth=120, threshold=sys.maxsize): # print array lines up to character 120 and floats using 3 digits print(annOp) iden = np.identity(N) with np.printoptions(precision=3, suppress=True, linewidth=120, threshold=sys.maxsize): # print array lines up to character 120 and floats using 3 digits print(iden) Nmat = 6 # number of bosonic dof as matrices: SU(2) -> 2^2-1=6 generators bosonList = [annOp] for bosons in range(0,Nmat-1): bosonList.append(iden) with np.printoptions(precision=3, suppress=True, linewidth=120, threshold=sys.maxsize): for i in bosonList: print(f"{i}\n") # This for loop takes the appropriate Kronecker products for each boson. for i in range(0,Nmat): for j in range(0,Nmat-1): # For the nth boson, the nth Kronecker product is with the annihilation operator. if j == i-1 and i != 0: bosonList[i] = np.kron(bosonList[i], annOp) # Else, the nth Kronecker product is with the identity matrix. else: bosonList[i] = np.kron(bosonList[i], iden) # the following will crash the system # with np.printoptions(precision=3, suppress=True, linewidth=120, threshold=sys.maxsize): # for i in bosonList: # print(f"{i}\n") [x.shape for x in bosonList] import matplotlib.pyplot as plt fig, ax = plt.subplots(ncols=6, figsize=(18, 6)) fig.subplots_adjust(left=0.02, bottom=0.06, right=0.95, top=0.94, wspace=0.5, hspace=1) for i,axi in enumerate(np.ravel(ax)): pos = axi.imshow(bosonList[i], cmap='jet') #fig.colorbar(pos, ax=axi) axi.set_title(f"Boson {i+1}") fig.suptitle('Operators', fontsize=16) fig.subplots_adjust(top=0.9) def bosonHamiltonians(numBosons, bosonMatrixDim, coupling=0.1): # This function takes the number of bosons (numBosons) and the size of the bosons (bosonMatrixDim) # as arguments. If the size of the boson is 2 x 2, for example, then bosonMatrixDim = 2. # coupling is lambda/2 and lambda is the 'tHooft coupling # Create the n x n annhiliation operator. Here, we create a list with all the integers from # the square root of 1 to the square root of n-1, where n x n is the size of the boson. # This list is injected as the upper diagonal in an array of zeros. annOP = np.array(np.diagflat(np.sqrt(np.linspace(1,bosonMatrixDim-1,bosonMatrixDim-1)),k=1)) # Create the n x n identity matrix. iden = np.identity(bosonMatrixDim) # Create a list which holds the six bosons. bosonList[0] is the first boson. bosonList[5] is the 6th boson. # For the first boson, the Kronecker product starts with the annihilation operator. bosonList = [annOP] # This for loop creates the list of bosons before the Kronecker products are taken. The first one was # already created in the previous line. for bosons in range(0,numBosons-1): bosonList.append(iden) # This for loop takes the appropriate Kronecker products for each boson. for i in range(0,numBosons): for j in range(0,numBosons-1): # For the nth boson, the nth Kronecker product is with the annihilation operator. if j == i-1 and i != 0: bosonList[i] = np.kron(bosonList[i], annOP) # Else, the nth Kronecker product is with the identity matrix. else: bosonList[i] = np.kron(bosonList[i], iden) # Create the position operators. Normalized as in the notes x = [] for r in range(0, numBosons): x.append((1/np.sqrt(2))*(bosonList[r] + np.transpose(np.conjugate(bosonList[r])))) # Create the simple quadratic Hamiltonian. H2MM = 0 for i in range(0,numBosons): # The @ symbol is a shorthand for matrix multiplication. It's equivalent to using np.matmul(). H2MM = H2MM + (np.transpose(np.conjugate(bosonList[i])) @ bosonList[i]) H2MM = H2MM + 0.5*numBosons*np.identity(bosonMatrixDim**(numBosons)) # Create the full quartic SU(2) Hamiltonian. x_sq = [] for i in x: x_sq.append(i @ i) H4MM1 = (H2MM + coupling*((x_sq[2] @ x_sq[3]) + (x_sq[2] @ x_sq[4]) + (x_sq[1] @ x_sq[3]) + (x_sq[1] @ x_sq[5]) + (x_sq[0] @ x_sq[4]) + (x_sq[0] @ x_sq[5]) - 2*((x[0] @ x[2]) @ (x[3] @ x[5])) - 2*((x[0] @ x[1]) @ (x[3] @ x[4])) - 2*((x[1] @ x[2]) @ (x[4] @ x[5])))) return H2MM, H4MM1 # Set the number of bosons here. For the proper full quartic SU(2) Hamiltonian, this has to be 6. numBosons = 6 # Set the size of the bosons here. For an n x n boson, bosonMatrixDim = n. # 5 will crash on laptop -> out of memory > 10GB # it also crashes this colab with 12Gb of RAM -> tries 6 of these tcmalloc: large alloc 1953128448 bytes # THIS IS ONLY BECAUSE WE ARE USING NUMPY IN THE FUNCTION! THIS CAN BE AVOIDED USING QISKIT OR QUTIP DIRECTLY TO CREATE SPARSE REPRESENTATIONS bosonMatrixDim = 4 # the function actually creates intermediate matrices x and x2 so the memory footprint is even higher...for N=5 it requires ~50GB of RAM H2MM, H4MM1 = bosonHamiltonians(numBosons, bosonMatrixDim, coupling=0.1) # we can change the coupling by adding coupling=0.5 to the args # Set the Hamiltonian that you want to run the VQE algorithm with here. hamiltonian = H4MM1 # Use numpy to find the eigenvalues of the simple quartic Hamiltonian # this can take a long time for large matrices val,vec=np.linalg.eig(hamiltonian) z = np.argsort(val) z = z[0:len(hamiltonian)] energies=(val[z]) if hamiltonian.all() == H4MM1.all(): # Sometimes there are negligible imaginary parts (e.g. order of 10^-16), so I take the real parts only. print('Full Quartic SU2 Eigenvalues:\n\n', np.real(energies)) else: print('Simple Quartic Eigenvalues:\n\n', energies) from qiskit.algorithms import VQE, NumPyEigensolver from qiskit import Aer # Convert the Hamiltonian Matrix to a qubit operator. import warnings import time from qiskit.opflow import MatrixOp start_time = time.time() warnings.filterwarnings("ignore") qubitOp = MatrixOp(primitive=hamiltonian) print("Size of Hamiltonian:", np.shape(hamiltonian)) print(qubitOp) end_time = time.time() runtime = end_time-start_time print('Program runtime: ',runtime) print("Total number of qubits: ",qubitOp.num_qubits) print(type(qubitOp).__name__) # Create the variational form. from qiskit.circuit.library import EfficientSU2 var_form = EfficientSU2(qubitOp.num_qubits, su2_gates=['ry'], entanglement="full", reps=1) var_form.draw(output='mpl',fold=100) # var_form.draw(output='mpl',fold=100, style={"fontsize":10, "displaycolor": {"ry": ('#9DC3E6','#000000')}},filename="../figures/var_form_bmn2_Ry_depth1.pdf") np.log2(hamiltonian.shape[0]) # This is a callback function that will allow us to store information about the optimizer while the VQE is running. # This is called when instantiating an object of the VQE class. def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) from qiskit.algorithms.optimizers import SLSQP from qiskit.utils import algorithm_globals, QuantumInstance warnings.filterwarnings("ignore") rngseed = 0 algorithm_globals.random_seed = rngseed backend = Aer.get_backend( "statevector_simulator", max_parallel_threads=6, max_parallel_experiments=0 ) q_instance = QuantumInstance( backend, seed_transpiler=rngseed, seed_simulator=rngseed ) counts = [] values = [] optim = SLSQP(maxiter=1000) # Setup the VQE algorithm vqe = VQE( ansatz=var_form, optimizer=optim, quantum_instance=q_instance, callback=store_intermediate_result, ) # run the VQE with out Hamiltonian operator result = vqe.compute_minimum_eigenvalue(qubitOp) vqe_result = np.real(result.eigenvalue) print(f"VQE gs energy: {vqe_result}") # Plot all of the optimizers in a single convergence plot. If you see that the optimizer isn't converging, # increase the maximum iterations or maximum function evaluations in the optimizer list above. labelList = ["SLSQP"] # Limit the range of the plot in order to make the convergence of each optimizer more visible. plt.plot(counts, values) plt.axhline(y=np.real(energies[0]),xmin=0,xmax=counts[-1],color='k',linestyle='--',label="Exact Energy") plt.xlabel('Eval count') plt.ylabel('Energy') plt.title('Energy convergence for various optimizers') plt.legend(loc='upper right', labels=labelList) from qiskit.algorithms.optimizers import SPSA from qiskit.utils import algorithm_globals, QuantumInstance warnings.filterwarnings("ignore") rngseed = 0 algorithm_globals.random_seed = rngseed backend = Aer.get_backend("qasm_simulator") q_instance = QuantumInstance( backend, shots=1024, seed_transpiler=rngseed, seed_simulator=rngseed ) counts = [] values = [] optim = SPSA(maxiter=1000) # Setup the VQE algorithm vqe = VQE( ansatz=var_form, optimizer=optim, quantum_instance=q_instance, callback=store_intermediate_result, ) # run the VQE with out Hamiltonian operator result = vqe.compute_minimum_eigenvalue(qubitOp) vqe_result = np.real(result.eigenvalue) print(f"VQE gs energy: {vqe_result}") # Plot convergence plot for the SPSA optimizer plt.figure(figsize=(15,15)) plt.plot(counts, values, label="SPSA") plt.plot(counts,[np.real(energies[0])]*len(counts), 'k--',label="Exact Energy") plt.xlabel('Eval count') plt.ylabel('Energy') plt.title('Energy convergence of SPSA optimizer (Qasm Simulation)') plt.legend(loc='upper right') from scipy.sparse import diags from scipy.sparse import identity from scipy.sparse import kron from scipy.sparse i def build_operators(L: int, N_bos: int) -> list: """Generate all the annihilation operators needed to build the hamiltonian Args: L (int): the cutoff of the single site Fock space N_bos (int): the number of bosonic sites Returns: list: a list of annihilation operators, length=N_bos """ # The annihilation operator for the single boson a_b = diags(np.sqrt(np.linspace(1, L - 1, L - 1)), offsets=1) # The identity operator of the Fock space of a single boson i_b = identity(L) # Bosonic Hilbert space product_list = [i_b] * N_bos # only the identity for bosons repeated N_bos times a_b_list = [] # this will contain a1...a6 for i in np.arange(0, N_bos): # loop over all bosonic operators operator_list = product_list.copy() # all elements are the identity operator operator_list[ i ] = a_b # the i^th element is now the annihilation operator for a single boson a_b_list.append( operator_list[0] ) # start taking tensor products from first element for a in operator_list[1:]: a_b_list[i] = kron( a_b_list[i], a ) # do the outer product between each operator_list element return a_b_list def build_gauge_casimir(L: int, N_bos: int) -> list: """Generate the gauge generators operators Args: L (int): the single site cutoff of the Fock space N_bos (int): the number of bosonic sites Returns: list : 3 generators (for SU(2)) """ # generate the annihilation operators bosons = build_operators(L, N_bos) # define the generator list for SU(2) g_list = [0] * 3 g_list[0] = 1j * ( bosons[1].conjugate().transpose() * bosons[2] - bosons[2].conjugate().transpose() * bosons[1] + bosons[4].conjugate().transpose() * bosons[5] - bosons[5].conjugate().transpose() * bosons[4] ) g_list[1] = 1j * ( bosons[2].conjugate().transpose() * bosons[0] - bosons[0].conjugate().transpose() * bosons[2] + bosons[5].conjugate().transpose() * bosons[3] - bosons[3].conjugate().transpose() * bosons[5] ) g_list[2] = 1j * ( bosons[0].conjugate().transpose() * bosons[1] - bosons[1].conjugate().transpose() * bosons[0] + bosons[3].conjugate().transpose() * bosons[4] - bosons[4].conjugate().transpose() * bosons[3] ) return g_list[0] * g_list[0] + g_list[1] * g_list[1] + g_list[2] * g_list[2] g2 = build_gauge_casimir(bosonMatrixDim,numBosons) # result is the output of the VQE bra = result.eigenstate.conjugate().transpose() ket = result.eigenstate op = g2 expect = bra.dot(op.dot(ket)) print(f"<0| g2 |0>: {expect.real}") counts = [] values = [] optim = SLSQP(maxiter=1000) # Setup the VQE algorithm vqe = VQE( ansatz=var_form, optimizer=optim, quantum_instance=q_instance, callback=store_intermediate_result, ) # run the VQE with our Hamiltonian operator result = vqe.compute_minimum_eigenvalue(qubitOp, aux_operators=[MatrixOp(g2)]) vqe_result = np.real(result.eigenvalue) print(f"VQE gs energy: {vqe_result}") print(result) print("<0| g2 |0> from VQE: ",result.aux_operator_eigenvalues[0,0].real) bra = result.eigenstate.conjugate().transpose() ket = result.eigenstate op = g2 expect = bra.dot(op.dot(ket)) print(f"<0| g2 |0> from matrix-vector: {expect.real}") from scipy.sparse.linalg import eigsh eigv, eigk = eigsh(H4MM1, 1, which="SA", return_eigenvectors=True, tol=0) # eigk[:,0] is the ground state vector bra = eigk[:,0].conjugate().transpose() ket = eigk[:,0] op = H4MM1 expect = bra.dot(op.dot(ket)) print(f"<0| H |0> from matrix-vector: {expect.real}") print(f"eigenvalue of H: {eigv[0]}") # eigk[:,0] is the ground state vector bra = eigk[:,0].conjugate().transpose() ket = eigk[:,0] op = g2 expect = bra.dot(op.dot(ket)) print(f"<0| G2 |0> from matrix-vector: {expect.real}") from numpy.linalg import eigh eigv, eigk = eigh(H4MM1) print(eigk.shape) print(eigv[0]) _, eigk = eigh(H4MM1) for i in np.arange(3): bra = eigk[:,i].conjugate().transpose() ket = eigk[:,i] expect = bra @ g2 @ ket print(f"<{i}| G2 |{i}> from matrix-vector: {expect.real}")
https://github.com/erinaldi/bmn2-qiskit
erinaldi
# Here's where the number of qubits are set. The Hamiltonian will be have a size of (N-2)x(N-2) qubits = 8 N = (2**qubits)+2 print(f"The Hamiltonian will be a {N-2}x{N-2} matrix") #lattice lower bound a = -6 #lattice upper bound b = 6 # Import necessary libraries import numpy as np import matplotlib.pyplot as plt # Define x grid and step size x = np.linspace(a,b,N) h = x[1]-x[0] print(f"Discretized grid with {N} sites and step size {h:.4f}") plt.plot(x,np.zeros(x.shape),'o', label="Grid points") plt.legend(loc='upper right'); print(f"The extremal points will not be considered. That is why we have a {N-2}x{N-2} Hamiltonian but {N} points.") # Define potential energy function. Change this to change the potential. def Vpot(x): return (1/2)*x**2 # Create Kinetic Energy Matrix T = np.zeros((N-2)**2).reshape(N-2,N-2) for i in range(N-2): for j in range(N-2): if i==j: T[i,j]= -2 elif np.abs(i-j)==1: T[i,j]=1 else: T[i,j]=0 # Create Potential Energy Matrix V = np.zeros((N-2)**2).reshape(N-2,N-2) for i in range(N-2): for j in range(N-2): if i==j: V[i,j]= Vpot(x[i+1]) else: V[i,j]=0 # Create Hamiltonian: a big matrix 😂 H = -T/(2*h**2) + V Tp = np.zeros((N-2,N-2)) # create a kinetic matrix full of zeros T_id = np.diag_indices(Tp.shape[0]) # select the indices on the diagonal T_idp = (T_id[0][:-1],(T_id[1][:-1]+1)) # select the indices above the diagonal y-x=1 T_idm = (T_id[0][:-1]+1,T_id[1][:-1]) # select the indices below the diagonal x-y=1 # fill the 3 "diagonals" with entries for the discretized derivative Tp[T_id] = -2.0 Tp[T_idp] = Tp[T_idm] = 1.0 # check it is the same as the matrix created with for loops assert(np.allclose(T,Tp)) Tp.shape Vp = np.zeros((N-2,N-2)) V_id = np.diag_indices(Vp.shape[0]) Vp[V_id] = Vpot(x[1:-1]) assert(np.allclose(V,Vp)) Vp.shape # this has 2 more sites x.shape # Create Hamiltonian: a big matrix 😂 Hp = -Tp/(2*h**2) + Vp assert(np.allclose(H,Hp)) plt.imshow(H, cmap='jet') plt.colorbar(); # Find eigenvalues and eigenvectors, then sort them in ascending order val, vec = np.linalg.eig(H) z = np.argsort(val) z = z[0:4] energies = val[z] print("Finite Difference Energies for the first 4 states: ", energies) # Compare finite difference calculation to theoretical calculation nVec = np.linspace(0, len(energies) - 1, len(energies)) En = nVec + 0.5 print("Theoretical Energies: ", En) percentError = ((En - energies) / (energies)) * 100 print("Percent Error: ", percentError) # potential energy # get the ground state gs_vec = vec[:,z[0]] # sandwich the potential energy gs_vec.T.dot(Vp.dot(gs_vec)) En[0]/2 # Plot wavefunctions for first 4 lowest states plt.figure(figsize=(12,10)) scalingFactor=1.5 for i in range(len(z)): y = [] y = np.append(y,vec[:,z[i]]) y = np.append(y,0) y = np.insert(y,0,0) plt.plot(x,scalingFactor*y+energies[i],lw=3, label="{} ".format(i)) plt.xlabel('x', size=14) plt.ylabel(r'$\Psi$(x)',size=14,color='tab:red') plt.legend(title="nth Quantum State") plt.title('normalized wavefunctions for a harmonic oscillator using finite difference method',size=14) # function to compute the ground state energy as a function of R and L def gs_energy(R, L, potential=Vpot): # add boundary points # Define x grid and step size x = np.linspace(-R, R, L) h = x[1] - x[0] # print(R,L,h) # add boundary x = np.append(x, x[-1] + h) x = np.insert(x, 0, x[0] - h) # kinetic Tp = np.zeros((L, L)) # create a kinetic matrix full of zeros T_id = np.diag_indices(Tp.shape[0]) # select the indices on the diagonal T_idp = ( T_id[0][:-1], (T_id[1][:-1] + 1), ) # select the indices above the diagonal y-x=1 T_idm = ( T_id[0][:-1] + 1, T_id[1][:-1], ) # select the indices below the diagonal x-y=1 # fill the 3 "diagonals" with entries for the discretized derivative Tp[T_id] = -2.0 Tp[T_idp] = Tp[T_idm] = 1.0 # Potential Vp = np.zeros((L, L)) V_id = np.diag_indices(Vp.shape[0]) Vp[V_id] = potential(x[1:-1]) # Hamiltonian Hp = -Tp / (2 * h**2) + Vp # Ground state val, vec = np.linalg.eig(Hp) z = np.argsort(val) # print(val[z[0]]) delta_energy = np.fabs(val[z[0]] - 0.5) # get the ground state gs_vec = vec[:, z[0]] # sandwich the potential energy potential_energy = gs_vec.T.dot(Vp.dot(gs_vec)) return np.array([h, R, L, delta_energy, potential_energy], dtype=np.float64) gs_energy(11,1050) from tqdm.notebook import tqdm df = list() # for r in tqdm([0.5,1.,1.5,2.,2.5,3.,3.5,4.,5.,7.,9.,11.], desc='R'): # for l in tqdm([50,150,250,350,450,550,650,850,1050], desc='L'): for r in tqdm([4.,5.,7.,9.,11.], desc='R'): for l in tqdm([450,550,650,850,1050], desc='L'): df.append(gs_energy(r,l)) df = np.asarray(df) import pandas as pd df = pd.DataFrame(df, columns=["A","R","L","D","P"], dtype=np.float64) df.head() import seaborn as sns g = sns.relplot(data=df, x="L", y="D", hue="R", palette='tab20', kind='line', height=4, aspect=2) g.set_axis_labels(r"$\Lambda$", r"$\Delta E_0$") g.set(yscale='log', xscale='log') g = sns.relplot(data=df, x="A", y="P", hue="L", palette='tab20', kind='line', height=4, aspect=2) g.set_axis_labels(r"$a_{dig}$", r"$V_p$") g.set(yscale='log', xscale='log') a_dig = 0.7 def ir_cutoff(a_dig): return 1_000 * a_dig def uv_cutoff(a_dig): return int(1 + 2 * ir_cutoff(a_dig) / a_dig) R = ir_cutoff(a_dig) L = uv_cutoff(a_dig) print(f"Choosing a_dig={a_dig} with R={R} and L={L}") # Define potential energy function. Change this to change the potential. # M^2 = 1 def Vpot_quartic(x): return (1/2)*x**2 + (1/4)*x**4 # M^2 = -1 def Vpot_quartic_neg(x): return -(1/2)*x**2 + (1/4)*x**4 gs_energy(R,L,potential=Vpot_quartic) gs_energy(R,L,potential=Vpot_quartic_neg) # T = 0.1 T = 0.1 beta = 1.0/T print(f"Temperature = {T} \n (beta={beta})") # Example: correction to the 0.5 ground state energy of the harmonic oscillator at zero temperature np.fabs(0.5 - 0.5*1./np.tanh(beta/2)) def harmonic_energy(beta): return 0.5*1./np.tanh(beta/2) # Example: harmonic oscillator potential energy at finite temperature v_beta = np.sum([np.exp(-beta*val[i])*(vec[:,i].T.dot(Vp.dot(vec[:,i]))) for i in z]) # normalize using the partition function z_beta = np.sum(np.exp(-beta*val)) v_beta /= z_beta print(f"Potential energy at beta={beta} : {v_beta}") # result "in the continuum": it is slightly higher than 0.25 because of thermal fluctuations harmonic_energy(beta)/2 # function to compute the average potential energy at finite temperature as a function of R and L def pot_energy(beta, R, L, potential=Vpot): # add boundary points # Define x grid and step size x = np.linspace(-R, R, L) h = x[1] - x[0] # print(R,L,h) # add boundary x = np.append(x, x[-1] + h) x = np.insert(x, 0, x[0] - h) # kinetic Tp = np.zeros((L, L)) # create a kinetic matrix full of zeros T_id = np.diag_indices(Tp.shape[0]) # select the indices on the diagonal T_idp = ( T_id[0][:-1], (T_id[1][:-1] + 1), ) # select the indices above the diagonal y-x=1 T_idm = ( T_id[0][:-1] + 1, T_id[1][:-1], ) # select the indices below the diagonal x-y=1 # fill the 3 "diagonals" with entries for the discretized derivative Tp[T_id] = -2.0 Tp[T_idp] = Tp[T_idm] = 1.0 # Potential Vp = np.zeros((L, L)) V_id = np.diag_indices(Vp.shape[0]) Vp[V_id] = potential(x[1:-1]) # Hamiltonian Hp = -Tp / (2 * h**2) + Vp # Spectrum: use eigh because eig will not return all eigenvalues correctly (contains nan) val, vec = np.linalg.eigh(Hp) ei = np.argsort(val) # partition function z_beta = np.sum(np.exp(-beta * val)) # potential energy v_beta = np.sum( [ np.exp(-beta * val[i]) * (vec[:, i].T.dot(Vp.dot(vec[:, i]))) / z_beta for i in ei[::-1] ] ) return np.array([h, R, L, z_beta, v_beta], dtype=np.float64) pot_energy(1/T, a, N, potential=Vpot) a_dig = 0.3 R = ir_cutoff(a_dig) L = uv_cutoff(a_dig) T = 0.1 beta = 1/T print(f"Quadratic potential: {pot_energy(beta, R, L, potential=Vpot)}") print(f"Quartic msq=1 potential: {pot_energy(beta, R, L, potential=Vpot_quartic)}") print(f"Quartic msq=-1 potential: {pot_energy(beta, R, L, potential=Vpot_quartic_neg)}") a_dig = 0.5 R = ir_cutoff(a_dig) L = uv_cutoff(a_dig) T = 0.1 beta = 1/T print(f"Quadratic potential: {pot_energy(beta, R, L, potential=Vpot)}") print(f"Quartic msq=1 potential: {pot_energy(beta, R, L, potential=Vpot_quartic)}") print(f"Quartic msq=-1 potential: {pot_energy(beta, R, L, potential=Vpot_quartic_neg)}") a_dig = 0.7 R = ir_cutoff(a_dig) L = uv_cutoff(a_dig) T = 0.1 beta = 1/T print(f"Quadratic potential: {pot_energy(beta, R, L, potential=Vpot)}") print(f"Quartic msq=1 potential: {pot_energy(beta, R, L, potential=Vpot_quartic)}") print(f"Quartic msq=-1 potential: {pot_energy(beta, R, L, potential=Vpot_quartic_neg)}") import warnings import time from qiskit.opflow import MatrixOp start_time = time.time() warnings.filterwarnings("ignore") qubitOp = MatrixOp(primitive=H) print("Size of Hamiltonian:", np.shape(H)) print(qubitOp) end_time = time.time() runtime = end_time-start_time print('Program runtime: ',runtime) from qiskit.circuit.library import EfficientSU2 var_form = EfficientSU2(qubitOp.num_qubits, su2_gates=['ry'], entanglement="full", reps=3) display(var_form.draw(output='mpl',fold=100)) from qiskit.algorithms import NumPyEigensolver # exactly diagonalize the system using numpy routines solver = NumPyEigensolver(k=4) exact_solution = solver.compute_eigenvalues(qubitOp) print("Exact Result of qubit hamiltonian:", np.real(exact_solution.eigenvalues)) print("Exact Result of discrete hamiltonian:", energies[0:4]) from qiskit import Aer # change this to Aer for C++ compiled code and the option to run on the GPU from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import SLSQP from qiskit.utils import algorithm_globals, QuantumInstance warnings.filterwarnings("ignore") rngseed = 0 algorithm_globals.random_seed = rngseed if HAS_GPU: # with GPU backend = Aer.get_backend("statevector_simulator", method="statevector_gpu") else: # without GPU backend = Aer.get_backend("statevector_simulator", max_parallel_threads=1, max_parallel_experiments=0) q_instance = QuantumInstance( backend, seed_transpiler=rngseed, seed_simulator=rngseed ) optimizer = SLSQP(maxiter=600) counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) # Run the VQE vqe = VQE( ansatz=var_form, optimizer=optimizer, quantum_instance=q_instance, callback=store_intermediate_result, ) ret = vqe.compute_minimum_eigenvalue(qubitOp) vqe_result = np.real(ret.eigenvalue) print("VQE Result:", vqe_result) # Plot convergence plot plt.figure(figsize=(12,10)) plt.plot(counts, values, label="SLSQP") plt.xlabel('Eval count') plt.ylabel('Energy') plt.title('Energy convergence') plt.legend(loc='upper right') ffrom qiskit.algorithms.optimizers import SPSA from qiskit.utils import algorithm_globals, QuantumInstance rngseed = 0 algorithm_globals.random_seed = rngseed if HAS_GPU: backendQasm = Aer.get_backend('qasm_simulator', method="statevector_gpu") else: backendQasm = Aer.get_backend('qasm_simulator', method="statevector") q_instance = QuantumInstance(backend=backendQasm, shots=1024, seed_transpiler=rngseed, seed_simulator=rngseed) optimizer = SPSA(maxiter=600) counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) # Run the VQE vqe = VQE( ansatz=var_form, optimizer=optimizer, quantum_instance=q_instance, callback=store_intermediate_result, ) ret = vqe.compute_minimum_eigenvalue(qubitOp) vqe_result = np.real(ret.eigenvalue) print("VQE Result:", vqe_result) # Plot convergence plot plt.figure(figsize=(12,10)) plt.plot(counts, values, label="SPSA") plt.xlabel('Eval count') plt.ylabel('Energy') plt.title('Energy convergence for various optimizers') plt.legend(loc='upper right') import qiskit.tools.jupyter %qiskit_version_table
https://github.com/erinaldi/bmn2-qiskit
erinaldi
import numpy as np from scipy.sparse import diags from scipy.sparse import identity from scipy.sparse import kron L = 2 # cutoff for Fock space -> can not go larger than 2 in qiskit without having problems for minimal BMN a_b = diags(np.sqrt(np.linspace(1,L-1,L-1)),offsets=1) a_b.todense() i_b = identity(L) i_b.todense() a_f = diags(np.sqrt(np.linspace(1,1,1)),offsets=1) a_f.todense() sz = diags([1.0,-1.0]) sz.todense() i_f = identity(2) i_f.todense() N_bos = 6 # number of boson sites -> fixed for mini-BMN 2 product_list = [i_b] * N_bos # only the identity for bosons repeated N_bos times a_b_list = [] # this will contain a1...a6 for i in np.arange(0,N_bos): # loop over all bosonic operators operator_list = product_list.copy() # all elements are the identity operator operator_list[i] = a_b # the i^th element is now the annihilation operator for a single boson a_b_list.append(operator_list[0]) # start taking tensor products from first element for a in operator_list[1:]: a_b_list[i] = kron(a_b_list[i],a) # do the outer product between each operator_list element len(a_b_list) N_f = 3 # number of fermionic sites -> fixed for the supersymmetric model mini-BMN with 2 matrices product_list = [i_f] * N_f # only the identity for fermions repeated N_f times a_f_list = [] # this will contain f1...f3 for i in np.arange(0,N_f): # loop over all bosonic operators operator_list = product_list.copy() # all elements are the identity operator operator_list[i] = a_f # the i^th element is now the annihilation operator for a single fermion for j in np.arange(0,i): # the 0:(i-1) elements are replaced by sigma_Z operator_list[j] = sz a_f_list.append(operator_list[0]) # start taking tensor products from the first operator for a in operator_list[1:]: a_f_list[i] = kron(a_f_list[i],a) # do the outer product i_b_tot = identity(L**N_bos) i_f_tot = identity(2**N_f) op_list = [] for a in a_b_list: op_list.append(kron(a,i_f_tot)) for a in a_f_list: op_list.append(kron(i_b_tot,a)) len(op_list) op_list[0] x_list = [] # only use the bosonic operators bosons = op_list[:N_bos] for op in bosons: x_list.append(1/np.sqrt(2)*(op.conjugate().transpose() + op)) # save the fermions operators for convenience in a new list fermions = op_list[-N_f:] # Create the simple quartic Hamiltonian. H_k = 0 for a in op_list[:N_bos]: H_k = H_k + a.conjugate().transpose() * a for a in op_list[-N_f:]: H_k = H_k + (3.0 / 2) * a.conjugate().transpose() * a # vacuum energy H_k = H_k + 0.25 * (2 * N_bos - 3 * N_f - 3) from scipy.sparse.linalg import eigsh eigv = eigsh(H_k,k=10,which='SA',return_eigenvectors=False,tol=0) print(f"Free Hamiltonian eigenvalues: {eigv[::-1]}") V_b = ( x_list[2] * x_list[2] * x_list[3] * x_list[3] + x_list[2] * x_list[2] * x_list[4] * x_list[4] + x_list[1] * x_list[1] * x_list[3] * x_list[3] + x_list[1] * x_list[1] * x_list[5] * x_list[5] + x_list[0] * x_list[0] * x_list[4] * x_list[4] + x_list[0] * x_list[0] * x_list[5] * x_list[5] - 2 * x_list[0] * x_list[2] * x_list[3] * x_list[5] - 2 * x_list[0] * x_list[1] * x_list[3] * x_list[4] - 2 * x_list[1] * x_list[2] * x_list[4] * x_list[5] ) V_bf = (2j / np.sqrt(2)) * ( (x_list[0] - 1j * x_list[3]) * fermions[1].conjugate().transpose() * fermions[2].conjugate().transpose() + (x_list[1] - 1j * x_list[4]) * fermions[2].conjugate().transpose() * fermions[0].conjugate().transpose() + (x_list[2] - 1j * x_list[5]) * fermions[0].conjugate().transpose() * fermions[1].conjugate().transpose() - (x_list[0] + 1j * x_list[3]) * fermions[2] * fermions[1] - (x_list[1] + 1j * x_list[4]) * fermions[0] * fermions[2] - (x_list[2] + 1j * x_list[5]) * fermions[1] * fermions[0] ) # t'Hooft coupling g2N = 0.2 # Number of colors N = 2 # full hamiltonian H = H_k + g2N/N*V_b + np.sqrt(g2N/N)*V_bf H.shape eigv = eigsh(H,k=10,which='SM',return_eigenvectors=False,tol=0) print(f"Full Hamiltonian with lambda={g2N} : {eigv[::-1]}") import warnings import time from qiskit.opflow import MatrixOp start_time = time.time() warnings.filterwarnings("ignore") qubitOp = MatrixOp(primitive=H) print("Size of Hamiltonian:", np.shape(H)) end_time = time.time() runtime = end_time-start_time print('Program runtime: ',runtime) from qiskit.circuit.library import EfficientSU2 var_form = EfficientSU2(qubitOp.num_qubits, su2_gates=['ry','rz'], entanglement="full", reps=1) var_form.draw(output='mpl') from qiskit.algorithms import NumPyEigensolver mes = NumPyEigensolver(k=4) # k is the number of eigenvalues to compute result = mes.compute_eigenvalues(qubitOp) print(result.eigenvalues) print("Exact Result of qubit hamiltonian:", np.real(result.eigenvalues)) print("Exact Result of discrete hamiltonian:", np.real(eigv[::-1][0:4])) from qiskit import Aer # change this to Aer for C++ compiled code and the option to run on the GPU from qiskit.algorithms import VQE # start a quantum instance # fix the random seed of the simulator to make values reproducible from qiskit.utils import algorithm_globals, QuantumInstance seed = 50 algorithm_globals.random_seed = seed # with GPU #backend = Aer.get_backend("statevector_simulator", method="statevector_gpu") # with parallel computation restricted to 2 OpenMP threads (0: maximum) backend = Aer.get_backend("statevector_simulator", max_parallel_threads=6, max_parallel_experiments=0) q_instance = QuantumInstance(backend, seed_transpiler=seed, seed_simulator=seed) from qiskit.algorithms.optimizers import SLSQP, COBYLA, L_BFGS_B, NELDER_MEAD, SPSA start_time = time.time() # choose one classical optimizer # optimizer = L_BFGS_B(maxiter=5000) # optimizer = SPSA(maxiter=5000) optimizer = COBYLA(maxiter=5000) counts = [] values = [] # callback functions to store the counts from each iteration of the VQE def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) # initital points #random_init = np.random.random(var_form.num_parameters) #fixed_init = result.optimal_point # Setup the VQE algorithm #vqe = VQE(ansatz=var_form, optimizer=optimizer, initial_point=random_init, quantum_instance=q_instance, callback=store_intermediate_result) #vqe = VQE(ansatz=var_form, optimizer=optimizer, initial_point=fixed_init, quantum_instance=q_instance, callback=store_intermediate_result) vqe = VQE(ansatz=var_form, optimizer=optimizer, quantum_instance=q_instance, callback=store_intermediate_result) # run the VQE with out Hamiltonian operator # since the VQE is a ground state solver, the syntax is the same as before ;-) result = vqe.compute_minimum_eigenvalue(qubitOp) vqe_result = np.real(result.eigenvalue) print("VQE Result:", vqe_result) end_time = time.time() runtime = end_time-start_time print('Program runtime:',runtime, "s") # Plot convergence plot from matplotlib import pyplot as plt plt.figure(figsize=(12,10)) plt.plot(counts, values, label="SLSQP") plt.xlabel('Eval count') plt.ylabel('Energy') plt.title('Energy convergence') plt.legend(loc='upper right') plt.show(); # start a quantum instance # fix the random seed of the simulator to make values reproducible from qiskit.utils import algorithm_globals, QuantumInstance seed = 50 algorithm_globals.random_seed = seed # with GPU # backend = Aer.get_backend('qasm_simulator', method="statevector_gpu") # with parallel computation restricted to 1 OpenMP threads (0: maximum) backend = Aer.get_backend('qasm_simulator', max_parallel_threads=1, max_parallel_experiments=0) q_instance = QuantumInstance(backend, seed_transpiler=seed, seed_simulator=seed, shots=1024) from qiskit.aqua.components.optimizers import SPSA from qiskit.aqua import QuantumInstance warnings.filterwarnings("ignore") optimizer = SPSA(maxiter=6000) counts = [] values = [] # callback functions to store the counts from each iteration of the VQE def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) # initital points #random_init = np.random.random(var_form.num_parameters) #fixed_init = result.optimal_point # Setup the VQE algorithm #vqe = VQE(ansatz=var_form, optimizer=optimizer, initial_point=random_init, quantum_instance=q_instance, callback=store_intermediate_result) #vqe = VQE(ansatz=var_form, optimizer=optimizer, initial_point=fixed_init, quantum_instance=q_instance, callback=store_intermediate_result) vqe = VQE(ansatz=var_form, optimizer=optimizer, quantum_instance=q_instance, callback=store_intermediate_result) # run the VQE with out Hamiltonian operator # since the VQE is a ground state solver, the syntax is the same as before ;-) result = vqe.compute_minimum_eigenvalue(qubitOp) vqe_result = np.real(result.eigenvalue) print("VQE Result:", vqe_result) # Plot convergence plot plt.figure(figsize=(12,10)) plt.plot(counts, values, label="SPSA") plt.xlabel('Eval count') plt.ylabel('Energy') plt.title('Energy convergence') plt.legend(loc='upper right') import qiskit.tools.jupyter %qiskit_version_table
https://github.com/erinaldi/bmn2-qiskit
erinaldi
# %% import time import fire import numpy as np import pandas as pd from scipy.sparse import diags from scipy.sparse import identity from scipy.sparse import kron from scipy.sparse.linalg import eigsh from qiskit import Aer from qiskit.opflow import MatrixOp from qiskit.circuit.library import EfficientSU2 from qiskit.algorithms import NumPyEigensolver, VQE from qiskit.algorithms.optimizers import SLSQP, COBYLA, L_BFGS_B, NELDER_MEAD from qiskit.utils import algorithm_globals, QuantumInstance # %% def build_operators(L: int, N: int) -> list: """Generate all the annihilation operators needed to build the hamiltonian Args: L (int): the cutoff of the single site Fock space N (int): the number of colors of gauge group SU(N) Returns: list: a list of annihilation operators, length=N_bos """ # The annihilation operator for the single boson a_b = diags(np.sqrt(np.linspace(1, L - 1, L - 1)), offsets=1) # The identity operator of the Fock space of a single boson i_b = identity(L) # Bosonic Hilbert space N_bos = int(2 * (N ** 2 - 1)) # number of boson sites -> fixed for mini-BMN 2 product_list = [i_b] * N_bos # only the identity for bosons repeated N_bos times a_b_list = [] # this will contain a1...a6 for i in np.arange(0, N_bos): # loop over all bosonic operators operator_list = product_list.copy() # all elements are the identity operator operator_list[ i ] = a_b # the i^th element is now the annihilation operator for a single boson a_b_list.append( operator_list[0] ) # start taking tensor products from first element for a in operator_list[1:]: a_b_list[i] = kron( a_b_list[i], a ) # do the outer product between each operator_list element return a_b_list # %% def build_gauge_casimir(L: int, N: int): """Generate the gauge generators operators Args: L (int): the single site cutoff of the Fock space N (int): the number of colors in the gauge group SU(N) Returns: scipy.sparse : The sparse matrix for \sum_i G_i^2 """ # generate the annihilation operators bosons = build_operators(L, N) # define the generator list for SU(2) g_list = [0] * 3 g_list[0] = 1j * ( bosons[1].conjugate().transpose() * bosons[2] - bosons[2].conjugate().transpose() * bosons[1] + bosons[4].conjugate().transpose() * bosons[5] - bosons[5].conjugate().transpose() * bosons[4] ) g_list[1] = 1j * ( bosons[2].conjugate().transpose() * bosons[0] - bosons[0].conjugate().transpose() * bosons[2] + bosons[5].conjugate().transpose() * bosons[3] - bosons[3].conjugate().transpose() * bosons[5] ) g_list[2] = 1j * ( bosons[0].conjugate().transpose() * bosons[1] - bosons[1].conjugate().transpose() * bosons[0] + bosons[3].conjugate().transpose() * bosons[4] - bosons[4].conjugate().transpose() * bosons[3] ) return g_list[0] * g_list[0] + g_list[1] * g_list[1] + g_list[2] * g_list[2] # %% def bmn2_hamiltonian(L: int = 2, N: int = 2, g2N: float = 0.2): """Construct the Hamiltonian of the bosonic BMN model as a sparse matrix. The cutoff for each boson is L while the 't Hooft coupling in g2N for a gauge group SU(N). The limited number of qubits only let us simulate N=2 and L=4 => for 6 bosons this is a 12 qubits problem. Args: L (int, optional): The cutoff of the bosonic modes (the annihilation operators will be LxL matrices). Defaults to 2. N (int, optional): The number of colors of a SU(N) gauge group. The degrees of freedom of one matrix will be N^2-1. Defaults to 2. g2N (float, optional): The 't Hooft coupling. Defaults to 0.2. """ print( f"Building bosonic BMN Hamiltonian for SU({N}) with cutoff={L} and coupling={g2N}\n" ) a_b_list = build_operators(L,N) N_bos = int(2 * (N ** 2 - 1)) # number of boson sites -> FIXED for mini-BMN 2 # Build the Hamiltonian # Start piece by piece x_list = [] # only use the bosonic operators for op in a_b_list: x_list.append(1 / np.sqrt(2) * (op.conjugate().transpose() + op)) # Free Hamiltonian H_k = 0 for a in a_b_list: H_k = H_k + a.conjugate().transpose() * a # vacuum energy H_k = H_k + 0.5 * N_bos * identity(L ** N_bos) # Interaction among bosons V_b = ( x_list[2] * x_list[2] * x_list[3] * x_list[3] + x_list[2] * x_list[2] * x_list[4] * x_list[4] + x_list[1] * x_list[1] * x_list[3] * x_list[3] + x_list[1] * x_list[1] * x_list[5] * x_list[5] + x_list[0] * x_list[0] * x_list[4] * x_list[4] + x_list[0] * x_list[0] * x_list[5] * x_list[5] - 2 * x_list[0] * x_list[2] * x_list[3] * x_list[5] - 2 * x_list[0] * x_list[1] * x_list[3] * x_list[4] - 2 * x_list[1] * x_list[2] * x_list[4] * x_list[5] ) # full hamiltonian return H_k + g2N / N * V_b def eigenvalues_scipy(H, k: int = 10): """Compute the lowest k eigenvalues of a sparse symmetric matrix H. Args: H (scipy.sparse matrix): The Hamiltonian in the form of a sparse matrix k (int): The number of lowest eigenvalues to compute. Defaults to 10. """ eigv = eigsh(H, k, which="SA", return_eigenvectors=False, tol=0) return np.real(eigv[::-1]) def eigenvalues_qiskit(qOp: MatrixOp, k: int = 10): """Compute the lowest k eigenvalues of a quantum operator in matrix form qOp. Internally it uses numpy. Args: qOp (MatrixOp): The quantum operator build from a matrix. k (int, optional): The number of lowest eigenvalues. Defaults to 10. """ mes = NumPyEigensolver(k) # k is the number of eigenvalues to compute result = mes.compute_eigenvalues(qOp) return np.real(result.eigenvalues) # %% def check_expectation(H, O, k: int = 1): """Compute the lowest k eigenstates of a sparse symmetric matrix H and then compute the expectation value of O. Args: H (scipy.sparse matrix): The Hamiltonian in the form of a sparse matrix O (scipy.sparse matrix): The operator to "measure" in the form of a sparse matrix k (int): The number of lowest eigenstates to compute. Defaults to 1. """ _, eigk = eigsh(H, k, which="SA", return_eigenvectors=True, tol=0) expect = [] for i in np.arange(k): bra = eigk[:,i].conjugate().transpose() ket = eigk[:,i] expect.append(bra.dot(O.dot(ket))) return np.real(np.array(expect)) # %% def run_vqe( L: int = 2, N: int = 2, g2N: float = 0.2, optimizer: str = "COBYLA", maxit: int = 5000, varform: list = ["ry"], depth: int = 3, nrep: int = 10, rngseed: int = 0, G2: bool = False, h5: bool = True, ): """Run the main VQE solver for a bosonic BMN Hamiltonian where bosons are LxL matrices and the 't Hooft coupling is g2N for a SU(N) gauge group. The VQE is initialized with a specific optimizer and a specific variational quantum circuit based on EfficientSU2. Args: L (int, optional): Cutoff of each bosonic degree of freedom. Defaults to 2. N (int, optional): Colors for the SU(N) gauge group. Defaults to 2. g2N (float, optional): 't Hooft coupling. Defaults to 0.2. optimizer (str, optional): VQE classical optimizer. Defaults to "COBYLA". maxit (int, optional): Max number of iterations for the optimizer. Defaults to 5000. varform (str, optional): EfficientSU2 rotation gates. Defaults to 'ry'. depth (int, optional): Depth of the variational form. Defaults to 3. nrep (int, optional): Number of different random initializations of parameters. Defaults to 1. rngseed (int, optional): The random seed. Defaults to 0. G2 (bool, optional): The flag to compute the expectation value of the gauge Casimir. Defaults to False. h5 (bool, optional): The flag to save in HDF5 format. Defaults to True. """ # Create the matrix Hamiltonian H = bmn2_hamiltonian(L, N, g2N) # Now, we take the Hamiltonian matrix and map it onto a qubit operator. qubitOp = MatrixOp(primitive=H) # check the exact eigenvalues print(f"Exact Result of discrete hamiltonian (matrix): {eigenvalues_scipy(H)}") print( f"Exact Result of discrete hamiltonian (qubit): {eigenvalues_qiskit(qubitOp)}" ) # create the gauge casimir and check it if requested if G2: G = build_gauge_casimir(L,N) print(f"Exact Result of Casimir on GS (matrix): {check_expectation(H,G)}") gOp = MatrixOp(primitive=G) # Next, we create the variational form. var_form = EfficientSU2( qubitOp.num_qubits, su2_gates=varform, entanglement="full", reps=depth ) # start a quantum instance # fix the random seed of the simulator to make values reproducible rng = np.random.default_rng(seed=rngseed) algorithm_globals.random_seed = rngseed backend = Aer.get_backend( "statevector_simulator", max_parallel_threads=6, max_parallel_experiments=0 ) q_instance = QuantumInstance( backend, seed_transpiler=rngseed, seed_simulator=rngseed ) # initialize optimizers' parameters: number of iterations optimizers = { "COBYLA": COBYLA(maxiter=maxit), "L-BFGS-B": L_BFGS_B(maxfun=maxit), "SLSQP": SLSQP(maxiter=maxit), "NELDER-MEAD": NELDER_MEAD(maxfev=maxit), } print(f"\nRunning VQE main loop ...") start_time = time.time() try: optim = optimizers[optimizer] print(f"{optimizer} settings: {optim.settings}") except KeyError: print( f"Optimizer {optimizer} not found in our list. Try one of {[x for x in optimizers.keys()]}" ) return results = {"counts": [], "energy": [], "casimir": []} casimir_result = 'NaN' # initialize to NaN since it will not be defined if we do not measure it # callback functions to store the counts from each iteration of the VQE def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) # run multiple random initial points for i in np.arange(nrep): counts = [] values = [] # initital points for the angles of the rotation gates random_init = rng.uniform(-2 * np.pi, 2 * np.pi, var_form.num_parameters) # Setup the VQE algorithm vqe = VQE( ansatz=var_form, optimizer=optim, initial_point=random_init, quantum_instance=q_instance, callback=store_intermediate_result, ) # run the VQE with our Hamiltonian operator if G2: result = vqe.compute_minimum_eigenvalue(qubitOp,aux_operators=[gOp]) vqe_result = np.real(result.eigenvalue) casimir_result = np.real(result.aux_operator_eigenvalues[0,0]) print(f"[{i}] - {varform} - [{optimizer}]: VQE gs energy: {vqe_result} | VQE gs gauge casimir: {casimir_result}") else: result = vqe.compute_minimum_eigenvalue(qubitOp) vqe_result = np.real(result.eigenvalue) print(f"[{i}] - {varform} - [{optimizer}]: VQE gs energy: {vqe_result}") # collect results results["counts"].append(counts) results["energy"].append(values) results["casimir"].append(casimir_result) end_time = time.time() runtime = end_time - start_time print(f"Program runtime: {runtime} s") # make a dataframe from the results df = pd.DataFrame.from_dict(results) data_types_dict = {"counts": int, "energy": float} df = df.explode(["counts", "energy"]).astype(data_types_dict).rename_axis("rep") # report summary of energy across reps converged = df["energy"].groupby("rep").apply(min).values print(f"Statistics across {nrep} repetitions:\n-------------------") print( f"Least upper bound: {np.min(converged)}\nWorst upper bound: {np.max(converged)}\nMean bound: {np.mean(converged)}\nStd bound: {np.std(converged)}" ) # save results on disk varname = "-".join(varform) g2Nstr = str(g2N).replace(".", "") if h5: outfile = f"data/bosBMN_L{L}_l{g2Nstr}_convergence_{optimizer}_{varname}_depth{depth}_reps{nrep}_max{maxit}.h5" print(f"Save results on disk: {outfile}") df.to_hdf(outfile, "vqe") else: outfile = f"data/bosBMN_L{L}_l{g2Nstr}_convergence_{optimizer}_{varname}_depth{depth}_reps{nrep}_max{maxit}.gz" print(f"Save results on disk: {outfile}") df.to_pickle(outfile) return # %% if __name__ == "__main__": fire.Fire(run_vqe)
https://github.com/erinaldi/bmn2-qiskit
erinaldi
# %% import time import fire import numpy as np import pandas as pd from scipy.sparse import diags from scipy.sparse import identity from scipy.sparse import kron from scipy.sparse.linalg import eigsh from qiskit import Aer from qiskit.opflow import MatrixOp from qiskit.circuit.library import EfficientSU2 from qiskit.algorithms import NumPyEigensolver, VQE from qiskit.algorithms.optimizers import SLSQP, COBYLA, L_BFGS_B, NELDER_MEAD from qiskit.utils import algorithm_globals, QuantumInstance # %% def build_operators(L: int, N: int) -> list: """Generate all the annihilation operators needed to build the hamiltonian Args: L (int): the cutoff of the single site Fock space N (int): the number of colors of gauge group SU(N) Returns: list: a list of annihilation operators, length=2*(N^2-1)+3 """ # The annihilation operator for the single boson a_b = diags(np.sqrt(np.linspace(1, L - 1, L - 1)), offsets=1) # The identity operator of the Fock space of a single boson i_b = identity(L) # The annihilation operator for the fermions (always cutoff = 2 because it is a spin) a_f = diags(np.sqrt(np.linspace(1, 1, 1)), offsets=1) # The Pauli $\sigma_z$ matrix sz = diags([1.0, -1.0]) # Identity for the single fermion space i_f = identity(2) # Bosonic Hilbert space N_bos = int(2 * (N ** 2 - 1)) # number of boson sites -> fixed for mini-BMN 2 product_list = [i_b] * N_bos # only the identity for bosons repeated N_bos times a_b_list = [] # this will contain a1...a6 for i in np.arange(0, N_bos): # loop over all bosonic operators operator_list = product_list.copy() # all elements are the identity operator operator_list[ i ] = a_b # the i^th element is now the annihilation operator for a single boson a_b_list.append( operator_list[0] ) # start taking tensor products from first element for a in operator_list[1:]: a_b_list[i] = kron( a_b_list[i], a ) # do the outer product between each operator_list element # Fermionic Hilbert space N_f = 3 # number of fermionic sites -> fixed for the supersymmetric model mini-BMN with 2 matrices product_list = [i_f] * N_f # only the identity for fermions repeated N_f times a_f_list = [] # this will contain f1...f3 for i in np.arange(0, N_f): # loop over all bosonic operators operator_list = product_list.copy() # all elements are the identity operator operator_list[ i ] = a_f # the i^th element is now the annihilation operator for a single fermion for j in np.arange(0, i): # the 0:(i-1) elements are replaced by sigma_Z operator_list[j] = sz a_f_list.append( operator_list[0] ) # start taking tensor products from the first operator for a in operator_list[1:]: a_f_list[i] = kron(a_f_list[i], a) # do the outer product # Combine the Bosonic and Fermionic space # - Identity for bosonic space (dimension will be $L^{N_{bos}} \times L^{N_{bos}}$) i_b_tot = identity(L ** N_bos) # - Identity for fermionic space (dimension will be $2^{N_f} \times 2^{N_f}$) i_f_tot = identity(2 ** N_f) # The new bosonic and fermionic operators combined into one list op_list = [] for a in a_b_list: op_list.append(kron(a, i_f_tot)) for a in a_f_list: op_list.append(kron(i_b_tot, a)) return op_list # %% def build_gauge_casimir(L: int, N: int): """Generate the gauge generators operators Args: L (int): the single site cutoff of the Fock space N (int): the number of colors in the gauge group SU(N) Returns: scipy.sparse : The sparse matrix for \sum_i G_i^2 """ # generate the annihilation operators op_list = build_operators(L, N) N_bos = int(2 * (N ** 2 - 1)) # number of boson sites -> FIXED for mini-BMN 2 N_f = 3 # number of fermionic sites -> FIXED for the supersymmetric model mini-BMN with 2 matrices bosons = op_list[:N_bos] fermions = op_list[-N_f:] # define the generator list for FIXED SU(2) g_list = [0] * 3 g_list[0] = 1j * ( bosons[1].conjugate().transpose() * bosons[2] - bosons[2].conjugate().transpose() * bosons[1] + bosons[4].conjugate().transpose() * bosons[5] - bosons[5].conjugate().transpose() * bosons[4] + fermions[1].conjugate().transpose() * fermions[2] - fermions[2].conjugate().transpose() * fermions[1] ) g_list[1] = 1j * ( bosons[2].conjugate().transpose() * bosons[0] - bosons[0].conjugate().transpose() * bosons[2] + bosons[5].conjugate().transpose() * bosons[3] - bosons[3].conjugate().transpose() * bosons[5] + fermions[2].conjugate().transpose() * fermions[0] - fermions[0].conjugate().transpose() * fermions[2] ) g_list[2] = 1j * ( bosons[0].conjugate().transpose() * bosons[1] - bosons[1].conjugate().transpose() * bosons[0] + bosons[3].conjugate().transpose() * bosons[4] - bosons[4].conjugate().transpose() * bosons[3] + fermions[0].conjugate().transpose() * fermions[1] - fermions[1].conjugate().transpose() * fermions[0] ) return g_list[0] * g_list[0] + g_list[1] * g_list[1] + g_list[2] * g_list[2] # %% def bmn2_hamiltonian(L: int = 2, N: int = 2, g2N: float = 0.2): """Construct the Hamiltonian of the minimal BMN model as a sparse matrix. The cutoff for each boson is L while the 't Hooft coupling in g2N for a gauge group SU(N). The limited number of qubits only let us simulate N=2 and L=2 => for 6 bosons and 3 fermions this is a 9 qubits problem. Args: L (int, optional): The cutoff of the bosonic modes (the annihilation operators will be LxL matrices). Defaults to 2. N (int, optional): The number of colors of a SU(N) gauge group. The degrees of freedom of one matrix will be N^2-1. Defaults to 2. g2N (float, optional): The 't Hooft coupling. Defaults to 0.2. """ print( f"Building minimal BMN Hamiltonian for SU({N}) with cutoff={L} and coupling={g2N}\n" ) # Built the annihilation operators op_list = build_operators(L,N) N_bos = int(2 * (N ** 2 - 1)) # number of boson sites -> FIXED for mini-BMN 2 N_f = 3 # number of fermionic sites -> FIXED for the supersymmetric model mini-BMN with 2 matrices # Build the Hamiltonian # Start piece by piece x_list = [] # only use the bosonic operators bosons = op_list[:N_bos] for op in bosons: x_list.append(1 / np.sqrt(2) * (op.conjugate().transpose() + op)) # save the fermions operators for convenience in a new list fermions = op_list[-N_f:] # Free Hamiltonian H_k = 0 for a in op_list[:N_bos]: H_k = H_k + a.conjugate().transpose() * a for a in op_list[-N_f:]: H_k = H_k + (3.0 / 2) * a.conjugate().transpose() * a # vacuum energy H_k = H_k + 0.25 * (2 * N_bos - 3 * N_f - 3) # Interaction among bosons V_b = ( x_list[2] * x_list[2] * x_list[3] * x_list[3] + x_list[2] * x_list[2] * x_list[4] * x_list[4] + x_list[1] * x_list[1] * x_list[3] * x_list[3] + x_list[1] * x_list[1] * x_list[5] * x_list[5] + x_list[0] * x_list[0] * x_list[4] * x_list[4] + x_list[0] * x_list[0] * x_list[5] * x_list[5] - 2 * x_list[0] * x_list[2] * x_list[3] * x_list[5] - 2 * x_list[0] * x_list[1] * x_list[3] * x_list[4] - 2 * x_list[1] * x_list[2] * x_list[4] * x_list[5] ) # Interactions between bosons and fermions V_bf = (2j / np.sqrt(2)) * ( (x_list[0] - 1j * x_list[3]) * fermions[1].conjugate().transpose() * fermions[2].conjugate().transpose() + (x_list[1] - 1j * x_list[4]) * fermions[2].conjugate().transpose() * fermions[0].conjugate().transpose() + (x_list[2] - 1j * x_list[5]) * fermions[0].conjugate().transpose() * fermions[1].conjugate().transpose() - (x_list[0] + 1j * x_list[3]) * fermions[2] * fermions[1] - (x_list[1] + 1j * x_list[4]) * fermions[0] * fermions[2] - (x_list[2] + 1j * x_list[5]) * fermions[1] * fermions[0] ) # full hamiltonian return H_k + g2N / N * V_b + np.sqrt(g2N / N) * V_bf # %% def eigenvalues_scipy(H, k: int = 10): """Compute the lowest k eigenvalues of a sparse symmetric matrix H. Args: H (scipy.sparse matrix): The Hamiltonian in the form of a sparse matrix k (int): The number of lowest eigenvalues to compute. Defaults to 10. """ eigv = eigsh(H, k, which="SA", return_eigenvectors=False, tol=0) return np.real(eigv[::-1]) # %% def eigenvalues_qiskit(qOp: MatrixOp, k: int = 10): """Compute the lowest k eigenvalues of a quantum operator in matrix form qOp. Internally it uses numpy. Args: qOp (MatrixOp): The quantum operator build from a matrix. k (int, optional): The number of lowest eigenvalues. Defaults to 10. """ mes = NumPyEigensolver(k) # k is the number of eigenvalues to compute result = mes.compute_eigenvalues(qOp) return np.real(result.eigenvalues) # %% def check_expectation(H, O, k: int = 1): """Compute the lowest k eigenstates of a sparse symmetric matrix H and then compute the expectation value of O. Args: H (scipy.sparse matrix): The Hamiltonian in the form of a sparse matrix O (scipy.sparse matrix): The operator to "measure" in the form of a sparse matrix k (int): The number of lowest eigenstates to compute. Defaults to 1. """ _, eigk = eigsh(H, k, which="SA", return_eigenvectors=True, tol=0) expect = [] for i in np.arange(k): bra = eigk[:,i].conjugate().transpose() ket = eigk[:,i] expect.append(bra.dot(O.dot(ket))) return np.real(np.array(expect)) # %% def run_vqe( L: int = 2, N: int = 2, g2N: float = 0.2, optimizer: str = "COBYLA", maxit: int = 5000, varform: list = ["ry"], depth: int = 3, nrep: int = 1, rngseed: int = 0, G2: bool = False, h5: bool = True, ): """Run the main VQE solver for a minimal BMN Hamiltonian where bosons are LxL matrices and the 't Hooft coupling is g2N for a SU(N) gauge group. The VQE is initialized with a specific optimizer and a specific variational quantum circuit based on EfficientSU2. Args: L (int, optional): Cutoff of each bosonic degree of freedom. Defaults to 2. N (int, optional): Colors for the SU(N) gauge group. Defaults to 2. g2N (float, optional): 't Hooft coupling. Defaults to 0.2. optimizer (str, optional): VQE classical optimizer. Defaults to "COBYLA". maxit (int, optional): Max number of iterations for the optimizer. Defaults to 5000. varform (str, optional): EfficientSU2 rotation gates. Defaults to 'ry'. depth (int, optional): Depth of the variational form. Defaults to 3. nrep (int, optional): Number of different random initializations of parameters. Defaults to 1. rngseed (int, optional): The random seed. Defaults to 0. G2 (bool, optional): The flag to compute the expectation value of the gauge Casimir. Defaults to False. h5 (bool, optional): The flag to save in HDF5 format. Defaults to True. """ # Create the matrix Hamiltonian H = bmn2_hamiltonian(L, N, g2N) # Now, we take the Hamiltonian matrix and map it onto a qubit operator. qubitOp = MatrixOp(primitive=H) # check the exact eigenvalues print(f"Exact Result of discrete hamiltonian (matrix): {eigenvalues_scipy(H)}") print( f"Exact Result of discrete hamiltonian (qubit): {eigenvalues_qiskit(qubitOp)}" ) # create the gauge casimir and check it if requested if G2: G = build_gauge_casimir(L,N) print(f"Exact Result of Casimir on GS (matrix): {check_expectation(H,G)}") gOp = MatrixOp(primitive=G) # Next, we create the variational form. var_form = EfficientSU2( qubitOp.num_qubits, su2_gates=varform, entanglement="full", reps=depth ) # start a quantum instance # fix the random seed of the simulator to make values reproducible rng = np.random.default_rng(seed=rngseed) algorithm_globals.random_seed = rngseed backend = Aer.get_backend( "statevector_simulator", max_parallel_threads=6, max_parallel_experiments=0 ) q_instance = QuantumInstance( backend, seed_transpiler=rngseed, seed_simulator=rngseed ) # initialize optimizers' parameters: number of iterations optimizers = { "COBYLA": COBYLA(maxiter=maxit), "L-BFGS-B": L_BFGS_B(maxfun=maxit), "SLSQP": SLSQP(maxiter=maxit), "NELDER-MEAD": NELDER_MEAD(maxfev=maxit), } print(f"\nRunning VQE main loop ...") start_time = time.time() try: optim = optimizers[optimizer] print(f"{optimizer} settings: {optim.settings}") except KeyError: print( f"Optimizer {optimizer} not found in our list. Try one of {[x for x in optimizers.keys()]}" ) return results = {"counts": [], "energy": [], "casimir": []} casimir_result = 'NaN' # callback functions to store the counts from each iteration of the VQE def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) # run multiple random initial points for i in np.arange(nrep): counts = [] values = [] # initital points for the angles of the rotation gates random_init = rng.uniform(-2 * np.pi, 2 * np.pi, var_form.num_parameters) # Setup the VQE algorithm vqe = VQE( ansatz=var_form, optimizer=optim, initial_point=random_init, quantum_instance=q_instance, callback=store_intermediate_result, ) # run the VQE with our Hamiltonian operator if G2: result = vqe.compute_minimum_eigenvalue(qubitOp,aux_operators=[gOp]) vqe_result = np.real(result.eigenvalue) casimir_result = np.real(result.aux_operator_eigenvalues[0,0]) print(f"[{i}] - {varform} - [{optimizer}]: VQE gs energy: {vqe_result} | VQE gs gauge casimir: {casimir_result}") else: result = vqe.compute_minimum_eigenvalue(qubitOp) vqe_result = np.real(result.eigenvalue) print(f"[{i}] - {varform} - [{optimizer}]: VQE gs energy: {vqe_result}") # collect results results["counts"].append(counts) results["energy"].append(values) results["casimir"].append(casimir_result) end_time = time.time() runtime = end_time - start_time print(f"Program runtime: {runtime} s") # make a dataframe from the results and save it on disk with HDF5 df = pd.DataFrame.from_dict(results) data_types_dict = {"counts": int, "energy": float} df = df.explode(["counts", "energy"]).astype(data_types_dict).rename_axis("rep") # report summary of energy across reps converged = df["energy"].groupby("rep").apply(min).values print(f"Statistics across {nrep} repetitions:\n-------------------") print( f"Least upper bound: {np.min(converged)}\nWorst upper bound: {np.max(converged)}\nMean bound: {np.mean(converged)}\nStd bound: {np.std(converged)}" ) # save on disk varname = "-".join(varform) g2Nstr = str(g2N).replace(".", "") if h5: outfile = f"data/miniBMN_L{L}_l{g2Nstr}_convergence_{optimizer}_{varname}_depth{depth}_reps{nrep}_max{maxit}.h5" print(f"Save results on disk: {outfile}") df.to_hdf(outfile, "vqe") else: outfile = f"data/miniBMN_L{L}_l{g2Nstr}_convergence_{optimizer}_{varname}_depth{depth}_reps{nrep}_max{maxit}.gz" print(f"Save results on disk: {outfile}") df.to_pickle(outfile) return # %% if __name__ == "__main__": fire.Fire(run_vqe)
https://github.com/erinaldi/bmn2-qiskit
erinaldi
# %% import time import fire import os import numpy as np import pandas as pd from scipy.sparse import diags from scipy.sparse import identity from qiskit import Aer from qiskit.opflow import MatrixOp, ListOp, TensoredOp, SummedOp, I from qiskit.circuit.library import EfficientSU2 from qiskit.algorithms import NumPyEigensolver, VQE from qiskit.algorithms.optimizers import SLSQP, COBYLA, L_BFGS_B, NELDER_MEAD from qiskit.utils import algorithm_globals, QuantumInstance # %% def build_operators(L: int, N: int) -> list: """Generate all the annihilation operators needed to build the hamiltonian Args: L (int): the cutoff of the single site Fock space N (int): the number of colors of gauge group SU(N) *it can not be different from 2 right now* Returns: list: a list of annihilation operators, length=N_bos, using PauliOp representation. """ # These are low-D (single boson) so we can use the MatrixOp for convenience # The annihilation operator for the single boson a_b = MatrixOp( diags(np.sqrt(np.linspace(1, L - 1, L - 1)), offsets=1) ).to_pauli_op() # The identity operator of the Fock space of a single boson i_b = MatrixOp(identity(L)).to_pauli_op() # Now the memory starts growing! Use the PauliOp structure # Bosonic Hilbert space N_bos = int(2 * (N ** 2 - 1)) # number of boson sites -> fixed for mini-BMN 2 a_b_list = [] # this will contain a1...a6 as a list of ListOp for i in np.arange(0, N_bos): # loop over all operators operator_list = [i_b] * N_bos # only the identity repeated Nmat times operator_list[ i ] = a_b # the i^th element is now the annihilation operator for a single boson a_b_list.append(ListOp(operator_list)) return [TensoredOp(a) for a in a_b_list] # %% def bmn2_hamiltonian(L: int = 2, N: int = 2, g2N: float = 0.2) -> SummedOp: """Construct the Hamiltonian of the bosonic BMN model as a sparse matrix. The cutoff for each boson is L while the 't Hooft coupling in g2N for a gauge group SU(N). The limited number of qubits only let us simulate N=2 and L=4 => for 6 bosons this is a 12 qubits problem. Args: L (int, optional): The cutoff of the bosonic modes (the annihilation operators will be LxL matrices). Defaults to 2. N (int, optional): The number of colors of a SU(N) gauge group. The degrees of freedom of one matrix will be N^2-1. Defaults to 2. g2N (float, optional): The 't Hooft coupling. Defaults to 0.2. Returns: SummedOp: the Hamiltonian in PauliOp form """ print( f"Building bosonic BMN Hamiltonian for SU({N}) with cutoff={L} and coupling={g2N}\n" ) # annihilation operators for bosons in full Hilbert space a_tensor = build_operators(L, N) N_bos = int(2 * (N ** 2 - 1)) # number of boson sites -> FIXED for mini-BMN 2 assert len(a_tensor) == N_bos # identity in full Hilbert space i_b = MatrixOp(identity(L)).to_pauli_op() i_tensor = TensoredOp(ListOp([i_b] * N_bos)) # Build the Hamiltonian # Start piece by piece # for each boson they are constructed using a and adag x_tensor = [1 / np.sqrt(2) * (~a + a) for a in a_tensor] # Free Hamiltonian # vacuum energy H_zero = 0.5 * N_bos * i_tensor # oscillators H_list = [H_zero] for a in a_tensor: H_list.append((~a @ a)) H_osc = SummedOp(H_list) # Interaction among bosons quartic1 = SummedOp( [ x_tensor[2] @ x_tensor[2] @ x_tensor[3] @ x_tensor[3], x_tensor[2] @ x_tensor[2] @ x_tensor[4] @ x_tensor[4], x_tensor[1] @ x_tensor[1] @ x_tensor[3] @ x_tensor[3], x_tensor[1] @ x_tensor[1] @ x_tensor[5] @ x_tensor[5], x_tensor[0] @ x_tensor[0] @ x_tensor[4] @ x_tensor[4], x_tensor[0] @ x_tensor[0] @ x_tensor[5] @ x_tensor[5], ] ) quartic2 = SummedOp( [ x_tensor[0] @ x_tensor[2] @ x_tensor[3] @ x_tensor[5], x_tensor[0] @ x_tensor[1] @ x_tensor[3] @ x_tensor[4], x_tensor[1] @ x_tensor[2] @ x_tensor[4] @ x_tensor[5], ], coeff=-2.0, ) ### Quartic Interaction V = quartic1 + quartic2 # full hamiltonian H = H_osc + g2N / N * V return H.to_pauli_op() # %% def run_vqe( L: int = 2, N: int = 2, g2N: float = 0.2, optimizer: str = "COBYLA", maxit: int = 5000, varform: list = ["ry"], depth: int = 3, nrep: int = 10, rngseed: int = 0, h5: bool = True, ): """Run the main VQE solver for a bosonic BMN Hamiltonian where bosons are LxL matrices and the 't Hooft coupling is g2N for a SU(N) gauge group. The VQE is initialized with a specific optimizer and a specific variational quantum circuit based on EfficientSU2. Args: L (int, optional): Cutoff of each bosonic degree of freedom. Defaults to 2. N (int, optional): Colors for the SU(N) gauge group. Defaults to 2. g2N (float, optional): 't Hooft coupling. Defaults to 0.2. optimizer (str, optional): VQE classical optimizer. Defaults to "COBYLA". maxit (int, optional): Max number of iterations for the optimizer. Defaults to 5000. varform (str, optional): EfficientSU2 rotation gates. Defaults to 'ry'. depth (int, optional): Depth of the variational form. Defaults to 3. nrep (int, optional): Number of different random initializations of parameters. Defaults to 1. rngseed (int, optional): The random seed. Defaults to 0. h5 (bool, optional): The flag to save in HDF5 format. Defaults to True. """ assert N == 2 # code only works for SU(2) :-( # Create the matrix Hamiltonian in PauliOp form qubitOp = bmn2_hamiltonian(L, N, g2N) # Next, we create the variational form. var_form = EfficientSU2( qubitOp.num_qubits, su2_gates=varform, entanglement="full", reps=depth ) # start a quantum instance # fix the random seed of the simulator to make values reproducible rng = np.random.default_rng(seed=rngseed) algorithm_globals.random_seed = rngseed algorithm_globals.massive=True # use the aer simulator instead of statevector backend = Aer.get_backend('aer_simulator') q_instance = QuantumInstance( backend, seed_transpiler=rngseed, seed_simulator=rngseed ) # initialize optimizers' parameters: number of iterations optimizers = { "COBYLA": COBYLA(maxiter=maxit), "L-BFGS-B": L_BFGS_B(maxfun=maxit), "SLSQP": SLSQP(maxiter=maxit), "NELDER-MEAD": NELDER_MEAD(maxfev=maxit), } print(f"\nRunning VQE main loop ...") start_time = time.time() try: optim = optimizers[optimizer] print(f"{optimizer} settings: {optim.settings}") except KeyError: print( f"Optimizer {optimizer} not found in our list. Try one of {[x for x in optimizers.keys()]}" ) return results = {"counts": [], "energy": [], "casimir": []} casimir_result = ( "NaN" # initialize to NaN since it will not be defined if we do not measure it ) # callback functions to store the counts from each iteration of the VQE def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) # run multiple random initial points for i in np.arange(nrep): counts = [] values = [] # initital points for the angles of the rotation gates random_init = rng.uniform(-2 * np.pi, 2 * np.pi, var_form.num_parameters) # Setup the VQE algorithm with include_custom=True for Pauli expectations with snapshot vqe = VQE( ansatz=var_form, optimizer=optim, initial_point=random_init, quantum_instance=q_instance, callback=store_intermediate_result, include_custom=True, ) # run the VQE with our Hamiltonian operator result = vqe.compute_minimum_eigenvalue(qubitOp) vqe_result = np.real(result.eigenvalue) print(f"[{i}] - {varform} - [{optimizer}]: VQE gs energy: {vqe_result}") # collect results results["counts"].append(counts) results["energy"].append(values) results["casimir"].append(casimir_result) end_time = time.time() runtime = end_time - start_time print(f"Program runtime: {runtime} s") # make a dataframe from the results df = pd.DataFrame.from_dict(results) data_types_dict = {"counts": int, "energy": float} df = df.explode(["counts", "energy"]).astype(data_types_dict).rename_axis("rep") # report summary of energy across reps converged = df["energy"].groupby("rep").apply(min).values print(f"Statistics across {nrep} repetitions:\n-------------------") print( f"Least upper bound: {np.min(converged)}\nWorst upper bound: {np.max(converged)}\nMean bound: {np.mean(converged)}\nStd bound: {np.std(converged)}" ) # save results on disk varname = "-".join(varform) g2Nstr = str(g2N).replace(".", "") os.makedirs("data", exist_ok=True) if h5: outfile = f"data/bosBMN_L{L}_l{g2Nstr}_convergence_{optimizer}_{varname}_depth{depth}_reps{nrep}_max{maxit}.h5" print(f"Save results on disk: {outfile}") df.to_hdf(outfile, "vqe") else: outfile = f"data/bosBMN_L{L}_l{g2Nstr}_convergence_{optimizer}_{varname}_depth{depth}_reps{nrep}_max{maxit}.gz" print(f"Save results on disk: {outfile}") df.to_pickle(outfile) return # %% if __name__ == "__main__": fire.Fire(run_vqe)
https://github.com/sintefmath/QuantumPoker
sintefmath
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, transpile from termcolor import colored class Board: def __init__(self, size=3, simulator=None): # Initialize the quantum circuit with one qubit and classical bit for each cell self.size = size self.simulator = simulator self.superposition_count = 0 self.cells = [[' ' for _ in range(size)] for _ in range(size)] # Initialize the board representation self.qubits = QuantumRegister(size**2, 'q') self.bits = ClassicalRegister(size**2, 'c') self.circuit = QuantumCircuit(self.qubits, self.bits) ''' For a 3x3 board, the winning lines are: - Horizontal lines: (0, 1, 2), (3, 4, 5), (6, 7, 8) - Vertical lines: (0, 3, 6), (1, 4, 7), (2, 5, 8) - Diagonal lines: (0, 4, 8), (2, 4, 6) ''' self.winning_lines = [tuple(range(i, size**2, size)) for i in range(size)] + \ [tuple(range(i * size, (i + 1) * size)) for i in range(size)] + \ [tuple(range(0, size**2, size + 1)), tuple(range(size - 1, size**2 - 1, size - 1))] def __str__(self): # Create a colorful string representation of the board board_str = '' for i, row in enumerate(self.cells): for cell in row: if '?' in cell: cell_color = 'cyan' # Quantum move elif cell == 'X': cell_color = 'red' elif cell == 'O': cell_color = 'green' else: cell_color = 'yellow' board_str += f' {colored(cell, cell_color)} ' board_str += '|' if '?' in cell else ' |' board_str = board_str[:-1] + '\n' # Remove last separator if i < self.size - 1: # Add horizontal separator board_str += '-' * (5 * self.size - 1) + '\n' return board_str def make_classical_move(self, row, col, player_mark, is_collapsed=False): if self.cells[row][col] == ' ' or is_collapsed: # Check if the cell is occupied self.cells[row][col] = player_mark index = row * self.size + col if player_mark == 'X': self.circuit.x(self.qubits[index]) else: self.circuit.id(self.qubits[index]) return True return False def make_swap_move(self, row1, col1, row2, col2, **kwargs): if self.cells[row1][col1] != ' ' and self.cells[row2][col2] != ' ': indices = [row1 * self.size + col1, row2 * self.size + col2] self.circuit.swap(self.qubits[indices[0]], self.qubits[indices[1]]) self.cells[row1][col1], self.cells[row2][col2] = self.cells[row2][col2], self.cells[row1][col1] return True return False def make_superposition_move(self, row, col, player_mark, **kwargs): if self.cells[row][col] == ' ': index = row * self.size + col self.circuit.h(self.qubits[index]) self.cells[row][col] = player_mark + '?' self.superposition_count += 1 return True return False def make_entangled_move(self, *positions, risk_level, player_mark, **kwargs): # Entangle the quantum states of 2 or 3 cells based on the risk level pos_count = len(positions) if pos_count not in [2, 3] or risk_level not in [1, 2, 3, 4] or len(set(positions)) != pos_count or \ (pos_count == 2 and risk_level not in [1, 3]) or (pos_count == 3 and risk_level not in [2, 4]) or \ any(self.cells[row][col] != ' ' for row, col in positions): return False indices = [row * self.size + col for row, col in positions] self.circuit.h(self.qubits[indices[0]]) if pos_count == 2: # Pairwise Entanglement with Bell state for 2 qubits: # Lv1. |Ψ+⟩ = (∣01⟩ + ∣10⟩)/√2 | Lv3. |Φ+⟩ = (∣00⟩ + ∣11⟩)/√2 if risk_level == 1: self.circuit.x(self.qubits[indices[1]]) self.circuit.cx(self.qubits[indices[0]], self.qubits[indices[1]]) else: # Triple Entanglement with GHZ state for 3 qubits: # Lv2. (∣010⟩ + ∣101⟩)/√2 | Lv4. (∣000⟩ + ∣111⟩)/√2 if risk_level == 2: self.circuit.x(self.qubits[indices[1]]) self.circuit.x(self.qubits[indices[2]]) # Apply CNOT chain to entangle all 3 qubits self.circuit.cx(self.qubits[indices[0]], self.qubits[indices[1]]) self.circuit.cx(self.qubits[indices[1]], self.qubits[indices[2]]) for row, col in positions: self.cells[row][col] = player_mark + '?' self.superposition_count += pos_count return True def can_be_collapsed(self): # If superpositions/entanglement cells form a potential winning line => collapse for line in self.winning_lines: if all(self.cells[i // self.size][i % self.size].endswith('?') for i in line): return True return False def collapse_board(self): # Update the board based on the measurement results and apply the corresponding classical moves self.circuit.barrier() self.circuit.measure(self.qubits, self.bits) # Measure all qubits to collapse them to classical states transpiled_circuit = transpile(self.circuit, self.simulator) job = self.simulator.run(transpiled_circuit, memory=True) counts = job.result().get_counts() max_state = max(counts, key=counts.get)[::-1] # Get the state with the highest probability for i in range(self.size ** 2): row, col = divmod(i, self.size) if self.cells[row][col].endswith('?'): self.circuit.reset(self.qubits[i]) self.make_classical_move(row, col, 'X' if max_state[i] == '1' else 'O', is_collapsed=True) self.superposition_count = 0 return counts def check_win(self): # Dynamic implementation for above logic with dynamic winning lines for line in self.winning_lines: # Check if all cells in the line are the same and not empty first_cell = self.cells[line[0] // self.size][line[0] % self.size] if first_cell not in [' ', 'X?', 'O?']: is_same = all(self.cells[i // self.size][i % self.size] == first_cell for i in line) if is_same: return line # If no spaces and no superpositions left => 'Draw' # If all cells are filled but some are still in superpositions => collapse_board if all(self.cells[i // self.size][i % self.size] not in [' '] for i in range(self.size**2)): if self.superposition_count <= 0: return 'Draw' return self.superposition_count return None
https://github.com/sintefmath/QuantumPoker
sintefmath
# Copyright SINTEF 2019 # Authors: Franz G. Fuchs <franzgeorgfuchs@gmail.com>, # Christian Johnsen <christian.johnsen97@gmail.com>, # Vemund Falch <vemfal@gmail.com> from os.path import dirname, abspath import sys sys.path.append(dirname(abspath(__file__))) from Python.interactive import InteractiveContainer from Python.Board import Board from Python.Buttons import InteractiveButtons from Python.helpFiles import distributeGates from numpy import amax, array, sum, empty, append, argwhere, copy, any, in1d, argsort, zeros from qiskit import execute, Aer from time import time class PokerGame: def __init__(self, deckOfGates, nPlayers, money, names = None, smallBlind=5, smallBlindPlayer=0, enableEntanglement=False, seed=None): if seed == None: seed = int(time()) self.boards = [Board(boardSeed=seed, enableEntanglement=enableEntanglement) for i in range(nPlayers)] self.playerGates = distributeGates(deckOfGates, nPlayers) self.interactive = InteractiveContainer(nPlayers, self.boards[0].getSize(), deckOfGates, [str(i) for i in range(nPlayers)] if (names is None) else names) self.interactiveButtons = InteractiveButtons(self.boards[0], self.interactive, self.check, self.fold, self.playerGates, deckOfGates, self.getPlayer) self.names = names self.nPlayers = nPlayers self.smallBlind = smallBlind self.allIn = empty(0, dtype=int) self.haveRaised = False self.playerMoney = money # Number at index i is player i's money self.playerBets = array([0 for i in range(nPlayers)], dtype=int) # Number at index i is player i's bet self.foldedPlayers = [] self.smallBlindPlayer = smallBlindPlayer self.lastPlayerInRound = (smallBlindPlayer+2)%self.nPlayers self.player = (smallBlindPlayer+2)%self.nPlayers self.bettingRound = 0 self.lastRaiser = (smallBlindPlayer+1)%self.nPlayers self.currentBet = self.smallBlind*2 self.gameOver = False self.interactive.connectBets(self.interactiveButtons, self.convertRaiseToInt) self.interactive.connectMouseclick(self.mouseClick) self.interactive.connectShowHandButton(self.interactiveButtons) self.doBlindBets() def doBlindBets(self): self.playerBets[self.smallBlindPlayer] += self.smallBlind self.playerBets[(self.smallBlindPlayer+1) % self.nPlayers] += self.smallBlind*2 self.playerMoney[self.smallBlindPlayer] -= self.smallBlind self.playerMoney[(self.smallBlindPlayer + 1) % self.nPlayers] -= self.smallBlind * 2 self.interactive.updateNextBet(self.playerBets[self.player], amax(self.playerBets)) self.interactive.updateCurrentBets(self.playerBets, self.playerMoney) self.interactive.setPlayerPatchColor(self.player, self.interactive.getCurrentPlayerColor()[0]) def advanceGame(self): """ Moves the game to the next player and round. :return: None """ if len(self.foldedPlayers) >= self.nPlayers - 1: self.interactive.disconnectShowHandButton() self.interactive.disconnectBets() self.interactive.setPlayerPatchColor(self.player, self.interactive.getFoldedColor()) self.endGame(allFolded=True) return if len(self.foldedPlayers) + self.allIn.shape[0] == self.nPlayers and self.bettingRound < 4: advanceRound = True else: advanceRound = False firstIter = True nextPlayer = self.player while firstIter or nextPlayer in self.foldedPlayers or (nextPlayer in self.allIn and self.bettingRound < 4): firstIter = False nextPlayer = (nextPlayer + 1) % self.nPlayers if nextPlayer == self.lastPlayerInRound: advanceRound = True if len(self.foldedPlayers) + self.allIn.shape[0] >= self.nPlayers - 1 and self.bettingRound < 4 and advanceRound: self.forwardToRound4() nextPlayer = self.lastRaiser elif advanceRound: if self.bettingRound == 0: self.showCards(3) self.interactive.connectBellAndBasis(self.interactiveButtons) nextPlayer = self.findRoundStarter() self.lastPlayerInRound = nextPlayer if self.haveRaised: self.interactive.setBetandCheck() self.haveRaised = False elif self.bettingRound == 1: self.showCards(1) nextPlayer = self.findRoundStarter() self.lastPlayerInRound = nextPlayer if self.haveRaised: self.interactive.setBetandCheck() self.haveRaised = False elif self.bettingRound == 2: self.showCards(1) nextPlayer = self.findRoundStarter() self.lastPlayerInRound = nextPlayer if self.haveRaised: self.interactive.setBetandCheck() self.haveRaised = False elif self.bettingRound == 3: self.interactive.disconnectBets() self.interactive.disconnectShowHandButton() self.interactive.connectEnd(self.endGateTurn) nextPlayer = self.lastRaiser self.lastPlayerInRound = nextPlayer elif self.bettingRound == 4: # "Round" in which gates were used self.endGame() self.interactive.setPlayerPatchColor(self.player, self.interactive.getDisconnectedColor()) self.interactive.disconnectAllGates() self.interactive.disconnectEnd() return self.bettingRound += 1 if self.bettingRound == 4: self.interactive.connectAllowedGates(self.interactiveButtons, self.playerGates[nextPlayer]) self.interactiveButtons.changePlayer(self.boards[nextPlayer]) if self.bettingRound == 4: self.inform("Apply the desired quantum gates\nthen click the end button.") elif self.bettingRound < 3: self.interactive.updateNextBet(self.playerBets[nextPlayer], amax(self.playerBets)) self.inform("Place a bet or fold.") self.updateColor(nextPlayer, self.bettingRound<4) self.interactive.updateBoard() self.player = nextPlayer def findRoundStarter(self): nextPlayer = self.smallBlindPlayer while nextPlayer in self.allIn or nextPlayer in self.foldedPlayers: nextPlayer = (nextPlayer+1)%self.nPlayers return nextPlayer def updateColor(self, nextPlayer, active): if nextPlayer == self.player: return if self.player in self.allIn: self.interactive.setPlayerPatchColor(self.player, self.interactive.getAllInColor()[0]) elif self.player in self.foldedPlayers: self.interactive.setPlayerPatchColor(self.player, self.interactive.foldedColor) else: self.interactive.setPlayerPatchColor(self.player, self.interactive.disconnectedColor) self.interactive.setPlayerPatchColor(nextPlayer, self.interactive.getCurrentPlayerColor()[0]) def forwardToRound4(self): while self.bettingRound < 4: if self.bettingRound == 0: self.showCards(3) self.interactive.connectBellAndBasis(self.interactiveButtons) elif self.bettingRound == 1: self.showCards(1) elif self.bettingRound == 2: self.showCards(1) self.bettingRound += 1 self.interactive.disconnectBets() self.interactive.disconnectShowHandButton() self.interactive.connectEnd(self.endGateTurn) def endGateTurn(self, event): """ Called by the "end" button when a user has finished using their gates. :return: None """ if self.gameOver: return self.interactive.disconnectAllGates() self.advanceGame() def endGame(self, allFolded=False): """ Called when the game is supposed to end. :return: None """ if allFolded: if len(self.foldedPlayers) == self.nPlayers: self.inform("Somehow you all folded! No winner.") self.inform("Exit to start a new game.") self.gameOver = True return for player in range(self.nPlayers): if player not in self.foldedPlayers: self.inform(self.names[player] + " won " + str(sum(self.playerBets)) + " because everyone else folded.") self.inform("Game over. Exit to start a new game.") self.gameOver = True self.playerMoney[player] += sum(self.playerBets) scoresDisplay = [-1 for i in range(self.nPlayers)] winnings = [0 for i in range(self.nPlayers)] winnings[player] = sum(self.playerBets) scoresDisplay[player] = -2 self.interactive.displayEndResults(scoresDisplay, winnings) return simulator = Aer.get_backend("qasm_simulator") scores = [0 for i in range(self.nPlayers)] for i in range(self.nPlayers): if i in self.foldedPlayers: scores[i] = -1 continue board = self.boards[i] board.qc.measure(board.q, board.c) counts = execute(board.qc, simulator, shots=1).result().get_counts(board.qc) for bitStr in list(counts.keys())[0]: if bitStr == "1": scores[i] += 1 print("\n---- Final scores----") winners = [] nWinners = 0 maxScore = max(scores) for i in range(self.nPlayers): print("Player", i + 1, end=": ") if scores[i] == -1: print("Folded") else: print(scores[i]) if scores[i] == maxScore: winners.append(i) nWinners += 1 self.allIn = self.allIn[argsort(self.playerBets[self.allIn])] pot = zeros(self.allIn.shape[0]+1, dtype=int) for nPot in range(self.allIn.shape[0]): currentPotBet = self.playerBets[self.allIn[nPot]] for player in range(self.nPlayers): betToPot = min(self.playerBets[player], currentPotBet) pot[nPot] += betToPot self.playerBets[player] -= betToPot pot[-1] = sum(self.playerBets) winnings = [0 for i in range(self.nPlayers)] originalScore = copy(scores) if self.allIn.shape[0] == 0 or not(any(in1d(array(winners), self.allIn))): self.printWinners(winners, nWinners, scores, pot[0]) for i in range(len(winners)): winnings[winners[i]] += pot[0]/nWinners else: for i in range(self.allIn.shape[0]): if pot[i] == 0 or self.allIn[i] not in winners: pot[i+1] += pot[i] continue self.printWinners(winners, nWinners, scores, pot[i]) for j in range(len(winners)): winnings[winners[j]] += pot[i]/nWinners scores[self.allIn[i]] = -1 winners = argwhere(scores == amax(scores)).flatten() nWinners = winners.shape[0] if not(any(in1d(array(winners), self.allIn))): pot[-1] = sum(pot[i+1:]) break if pot[-1] > 0: self.printWinners(winners, nWinners, scores, pot[-1]) for j in range(len(winners)): winnings[winners[j]] += pot[-1]/nWinners self.interactive.displayEndResults(originalScore, winnings) self.gameOver = True self.inform("Game over. Exit to start a new game.") def printWinners(self, winners, nWinners, scores, pot): if nWinners == 0: self.inform("No winners!") elif nWinners == 1: self.inform(self.names[winners[0]] + " won " + str(pot) + " with a score of " + str(scores[winners[0]]) + ".") self.playerMoney[winners[0]] += pot else: text = "" pot /= nWinners for i in range(nWinners): self.playerMoney[winners[i]] += pot text += self.names[winners[i]] if i == nWinners - 2: if nWinners != 2: text += "," text += " and " elif i < nWinners - 1: text += ", " text += " each won " + str(round(pot, 2)) + " with a score of " + str(scores[winners[0]]) self.inform(text) def fold(self): """ Called by the "fold" button. :return: None """ if self.bettingRound > 3 or self.gameOver: return self.interactive.updateCurrentBets(self.playerBets, self.playerMoney) self.foldedPlayers.append(self.player) if self.interactiveButtons.getCurrentlyShowingPlayer(): self.interactiveButtons.showHand(None, updateBoard=False) self.advanceGame() def check(self): if self.bettingRound > 3 or self.gameOver: return """ Called by the "check" button. :return: None """ if (self.currentBet-self.playerBets[self.player] > self.playerMoney[self.player]): self.bet(self.playerMoney[self.player]) else: self.bet(self.currentBet-self.playerBets[self.player]) def convertRaiseToInt(self, amountStr, text_box): if text_box is not None: text_box.set_val("") try: amount = int(amountStr) except ValueError: self.inform("Enter a valid number.") return if amount < 0: self.inform("Enter a non-negative number.") return self.bet(amount + self.currentBet - self.playerBets[self.player]) def bet(self, amount): """ Called by the input text box when the user hits enter. :param amountStr: String that was in the text box, text_box: input box from text :return: None """ if amount == self.playerMoney[self.player]: # All In self.allIn = append(self.allIn, self.player) elif amount + self.playerBets[self.player] < self.currentBet: self.inform("To bet you must either raise or check. Enter a large enough number.") return elif amount > self.playerMoney[self.player]: self.inform("You cannot raise by more than " + str(self.playerMoney[self.player]+\ self.playerBets[self.player]-self.currentBet) + ".") return if self.interactiveButtons.getCurrentlyShowingPlayer(): self.interactiveButtons.showHand(None, updateBoard=False) self.playerBets[self.player] += amount self.playerMoney[self.player] -= amount if self.playerBets[self.player] > self.currentBet: self.currentBet = self.playerBets[self.player] self.lastRaiser = self.player self.lastPlayerInRound = self.player if not (self.haveRaised): self.interactive.setRaiseandCall() self.haveRaised = True self.interactive.updateCurrentBets(self.playerBets, self.playerMoney) self.interactive.updateNextBet(self.playerBets[(self.player+1)%self.nPlayers], amax(self.playerBets)) self.advanceGame() def showCards(self, nCards): """ Makes nCards more qubits visible on the board. :param nCards: Number of additional cards to show. :return: None """ self.interactiveButtons.updateQubitsShowing(nCards) def inform(self, text): self.interactive.updateInfoText(text) self.interactive.fig.canvas.draw() def mouseClick(self, qubit): """ Logic for mouseclick :param qubit: the target qubit :return: Nothing """ if self.gameOver: return isGate, button = self.interactiveButtons.mouseClick(qubit) if isGate: self.playerGates[self.player][button] -= 1 if self.playerGates[self.player][button] == 0: del self.playerGates[self.player][button] self.interactive.disconnectGate(button) self.interactive.updatePlayerGate(self.playerGates[self.player], hover=True, showZero=True) self.interactive.updateBoard() def getPlayer(self): return self.player
https://github.com/sintefmath/QuantumPoker
sintefmath
import sys IN_COLAB = 'google.colab' in sys.modules if IN_COLAB: from google.colab import output output.enable_custom_widget_manager() !pip install qiskit !pip install ipympl !rm -rf /content/QuantumPoker/ !git clone https://github.com/sintefmath/QuantumPoker sys.path.append('/content/QuantumPoker/Python') sys.path.append('/content/QuantumPoker') get_ipython().magic('matplotlib ipympl') else: get_ipython().magic('matplotlib notebook') from os.path import dirname, abspath import sys sys.path.append(dirname(abspath(''))) from PokerGame import PokerGame import matplotlib.pyplot as plt from numpy import array, count_nonzero dealer = 0 nPlayers = 3 gameHasRun = False deckOfGates = {"H": nPlayers, "X": nPlayers, "ZH": nPlayers, "CX": nPlayers} money = array([100 for i in range(nPlayers)]) names = ["James", "Lilly", "Harry"] if not count_nonzero(money==0) == (nPlayers-1): if gameHasRun: dealer = (dealer + 1) % nPlayers if 0 in money: toDelete=nonzero(money==0)[0] for i in flip(toDelete): if i < dealer: dealer -= 1 names = delete(names, nonzero(money==0)[0]) money = delete(money, nonzero(money==0)[0]) nPlayers = money.shape[0] gameHasRun = True pokerGame = PokerGame(deckOfGates, nPlayers, money, names = names, smallBlind=5, smallBlindPlayer=dealer, enableEntanglement=True)
https://github.com/sintefmath/QuantumPoker
sintefmath
%matplotlib inline from os.path import dirname, abspath import sys sys.path.append(dirname(abspath(''))) from PokerGame import PokerGame import matplotlib.pyplot as plt from numpy import array nPlayers = 3 deckOfGates = {"H": nPlayers, "X": nPlayers, "ZH": nPlayers, "CX": nPlayers} money = array([100 for i in range(nPlayers)]) names = ["James", "Lilly", "Harry"] pokerGame = PokerGame(deckOfGates, nPlayers, money, names = names, smallBlind=5, smallBlindPlayer=0, seed=4, enableEntanglement=True) fig = pokerGame.interactive.fig pokerGame.interactiveButtons.showHand(None, updateBoard=False) fig pokerGame.fold() pokerGame.interactiveButtons.showHand(None, updateBoard=False) fig pokerGame.check() pokerGame.check() fig pokerGame.bet(10) fig pokerGame.check() pokerGame.check() pokerGame.check() pokerGame.interactiveButtons.checkBellStates2(None) pokerGame.mouseClick(1) pokerGame.mouseClick(4) fig pokerGame.check() pokerGame.check() fig pokerGame.interactiveButtons.CX(None) pokerGame.mouseClick(1) pokerGame.mouseClick(4) fig pokerGame.interactiveButtons.X(None) pokerGame.mouseClick(2) pokerGame.interactiveButtons.ZH(None) pokerGame.mouseClick(4) fig pokerGame.endGateTurn(None) fig pokerGame.interactiveButtons.X(None) pokerGame.mouseClick(2) pokerGame.interactiveButtons.H(None) pokerGame.mouseClick(3) fig pokerGame.endGateTurn(None) fig
https://github.com/t-imamichi/qiskit-utility
t-imamichi
#!/usr/bin/env python # 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. ''' Translate a QASM file to a QOBJ file. Examples: $ python qasm2qobj.py -i input.qasm -o output.qobj # mapping for all-to-all $ python qasm2qobj.py -i input.qasm -o output.qobj -b ibmq_5_tenerife # mapping for ibmq_5_tenerife ''' import json from qiskit import register, available_backends, load_qasm_file, compile from argparse import ArgumentParser import numpy as np import Qconfig def backends(qconsole=False): key = 'qconsole' if qconsole else 'qx' token = Qconfig.APItoken[key] config = Qconfig.config[key] url = config.get('url', None) hub = config.get('hub', None) group = config.get('group', None) project = config.get('project', None) register(token, url, hub, group, project) return available_backends() def options(): parser = ArgumentParser() parser.add_argument('-i', '--qasm', action='store', help='input QASM file') parser.add_argument('-o', '--qobj', action='store', help='output QOBJ file') parser.add_argument('-s', '--shots', action='store', help='number of shots', type=int, default=1024) parser.add_argument('--out-qasm', action='store', help='output QASM file') parser.add_argument('-b', '--backend', action='store', help='backend (default: local_qasm_simulator)', default='local_qasm_simulator') parser.add_argument('-z', '--qconsole', action='store_true', help='Use qconsole') args = parser.parse_args() print('options:', args) if not args.qasm or not args.qobj: parser.print_help() quit() set_backends = backends(args.qconsole) print('backends:', set_backends) if args.backend not in set_backends: print('invalid backend: {}'.format(args.backend)) print('available backends: {}'.format(set_backends)) #quit() return args def support_npint(val): if isinstance(val, (np.int32, np.int64)): return int(val) return val def main(): args = options() circuit = load_qasm_file(args.qasm, name=args.qasm) qobj = compile(circuit, backend=args.backend, shots=args.shots) with open(args.qobj, 'w') as outfile: json.dump(qobj, outfile, indent=2, sort_keys=True, default=support_npint) if args.out_qasm: with open(args.out_qasm, 'w') as outfile: outfile.write(qobj['circuits'][0]['compiled_circuit_qasm']) if __name__ == '__main__': main()
https://github.com/LuukCoopmans/Qiskit-Hackathon-QIP
LuukCoopmans
import numpy as np from matplotlib import pyplot as plt import os import cv2 from qiskit import * def rgb2gray(rgb): return np.dot(rgb[...,:3], [0.2989, 0.5870, 0.1140]) def get_Coeff(Image, watermark=None): """ Function that takes in an Greyscale Image matrix of any size and and optional watermark image and shape and returns qubit coefficients in the computational basis. TO DO: build in a check that ensures the sizes of the Image and watermark are the same """ Flatten_Image = np.reshape(Image, np.shape(Image)[0]*np.shape(Image)[1]) # Get the theta angles of the Image and watermark from the greyscale values Theta_I = 2*np.arccos(np.sqrt(Flatten_Image/255)) if watermark is None: Theta_W = np.zeros(len(Theta_I)) else: Flatten_watermark = np.reshape(watermark, np.shape(watermark)[0]*np.shape(watermark)[1]) Theta_W = 2*np.arccos(np.sqrt(Flatten_watermark/255)) # Compute the qubit Coeff and return them in a normalized qubit state vector. Coeff = np.stack((np.cos(Theta_I/2)*np.cos(Theta_W/2), np.cos(Theta_I/2)*np.sin(Theta_W/2), np.sin(Theta_I/2)*np.cos(Theta_W/2), np.sin(Theta_I/2)*np.sin(Theta_W/2))) Coeff = np.ndarray.flatten(np.transpose(Coeff)) return Coeff/np.linalg.norm(Coeff) def initialise_state(desired_initial_state): """ Returns an initialized quantum circuit for a given input state""" n = int(round(np.log2(desired_initial_state.size))) #number of qubits qc_init = QuantumCircuit(n) qc_init.initialize(desired_initial_state, range(n)) return qc_init def get_Images(probability_vector): """ Takes in an probability vector obtained from measuring all the qubits in the quantum circuit and returns the corresponding matrices of the greyscale values of the measured images. TO DO: vectorize this function """ n = int(np.round(len(probability_vector)/4)) # get sizes back of classical images c_Image = np.zeros(n) w_Image = np.zeros(n) # Sum and normalize the probabilities to get the greyscale pixel value out for i in range(n): c_Image[i] = (probability_vector[4*i]+probability_vector[4*i+1])*255/np.sum(probability_vector[4*i:(4*i)+4]) w_Image[i] = (probability_vector[4*i]+probability_vector[4*i+2])*255/np.sum(probability_vector[4*i:(4*i)+4]) c_Image = np.reshape(c_Image,[np.int(np.round(np.sqrt(n))),np.int(np.round(np.sqrt(n)))]) w_Image = np.reshape(w_Image,[np.int(np.round(np.sqrt(n))),np.int(np.round(np.sqrt(n)))]) return c_Image, w_Image N = 16 #size in pixels # Carrier Image img_file = os.path.expanduser("cat.png") img = cv2.imread(img_file) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) res = cv2.resize(img, dsize=(N, N), interpolation=cv2.INTER_CUBIC) C_Image = rgb2gray(res) # Watermark img_file2 = os.path.expanduser("IBM-logo.png") img2 = cv2.imread(img_file2) img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB) res2 = cv2.resize(img2, dsize=(N, N), interpolation=cv2.INTER_CUBIC) W_Image = rgb2gray(res2) plt.rcParams['figure.figsize'] = [9, 7] plt.rcParams['figure.dpi'] = 100 fig, axs = plt.subplots(1,2) axs[0].imshow(C_Image/255, cmap=plt.get_cmap('gray'), vmin=0, vmax=1) axs[0].title.set_text('Carrier Image') axs[1].imshow(W_Image/255, cmap=plt.get_cmap('gray'), vmin=0, vmax=1) axs[1].title.set_text('Watermark Image') State_vector = get_Coeff(C_Image, W_Image) qc_init = initialise_state(State_vector) #qc_init.draw('mpl') n = int(round(np.log2(State_vector.size))) # number of qubits shots0 = 100000 # Create a Quantum Circuit meas = QuantumCircuit(n, n) meas.barrier(range(n)) # map the quantum measurement to the classical bits meas.measure(range(n), range(n)) # The Qiskit circuit object supports composition using # the addition operator. qc = qc_init + meas #drawing the circuit #qc.draw('mpl') # Use Aer's qasm_simulator backend_sim = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator. job_sim = execute(qc, backend_sim, shots=shots0) # Grab the results from the job. result_sim = job_sim.result() #from qiskit import IBMQ #IBMQ.load_account() #provider = IBMQ.get_provider("ibm-q") #backend = provider.get_backend("ibmq_essex") #job = q.execute(qc, backend=backend, shots=shots0) #job_monitor(job) counts = result_sim.get_counts(qc) probability_vector = np.zeros(2**n) int_counts = counts.int_outcomes() for k in range(2**n): probability_vector[k] = int_counts.get(k, 0)/shots0 RC_Image, RW_Image = get_Images(probability_vector) fig, axs = plt.subplots(2,2) axs[0,0].imshow(RC_Image/255, cmap=plt.get_cmap('gray'), vmin=0, vmax=1) axs[0,0].title.set_text('Retrieved Carrier Image') axs[0,1].imshow(C_Image/255, cmap=plt.get_cmap('gray'), vmin=0, vmax=1) axs[0,1].title.set_text('Original Carrier Image') axs[1,0].imshow(RW_Image/255, cmap=plt.get_cmap('gray'), vmin=0, vmax=1) axs[1,0].title.set_text('Retrieved Watermark Image') axs[1,1].imshow(W_Image/255, cmap=plt.get_cmap('gray'), vmin=0, vmax=1) axs[1,1].title.set_text('Original Watermark Image') plt.show() n = int(round(np.log2(State_vector.size))) shots0 = 100000 # Create the Quantum Scramble Circuit with controlled U3 rotations meas = QuantumCircuit(n, n) meas.barrier(range(n)) meas.cu3(np.pi/4, 0, 0, 3, 0) meas.cu3(-np.pi/4, 0, 0, 4, 0) meas.cu3(-np.pi/2, 0, 0, 5, 0) meas.cu3(-np.pi/3, 0, 0, 6, 0) meas.cu3(np.pi/2, 0, 0, 7, 0) # map the quantum measurement to the classical bits meas.measure(range(n), range(n)) # The Qiskit circuit object supports composition using # the addition operator. qc = qc_init + meas # Optional uncomment to draw the circuit #qc.draw('mpl') # Use Aer's qasm_simulator backend_sim = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator. # We've set the number of repeats of the circuit # to be 1024, which is the default. job_sim = execute(qc, backend_sim, shots=shots0) # Grab the results from the job. result_sim = job_sim.result() counts = result_sim.get_counts(qc) probability_vector = np.zeros(2**n) int_counts = counts.int_outcomes() for k in range(2**n): probability_vector[k] = int_counts.get(k, 0)/shots0 RRC_Image, SCrW_Image = get_Images(probability_vector) fig, axs = plt.subplots(2,2) axs[0,0].imshow(RRC_Image/255, cmap=plt.get_cmap('gray'), vmin=0, vmax=1) axs[0,0].title.set_text('Retrieved Carrier Image') axs[0,1].imshow(C_Image/255, cmap=plt.get_cmap('gray'), vmin=0, vmax=1) axs[0,1].title.set_text('Original Carrier Image') axs[1,0].imshow(SCrW_Image/255, cmap=plt.get_cmap('gray'), vmin=0, vmax=1) axs[1,0].title.set_text('Scrambled Watermark Image') axs[1,1].imshow(W_Image/255, cmap=plt.get_cmap('gray'), vmin=0, vmax=1) axs[1,1].title.set_text('Original Watermark Image') plt.show()
https://github.com/quantumjim/pewpew_qiskit_workshops
quantumjim
%matplotlib notebook import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen qc = QuantumCircuit(2,2) # create an empty circuit with two qubits and two output bits # create a circuit with the required measurements, so we can add them in easily meas = QuantumCircuit(2,2) meas.measure(0,0) meas.measure(1,1) # loop over the squares centered on (1,2) and (6,2) and make all dim for (X,Y) in [(1,2),(6,2)]: for dX in [+1,0,-1]: for dY in [+1,0,-1]: screen.pixel(X+dX,Y+dY,2) for (X,Y) in [(1,2),(6,2)]: screen.pixel(X,Y,0) # turn off the center pixels of the squares old_keys = 0 while True: # loop which checks for user input and responds # look for and act upon key presses keys = pew.keys() # get current key presses if keys!=0 and keys!=old_keys: if keys&pew.K_UP: qc.x(0) # x for qubit 0 when UP is pressed if keys&pew.K_LEFT: qc.x(1) # x for qubit 1 when LEFT is pressed old_keys = keys # execute the circuit and get a single sample of memory m = simulate(qc+meas,shots=1,get='memory') # turn the pixel (1,2) on or off depending on whether the first bit value is 1 or 0 if m[0][0]=='1': screen.pixel(1,2,3) else: screen.pixel(1,2,0) # do the same for pixel (6,2) if m[0][1]=='1': screen.pixel(6,2,3) else: screen.pixel(6,2,0) pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen # create an empty circuit with two qubits and two output bits qc = QuantumCircuit(2,2) cnot = QuantumCircuit(2,2) cnot.cx(0,1) # create a circuit with the required measurements, so we can add them in easily meas = QuantumCircuit(2,2) meas.measure(0,0) meas.measure(1,1) # loop over the square centered on (1,2) and make all dim for (X,Y) in [(1,2),(6,2)]: for dX in [+1,0,-1]: for dY in [+1,0,-1]: screen.pixel(X+dX,Y+dY,2) for (X,Y) in [(1,2),(6,2)]: screen.pixel(X,Y,0) # turn off the center pixels of the squares old_keys = 0 while True: # loop which checks for user input and responds # look for and act upon key presses keys = pew.keys() # get current key presses if keys!=0 and keys!=old_keys: if keys&pew.K_UP: qc.x(0) # x for qubit 0 when UP is pressed if keys&pew.K_LEFT: qc.x(1) # x for qubit 1 when LEFT is pressed old_keys = keys # execute the circuit and get a single sample of memory m = simulate(qc+meas,shots=1,get='memory') # turn the pixel (1,2) on or off depending on whether the first bit value is 1 or 0 if m[0][0]=='1': screen.pixel(1,2,3) else: screen.pixel(1,2,0) # do the same for pixel (6,2) if m[0][1]=='1': screen.pixel(6,2,3) else: screen.pixel(6,2,0) m = simulate(qc+cnot+meas,shots=1,get='memory') xor = m[0][0] if xor=='0': for (X,Y) in [(3,2),(4,2)]: screen.pixel(X,Y,0) else: for (X,Y) in [(3,2),(4,2)]: screen.pixel(X,Y,3) pew.show(screen) # update screen to display any changes pew.tick(1/6) # pause for a sixth of a second
https://github.com/quantumjim/pewpew_qiskit_workshops
quantumjim
run controller.py
https://github.com/quantumjim/pewpew_qiskit_workshops
quantumjim
%matplotlib notebook import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen qc = QuantumCircuit(2,2) # create an empty circuit with two qubits and two output bits # put a hadamard on both qubits qc.h(0) qc.h(1) # put a measurement on both qubit, whose results go to the corresponding output bit qc.measure(0,0) qc.measure(1,1) # loop over the square centered on (1,2) and make all dim (X,Y) = (1,2) for dX in [+1,0,-1]: for dY in [+1,0,-1]: screen.pixel(X+dX,Y+dY,2) screen.pixel(X,Y,0) # turn off pixel at (1,2) while True: # loop which checks for user input and responds # execute the circuit and get a single sample of memory m = simulate(qc,shots=1,get='memory') # the resulting bit string m[0] is converted to the corresponding number and used as brightness screen.pixel(X,Y,int(m[0],2)) pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen qc = QuantumCircuit(2,2) # create an empty circuit with two qubits and two output bits # put a hadamard on both qubits qc.h(0) qc.h(1) # put a measurement on both qubit, whose results go to the corresponding output bit qc.measure(0,0) qc.measure(1,1) # loop over the squares centered on (1,2) and (6,2) and make all dim for (X,Y) in [(1,2),(6,2)]: for dX in [+1,0,-1]: for dY in [+1,0,-1]: screen.pixel(X+dX,Y+dY,2) for (X,Y) in [(1,2),(6,2)]: screen.pixel(X,Y,0) # turn off the center pixels of the squares while True: # loop which checks for user input and responds # execute the circuit and get a single sample of memory m = simulate(qc,shots=1,get='memory') # turn the pixel (1,2) on or off depending on whether the first bit value is 1 or 0 if m[0][0]=='1': screen.pixel(1,2,3) else: screen.pixel(1,2,0) # do the same for pixel (6,2) if m[0][1]=='1': screen.pixel(6,2,3) else: screen.pixel(6,2,0) pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second
https://github.com/quantumjim/pewpew_qiskit_workshops
quantumjim
%matplotlib notebook import pew # setting up tools for the pewpew pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen screen.pixel(1,2,3) # put a bright pixel at (1,2) pew.show(screen) # update screen to display the above change pew.tick(5) # pause for 5 seconds before quitting import pew # setting up tools for the pewpew pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen # loop over the square centered on (1,2) and make all dim (X,Y) = (1,2) for dX in [+1,0,-1]: for dY in [+1,0,-1]: screen.pixel(X+dX,Y+dY,2) pew.show(screen) # update screen to display the above changes pew.tick(5) # pause for 5 seconds before quitting import pew # setting up tools for the pewpew pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen # loop over the square centered on (1,2) and make all dim (X,Y) = (1,2) for dX in [+1,0,-1]: for dY in [+1,0,-1]: screen.pixel(X+dX,Y+dY,2) screen.pixel(X,Y,0) # turn off pixel at (1,2) pew.show(screen) # update screen to display the above changes pew.tick(5) # pause for 5 seconds before quitting import pew # setting up tools for the pewpew pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen # loop over the square centered on (1,2) and make all dim (X,Y) = (1,2) for dX in [+1,0,-1]: for dY in [+1,0,-1]: screen.pixel(X+dX,Y+dY,2) screen.pixel(X,Y,0) # turn off pixel at (1,2) while True: # loop which checks for user input and responds keys = pew.keys() # get current key presses if keys!=0: if keys&pew.K_UP: # if UP is pressed, turn the pixel at (1,2) on (to a brightness of 3) screen.pixel(X,Y,3) pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second
https://github.com/quantumjim/pewpew_qiskit_workshops
quantumjim
%matplotlib notebook import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum from math import pi pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen qc = QuantumCircuit(1,1) # create an empty circuit with one qubit and one output bit # create circuits with the required measurements, so we can add them in easily meas = {} meas['Z'] = QuantumCircuit(1,1) meas['Z'].measure(0,0) meas['X'] = QuantumCircuit(1,1) meas['X'].h(0) meas['X'].measure(0,0) basis = 'Z' # set the initial measurement basis for each qubit # loop over the squares centered on (1,2) and (1,4) and make all dim for (X,Y) in [(1,2),(1,4)]: for dX in [+1,0,-1]: for dY in [+1,0,-1]: screen.pixel(X+dX,Y+dY,2) pew.show(screen) for (X,Y) in [(1,2),(1,4)]: screen.pixel(X,Y,0) # turn off the center pixels of the squares old_keys = 0 while True: # loop which checks for user input and responds # look for and act upon key presses keys = pew.keys() # get current key presses if keys!=0 and keys!=old_keys: if keys==pew.K_X: basis = 'X'*(basis=='Z') + 'Z'*(basis=='X') # toggle basis if keys==pew.K_LEFT: qc.x(0) # x when LEFT is pressed if keys==pew.K_UP: qc.rx(pi/4,0) # x when LEFT is pressed if keys==pew.K_DOWN: qc.h(0) # h when DOWN is pressed old_keys = keys # execute the circuit and get a single sample of memory for the given measurement bases m = simulate(qc+meas[basis],shots=1,get='memory') # turn the pixels (1,2) and (1,4) (depending on basis) on or off (depending on m[0]) if m[0]=='1': if basis=='Z': screen.pixel(1,2,3) else: screen.pixel(1,4,3) else: if basis=='Z': screen.pixel(1,2,0) else: screen.pixel(1,4,0) # turn the pixels not used to display m[0] to dim if basis=='Z': screen.pixel(1,4,2) else: screen.pixel(1,2,2) pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum from math import pi pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen qc = QuantumCircuit(1,1) # create an empty circuit with one qubit and one output bit # create circuits with the required measurements, so we can add them in easily meas = {} meas['Z'] = QuantumCircuit(1,1) meas['Z'].measure(0,0) meas['X'] = QuantumCircuit(1,1) meas['X'].h(0) meas['X'].measure(0,0) meas['Y'] = QuantumCircuit(1,1) meas['Y'].rx(pi/2,0) meas['Y'].measure(0,0) basis = 'Z' # set the initial measurement basis for each qubit # loop over the squares centered on (1,2) and (1,4) and make all dim for (X,Y) in [(1,2),(1,4),(1,6)]: for dX in [+1,0,-1]: for dY in [+1,0,-1]: screen.pixel(X+dX,Y+dY,2) pew.show(screen) for (X,Y) in [(1,2),(1,4),(1,6)]: screen.pixel(X,Y,0) # turn off the center pixels of the squares old_keys = 0 while True: # loop which checks for user input and responds # look for and act upon key presses keys = pew.keys() # get current key presses if keys!=0 and keys!=old_keys: if keys==pew.K_X: basis = 'X'*(basis=='Z') + 'Z'*(basis=='X') + 'Y'*(basis=='Y') # toggle basis between X and Z if keys==pew.K_O: basis = 'X'*(basis=='Y') + 'Y'*(basis=='X') + 'Z'*(basis=='Z') # toggle basis between X and Y if keys==pew.K_LEFT: qc.x(0) # x when LEFT is pressed if keys==pew.K_UP: qc.rx(pi/4,0) # x when LEFT is pressed if keys==pew.K_DOWN: qc.h(0) # h when DOWN is pressed old_keys = keys # execute the circuit and get a single sample of memory for the given measurement bases m = simulate(qc+meas[basis],shots=1,get='memory') # turn the pixels (1,2) and (1,4) (depending on basis) on or off (depending on m[0]) if m[0]=='1': if basis=='Z': screen.pixel(1,2,3) elif basis=='X': screen.pixel(1,4,3) else: screen.pixel(1,6,3) else: if basis=='Z': screen.pixel(1,2,0) elif basis=='X': screen.pixel(1,4,0) else: screen.pixel(1,6,0) # turn the pixels not used to display m[0] to dim if basis=='Z': screen.pixel(1,4,2) screen.pixel(1,6,2) elif basis=='X': screen.pixel(1,2,2) screen.pixel(1,6,2) else: screen.pixel(1,2,2) screen.pixel(1,4,2) pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum from math import pi pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen qc = QuantumCircuit(1,1) # create an empty circuit with one qubit and one output bit # create circuits with the required measurements, so we can add them in easily meas = {} meas['Z'] = QuantumCircuit(1,1) meas['Z'].measure(0,0) meas['X'] = QuantumCircuit(1,1) meas['X'].h(0) meas['X'].measure(0,0) meas['Y'] = QuantumCircuit(1,1) meas['Y'].rx(pi/2,0) meas['Y'].measure(0,0) basis = 'Z' # set the initial measurement basis for each qubit # loop over the squares centered on (1,2) and (1,4) and make all dim for (X,Y) in [(1,2),(1,4),(1,6)]: for dX in [+1,0,-1]: for dY in [+1,0,-1]: screen.pixel(X+dX,Y+dY,2) pew.show(screen) for (X,Y) in [(1,2),(1,4),(1,6)]: screen.pixel(X,Y,0) # turn off the center pixels of the squares old_keys = 0 while True: # loop which checks for user input and responds # look for and act upon key presses keys = pew.keys() # get current key presses if keys!=0 and keys!=old_keys: if keys==pew.K_X: basis = 'X'*(basis=='Z') + 'Z'*(basis=='X') + 'Y'*(basis=='Y') # toggle basis between X and Z if keys==pew.K_O: basis = 'X'*(basis=='Y') + 'Y'*(basis=='X') + 'Z'*(basis=='Z') # toggle basis between X and Y if keys==pew.K_LEFT: qc.x(0) # x when LEFT is pressed if keys==pew.K_UP: qc.rx(pi/4,0) # x when UP is pressed if keys==pew.K_DOWN: qc.h(0) # h when DOWN is pressed old_keys = keys # execute the circuit and get a single sample of memory for the given measurement bases m = simulate(qc+meas[basis],shots=1,get='memory') # turn the pixels (1,2) and (1,4) (depending on basis) on or off (depending on m[0]) if m[0]=='1': if basis=='Z': screen.pixel(1,2,3) elif basis=='X': screen.pixel(1,4,3) else: screen.pixel(1,6,3) else: if basis=='Z': screen.pixel(1,2,0) elif basis=='X': screen.pixel(1,4,0) else: screen.pixel(1,6,0) # display probabilities as lines for each basis p = simulate(qc+meas['Z'],shots=1000,get='counts')['1']/1000 for j in range(0,8): if p>(j/8): screen.pixel(5,7-j,3) else: screen.pixel(5,7-j,2) p = simulate(qc+meas['X'],shots=1000,get='counts')['1']/1000 for j in range(0,8): if p>(j/8): screen.pixel(6,7-j,3) else: screen.pixel(6,7-j,2) p = simulate(qc+meas['Y'],shots=1000,get='counts')['1']/1000 for j in range(0,8): if p>(j/8): screen.pixel(7,7-j,3) else: screen.pixel(7,7-j,2) # turn the pixels not used to display m[0] to dim if basis=='Z': screen.pixel(1,4,2) screen.pixel(1,6,2) elif basis=='X': screen.pixel(1,2,2) screen.pixel(1,6,2) else: screen.pixel(1,2,2) screen.pixel(1,4,2) pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second
https://github.com/quantumjim/pewpew_qiskit_workshops
quantumjim
%matplotlib notebook import pew pew.init() screen = pew.Pix() # create a border of B=2 pixels for A in range(8): for B in [0,7]: screen.pixel(A,B,2) screen.pixel(B,A,2) # the player is a B=3 pixel X,Y = 4,6 screen.pixel(X,Y,3) while True: # loop which checks for user input and responds # use key presses to determine how the player moves dX,dY = 0,1 # default is to fall keys = pew.keys() if keys!=0: if keys&pew.K_O: # fly up with O dY = -1 # just left and right if keys&pew.K_LEFT: dX = -1 dY = 0 if keys&pew.K_RIGHT: dX = +1 dY = 0 # blank player pixel at old pos screen.pixel(X,Y,0) # change pos if Y+dY in range(1,7): Y+=dY if X+dX in range(1,7): X+=dX # put player pixel at new pos screen.pixel(X,Y,3) pew.show(screen) pew.tick(1/6) import pew from microqiskit import * pew.init() screen = pew.Pix() # set positions of doors l = (0,4) r = (7,4) u = (3,0) d = (3,7) doors = [l,r,u,d] # create a border of B=2 pixels for A in range(8): for B in [0,7]: screen.pixel(A,B,2) screen.pixel(B,A,2) # the player is a B=3 pixel X,Y = 4,6 screen.pixel(X,Y,3) # set up the circuit that decides whether doors are open qc = QuantumCircuit(2,2) # and those for measurement meas_zz = QuantumCircuit(2,2) meas_zz.measure(0,0) meas_zz.measure(1,1) meas_xx = QuantumCircuit(2,2) meas_xx.h(0) meas_xx.h(1) meas_xx.measure(0,0) meas_xx.measure(1,1) # use the results to set which doors are open m_zz = simulate(qc+meas_zz,shots=1,get='memory')[0] m_xx = simulate(qc+meas_xx,shots=1,get='memory')[0] opened = [] if m_zz[0]=='0': opened.append(l) if m_zz[1]=='0': opened.append(r) if m_xx[0]=='0': opened.append(u) if m_xx[1]=='0': opened.append(d) # set open door pixels to B=0 for door in doors: screen.pixel(door[0],door[1],2) for door in opened: screen.pixel(door[0],door[1],0) while (X,Y) not in opened: # use key presses to determine how the player moves dX,dY = 0,1 # default is to fall keys = pew.keys() if keys!=0: if keys&pew.K_O: # fly up with O dY = -1 # just left and right if keys&pew.K_LEFT: dX = -1 dY = 0 if keys&pew.K_RIGHT: dX = +1 dY = 0 # blank player pixel at old pos screen.pixel(X,Y,0) # change pos if ( Y+dY in range(1,7) and X+dX in range(1,7) ) or ( (X+dX,Y+dY) in opened ): X+=dX Y+=dY # put player pixel at new pos screen.pixel(X,Y,3) pew.show(screen) pew.tick(1/6) import pew from microqiskit import * pew.init() screen = pew.Pix() # set positions of doors l = (0,4) r = (7,4) u = (3,0) d = (3,7) doors = [l,r,u,d] # create a border of B=2 pixels for A in range(8): for B in [0,7]: screen.pixel(A,B,2) screen.pixel(B,A,2) # the player is a B=3 pixel X,Y = 4,6 screen.pixel(X,Y,3) # set up the circuit that decides whether doors are open qc = QuantumCircuit(2,2) # and those for measurement meas_zz = QuantumCircuit(2,2) meas_zz.measure(0,0) meas_zz.measure(1,1) meas_xx = QuantumCircuit(2,2) meas_xx.h(0) meas_xx.h(1) meas_xx.measure(0,0) meas_xx.measure(1,1) while True: # use the results to set which doors are open m_zz = simulate(qc+meas_zz,shots=1,get='memory')[0] m_xx = simulate(qc+meas_xx,shots=1,get='memory')[0] opened = [] if m_zz[0]=='0': opened.append(l) if m_zz[1]=='0': opened.append(r) if m_xx[0]=='0': opened.append(u) if m_xx[1]=='0': opened.append(d) # set open door pixels to B=0 for door in doors: screen.pixel(door[0],door[1],2) for door in opened: screen.pixel(door[0],door[1],0) while (X,Y) not in opened: # use key presses to determine how the player moves dX,dY = 0,1 # default is to fall keys = pew.keys() if keys!=0: if keys&pew.K_O: # fly up with O dY = -1 # just left and right if keys&pew.K_LEFT: dX = -1 dY = 0 if keys&pew.K_RIGHT: dX = +1 dY = 0 # blank player pixel at old pos screen.pixel(X,Y,0) # change pos if ( Y+dY in range(1,7) and X+dX in range(1,7) ) or ( (X+dX,Y+dY) in opened ): X+=dX Y+=dY # put player pixel at new pos screen.pixel(X,Y,3) pew.show(screen) pew.tick(1/6) if (X,Y)==u: X,Y = 3,6 if (X,Y)==d: X,Y = 3,1 if (X,Y)==l: X,Y = 6,4 if (X,Y)==r: X,Y = 1,4 import pew from microqiskit import * pew.init() screen = pew.Pix() # set positions of doors l = (0,4) r = (7,4) u = (3,0) d = (3,7) doors = [l,r,u,d] # create a border of B=2 pixels for A in range(8): for B in [0,7]: screen.pixel(A,B,2) screen.pixel(B,A,2) # the player is a B=3 pixel X,Y = 4,6 screen.pixel(X,Y,3) # set positions of the hadamard objects H = [[],[]] H[0] = [6,6] H[1] = [1,1] # set up the circuit that decides whether doors are open qc = QuantumCircuit(2,2) # and those for measurement meas_zz = QuantumCircuit(2,2) meas_zz.measure(0,0) meas_zz.measure(1,1) meas_xx = QuantumCircuit(2,2) meas_xx.h(0) meas_xx.h(1) meas_xx.measure(0,0) meas_xx.measure(1,1) qrng = QuantumCircuit(2,2) while True: # use the results to set which doors are open m_zz = simulate(qc+meas_zz,shots=1,get='memory')[0] m_xx = simulate(qc+meas_xx,shots=1,get='memory')[0] opened = [] if m_zz[0]=='0': opened.append(l) if m_zz[1]=='0': opened.append(r) if m_xx[0]=='0': opened.append(u) if m_xx[1]=='0': opened.append(d) # set open door pixels to B=0 for door in doors: screen.pixel(door[0],door[1],2) for door in opened: screen.pixel(door[0],door[1],0) frame = 0 while (X,Y) not in opened: # randomly move the positions of H[0] and H[1] for j in range(2): screen.pixel(H[j][0],H[j][1],0) m = simulate(qrng+meas_xx,shots=1,get='memory')[0] for j in range(2): dH = (m[j]=='0') - (m[j]=='1') if H[j][0]+dH in range(1,7): H[j][0]+=dH frame += 1 # brightness flashes, and so depends on frame for j in range(2): screen.pixel(H[j][0],H[j][1],1+(frame%2)) # use key presses to determine how the player moves dX,dY = 0,1 # default is to fall keys = pew.keys() if keys!=0: if keys&pew.K_O: # fly up with O dY = -1 # just left and right if keys&pew.K_LEFT: dX = -1 dY = 0 if keys&pew.K_RIGHT: dX = +1 dY = 0 # blank player pixel at old pos screen.pixel(X,Y,0) # change pos if ( Y+dY in range(1,7) and X+dX in range(1,7) ) or ( (X+dX,Y+dY) in opened ): X+=dX Y+=dY # put player pixel at new pos screen.pixel(X,Y,3) # if the player is at the same pos as H[0] or H[1] # apply the corresponding Hadamard for j in range(2): if (X,Y)==(H[j][0],H[j][1]): qc.h(j) pew.show(screen) pew.tick(1/6) if (X,Y)==u: X,Y = 3,6 if (X,Y)==d: X,Y = 3,1 if (X,Y)==l: X,Y = 6,4 if (X,Y)==r: X,Y = 1,4 import pew from microqiskit import * pew.init() screen = pew.Pix() # set positions of doors l = (0,4) r = (7,4) u = (3,0) d = (3,7) doors = [l,r,u,d] # create a border of B=2 pixels for A in range(8): for B in [0,7]: screen.pixel(A,B,2) screen.pixel(B,A,2) # the player is a B=3 pixel X,Y = 4,6 screen.pixel(X,Y,3) # set how high the player has gone up the tower height = 0 # set positions of the hadamard objects H = [[],[]] H[0] = [6,6] H[1] = [1,1] # set up the circuit that decides whether doors are open qc = QuantumCircuit(2,2) # and those for measurement meas_zz = QuantumCircuit(2,2) meas_zz.measure(0,0) meas_zz.measure(1,1) meas_xx = QuantumCircuit(2,2) meas_xx.h(0) meas_xx.h(1) meas_xx.measure(0,0) meas_xx.measure(1,1) qrng = QuantumCircuit(2,2) while height<10: # use the results to set which doors are open m_zz = simulate(qc+meas_zz,shots=1,get='memory')[0] m_xx = simulate(qc+meas_xx,shots=1,get='memory')[0] opened = [] if m_zz[0]=='0': opened.append(l) if m_zz[1]=='0': opened.append(r) if m_xx[0]=='0': opened.append(u) if m_xx[1]=='0': opened.append(d) # set open door pixels to B=0 for door in doors: screen.pixel(door[0],door[1],2) for door in opened: screen.pixel(door[0],door[1],0) frame = 0 while (X,Y) not in opened: # randomly move the positions of H[0] and H[1] for j in range(2): screen.pixel(H[j][0],H[j][1],0) m = simulate(qrng+meas_xx,shots=1,get='memory')[0] for j in range(2): dH = (m[j]=='0') - (m[j]=='1') if H[j][0]+dH in range(1,7): H[j][0]+=dH frame += 1 # brightness flashes, and so depends on frame for j in range(2): screen.pixel(H[j][0],H[j][1],1+(frame%2)) # use key presses to determine how the player moves dX,dY = 0,1 # default is to fall keys = pew.keys() if keys!=0: if keys&pew.K_O: # fly up with O dY = -1 # just left and right if keys&pew.K_LEFT: dX = -1 dY = 0 if keys&pew.K_RIGHT: dX = +1 dY = 0 # blank player pixel at old pos screen.pixel(X,Y,0) # change pos if ( Y+dY in range(1,7) and X+dX in range(1,7) ) or ( (X+dX,Y+dY) in opened ): X+=dX Y+=dY # put player pixel at new pos screen.pixel(X,Y,3) # if the player is at the same pos as H[0] or H[1] # apply the corresponding Hadamard for j in range(2): if (X,Y)==(H[j][0],H[j][1]): qc.h(j) pew.show(screen) pew.tick(1/6) if (X,Y)==u: X,Y = 3,6 height += 1 if (X,Y)==d: X,Y = 3,1 height -= 1 if (X,Y)==l: X,Y = 6,4 if (X,Y)==r: X,Y = 1,4 while True: for x in range(4): for y in range(4): m_zz = simulate(qc+meas_zz,shots=1,get='memory')[0] m_xx = simulate(qc+meas_xx,shots=1,get='memory')[0] screen.pixel(x,y,1+2*(m_zz[0]=='0')) screen.pixel(x+4,y,1+2*(m_zz[1]=='0')) screen.pixel(x,y+4,1+2*(m_xx[0]=='0')) screen.pixel(x+4,y+4,1+2*(m_xx[1]=='0')) pew.show(screen) pew.tick(1/6)
https://github.com/quantumjim/pewpew_qiskit_workshops
quantumjim
%matplotlib notebook # define a function that determines a brightness for any given point # uses a seed that is a list of four numbers def get_brightness(x,y): qc.data.clear() # empty the circuit # perform rotations, whose angles depend on x and y qc.rx((2*pi/360)*(seed[0]*x-seed[1]*y)*45,0) qc.h(0) qc.rx((2*pi/360)*(seed[2]*x+seed[3]*y**2)*45,0) # calculate probability for outcome 1 qc.measure(0,0) p = simulate(qc,shots=1000,get='counts')['1']/1000 # return brightness depending on this probability # the chosen values here are fairly arbitrarily if p>0.7: if p<0.8: return 1 elif p<0.9: return 2 else: return 3 else: return 0 from microqiskit import QuantumCircuit, simulate from math import pi from random import random seed = [random() for _ in range(4)] # initialize circuit used by the function qc = QuantumCircuit(1,1) for (x,y) in [(3,3),(3,4),(4,3),(4,4)]: print('Brightness at',(x,y),'is B =',get_brightness(x,y)) ########################################################### # Replace this comment with the `get_brightness` function # # if running anywhere other than this notebook # ########################################################### import pew from microqiskit import QuantumCircuit, simulate from math import pi from random import random pew.init() screen = pew.Pix() # initialize circuit qc = QuantumCircuit(1,1) # set a random seed, composed of four numbers seed = [random() for _ in range(4)] # loop over all points, and display the brightness for x in range(8): for y in range(8): B = get_brightness(x,y) screen.pixel(x,y,B) pew.show(screen) pew.tick(5) ########################################################### # Replace this comment with the `get_brightness` function # # if running anywhere other than this notebook # ########################################################### import pew from microqiskit import QuantumCircuit, simulate from math import * from random import random pew.init() screen = pew.Pix() # initialize circuit qc = QuantumCircuit(1,1) # set a random seed, composed of four numbers seed = [(2*(random()<0.5)-1)*(1+random())/2 for _ in range(4)] # coordinate of the current screen X,Y = 0,0 # loop to allow player to move half a screen while True: # arrow keys move to neighbouring screens keys = pew.keys() if keys!=0: if keys&pew.K_UP: Y -= 4 if keys&pew.K_DOWN: Y += 4 if keys&pew.K_LEFT: X -= 4 if keys&pew.K_RIGHT: X += 4 # loop over all points on the screen, and display the brightness for x in range(8): for y in range(8): B = get_brightness(x+X,y+Y) # coordinate of the player is accounted for also screen.pixel(x,y,B) pew.show(screen) pew.tick(1/6)
https://github.com/quantumjim/pewpew_qiskit_workshops
quantumjim
%matplotlib notebook import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen qc = QuantumCircuit(2,2) # create an empty circuit with two qubits and two output bits # create circuits with the required measurements, so we can add them in easily meas = [{},{}] for j in range(2): meas[j]['Z'] = QuantumCircuit(2,2) meas[j]['Z'].measure(j,j) meas[j]['X'] = QuantumCircuit(2,2) meas[j]['X'].h(j) meas[j]['X'].measure(j,j) basis = ['Z','Z'] # set the initial measurement basis for each qubit # loop over the squares centered on (1,2), (6,2) (1,4) and (6,4) and make all dim for (X,Y) in [(1,2),(6,2),(1,4),(6,4)]: for dX in [+1,0,-1]: for dY in [+1,0,-1]: screen.pixel(X+dX,Y+dY,2) pew.show(screen) for (X,Y) in [(1,2),(6,2),(1,4),(6,4)]: screen.pixel(X,Y,0) # turn off the center pixels of the squares old_keys = 0 while True: # loop which checks for user input and responds # look for and act upon key presses keys = pew.keys() # get current key presses if keys!=0 and keys!=old_keys: if keys&pew.K_O: basis[0] = 'X'*(basis[0]=='Z') + 'Z'*(basis[0]=='X') # toggle basis for right qubit if keys&pew.K_X: basis[1] = 'X'*(basis[1]=='Z') + 'Z'*(basis[1]=='X') # toggle basis for left qubit old_keys = keys # execute the circuit and get a single sample of memory for the given measurement bases m = simulate(qc+meas[0][basis[0]]+meas[1][basis[1]],shots=1,get='memory') # turn the pixels (1,2) and (1,4) (depending on basis[1]) on or off (depending on m[0][0]) if m[0][0]=='1': if basis[1]=='Z': screen.pixel(1,2,3) else: screen.pixel(1,4,3) else: if basis[1]=='Z': screen.pixel(1,2,0) else: screen.pixel(1,4,0) # do the same for pixels (6,2) and (6,4) if m[0][1]=='1': if basis[0]=='Z': screen.pixel(6,2,3) else: screen.pixel(6,4,3) else: if basis[0]=='Z': screen.pixel(6,2,0) else: screen.pixel(6,4,0) # turn the pixels not used to display m[0] to dim if basis[1]=='Z': screen.pixel(1,4,2) else: screen.pixel(1,2,2) if basis[0]=='Z': screen.pixel(6,4,2) else: screen.pixel(6,2,2) pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen qc = QuantumCircuit(2,2) # create an empty circuit with two qubits and two output bits # create circuits with the required measurements, so we can add them in easily meas = [{},{}] for j in range(2): meas[j]['Z'] = QuantumCircuit(2,2) meas[j]['Z'].measure(j,j) meas[j]['X'] = QuantumCircuit(2,2) meas[j]['X'].h(j) meas[j]['X'].measure(j,j) basis = ['Z','Z'] # set the initial measurement basis for each qubit # loop over the squares centered on (1,2), (6,2) (1,4) and (6,4) and make all dim for (X,Y) in [(1,2),(6,2),(1,4),(6,4)]: for dX in [+1,0,-1]: for dY in [+1,0,-1]: screen.pixel(X+dX,Y+dY,2) pew.show(screen) for (X,Y) in [(1,2),(6,2),(1,4),(6,4)]: screen.pixel(X,Y,0) # turn off the center pixels of the squares old_keys = 0 while True: # loop which checks for user input and responds # look for and act upon key presses keys = pew.keys() # get current key presses if keys!=0 and keys!=old_keys: if keys&pew.K_O: basis[0] = 'X'*(basis[0]=='Z') + 'Z'*(basis[0]=='X') # toggle basis for right qubit if keys&pew.K_X: basis[1] = 'X'*(basis[1]=='Z') + 'Z'*(basis[1]=='X') # toggle basis for left qubit if keys&pew.K_UP: qc.x(0) # x for qubit 0 when UP is pressed if keys&pew.K_LEFT: qc.x(1) # x for qubit 1 when LEFT is pressed if keys&pew.K_RIGHT: qc.h(0) # h for qubit 0 when RIGHT is pressed if keys&pew.K_DOWN: qc.h(1) # h for qubit 1 when DOWN is pressed old_keys = keys # execute the circuit and get a single sample of memory for the given measurement bases m = simulate(qc+meas[0][basis[0]]+meas[1][basis[1]],shots=1,get='memory') # turn the pixels (1,2) and (1,4) (depending on basis[1]) on or off (depending on m[0][0]) if m[0][0]=='1': if basis[1]=='Z': screen.pixel(1,2,3) else: screen.pixel(1,4,3) else: if basis[1]=='Z': screen.pixel(1,2,0) else: screen.pixel(1,4,0) # do the same for pixels (6,2) and (6,4) if m[0][1]=='1': if basis[0]=='Z': screen.pixel(6,2,3) else: screen.pixel(6,4,3) else: if basis[0]=='Z': screen.pixel(6,2,0) else: screen.pixel(6,4,0) # turn the pixels not used to display m[0] to dim if basis[1]=='Z': screen.pixel(1,4,2) else: screen.pixel(1,2,2) if basis[0]=='Z': screen.pixel(6,4,2) else: screen.pixel(6,2,2) pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen qc = QuantumCircuit(2,2) # create an empty circuit with two qubits and two output bits qc.h(0) qc.cx(0,1) # create circuits with the required measurements, so we can add them in easily meas = [{},{}] for j in range(2): meas[j]['Z'] = QuantumCircuit(2,2) meas[j]['Z'].measure(j,j) meas[j]['X'] = QuantumCircuit(2,2) meas[j]['X'].h(j) meas[j]['X'].measure(j,j) basis = ['Z','Z'] # set the initial measurement basis for each qubit # loop over the squares centered on (1,2), (6,2) (1,4) and (6,4) and make all dim for (X,Y) in [(1,2),(6,2),(1,4),(6,4)]: for dX in [+1,0,-1]: for dY in [+1,0,-1]: screen.pixel(X+dX,Y+dY,2) pew.show(screen) for (X,Y) in [(1,2),(6,2),(1,4),(6,4)]: screen.pixel(X,Y,0) # turn off the center pixels of the squares old_keys = 0 while True: # loop which checks for user input and responds # look for and act upon key presses keys = pew.keys() # get current key presses if keys!=0 and keys!=old_keys: if keys==pew.K_O: basis[0] = 'X'*(basis[0]=='Z') + 'Z'*(basis[0]=='X') # toggle basis for right qubit if keys==pew.K_X: basis[1] = 'X'*(basis[1]=='Z') + 'Z'*(basis[1]=='X') # toggle basis for left qubit if keys==pew.K_UP: qc.x(0) # x for qubit 0 when UP is pressed if keys==pew.K_LEFT: qc.x(1) # x for qubit 1 when LEFT is pressed if keys==pew.K_RIGHT: qc.h(0) # h for qubit 0 when RIGHT is pressed if keys==pew.K_DOWN: qc.h(1) # h for qubit 1 when DOWN is pressed old_keys = keys # execute the circuit and get a single sample of memory for the given measurement bases m = simulate(qc+meas[0][basis[0]]+meas[1][basis[1]],shots=1,get='memory') # turn the pixels (1,2) and (1,4) (depending on basis[1]) on or off (depending on m[0][0]) if m[0][0]=='1': if basis[1]=='Z': screen.pixel(1,2,3) else: screen.pixel(1,4,3) else: if basis[1]=='Z': screen.pixel(1,2,0) else: screen.pixel(1,4,0) # do the same for pixels (6,2) and (6,4) if m[0][1]=='1': if basis[0]=='Z': screen.pixel(6,2,3) else: screen.pixel(6,4,3) else: if basis[0]=='Z': screen.pixel(6,2,0) else: screen.pixel(6,4,0) # turn the pixels not used to display m[0] to dim if basis[1]=='Z': screen.pixel(1,4,2) else: screen.pixel(1,2,2) if basis[0]=='Z': screen.pixel(6,4,2) else: screen.pixel(6,2,2) # flag up the '11' output by lighting up pixels in the bottom-center if m[0]=='11': screen.pixel(3,6,3) screen.pixel(4,6,3) else: screen.pixel(3,6,0) screen.pixel(4,6,0) # same with '00' and the top center if m[0]=='00': screen.pixel(3,0,3) screen.pixel(4,0,3) else: screen.pixel(3,0,0) screen.pixel(4,0,0) pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen qc = QuantumCircuit(2,2) # create an empty circuit with two qubits and two output bits qc.initialize([0,0.57735,0.57735,0.57735]) # create circuits with the required measurements, so we can add them in easily meas = [{},{}] for j in range(2): meas[j]['Z'] = QuantumCircuit(2,2) meas[j]['Z'].measure(j,j) meas[j]['X'] = QuantumCircuit(2,2) meas[j]['X'].h(j) meas[j]['X'].measure(j,j) basis = ['Z','Z'] # set the initial measurement basis for each qubit # loop over the squares centered on (1,2), (6,2) (1,4) and (6,4) and make all dim for (X,Y) in [(1,2),(6,2),(1,4),(6,4)]: for dX in [+1,0,-1]: for dY in [+1,0,-1]: screen.pixel(X+dX,Y+dY,2) pew.show(screen) for (X,Y) in [(1,2),(6,2),(1,4),(6,4)]: screen.pixel(X,Y,0) # turn off the center pixels of the squares old_keys = 0 while True: # loop which checks for user input and responds # look for and act upon key presses keys = pew.keys() # get current key presses if keys!=0 and keys!=old_keys: if keys&pew.K_O: basis[0] = 'X'*(basis[0]=='Z') + 'Z'*(basis[0]=='X') # toggle basis for right qubit if keys&pew.K_X: basis[1] = 'X'*(basis[1]=='Z') + 'Z'*(basis[1]=='X') # toggle basis for left qubit if keys&pew.K_UP: qc.x(0) # x for qubit 0 when UP is pressed if keys&pew.K_LEFT: qc.x(1) # x for qubit 1 when LEFT is pressed if keys&pew.K_RIGHT: qc.h(0) # h for qubit 0 when RIGHT is pressed if keys&pew.K_DOWN: qc.h(1) # h for qubit 1 when DOWN is pressed old_keys = keys # execute the circuit and get a single sample of memory for the given measurement bases m = simulate(qc+meas[0][basis[0]]+meas[1][basis[1]],shots=1,get='memory') # turn the pixels (1,2) and (1,4) (depending on basis[1]) on or off (depending on m[0][0]) if m[0][0]=='1': if basis[1]=='Z': screen.pixel(1,2,3) else: screen.pixel(1,4,3) else: if basis[1]=='Z': screen.pixel(1,2,0) else: screen.pixel(1,4,0) # do the same for pixels (6,2) and (6,4) if m[0][1]=='1': if basis[0]=='Z': screen.pixel(6,2,3) else: screen.pixel(6,4,3) else: if basis[0]=='Z': screen.pixel(6,2,0) else: screen.pixel(6,4,0) # turn the pixels not used to display m[0] to dim if basis[1]=='Z': screen.pixel(1,4,2) else: screen.pixel(1,2,2) if basis[0]=='Z': screen.pixel(6,4,2) else: screen.pixel(6,2,2) # flag up the '11' output by lighting up pixels in the bottom-center if m[0]=='11': screen.pixel(3,6,3) screen.pixel(4,6,3) else: screen.pixel(3,6,0) screen.pixel(4,6,0) # same with '00' and the top center if m[0]=='00': screen.pixel(3,0,3) screen.pixel(4,0,3) else: screen.pixel(3,0,0) screen.pixel(4,0,0) pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second
https://github.com/adlrocha/cryptoq
adlrocha
from qiskit import execute, QuantumCircuit, QuantumRegister, ClassicalRegister, Aer from qiskit.quantum_info.operators import Operator from qiskit.quantum_info import process_fidelity from qiskit.providers.aer import QasmSimulator from qiskit.providers.aer.noise import NoiseModel, errors from qiskit.aqua.components.oracles import LogicalExpressionOracle, TruthTableOracle import math from qiskit.tools.visualization import plot_histogram import numpy as np import matplotlib.pyplot as plot from qiskit import IBMQ IBMQ.load_accounts() # ParityCircuit for random bit generator and parity bit def parityCircuitCheating(cheating=False, cheatingType=0): if cheating: # Cheating operator c1 = cheatingMatrices()[cheatingType] else: c1 = np.identity(2) id_op = Operator(c1) truthtable = "10011001" oracle = TruthTableOracle(truthtable) or_cx = oracle.construct_circuit() # print(oracle.output_register) v = oracle.variable_register o = oracle.output_register cr1 = ClassicalRegister(3) cr2 = ClassicalRegister(1) cx_circ = QuantumCircuit(v, cr2) or_cx.add_register(cr1) cx_circ.h(v[1]) cx_circ.cx(v[1], v[0]) cx_circ.unitary(id_op, v[cheatingType+1:cheatingType+2], label='idop') total_cx = cx_circ + or_cx total_cx.measure(v, cr1) total_cx.measure(o, cr2) return total_cx x = np.identity(16) theta = 0.01 x[0][0] = math.cos(theta) x[1][0] = math.sin(theta) x[0][1] = -math.sin(theta) x[1][1] = math.cos(theta) def rotationMatrix(theta): x = np.identity(2) x[0][0] = math.cos(theta) x[1][0] = math.sin(theta) x[0][1] = -math.sin(theta) x[1][1] = math.cos(theta) return x # ParityCircuit for random bit generator and parity bit def parityCircuitCheating(cheating=False, cheatingType=0): if cheating: # Cheating operator c1 = cheatingMatrices()[cheatingType] else: c1 = np.identity(2) id_op = Operator(c1) truthtable = "10011001" oracle = TruthTableOracle(truthtable) or_cx = oracle.construct_circuit() # print(oracle.output_register) v = oracle.variable_register o = oracle.output_register cr1 = ClassicalRegister(3) cr2 = ClassicalRegister(1) cx_circ = QuantumCircuit(v, cr2) or_cx.add_register(cr1) cx_circ.h(v[1]) cx_circ.cx(v[1], v[0]) cx_circ.unitary(id_op, v[cheatingType+1:cheatingType+2], label='idop') total_cx = cx_circ + or_cx total_cx.measure(v, cr1) total_cx.measure(o, cr2) return total_cx def generateQK(num_bits, theta1=0, theta2=0, securityThresh=1000, simulation=True, withHist=False): # Create the circuit cx_circ = parityCircuit(theta1, theta2) if simulation: # Execute the circuit print("Running on simulation...") job = execute(cx_circ, backend = Aer.get_backend('qasm_simulator'), shots=256*num_bits, memory=True) result = job.result() else: # Execute the circuit print("Running on real quantum computer...") job = execute(cx_circ, backend = IBMQ.get_backend('ibmqx2'), shots=256*num_bits, memory=True) result = job.result() # Print circuit. # print(cx_circ) # Print the result if withHist: counts = result.get_counts(cx_circ) plot.bar(counts.keys(), counts.values(), 1.0, color='g') plot.show() memory = result.get_memory() num_bits = int(num_bits) # memory = memory[len(memory)-num_bits: len(memory)] res = {'A': '', 'B': '', 'errorCounter':0, 'valid': True} counter = 0 i = len(memory)-1 while len(res["A"]) != num_bits: # print('Memory', memory[i], i) # Check if error in parity bit and discard if there is if memory[i][4] == '0': counter+=1 else: res["A"] = res["A"] + memory[i][1] res["B"] = res["B"] + memory[i][2] # SecurityThreshold from which we discard the key if counter >= securityThresh: res['valid'] = False res["errorCounter"] = counter return res i-=1 res["errorCounter"] = counter return res # ParityCircuit for random bit generator and parity bit def parityCircuitCheating(cheating=False, cheatingType=0): if cheating: # Cheating operator c1 = cheatingMatrices()[cheatingType] else: c1 = np.identity(2) id_op = Operator(c1) truthtable = "10011001" oracle = TruthTableOracle(truthtable) or_cx = oracle.construct_circuit() # print(oracle.output_register) v = oracle.variable_register o = oracle.output_register cr1 = ClassicalRegister(3) cr2 = ClassicalRegister(1) cx_circ = QuantumCircuit(v, cr2) or_cx.add_register(cr1) cx_circ.h(v[1]) cx_circ.cx(v[1], v[0]) cx_circ.unitary(id_op, v[cheatingType+1:cheatingType+2], label='idop') total_cx = cx_circ + or_cx total_cx.measure(v, cr1) total_cx.measure(o, cr2) return total_cx def quantumConsensus(nodes=3, cheating=False, cheatingType=[0,0,0]): # Placeholder for the nodes results res = dict(zip(string.ascii_uppercase, range(1, nodes+1))) toSend = dict(zip(string.ascii_uppercase, range(1, nodes+1))) # While two nodes with the same value while sum(res.values()) != 1: # Placeholder for all measurements pkts = '' for i in range(nodes): cx_circ = parityCircuitCheating(cheating, cheatingType[i]) job = execute(cx_circ, backend = Aer.get_backend('qasm_simulator'), shots=1, memory=True) result = job.result() memory = result.get_memory() res[list(res.keys())[i]] = int(memory[0][1]) #Adding measurements pkts += memory[0][2] pkts += memory[0][1] print(res) print(res) tmp = res.copy() for value in tmp: if res[value] == 1: res['winner'] = value # Corner case print(pkts) toSend[list(toSend.keys())[0]] = pkts[0] + pkts[len(pkts)-1] #Adding proper nodes for i in range(0, nodes): # Preparing the packets toSend[list(toSend.keys())[i]] = pkts[2*i] + pkts[2*i-1] return res, toSend def network3nodes(cheating, cheatingType): res = quantumConsensus(3, cheating, cheatingType) toSend = res[1] #TODO: Check the mistake here in the validation. # Cheat check if toSend['A'][1] == toSend['C'][0]: print('As validation correct') else: print('As validation failed. Someone cheating') if toSend['B'][1] == toSend['A'][0]: print('Bs validation correct') else: print('Bs validation failed. Someone cheating') if toSend['C'][1] == toSend['B'][0]: print('Cs validation correct') else: print('Cs validation failed. Someone cheating')
https://github.com/adlrocha/cryptoq
adlrocha
#8ec67edd7b4c8e358b08222c23234d995de520b29686a14582cf2d797ac399124c799747364b30c8b86f34b5facbcc8d72734d652645bfad82ea6a4f4a46b7b1 from qiskit import IBMQ IBMQ.load_accounts()
https://github.com/adlrocha/cryptoq
adlrocha
from qiskit import execute, QuantumCircuit, QuantumRegister, ClassicalRegister, Aer from qiskit.quantum_info.operators import Operator from qiskit.quantum_info import process_fidelity from qiskit.providers.aer import QasmSimulator from qiskit.providers.aer.noise import NoiseModel, errors from qiskit.aqua.components.oracles import LogicalExpressionOracle, TruthTableOracle import math from qiskit.tools.visualization import plot_histogram import numpy as np import matplotlib.pyplot as plot import string from qiskit import IBMQ IBMQ.load_accounts() # Noise matrix x = np.identity(16) theta = 0.01 x[0][0] = math.cos(theta) x[1][0] = math.sin(theta) x[0][1] = -math.sin(theta) x[1][1] = math.cos(theta) def cheatingMatrices(): c1 = np.identity(2) f = 1/math.sqrt(2) c1[0][0] = f c1[1][0] = -f c1[0][1] = f c1[1][1] = f c2 = np.identity(2) c2[0][0] = f c2[1][0] = f c2[0][1] = f c2[1][1] = -f return c1, c2 def rotationMatrix(theta): x = np.identity(2) x[0][0] = math.cos(theta) x[1][0] = math.sin(theta) x[0][1] = -math.sin(theta) x[1][1] = math.cos(theta) return x #theta1 and theta2 eavsdroppter error def generateQK(num_bits, theta1=0, theta2=0, securityThresh=1000, simulation=True, withHist=False): # Create the circuit cx_circ = parityCircuit(theta1, theta2) if simulation: # Execute the circuit print("Running on simulation...") job = execute(cx_circ, backend = Aer.get_backend('qasm_simulator'), shots=256*num_bits, memory=True) result = job.result() else: # Execute the circuit print("Running on real quantum computer...") job = execute(cx_circ, backend = IBMQ.get_backend('ibmqx2'), shots=256*num_bits, memory=True) result = job.result() # Print circuit. # print(cx_circ) # Print the result if withHist: counts = result.get_counts(cx_circ) plot.bar(counts.keys(), counts.values(), 1.0, color='g') plot.show() memory = result.get_memory() num_bits = int(num_bits) # memory = memory[len(memory)-num_bits: len(memory)] res = {'A': '', 'B': '', 'errorCounter':0, 'valid': True} counter = 0 i = len(memory)-1 while len(res["A"]) != num_bits: # print('Memory', memory[i], i) # Check if error in parity bit and discard if there is if memory[i][4] == '0': counter+=1 else: res["A"] = res["A"] + memory[i][1] res["B"] = res["B"] + memory[i][2] # SecurityThreshold from which we discard the key if counter >= securityThresh: res['valid'] = False res["errorCounter"] = counter return res i-=1 res["errorCounter"] = counter return res # ParityCircuit for random bit generator and parity bit def parityCircuit(theta1=0, theta2=0): # Noise rotation matrix. n1 = rotationMatrix(theta1) n2 = rotationMatrix(theta2) n = np.kron(n1, n2) # Noise operator id_op = Operator(n) truthtable = "10011001" oracle = TruthTableOracle(truthtable) or_cx = oracle.construct_circuit() # print(oracle.output_register) v = oracle.variable_register o = oracle.output_register cr1 = ClassicalRegister(3) cr2 = ClassicalRegister(1) cx_circ = QuantumCircuit(v, cr2) or_cx.add_register(cr1) cx_circ.h(v[1]) cx_circ.cx(v[1], v[0]) cx_circ.unitary(id_op, v[1:3], label='idop') total_cx = cx_circ + or_cx total_cx.measure(v, cr1) total_cx.measure(o, cr2) return total_cx # ParityCircuit for random bit generator and parity bit def parityCircuitCheating(cheating=False, cheatingType=0): if cheating: # Cheating operator c1 = cheatingMatrices()[cheatingType] else: c1 = np.identity(2) id_op = Operator(c1) truthtable = "10011001" oracle = TruthTableOracle(truthtable) or_cx = oracle.construct_circuit() # print(oracle.output_register) v = oracle.variable_register o = oracle.output_register cr1 = ClassicalRegister(3) cr2 = ClassicalRegister(1) cx_circ = QuantumCircuit(v, cr2) or_cx.add_register(cr1) cx_circ.h(v[1]) cx_circ.cx(v[1], v[0]) cx_circ.unitary(id_op, v[cheatingType+1:cheatingType+2], label='idop') total_cx = cx_circ + or_cx total_cx.measure(v, cr1) total_cx.measure(o, cr2) return total_cx def quantumConsensus(nodes=3, cheating=False, cheatingType=[0,0,0]): # Placeholder for the nodes results res = dict(zip(string.ascii_uppercase, range(1, nodes+1))) toSend = dict(zip(string.ascii_uppercase, range(1, nodes+1))) # While two nodes with the same value while sum(res.values()) != 1: # Placeholder for all measurements pkts = '' for i in range(nodes): cx_circ = parityCircuitCheating(cheating, cheatingType[i]) job = execute(cx_circ, backend = Aer.get_backend('qasm_simulator'), shots=1, memory=True) result = job.result() memory = result.get_memory() res[list(res.keys())[i]] = int(memory[0][1]) #Adding measurements pkts += memory[0][2] pkts += memory[0][1] print(res) print(res) tmp = res.copy() for value in tmp: if res[value] == 1: res['winner'] = value # Corner case print(pkts) toSend[list(toSend.keys())[0]] = pkts[0] + pkts[len(pkts)-1] #Adding proper nodes for i in range(0, nodes): # Preparing the packets toSend[list(toSend.keys())[i]] = pkts[2*i] + pkts[2*i-1] return res, toSend def network3nodes(cheating, cheatingType): res = quantumConsensus(3, cheating, cheatingType) toSend = res[1] # Cheat check if toSend['A'][1] == toSend['C'][0]: print('As validation correct') else: print('As validation failed. Someone cheating') if toSend['B'][1] == toSend['A'][0]: print('Bs validation correct') else: print('Bs validation failed. Someone cheating') if toSend['C'][1] == toSend['B'][0]: print('Cs validation correct') else: print('Cs validation failed. Someone cheating') return res[0] # print(generateQK(8, 1, 0.5, 100, False)) # print(quantumConsensus()) # print(network3nodes(False, [0,0,0])) # print(cheatingMatrices()) # print(parityCircuit())
https://github.com/anpaschool/quantum-computing
anpaschool
from qiskit import * from math import pi import numpy as np from qiskit.visualization import plot_bloch_multivector,plot_state_qsphere import matplotlib.pyplot as plt q = np.array([1.+0.j, 0.+0.j]) plot_bloch_multivector(q) plot_state_qsphere(q) q = np.array([0.+0.j, 1.+0.j]) plot_bloch_multivector(q) plot_state_qsphere(q) qc = QuantumCircuit(1) qc.barrier() qc1 = qc.copy() qc.x(0) qc.barrier() qc2 =qc.copy() qc.draw('mpl') backend = Aer.get_backend('statevector_simulator') q1 = execute(qc1,backend).result().get_statevector() q2 = execute(qc2,backend).result().get_statevector() print(q1,q2) q = np.array([1/np.sqrt(2)+0.j, 1/np.sqrt(2)+0.j]) plot_bloch_multivector(q) plot_state_qsphere(q) q = np.array([1/np.sqrt(2)+0.j, -(1/np.sqrt(2))+0.j]) plot_bloch_multivector(q) plot_state_qsphere(q) qc = QuantumCircuit(1) qc.barrier() qc1 = qc.copy() qc.h(0) qc.barrier() qc2 =qc.copy() qc.draw('mpl') backend = Aer.get_backend('statevector_simulator') q1 = execute(qc1,backend).result().get_statevector() q2 = execute(qc2,backend).result().get_statevector() print(q1,q2) qc = QuantumCircuit(1) qc.barrier() qc1 = qc.copy() qc.x(0) qc.h(0) qc.barrier() qc2 =qc.copy() qc.draw('mpl') backend = Aer.get_backend('statevector_simulator') q1 = execute(qc1,backend).result().get_statevector() q2 = execute(qc2,backend).result().get_statevector() print(q1,q2)
https://github.com/anpaschool/quantum-computing
anpaschool
from qiskit import * from math import pi from qiskit.visualization import plot_bloch_multivector # Let's do an X-gate on a |0> qubit qc = QuantumCircuit(1) qc.x(0) qc.draw('mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) plot_bloch_multivector(out) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() # Show the results print(result.get_unitary(qc, decimals=3)) # Let's do an X-gate on a |0> qubit qc = QuantumCircuit(1) qc.y(0) qc.draw('mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) plot_bloch_multivector(out) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) print(out) result = job.result() # Show the results print(result.get_unitary(qc, decimals=3)) qc = QuantumCircuit(1) qc.z(0) qc.draw(output='mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) plot_bloch_multivector(out) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) print(out) result = job.result() # Show the results print(result.get_unitary(qc, decimals=3)) # Let's do an X-gate on a |0> qubit qc = QuantumCircuit(1) qc.x(0) qc.x(0) qc.y(0) qc.y(0) qc.z(0) qc.z(0) qc.draw('mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) plot_bloch_multivector(out) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() # Show the results print(result.get_unitary(qc, decimals=3)) # Let's do an X-gate on a |0> qubit qc = QuantumCircuit(2) qc.x(0) qc.y(1) qc.draw('mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) plot_bloch_multivector(out) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() # Show the results print(result.get_unitary(qc, decimals=3)) # Let's do an X-gate on a |0> qubit qc = QuantumCircuit(2) qc.x(0) qc.y(1) qc.z(0) qc.x(1) qc.draw('mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) plot_bloch_multivector(out) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() # Show the results print(result.get_unitary(qc, decimals=3)) # Let's do an X-gate on a |0> qubit qc = QuantumCircuit(3) qc.x(0) qc.y(1) qc.z(2) qc.draw('mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) plot_bloch_multivector(out) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() # Show the results print(result.get_unitary(qc, decimals=3))
https://github.com/anpaschool/quantum-computing
anpaschool
from qiskit import * from math import pi import numpy as np from qiskit.visualization import * import matplotlib.pyplot as plt qc = QuantumCircuit(1) qc.h(0) qc.draw(output='mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) plot_bloch_multivector(out) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() # Show the results print(result.get_unitary(qc, decimals=3)) qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.barrier() qc.h(1) qc.draw(output='mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) plot_bloch_multivector(out) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() # Show the results print(result.get_unitary(qc, decimals=3)) qc = QuantumCircuit(3) qc.h(0) qc.h(1) qc.h(2) qc.barrier() qc1 = qc.copy() qc.x(0) qc.y(1) qc.z(2) qc.barrier() qc2 = qc.copy() qc.x(0) qc.y(1) qc.z(2) qc.barrier() qc3 = qc.copy() qc.h(0) qc.h(1) qc.h(2) qc.draw(output='mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) plot_bloch_multivector(out) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() # Show the results print(result.get_unitary(qc, decimals=3)) # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc1,backend).result().get_statevector() print(out) plot_bloch_multivector(out) # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc2,backend).result().get_statevector() print(out) plot_bloch_multivector(out) # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc3,backend).result().get_statevector() print(out) plot_bloch_multivector(out) qc = QuantumCircuit(1) qc.s(0) qc.draw(output='mpl') qc = QuantumCircuit(1) qc.sdg(0) qc.draw(output='mpl') qc = QuantumCircuit(1) qc.t(0) qc.draw(output='mpl') qc = QuantumCircuit(1) qc.tdg(0) qc.draw(output='mpl') qc = QuantumCircuit(1) qc.x(0) qc.barrier() qc1 = qc.copy() qc.h(0) qc.barrier() qc2 = qc.copy() qc.s(0) qc.barrier() qc3 = qc.copy() qc.s(0) qc.barrier() qc4 = qc.copy() qc.s(0) qc.barrier() qc5 = qc.copy() qc.sdg(0) qc.h(0) qc.barrier() qc6 = qc.copy() qc.draw(output='mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) plot_bloch_multivector(out) # Let's see the result backend = Aer.get_backend('statevector_simulator') for qc in [qc1,qc2,qc3,qc4,qc5,qc6]: out = execute(qc,backend).result().get_statevector() print(out)
https://github.com/anpaschool/quantum-computing
anpaschool
from qiskit import * from math import pi from qiskit.visualization import plot_bloch_multivector qc = QuantumCircuit(1) qc.u3(pi/4,pi/4,pi/4,0) qc.draw(output='mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() plot_bloch_multivector(out) qc = QuantumCircuit(1) qc.u2(pi/4,pi/4,0) qc.draw(output='mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() plot_bloch_multivector(out) qc = QuantumCircuit(1) qc.x(0) qc.u1(pi/4,0) qc.draw(output='mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) plot_bloch_multivector(out) qc = QuantumCircuit(1) qc.rx(pi/2,0) qc.draw(output='mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() plot_bloch_multivector(out) qc = QuantumCircuit(1) qc.ry(pi/2,0) qc.draw(output='mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) plot_bloch_multivector(out) qc = QuantumCircuit(1) qc.rz(pi/2,0) qc.draw(output='mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) plot_bloch_multivector(out)
https://github.com/anpaschool/quantum-computing
anpaschool
from qiskit import * from math import pi import numpy as np from qiskit.visualization import plot_bloch_multivector,plot_state_qsphere import matplotlib.pyplot as plt q = QuantumRegister(2) qc = QuantumCircuit(2) qc.cx(0,1) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) qc = QuantumCircuit(2) qc.cy(0,1) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) qc = QuantumCircuit(2) qc.cz(0,1) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) qc = QuantumCircuit(2) qc.ch(0,1) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) qc = QuantumCircuit(2) qc.crz(pi/2,0,1) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) qc = QuantumCircuit(2) qc.cu1(pi/2,0,1) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) qc = QuantumCircuit(2) qc.cu3(pi/2, pi/2, pi/2, 0,1) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) qc = QuantumCircuit(2) qc.swap(0,1) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3))
https://github.com/anpaschool/quantum-computing
anpaschool
from qiskit import * from math import pi import numpy as np from qiskit.visualization import * import matplotlib.pyplot as plt qc = QuantumCircuit(3) qc.ccx(0,1,2) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) qc = QuantumCircuit(3) qc.cswap(0,1,2) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3))
https://github.com/anpaschool/quantum-computing
anpaschool
from qiskit import * from math import pi import numpy as np from qiskit.visualization import * import matplotlib.pyplot as plt from qutip import * q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(0) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(0) qc.h(0) qc.draw(output='mpl') # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() # Show the results print(result.get_unitary(qc, decimals=3)) H = np.array([[ 0.707+0.j, 0.707-0.j],[ 0.707+0.j, -0.707+0.j]]) np.dot(H,H) q = QuantumRegister(1) qc = QuantumCircuit(q) qc.barrier() qc0 = qc.copy() qc.h(0) qc.barrier() qc1 = qc.copy() qc.x(0) qc.barrier() qc2 = qc.copy() qc.y(0) qc.barrier() qc3 = qc.copy() qc.z(0) qc.barrier() qc4 = qc.copy() qc.draw(output='mpl') # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() # Show the results print(result.get_unitary(qc, decimals=3)) X = sigmax() Y = sigmay() Z = sigmaz() H = np.array([[ 0.707+0.j, 0.707-0.j],[ 0.707+0.j, -0.707+0.j]]) np.dot(np.dot(Z,Y),np.dot(X,H)) backend = Aer.get_backend('statevector_simulator') for qc in [qc0,qc1,qc2,qc3,qc4]: out = execute(qc,backend).result().get_statevector() print(out)
https://github.com/anpaschool/quantum-computing
anpaschool
from qiskit import * from math import pi import numpy as np from qiskit.visualization import * import matplotlib.pyplot as plt from qutip import * qc = QuantumCircuit(2) qc.h(0) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) H = np.array([[ 0.707+0.j, 0.707-0.j],[ 0.707+0.j, -0.707+0.j]]) I = np.eye(2) np.kron(I,H) qc = QuantumCircuit(2) qc.h(1) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) H = np.array([[ 0.707+0.j, 0.707-0.j],[ 0.707+0.j, -0.707+0.j]]) I = np.eye(2) np.kron(H,I) q = QuantumRegister(2) qc = QuantumCircuit(q) qc.h(0) qc.h(1) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) H = np.array([[ 0.707+0.j, 0.707-0.j],[ 0.707+0.j, -0.707+0.j]]) np.kron(H,H) qc = QuantumCircuit(2) qc.barrier() qc0 = qc.copy() qc.h(0) qc.x(1) qc.barrier() qc1 = qc.copy() qc.y(0) qc.h(1) qc.barrier() qc2 = qc.copy() qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) H = np.array([[ 0.707+0.j, 0.707-0.j],[ 0.707+0.j, -0.707+0.j]]) X = sigmax() Y = sigmay() XKH = np.kron(X,H) HKY = np.kron(H,Y) np.dot(HKY,XKH) backend = Aer.get_backend('statevector_simulator') qc_vec = [] for qc in [qc0,qc1,qc2]: out = execute(qc,backend).result().get_statevector() qc_vec.append(out) print(out) qca = QuantumCircuit(1) qca.barrier() qca0 = qca.copy() qca.h(0) qca.barrier() qca1 = qca.copy() qca.y(0) qca.barrier() qca2 = qca.copy() qca.draw(output='mpl') backend = Aer.get_backend('statevector_simulator') qca_vec = [] for qc in [qca0,qca1,qca2]: out = execute(qc,backend).result().get_statevector() qca_vec.append(out) print(out) qcb = QuantumCircuit(1) qcb.barrier() qcb0 = qcb.copy() qcb.x(0) qcb.barrier() qcb1 = qcb.copy() qcb.h(0) qcb.barrier() qcb2 = qcb.copy() qcb.draw(output='mpl') backend = Aer.get_backend('statevector_simulator') qcb_vec = [] for qc in [qcb0,qcb1,qcb2]: out = execute(qc,backend).result().get_statevector() qcb_vec.append(out) print(out) for qcv,qcav,qcbv in zip(qc_vec,qca_vec,qcb_vec): print(qcv,"|", np.kron(qcbv,qcav))
https://github.com/anpaschool/quantum-computing
anpaschool
from qiskit import * from math import pi import numpy as np from qiskit.visualization import * import matplotlib.pyplot as plt from qutip import * q = QuantumRegister(3) qc = QuantumCircuit(q) qc.u3(pi/2,pi/2,pi/2,q[0]) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) q = QuantumRegister(3) qc = QuantumCircuit(q) qc.u3(pi/2,pi/2,pi/2,q[1]) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) q = QuantumRegister(3) qc = QuantumCircuit(q) qc.u3(pi/2,pi/2,pi/2,q[2]) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) q = QuantumRegister(3) qc = QuantumCircuit(q) qc.u3(pi/2,pi/2,pi/2,q[0]) qc.u3(pi/2,pi/2,pi/2,q[1]) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) q = QuantumRegister(3) qc = QuantumCircuit(q) qc.u3(pi/2,pi/2,pi/2,q[0]) qc.u3(pi/2,pi/2,pi/2,q[1]) qc.u3(pi/2,pi/2,pi/2,q[2]) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) q = QuantumRegister(3) qc = QuantumCircuit(q) qc.u3(pi/2,pi/2,pi/2,q[0]) qc.u3(pi/2,pi/2,pi/2,q[0]) qc.u3(pi/4,pi/4,pi/4,q[1]) qc.u3(3*pi/4,3*pi/4,3*pi/4,q[1]) qc.u3(pi/6,pi/6,pi/6,q[2]) qc.u3(5*pi/6,5*pi/6,5*pi/6,q[2]) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3))
https://github.com/anpaschool/quantum-computing
anpaschool
from qiskit import * from math import pi import numpy as np from qiskit.visualization import * import matplotlib.pyplot as plt from qutip import * q = QuantumRegister(2) qc = QuantumCircuit(q) qc.cu1(pi/2,q[0], q[1]) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) q = QuantumRegister(3) qc = QuantumCircuit(q) qc.u3(pi/2,pi/2,pi/2,q[0]) qc.cu1(pi/2,q[0], q[1]) qc.u3(pi/2,pi/2,pi/2,q[1]) qc.cu1(pi/2,q[1], q[2]) qc.u3(pi/2,pi/2,pi/2,q[2]) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) q = QuantumRegister(4) qc = QuantumCircuit(q) qc.u3(pi/2,pi/2,pi/2,q[0]) qc.cu1(pi/2,q[0], q[1]) qc.u2(pi/2,pi/2,q[1]) qc.u1(pi/2,q[2]) qc.x(q[0]) qc.ccx(q[1],q[2],q[3]) qc.y(q[1]) qc.z(q[2]) qc.cx(q[2],q[3]) qc.z(q[3]) qc.h(q[3]) qc.s(q[0]) qc.cu1(pi/2,q[1], q[2]) qc.swap(q[0],q[2]) qc.cswap(q[0],q[1],q[3]) qc.draw(output='mpl') backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3))
https://github.com/anpaschool/quantum-computing
anpaschool
from qiskit import * from math import pi import numpy as np from qiskit.visualization import * import matplotlib.pyplot as plt from qutip import * qc = QuantumCircuit(2) qc.barrier() qc.h(0) qc.cx(0, 1) qc.barrier() qc.draw('mpl') backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) I = np.eye(2,2) H = 1/np.sqrt(2)*np.array([[1,1],[1,-1]]) CNOT = np.array([[1,0,0,0],[0,0,0,1],[0,0,1,0],[0,1,0,0]]) IKH = np.kron(I,H) U = np.dot(CNOT,IKH) print(U) backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) ket_00 = np.array([1,0,0,0]) np.dot(U,ket_00) qc = QuantumCircuit(2) qc.x(1) qc.barrier() qc.h(0) qc.cx(0, 1) qc.barrier() qc.draw('mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) qc = QuantumCircuit(2) qc.x(0) qc.barrier() qc.h(0) qc.cx(0, 1) qc.barrier() qc.draw('mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) qc = QuantumCircuit(2) qc.x(0) qc.x(1) qc.barrier() qc.h(0) qc.cx(0, 1) qc.barrier() qc.draw('mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out)
https://github.com/anpaschool/quantum-computing
anpaschool
%matplotlib inline import numpy as np import IPython import matplotlib.pyplot as plt from qiskit import QuantumCircuit,ClassicalRegister,QuantumRegister from qiskit import BasicAer from qiskit.tools.jupyter import * from qiskit.visualization import * import seaborn as sns sns.set() from helper import * def circuit1(): qc = QuantumCircuit(2,2) qc.h(0) return qc hqc = circuit1() drawCircuit_2q(hqc) hqc = circuit1() writeState(hqc) hqc = circuit1() simCircuit(hqc) hqc = circuit1() blochSphere(hqc) hqc = circuit1() drawCircuit_2q(hqc) I = np.eye(2,2) H = 1/np.sqrt(2)*np.array([[1,1],[1,-1]]) U = np.kron(I,H) print(U) ket_00 = np.array([1,0,0,0]) np.dot(U,ket_00) hqc = circuit1() plotMatrix(hqc) def circuit2(): qc = QuantumCircuit(2,2) qc.h(0) qc.h(1) return qc hqc = circuit2() drawCircuit_2q(hqc) hqc = circuit2() writeState(hqc) def getPhaseSeq(): phaseDic = [] qc0 = QuantumCircuit(2,2) qc1 = QuantumCircuit(2,2) qc1.h(0) qc1.h(1) for iqc in [qc0,qc1]: phaseDic.append(getPhase(iqc)) return phaseDic drawPhase(getPhaseSeq()) hqc = circuit2() simCircuit(hqc) hqc = circuit2() drawCircuit_2q(hqc) H = 1/np.sqrt(2)*np.array([[1,1],[1,-1]]) U = np.kron(H,H) print(U) ket = np.array([1,0,0,0]) np.dot(U,ket) hqc = circuit2() plotMatrix(hqc) n = 3 q = QuantumRegister(n) c = ClassicalRegister(n) hqc3 = QuantumCircuit(q,c) for k in range(3): hqc3.h(q[k]) hqc3.barrier() hqc3.measure(q,c) style = {'backgroundcolor': 'lavender'} hqc3.draw(output='mpl', style = style)
https://github.com/anpaschool/quantum-computing
anpaschool
from qiskit import * from math import pi import numpy as np from qiskit.visualization import * import matplotlib.pyplot as plt from qutip import * qc = QuantumCircuit(2) qc.h(1) qc.barrier() qc.cu1(np.pi/2, 0, 1) qc.barrier() qc.h(0) qc.barrier() qc.swap(0,1) qc.draw('mpl') backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() print(result.get_unitary(qc, decimals=3)) I = np.eye(2,2) H = 1/np.sqrt(2)*np.array([[1,1],[1,-1]]) H_kron_I = np.kron(H,I) CU1 = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,0.+1.j]]) I_kron_H = np.kron(I,H) SWAP = np.array([[1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]]) U = np.dot(H_kron_I,np.dot(CU1,np.dot(I_kron_H,SWAP))) U ket = np.array([1,0,0,0]) np.dot(U,ket) def qft3(): n = 3 q = QuantumRegister(n) c = ClassicalRegister(n) qc = QuantumCircuit(q,c) qc.h(q[2]) qc.barrier() qc.cu1(np.pi/2, q[1], q[2]) qc.barrier() qc.h(q[1]) qc.barrier() qc.cu1(np.pi/4, q[0], q[2]) qc.barrier() qc.cu1(np.pi/2, q[0], q[1]) qc.barrier() qc.h(q[0]) qc.barrier() qc.swap(q[0], q[2]) return q,c,qc q,c,qc = qft3() qc.barrier() qc.draw(output='mpl') backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out)
https://github.com/anpaschool/quantum-computing
anpaschool
https://github.com/anpaschool/quantum-computing
anpaschool
https://github.com/anpaschool/quantum-computing
anpaschool
# Useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np from math import pi from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit import Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.visualization import * from qiskit.providers.aer import UnitarySimulator from qiskit.tools.visualization import circuit_drawer from qiskit.quantum_info import state_fidelity from qiskit import BasicAer backend = BasicAer.get_backend('unitary_simulator') qr = QuantumRegister(2) cr = ClassicalRegister(2) groverCircuit = QuantumCircuit(qr,cr) groverCircuit.h(qr) groverCircuit.draw(output="mpl") job = execute(groverCircuit, backend) job.result().get_unitary(groverCircuit, decimals=3) groverCircuit.measure(qr,cr) groverCircuit.draw(output="mpl") simulator = Aer.get_backend('qasm_simulator') result = execute(groverCircuit, simulator).result() counts = result.get_counts(groverCircuit) plot_histogram(counts, title='Grover Intermediate measurement') qr = QuantumRegister(2) cr = ClassicalRegister(2) groverCircuit = QuantumCircuit(qr,cr) groverCircuit.h(qr) '''oracle w = |00>''' groverCircuit.x(qr) groverCircuit.cz(qr[0],qr[1]) groverCircuit.x(qr) groverCircuit.draw(output="mpl") job = execute(groverCircuit, backend) job.result().get_unitary(groverCircuit, decimals=3) INIT = 0.5*np.array([[1,1,1,1],[1,-1,1,-1],[1,1,-1,-1],[1,-1,-1,1]]) CZ = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,-1]]) XX = np.array([[0,0,0,1],[0,0,1,0],[0,1,0,0],[1,0,0,0]]) '''Oracle''' ORCL = np.dot(XX,np.dot(CZ,XX)) print(ORCL) '''FUll circuit matrix so far''' np.dot(ORCL,INIT) groverCircuit.measure(qr,cr) groverCircuit.draw(output="mpl") simulator = Aer.get_backend('qasm_simulator') result = execute(groverCircuit, simulator).result() counts = result.get_counts(groverCircuit) plot_histogram(counts, title='Grover Intermediate measurement') qr = QuantumRegister(2) cr = ClassicalRegister(2) groverCircuit = QuantumCircuit(qr,cr) groverCircuit.h(qr) '''oracle w = |00>''' groverCircuit.x(qr) groverCircuit.cz(qr[0],qr[1]) groverCircuit.x(qr) '''Grover Transform''' groverCircuit.h(qr) '''Reflection''' groverCircuit.z(qr) groverCircuit.cz(qr[0],qr[1]) '''end of Reflection''' groverCircuit.h(qr) '''end of Grover Transform''' groverCircuit.draw(output="mpl") job = execute(groverCircuit, backend) job.result().get_unitary(groverCircuit, decimals=3) HH = 0.5*np.array([[1,1,1,1],[1,-1,1,-1],[1,1,-1,-1],[1,-1,-1,1]]) ZZ = np.array([[1,0,0,0],[0,-1,0,0],[0,0,-1,0],[0,0,0,1]]) '''Grover Transform''' GT = np.dot(HH,np.dot(CZ,np.dot(ZZ,HH))) print(GT) '''FUll circut matrix''' np.dot(INIT,np.dot(ORCL,GT)) simulator = Aer.get_backend('qasm_simulator') result = execute(groverCircuit, simulator).result() counts = result.get_counts(groverCircuit) plot_histogram(counts, title='Grover Intermediate measurement')
https://github.com/dhanton/quantum-chess
dhanton
import itertools from qiskit import * from . import qutils from qchess.point import Point from qchess.piece import * from qchess.pawn import Pawn from qchess.engines.base_engine import BaseEngine class QiskitEngine(BaseEngine): def __init__(self, qchess, width, height): self.qchess = qchess self.classical_board = qchess.board self.width = width self.height = height NullPiece.qflag = 0 self.qflag_index = 0 if width * height > qutils.MAX_QUBIT_MEMORY: print() print('-----------WARNING-----------') print('Maximum number of qubits exceeded') print('You can still play the game, but the program might crash if the system becomes too entangled') print() self.generate_circuit() def generate_circuit(self): #board main quantum register self.qregister = QuantumRegister(self.width * self.height) #ancilla qubits used for some intermediate operations self.aregister = QuantumRegister(3) #ancilla qubits used by the mct function in qutils self.mct_register = QuantumRegister(6) #classical bits to collapse each square individually self.cregister = ClassicalRegister(self.width * self.height) #classical bit for other operations self.cbit_misc = ClassicalRegister(1) self.qcircuit = QuantumCircuit(self.qregister, self.aregister, self.mct_register, self.cregister, self.cbit_misc) #populate the qubits if pieces already exist for i in range(self.width * self.height): if self.qchess.get_piece(i) != NullPiece: self.qcircuit.x(self.qregister[i]) def on_add_piece(self, x, y, piece): piece.qflag = 1 << self.qflag_index self.qflag_index += 1 #the value is already |0> (no piece) #since we want to add the piece with 100% probability, we swap to |1> q1 = self.get_qubit(x, y) self.qcircuit.x(q1) def on_pawn_promotion(self, promoted_pawn, pawn): promoted_pawn.qflag = pawn.qflag def get_qubit(self, x, y): return self.qregister[self.qchess.get_array_index(x, y)] def get_bit(self, x, y): return self.cregister[self.qchess.get_array_index(x, y)] def get_all_entangled_points(self, x, y): points = [] qflag = self.classical_board[x][y].qflag if qflag != 0: for i in range(self.width): for j in range(self.height): if self.classical_board[i][j].qflag & qflag != 0: points.append(Point(i, j)) return points def entangle_flags(self, qflag1, qflag2): #nullpiece if not qflag1 or not qflag2: return #already entangled if qflag1 & qflag2 != 0: return for i in range(self.width * self.height): piece = self.qchess.get_piece(i) if piece.qflag & qflag1 != 0: piece.qflag |= qflag2 elif piece.qflag & qflag2 != 0: piece.qflag |= qflag1 def entangle_path_flags(self, qflag, source, target): all_qflags = 0 pieces = self.qchess.get_path_pieces(source, target) for piece in pieces: all_qflags |= piece.qflag self.entangle_flags(all_qflags, qflag) return bool(pieces) def collapse_by_flag(self, qflag, collapse_all=False): #nullpiece if not qflag and not collapse_all: return collapsed_indices = [] for i in range(self.width * self.height): piece = self.qchess.get_piece(i) if ( not piece.collapsed and piece != NullPiece and (collapse_all or piece.qflag & qflag != 0) ): #measure the ith qubit to the ith bit self.qcircuit.measure(self.qregister[i], self.cregister[i]) collapsed_indices.append(i) if collapsed_indices: job = execute(self.qcircuit, backend=qutils.backend, shots=1) result = job.result() bitstring = list(result.get_counts().keys())[0].split(' ')[1] for i, char in enumerate(bitstring[::-1]): pos = self.qchess.get_board_point(i) if char == '0' and i in collapsed_indices: self.classical_board[pos.x][pos.y] = NullPiece #set to |0> in circuit self.qcircuit.reset(self.qregister[i]) if char == '1' and i in collapsed_indices: #set to |1> in circuit self.qcircuit.reset(self.qregister[i]) self.qcircuit.x(self.qregister[i]) piece = self.qchess.get_piece(i) assert(piece != NullPiece) piece.collapsed = True #since we can't be 100% sure of the original qflag of a piece #we assign them at random from the qflag used to collapse #(note: binary qflag has as many '1's as the number of collapsed pieces) if not collapse_all: #find the position of the first '1' in binary qflag binary_qflag = bin(qflag)[2:] index = len(binary_qflag) - binary_qflag.find('1') - 1 #there should always be enough '1's for every collapsed piece assert(index < len(bin(qflag))) #generate a new qflag with all '0's except a '1' in that position new_qflag = 1 << index #remove the '1' in that position from binary qflag qflag ^= new_qflag #assign new original qflag piece.qflag = new_qflag #assign new qflags to all the pieces if collapse_all: self.qflag_index = 0 for i in range(self.height * self.width): piece = self.qchess.get_piece(i) if piece == NullPiece: continue piece.qflag = 1 << self.qflag_index self.qflag_index += 1 all_collapsed = collapse_all if not all_collapsed: all_collapsed = True for i in range(self.width * self.height): if not self.qchess.get_piece(i).collapsed: all_collapsed = False break #the circuit is reset when all pieces are collapsed, even if #no new pieces were collapsed in this call #when all the qubits are |0> or |1>, it's cheaper to just reset #the circuit than to keep track of all the qubits operations if all_collapsed: self.generate_circuit() def set_piece_uncollapsed(self, point): if self.classical_board[point.x][point.y] != NullPiece: self.classical_board[point.x][point.y].collapsed = False def collapse_path(self, source, target, collapse_target=False, collapse_source=False): qflag = 0 for piece in self.qchess.get_path_pieces(source, target): qflag |= piece.qflag source_piece = self.classical_board[source.x][source.y] if source_piece != NullPiece and collapse_source: #force the piece to get collapsed source_piece.collapsed = False qflag |= source_piece.qflag target_piece = self.classical_board[target.x][target.y] if target_piece != NullPiece and collapse_source: #force the piece to get collapsed target_piece.collapsed = False qflag |= target_piece.qflag self.collapse_by_flag(qflag) #return true if path is clear after collapse return not bool(self.qchess.get_path_pieces(source, target)) def collapse_point(self, x, y): self.collapse_by_flag(self.classical_board[x][y].qflag) def collapse_all(self): self.collapse_by_flag(None, collapse_all=True) """ The idea of this function is to calculate all posible permutations of the pieces entangled with target to see if, in any of the combinations, target is not empty and the path is blocked at the same time. This would violate double occupancy so a measurement has to be performed. """ def does_slide_violate_double_occupancy(self, source, target): target_piece = self.classical_board[target.x][target.y] if target_piece == NullPiece: #target is always empty return False entangled_points = [] path = self.qchess.get_path_points(source, target) for i in range(self.width * self.height): point = self.qchess.get_board_point(i) if self.classical_board[point.x][point.y].qflag & target_piece.qflag != 0: entangled_points.append(point) #if a piece is blocking the path independently of the entanglement #of target, then DO is violated for point in path: if self.classical_board[point.x][point.y] != NullPiece and not point in entangled_points: return True #the number of pieces is the number of 1s in the target qflag number_of_pieces = list(bin(target_piece.qflag)).count('1') assert(len(entangled_points) >= number_of_pieces) #contains 1 for each piece and the rest are zeroes (empty squares) permutations = [1] * number_of_pieces + [0] * (len(entangled_points) - number_of_pieces) #unique permutations of number of pieces in all points permutations = set(list(itertools.permutations(permutations))) for perm in permutations: blocked = False target_empty = True #entangled_points and all permutations have the same length #so they correspond to the same point for the same index for i, point in enumerate(entangled_points): if point in path and perm[i] == 1: blocked = True if point == target and perm[i] == 1: target_empty = False if blocked and not target_empty: return True return False def standard_move(self, source, target, force=False): piece = self.classical_board[source.x][source.y] if not force and piece.type == PieceType.PAWN: return self._standard_pawn_move(source, target) target_piece = self.classical_board[target.x][target.y] if target_piece == NullPiece or target_piece == piece: if piece.is_move_slide(): if self.entangle_path_flags(piece.qflag, source, target): piece.collapsed = False #if something may be blocking then the piece might stay in place #so we don't want to remove it clasically if target_piece == NullPiece: target_piece = piece qutils.perform_standard_slide(self, source, target) else: qutils.perform_standard_jump(self, source, target) self.classical_board[source.x][source.y] = target_piece.copy() self.classical_board[target.x][target.y] = piece.copy() else: if target_piece.color == piece.color: self.collapse_by_flag(target_piece.qflag) if ( self.classical_board[source.x][source.y] != NullPiece and self.classical_board[target.x][target.y] == NullPiece ): new_source_piece = NullPiece if piece.is_move_slide(): if self.entangle_path_flags(piece.qflag, source, target): #if something may be blocking then the piece might stay in place #so we don't want to remove it clasically piece.collapsed = False new_source_piece = piece qutils.perform_standard_slide(self, source, target) else: qutils.perform_standard_jump(self, source, target) self.classical_board[source.x][source.y] = new_source_piece.copy() self.classical_board[target.x][target.y] = piece.copy() else: self.collapse_by_flag(piece.qflag) if self.classical_board[source.x][source.y] != NullPiece: path_empty = self.qchess.is_path_empty(source, target) #if the path is empty the move is just a jump if piece.is_move_slide() and not path_empty: """ Afer qutils.perform_capture_slide the path is collapsed already unless does_slide_violate_double_occupancy returns 0, in which case entanglement occurs. We call collapse_path to update the classical board. """ if qutils.perform_capture_slide(self, source, target): if self.does_slide_violate_double_occupancy(source, target): path_clear = self.collapse_path(source, target, collapse_source=True) if path_clear and self.classical_board[source.x][source.y] == NullPiece: self.classical_board[target.x][target.y] = piece.copy() else: if not self.entangle_path_flags(piece.qflag, source, target): self.classical_board[source.x][source.y] = NullPiece else: piece.collapsed = False self.classical_board[target.x][target.y] = piece.copy() else: path_clear = self.collapse_path(source, target, collapse_source=True) if path_clear and self.classical_board[source.x][source.y] == NullPiece: self.classical_board[target.x][target.y] = piece.copy() else: qutils.perform_capture_jump(self, source, target) self.classical_board[source.x][source.y] = NullPiece self.classical_board[target.x][target.y] = piece.copy() def _standard_pawn_move(self, source, target): pawn = self.classical_board[source.x][source.y] target_piece = self.classical_board[target.x][target.y] move_type, ep_point = pawn.is_move_valid(source, target, qchess=self.qchess) #this is checked in QChess class assert(move_type != Pawn.MoveType.INVALID) if ( move_type == Pawn.MoveType.SINGLE_STEP or move_type == Pawn.MoveType.DOUBLE_STEP ): self.collapse_by_flag(target_piece.qflag) if ( self.classical_board[source.x][source.y] != NullPiece and self.classical_board[target.x][target.y] == NullPiece ): if move_type == Pawn.MoveType.SINGLE_STEP: qutils.perform_standard_jump(self, source, target) self.classical_board[source.x][source.y] = NullPiece else: if not self.entangle_path_flags(pawn.qflag, source, target): self.classical_board[source.x][source.y] = NullPiece else: pawn.collapsed = False qutils.perform_standard_slide(self, source, target) self.classical_board[target.x][target.y] = pawn.copy() elif move_type == Pawn.MoveType.CAPTURE: #pawn is the only piece that needs to collapse target when capturing #because it can't move diagonally unless capturing self.collapse_by_flag(pawn.qflag | target_piece.qflag) if ( self.classical_board[source.x][source.y] != NullPiece and self.classical_board[target.x][target.y] != NullPiece ): qutils.perform_capture_jump(self, source, target) self.classical_board[source.x][source.y] = NullPiece self.classical_board[target.x][target.y] = pawn.copy() elif move_type == Pawn.MoveType.EN_PASSANT: if target_piece == NullPiece: qutils.perform_standard_en_passant(self, source, target, ep_point) self.classical_board[source.x][source.y] = NullPiece self.classical_board[target.x][target.y] = pawn self.classical_board[ep_point.x][ep_point.y] = NullPiece elif target_piece.color == pawn.color: self.collapse_by_flag(target_piece.qflag) if self.classical_board[target.x][target.y] == NullPiece: qutils.perform_standard_en_passant(self, source, target, ep_point) self.classical_board[source.x][source.y] = NullPiece self.classical_board[target.x][target.y] = pawn.copy() self.classical_board[ep_point.x][ep_point.y] = NullPiece else: self.collapse_by_flag(pawn.qflag) if self.classical_board[source.x][source.y] != NullPiece: qutils.perform_capture_en_passant(self, source, target, ep_point) self.classical_board[source.x][source.y] = NullPiece self.classical_board[target.x][target.y] = pawn.copy() self.classical_board[ep_point.x][ep_point.y] = NullPiece def split_move(self, source, target1, target2): piece = self.classical_board[source.x][source.y] target_piece1 = self.classical_board[target1.x][target1.y] target_piece2 = self.classical_board[target2.x][target2.y] #the source piece is always swapped with the target2 #so unless the path is blocked we know what piece target2 has new_source_piece = target_piece2 if piece.is_move_slide(): qutils.perform_split_slide(self, source, target1, target2) path1_blocked = self.entangle_path_flags(piece.qflag, source, target1) path2_blocked = self.entangle_path_flags(piece.qflag, source, target2) #set the source piece to null if any of the paths is not blocked, #since the piece will always slide through that one if the other is blocked if path1_blocked and path2_blocked and new_source_piece == NullPiece: new_source_piece = piece new_source_piece.collapsed = False else: qutils.perform_split_jump(self, source, target1, target2) if not piece.collapsed or not target_piece1.collapsed: #entangle only the pieces affected by iSwap_sqrt self.entangle_flags(piece.qflag, target_piece1.qflag) if target_piece1 == NullPiece: self.classical_board[target1.x][target1.y] = piece.copy() self.classical_board[target2.x][target2.y] = piece.copy() self.classical_board[source.x][source.y] = new_source_piece.copy() #only uncollapse the pieces if state |t1, t2> is not |00> or |11> #because iSwap_sqrt leaves these states untouched if target_piece1 == NullPiece: self.set_piece_uncollapsed(target1) self.set_piece_uncollapsed(target2) def merge_move(self, source1, source2, target): piece1 = self.classical_board[source1.x][source1.y] piece2 = self.classical_board[source2.x][source2.y] target_piece = self.classical_board[target.x][target.y] #the target piece is always swapped with the source2 #so unless the path is blocked we know what piece source2 has new_source2_piece = target_piece if piece1.is_move_slide(): qutils.perform_merge_slide(self, source1, source2, target) self.entangle_path_flags(piece1.qflag, source1, target) path2_blocked = self.entangle_path_flags(piece2.qflag, source2, target) if path2_blocked and new_source2_piece == NullPiece: new_source2_piece = piece1 new_source2_piece.collapsed = False else: qutils.perform_merge_jump(self, source1, source2, target) if not piece1.collapsed or not piece2.collapsed: #entangle only the pieces affected by iSwap_sqrt self.entangle_flags(piece1.qflag, piece2.qflag) if target_piece == NullPiece: self.classical_board[target.x][target.y] = piece1.copy() self.classical_board[source1.x][source1.y] = piece2.copy() self.classical_board[source2.x][source2.y] = new_source2_piece.copy() if target_piece == NullPiece: self.set_piece_uncollapsed(source1) self.set_piece_uncollapsed(target) def castling_move(self, king_source, rook_source, king_target, rook_target): king = self.classical_board[king_source.x][king_source.y] rook = self.classical_board[rook_source.x][rook_source.y] king_target_piece = self.classical_board[king_target.x][king_target.y] rook_target_piece = self.classical_board[rook_target.x][rook_target.y] #collapse target pieces self.collapse_by_flag(king_target_piece.qflag | rook_target_piece.qflag) #if both targets are empty if ( self.classical_board[king_target.x][king_target.y] == NullPiece and self.classical_board[rook_target.x][rook_target.y] == NullPiece ): #the path doesn't neccesarily have to be the shortest straight path #between king and rook king_path = self.qchess.get_path_points(king_source, king_target) rook_path = self.qchess.get_path_points(rook_source, rook_target) # in general it's the unique combination of their paths path = [] for point in king_path + rook_path: if point == king_target or point == rook_target: continue #we don't need to include empty squares if self.classical_board[point.x][point.y] == NullPiece: continue if not point in path: path.append(point) #exclude king_target and rook_target just in case if king_target in path: path.remove(king_target) if rook_target in path: path.remove(rook_target) #perform the quantum move qutils.perform_castle(self, king_source, rook_source, king_target, rook_target, path) if not path: #remove from source only if path is empty self.classical_board[king_source.x][king_source.y] = NullPiece self.classical_board[rook_source.x][rook_source.y] = NullPiece else: #entangle with all the pieces in the path path_qflags = 0 for point in path: path_qflags |= self.classical_board[point.x][point.y].qflag self.entangle_flags(king.qflag, rook.qflag) self.entangle_flags(path_qflags, king.qflag) king.collapsed = False rook.collapsed = False self.classical_board[king_target.x][king_target.y] = king.copy() self.classical_board[rook_target.x][rook_target.y] = rook.copy()
https://github.com/dhanton/quantum-chess
dhanton
import math from qiskit import QuantumCircuit, QuantumRegister from qiskit.quantum_info.operators import Operator from qiskit import Aer from qiskit import execute from qiskit.tools.visualization import plot_histogram backend = Aer.get_backend('qasm_simulator') MAX_QUBIT_MEMORY = backend.MAX_QUBIT_MEMORY b = math.sqrt(2) iSwap = Operator([ [1, 0, 0, 0], [0, 0, 1j, 0], [0, 1j, 0, 0], [0, 0, 0, 1], ]) #when the controlled qubit holds if a path is clear #then this gate can be understood as the slide gate iSwap_controlled = Operator([ [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1j, 0, 0, 0, 0, 0], [0, 1j, 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], ]) iSwap_sqrt = Operator([ [1, 0, 0, 0], [0, 1/b, 1j/b, 0], [0, 1j/b, 1/b, 0], [0, 0, 0, 1], ]) #in base s, t, control iSwap_sqrt_controlled = Operator([ [1, 0, 0, 0, 0, 0, 0, 0], [0, 1/b, 1j/b, 0, 0, 0, 0, 0], [0, 1j/b, 1/b, 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], ]) def perform_standard_jump(engine, source, target): qsource = engine.get_qubit(source.x, source.y) qtarget = engine.get_qubit(target.x, target.y) engine.qcircuit.unitary(iSwap, [qsource, qtarget], label='iSwap') def perform_capture_jump(engine, source, target): qsource = engine.get_qubit(source.x, source.y) qtarget = engine.get_qubit(target.x, target.y) #this ancilla qubit is going to hold the captured piece captured_piece = engine.aregister[0] engine.qcircuit.reset(captured_piece) engine.qcircuit.unitary(iSwap, [qtarget, captured_piece], label='iSwap') engine.qcircuit.unitary(iSwap, [qsource, qtarget], label='iSwap') def perform_split_jump(engine, source, target1, target2): qsource = engine.get_qubit(source.x, source.y) qtarget1 = engine.get_qubit(target1.x, target1.y) qtarget2 = engine.get_qubit(target2.x, target2.y) engine.qcircuit.unitary(iSwap_sqrt, [qtarget1, qsource], label='iSwap_sqrt') engine.qcircuit.unitary(iSwap, [qsource, qtarget2], label='iSwap') def perform_merge_jump(engine, source1, source2, target): qsource1 = engine.get_qubit(source1.x, source1.y) qsource2 = engine.get_qubit(source2.x, source2.y) qtarget = engine.get_qubit(target.x, target.y) engine.qcircuit.unitary(iSwap, [qtarget, qsource2], label='iSwap') engine.qcircuit.unitary(iSwap_sqrt, [qsource1, qtarget], label='iSwap_sqrt') def perform_standard_slide(engine, source, target): control_qubits = [] for point in engine.qchess.get_path_points(source, target): control_qubits.append(engine.get_qubit(point.x, point.y)) engine.qcircuit.x(engine.get_qubit(point.x, point.y)) qsource = engine.get_qubit(source.x, source.y) qtarget = engine.get_qubit(target.x, target.y) path_ancilla = engine.aregister[0] engine.qcircuit.reset(path_ancilla) engine.qcircuit.x(path_ancilla) engine.qcircuit.mct(control_qubits, path_ancilla, engine.mct_register, mode='advanced') engine.qcircuit.unitary(iSwap_controlled, [qsource, qtarget, path_ancilla]) for point in engine.qchess.get_path_points(source, target): engine.qcircuit.x(engine.get_qubit(point.x, point.y)) """ *The source piece has already been collapsed before this is called* So the basic idea behind this circuit is that if: -The path is clear (doesn't matter if target is empty or not) OR -The path is not clear but the target is empty Then there's no double occupancy and the piece can capture. """ def perform_capture_slide(engine, source, target): control_qubits = [] for point in engine.qchess.get_path_points(source, target): control_qubits.append(engine.get_qubit(point.x, point.y)) engine.qcircuit.x(engine.get_qubit(point.x, point.y)) qsource = engine.get_qubit(source.x, source.y) qtarget = engine.get_qubit(target.x, target.y) #holds if the path is clear or not path_ancilla = engine.aregister[0] engine.qcircuit.reset(path_ancilla) engine.qcircuit.x(path_ancilla) engine.qcircuit.mct(control_qubits, path_ancilla, engine.mct_register, mode='advanced') #holds the final condition that's going to be measured cond_ancilla = engine.aregister[1] engine.qcircuit.reset(cond_ancilla) #holds the captured piece captured_piece = engine.aregister[2] engine.qcircuit.reset(captured_piece) #path is not blocked engine.qcircuit.x(path_ancilla) engine.qcircuit.cx(path_ancilla, cond_ancilla) engine.qcircuit.x(path_ancilla) #blocked but target empty engine.qcircuit.x(qtarget) engine.qcircuit.ccx(qtarget, path_ancilla, cond_ancilla) engine.qcircuit.x(qtarget) engine.qcircuit.measure(cond_ancilla, engine.cbit_misc[0]) engine.qcircuit.unitary(iSwap_controlled, [qtarget, captured_piece, path_ancilla]).c_if(engine.cbit_misc, 1) engine.qcircuit.unitary(iSwap_controlled, [qsource, qtarget, path_ancilla]).c_if(engine.cbit_misc, 1) for qubit in control_qubits: engine.qcircuit.x(qubit) result = execute(engine.qcircuit, backend=backend, shots=1).result() #since get_counts() gives '1 00000001' #a bit hacky but I don't know any other way to get this result cbit_value = int(list(result.get_counts().keys())[0].split(' ')[0]) return (cbit_value == 1) """ Since the differences between both operations are only two gates, it's useful to implement them together. The args (single, double1, double2) are split: (source, target1, target2) merge: (target, source1, source2) """ def _slide_split_merge(engine, single, double1, double2, is_split): qsingle = engine.get_qubit(single.x, single.y) qdouble1 = engine.get_qubit(double1.x, double1.y) qdouble2 = engine.get_qubit(double2.x, double2.y) #get all qubits in first path control_qubits1 = [] for point in engine.qchess.get_path_points(single, double1): control_qubits1.append(engine.get_qubit(point.x, point.y)) engine.qcircuit.x(engine.get_qubit(point.x, point.y)) #holds if the first path is clear or not path_ancilla1 = engine.aregister[0] engine.qcircuit.reset(path_ancilla1) engine.qcircuit.x(path_ancilla1) #perform their combined CNOT engine.qcircuit.mct(control_qubits1, path_ancilla1, engine.mct_register, mode='advanced') #undo the X for qubit in control_qubits1: engine.qcircuit.x(qubit) #get all qubits in second path control_qubits2 = [] for point in engine.qchess.get_path_points(single, double2): control_qubits2.append(engine.get_qubit(point.x, point.y)) engine.qcircuit.x(engine.get_qubit(point.x, point.y)) #holds if the second path is clear or not path_ancilla2 = engine.aregister[1] engine.qcircuit.reset(path_ancilla2) engine.qcircuit.x(path_ancilla2) #perform their combined CNOT engine.qcircuit.mct(control_qubits2, path_ancilla2, engine.mct_register, mode='advanced') for qubit in control_qubits2: engine.qcircuit.x(qubit) #holds the control for jump and slide control_ancilla = engine.aregister[2] engine.qcircuit.reset(control_ancilla) engine.qcircuit.x(control_ancilla) #perform the split/merge engine.qcircuit.x(path_ancilla1) engine.qcircuit.x(path_ancilla2) engine.qcircuit.ccx(path_ancilla1, path_ancilla2, control_ancilla) if is_split: engine.qcircuit.unitary(iSwap_sqrt_controlled, [qdouble1, qsingle, control_ancilla]) engine.qcircuit.unitary(iSwap_controlled, [qsingle, qdouble2, control_ancilla]) else: engine.qcircuit.unitary(iSwap_controlled, [qsingle, qdouble2, control_ancilla]) engine.qcircuit.unitary(iSwap_sqrt_controlled, [qdouble1, qsingle, control_ancilla]) engine.qcircuit.x(path_ancilla1) engine.qcircuit.x(path_ancilla2) #reset the control engine.qcircuit.reset(control_ancilla) engine.qcircuit.x(control_ancilla) #perform one jump engine.qcircuit.x(path_ancilla1) engine.qcircuit.ccx(path_ancilla1, path_ancilla2, control_ancilla) engine.qcircuit.unitary(iSwap_controlled, [qdouble1, qsingle, control_ancilla]) engine.qcircuit.x(path_ancilla1) #reset the control engine.qcircuit.reset(control_ancilla) engine.qcircuit.x(control_ancilla) #perform the other jump engine.qcircuit.x(path_ancilla2) engine.qcircuit.ccx(path_ancilla1, path_ancilla2, control_ancilla) engine.qcircuit.unitary(iSwap_controlled, [qsingle, qdouble2, control_ancilla]) engine.qcircuit.x(path_ancilla2) def perform_split_slide(engine, source, target1, target2): _slide_split_merge(engine, source, target1, target2, is_split=True) def perform_merge_slide(engine, source1, source2, target): _slide_split_merge(engine, target, source1, source2, is_split=False) def perform_standard_en_passant(engine, source, target, ep_target): qsource = engine.get_qubit(source.x, source.y) qtarget = engine.get_qubit(target.x, target.y) qep_target = engine.get_qubit(ep_target.x, ep_target.y) captured_ancilla = engine.aregister[0] engine.qcircuit.reset(captured_ancilla) #holds if both source and ep_target are empty or not at the same time both_pieces_ancilla = engine.aregister[1] engine.qcircuit.reset(both_pieces_ancilla) engine.qcircuit.ccx(qsource, qep_target, both_pieces_ancilla) engine.qcircuit.x(both_pieces_ancilla) engine.qcircuit.unitary(iSwap_controlled, [qep_target, captured_ancilla, both_pieces_ancilla]) engine.qcircuit.unitary(iSwap_controlled, [qsource, qtarget, both_pieces_ancilla]) def perform_capture_en_passant(engine, source, target, ep_target): qsource = engine.get_qubit(source.x, source.y) qtarget = engine.get_qubit(target.x, target.y) qep_target = engine.get_qubit(ep_target.x, ep_target.y) #since this move can capture two pieces at the same time, #we need two ancillas to hold them captured_ancilla1 = engine.aregister[0] engine.qcircuit.reset(captured_ancilla1) captured_ancilla2 = engine.aregister[1] engine.qcircuit.reset(captured_ancilla2) #holds if any of target, ep_target exist #Note: It's impossible for them to exist at the same time (during this function's call), # since if they did that would mean that target piece has reached its position # after the pawn moved and thus EP would not be not a valid move. any_piece_ancilla = engine.aregister[2] engine.qcircuit.reset(any_piece_ancilla) engine.qcircuit.cx(qep_target, any_piece_ancilla) engine.qcircuit.cx(qtarget, any_piece_ancilla) engine.qcircuit.x(any_piece_ancilla) engine.qcircuit.unitary(iSwap_controlled, [qep_target, captured_ancilla1, any_piece_ancilla]) engine.qcircuit.unitary(iSwap_controlled, [qtarget, captured_ancilla2, any_piece_ancilla]) engine.qcircuit.unitary(iSwap_controlled, [qsource, qtarget, any_piece_ancilla]) #path holds all points that must be empty for the move to be valid (excluding targets) def perform_castle(engine, king_source, rook_source, king_target, rook_target, path=None): qking_source = engine.get_qubit(king_source.x, king_source.y) qrook_source = engine.get_qubit(rook_source.x, rook_source.y) qking_target = engine.get_qubit(king_target.x, king_target.y) qrook_target = engine.get_qubit(rook_target.x, rook_target.y) if path: #holds all the qubits of the path control_qubits = [] for point in path: control_qubits.append(engine.get_qubit(point.x, point.y)) engine.qcircuit.x(engine.get_qubit(point.x, point.y)) #holds if the path is empty or not path_ancilla = engine.aregister[0] engine.qcircuit.reset(path_ancilla) engine.qcircuit.x(path_ancilla) engine.qcircuit.mct(control_qubits, path_ancilla, engine.mct_register, mode='advanced') #undo the x for qubit in control_qubits: engine.qcircuit.x(qubit) #perform the movement engine.qcircuit.unitary(iSwap_controlled, [qking_source, qking_target, path_ancilla]) engine.qcircuit.unitary(iSwap_controlled, [qrook_source, qrook_target, path_ancilla]) else: #perform the movement engine.qcircuit.unitary(iSwap, [qking_source, qking_target]) engine.qcircuit.unitary(iSwap, [qrook_source, qrook_target])
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
from qiskit import QuantumCircuit from QCLG_lvl3.oracles.secret_number_oracle import SecretNUmberOracle class BernsteinVazirani: @classmethod def bernstein_vazirani(cls, random_binary, eval_mode: bool) -> QuantumCircuit: # Construct secret number oracle secret_number_oracle = SecretNUmberOracle.create_secret_number_oracle(random_binary=random_binary, eval_mode=eval_mode) num_of_qubits = secret_number_oracle.num_qubits # Construct circuit according to the length of the number dj_circuit = QuantumCircuit(num_of_qubits, num_of_qubits - 1) dj_circuit_before_oracle = QuantumCircuit(num_of_qubits, num_of_qubits - 1) # Apply H-gates for qubit in range(num_of_qubits - 1): dj_circuit_before_oracle.h(qubit) # Put output qubit in state |-> dj_circuit_before_oracle.x(num_of_qubits - 1) dj_circuit_before_oracle.h(num_of_qubits - 1) dj_circuit += dj_circuit_before_oracle # Add oracle dj_circuit += secret_number_oracle dj_circuit_after_oracle = QuantumCircuit(num_of_qubits, num_of_qubits - 1) # Repeat H-gates for qubit in range(num_of_qubits - 1): dj_circuit_after_oracle.h(qubit) dj_circuit_after_oracle.barrier() # Measure for i in range(num_of_qubits - 1): dj_circuit_after_oracle.measure(i, i) dj_circuit += dj_circuit_after_oracle if not eval_mode: print("Circuit before the oracle\n") print(QuantumCircuit.draw(dj_circuit_before_oracle)) print("Circuit after the oracle\n") print(QuantumCircuit.draw(dj_circuit_after_oracle)) print(dj_circuit) return dj_circuit
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 19 19:13:26 2023 @author: abdullahalshihry """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 18 19:15:12 2023 @author: abdullahalshihry """ import qiskit as qs import qiskit.visualization as qv import random import qiskit.circuit as qf def Deutsch_Jozsa(circuit): qr = qs.QuantumRegister(5,'q') cr = qs.ClassicalRegister(4,'c') qc = qs.QuantumCircuit(qr,cr) qc.x(qr[4]) qc.barrier(range(5)) qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.h(qr[3]) qc.h(qr[4]) qc.barrier(range(5)) qc = qc.compose(circuit) qc.barrier(range(5)) qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.h(qr[3]) qc.barrier(range(5)) qc.measure(0,0) qc.measure(1,1) qc.measure(2,2) qc.measure(3,3) job1 = qs.execute(qc, qs.Aer.get_backend('aer_simulator'), shots = 1024) output1 = job1.result().get_counts() print(output1) qc.draw('mpl') def Oracle(): qr = qs.QuantumRegister(5,'q') cr = qs.ClassicalRegister(4,'c') qc = qs.QuantumCircuit(qr,cr) qq = qs.QuantumCircuit(5,name='Uf') v = random.randint(1, 2) if v == 1: qc.cx(0,4) qc.cx(1,4) qc.cx(2,4) qc.cx(3,4) print('Balanced (1)') elif v == 2: qq.i(qr[0]) qq.i(qr[1]) qq.i(qr[2]) qq.i(qr[3]) print('Constant (0)') qq =qq.to_gate() qc.append(qq,[0,1,2,3,4]) return qc Deutsch_Jozsa(Oracle())
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
"""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/jdanielescanez/quantum-solver
jdanielescanez
#!/usr/bin/env python3 # Author: Daniel Escanez-Exposito from qiskit import QuantumCircuit from algorithms.qalgorithm import QAlgorithm ## A Quantum Algorithm to obtain random numbers for QuantumSolver class QRand(QAlgorithm): ## Constructor def __init__(self): ## The name of the algorithm self.name = 'QRand' ## A short description self.description = 'Gives a random number between 0 and 2 ^ n_qubits - 1' ## The required parameters for the algorithm self.parameters = [ { 'type': 'int', 'description': 'A positive number of qubits to use', 'constraint': 'Can\'t be bigger than the number of qubits of the selected backend' } ] ## How to parse the result of the circuit execution self.parse_result = lambda counts: int(list(counts.keys())[0], 2) ## How to parse the input parameters self.parse_parameters = lambda parameters: [int(parameters[0])] ## Verify that the parameter is the number of qubits to use def check_parameters(self, parameters): if len(parameters) == 1 and type(parameters[0]) == str: try: return int(parameters[0]) > 0 except: return False ## Create the circuit def circuit(self, n=1): # Create a Quantum Circuit circuit = QuantumCircuit(n, n) n_range = list(range(n)) # Add a H gate on every qubit circuit.h(n_range) circuit.barrier() # Map the quantum measurement to the classical bits circuit.measure(n_range, n_range) return circuit
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
''' This is a implementation of the quantum teleportation algorithm ''' from qiskit import * from qiskit.visualization import plot_histogram import os, shutil, numpy from matplotlib.pyplot import plot, draw, show LaTex_folder_Quantum_Teleportation = str(os.getcwd())+'/Latex_quantum_gates/Quantum_Teleportation/' if not os.path.exists(LaTex_folder_Quantum_Teleportation): os.makedirs(LaTex_folder_Quantum_Teleportation) else: shutil.rmtree(LaTex_folder_Quantum_Teleportation) os.makedirs(LaTex_folder_Quantum_Teleportation) qc = QuantumCircuit(3,3) ## prepare the state to be teleported phi = 0*numpy.pi theta= 0.5*numpy.pi lam = 0*numpy.pi qc.u(phi=phi, theta=theta,lam=lam,qubit=0) ## teleport the state qc.barrier() qc.h(1) qc.cx(1,2) qc.cz(0,1) qc.h(0) qc.h(1) qc.barrier() qc.measure([0,1],[0,1]) qc.barrier() qc.x(2).c_if(0,1) qc.z(2).c_if(1,1) qc.h(2) qc.measure(2,2) LaTex_code = qc.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit f_name = 'quantum_teleportation.tex' with open(LaTex_folder_Quantum_Teleportation+f_name, 'w') as f: f.write(LaTex_code) # simulation simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend=simulator, shots=100000).result() counts = {'0':0, '1': 0} print(result.get_counts().keys()) for key, value in result.get_counts().items(): if(key[0] == '0'): counts['0'] += value else: counts['1'] += value print(counts) plt = plot_histogram(counts) draw() show(block=True)
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
import qiskit from .common_gates import * import random def superdense_coding_circuit(msg): qc = qiskit.QuantumCircuit(2) phi_plus = phi_plus_gate() qc.append(phi_plus, [0, 1]) qc.barrier() if msg[1] == '1': qc.z(0) if msg[0] == '1': qc.x(0) qc.barrier() qc.append(phi_plus.inverse(), [0, 1]) qc.name = "SC" return qc def superdense_coding_example(): msg = random.choice(["00", "01", "10", "11"]) qc = qiskit.QuantumCircuit(2, 2) sc_qc = superdense_coding_circuit(msg) qc.append(sc_qc, [0, 1]) if msg[0] == '1': qc.x(1) if msg[1] == '1': qc.x(0) qc.measure([0, 1], [0, 1]) print(msg) print(qc.draw(output="text")) return qc
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
from qiskit import QuantumCircuit from math import log2 class QSCircuit(QuantumCircuit): def __init__(self, size): self.size = size super().__init__(size, size) def not1(self, a): self.x(a) def not2(self, a, result): self.reset(result) self.cx(a, result) self.x(result) def or3(self, a, b, result): self.reset(result) self.x([a, b]) self.ccx(a, b, result) self.x([a, b, result]) def or_list(self, indexes, result, aux): self.reset(result) for a in indexes: self.or3(a, result, aux) self.reset(result) self.xor2(aux, result) def and3(self, a, b, result): self.reset(result) self.ccx(a, b, result) def and_list(self, indexes, result, aux): self.reset(result) self.not1(result) for a in indexes: self.and3(a, result, aux) self.reset(result) self.xor2(aux, result) def nand3(self, a, b, result): self.and3(a, b, result) self.not1(result) # copy the source to the destiny if conditional def copy_if(self, conditional, source, destiny): for i in range(len(source)): self.and3(conditional, source[i], destiny[i]) def xor2(self, a, result): self.cx(a, result) def xor3(self, a, b, result): self.reset(result) self.cx(b, result) self.cx(a, result) def swap2(self, a, b): self.swap(a, b) def shift_left(self, indexes): indexes.sort() self.swap(indexes[:-1], indexes[1:]) def shift_right(self, indexes): indexes.sort(reverse=True) self.swap(indexes[:-1], indexes[1:]) def reset1(self, a): self.reset(a) def set1(self, a): self.reset(a) self.x(a) def set_bin_reg(self, values, indexes): self.set_reg(values[::-1], indexes) def set_reg(self, values, indexes): for i, value in enumerate(values): if value == '1': self.set1(indexes[i]) else: self.reset1(indexes[i]) # output in indexes2 def full_add_regs(self, indexes1, indexes2, carry, auxs): a_xor_b, a_prod_b, aux = auxs self.reset1(carry) for a, b in zip(indexes1, indexes2): self.reset1([a_xor_b, a_prod_b, aux]) # a_xor_b = a xor b self.xor3(a, b, a_xor_b) # a_prod_b = a * b self.and3(a, b, a_prod_b) # aux = carry_in * (a xor b) self.and3(carry, a_xor_b, aux) # output = a xor b xor carry_in self.xor3(a_xor_b, carry, b) # carry_out = (a * b) + (carry_in * (a xor b)) self.or3(a_prod_b, aux, carry) # output in indexes2 def half_add_regs(self, indexes1, indexes2, carries): self.reset1(carries) for a, b, c in zip(indexes1, indexes2, carries): self.and3(a, b, c) # c = ab self.xor2(a, b) # b = b xor a self.swap2(b, c) # b = ab; c = a xor b def encoder(self, inputs, outputs, aux): n = len(inputs) m = int(log2(n)) assert(m == len(outputs)) relative_indexes = [[inputs[num] for num in range(2 ** m) if (num >> i) & 1 == 1] for i in range(m)] for i in range(m): self.or_list(relative_indexes[i], outputs[i], aux) def decoder(self, inputs, outputs, flipped_inputs, aux): n = len(inputs) m = int(2 ** n) assert(m == len(outputs)) self.xor2(inputs, flipped_inputs) self.not1(flipped_inputs) for i in range(m): tag = format(i, '0' + str(n) + 'b')[::-1] relative_inputs = [flipped_inputs[j] if x == '0' else inputs[j] for j, x in enumerate(tag)] self.and_list(relative_inputs, outputs[i], aux) ''' Modify inputs to its pruduct by its code ''' def multiplexer(self, inputs, selectors, flipped_selectors, output, aux): n = len(inputs) m = int(log2(n)) assert(m == len(selectors)) self.xor2(selectors, flipped_selectors) self.not1(flipped_selectors) for i in range(n): tag = format(i, '0' + str(m) + 'b')[::-1] relative_selectors = [flipped_selectors[j] if x == '0' else selectors[j] for j, x in enumerate(tag)] self.and_list([inputs[i]] + relative_selectors, output, aux) self.swap(inputs[i], output) self.or_list(inputs, output, aux)
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, QuantumCircuit from qiskit_aer import AerSimulator SIZE_REG = 16 CIRCUIT_SIZE = SIZE_REG * 2 ALPHABET = ['0', '1'] class QS_SAES_Circuit(QSCircuit): def __init__(self, CIRCUIT_SIZE, msg, key, msg_indexes, key_indexes): super().__init__(CIRCUIT_SIZE) self.msg_indexes = msg_indexes self.key_indexes = key_indexes self.set_bin_reg(msg, self.msg_indexes) self.set_bin_reg(key, self.key_indexes) self.build() def build(self): self.barrier() self.add_roundkey() self.barrier() self.s_box() self.barrier() self.shift_rows() self.barrier() self.mix_columns() self.barrier() self.key_expansion('10000000'[::-1]) self.barrier() self.add_roundkey() self.barrier() self.s_box() self.barrier() self.shift_rows() self.barrier() self.key_expansion('00110000'[::-1]) self.barrier() self.add_roundkey() def add_roundkey(self): self.xor2(self.key_indexes, self.msg_indexes) def s_key(self): for limit in range(0, 8, 4): x0, x1, x2, x3 = [self.key_indexes[i] for i in list(range(limit, limit + 4))] self.swap2(x0, x3) self.swap2(x1, x2) self.xor2(x2, x1) self.ccx(x3, x1, x0) self.ccx(x0, x2, x3) self.ccx(x0, x3, x1) self.mcx([x0, x1, x3], x2) self.cx(x3, x0) self.not1([x2, x3]) self.cx(x0, x2) self.ccx(x1, x2, x0) self.ccx(x0, x3, x1) self.ccx(x0, x1, x3) self.shift_right([x0, x1, x2, x3]) self.swap2(x0, x3) self.swap2(x1, x2) def s_key_inv(self): qc = QuantumCircuit(4) qc.swap(0, 3) qc.swap(1, 2) qc.cx(2, 1) qc.ccx(3, 1, 0) qc.ccx(0, 2, 3) qc.ccx(0, 3, 1) qc.mcx([0, 1, 3], 2) qc.cx(3, 0) qc.x([2, 3]) qc.cx(0, 2) qc.ccx(1, 2, 0) qc.ccx(0, 3, 1) qc.ccx(0, 1, 3) indexes = [0, 1, 2, 3] indexes.sort(reverse=True) qc.swap(indexes[:-1], indexes[1:]) qc.swap(0, 3) qc.swap(1, 2) qc_inv = qc.to_gate().inverse() for limit in range(0, 8, 4): self.append(qc_inv, [self.key_indexes[i] for i in list(range(limit, limit + 4))]) def s_box(self): for limit in range(0, 16, 4): x0, x1, x2, x3 = [self.msg_indexes[i] for i in list(range(limit, limit + 4))] self.swap2(x0, x3) self.swap2(x1, x2) self.xor2(x2, x1) self.ccx(x3, x1, x0) self.ccx(x0, x2, x3) self.ccx(x0, x3, x1) self.mcx([x0, x1, x3], x2) self.cx(x3, x0) self.not1([x2, x3]) self.cx(x0, x2) self.ccx(x1, x2, x0) self.ccx(x0, x3, x1) self.ccx(x0, x1, x3) self.shift_right([x0, x1, x2, x3]) self.swap2(x0, x3) self.swap2(x1, x2) def mix_columns(self): for limit in range(0, 16, 8): b0, b1, b2, b3, b4, b5, b6, b7 = [self.msg_indexes[i] for i in list(range(limit, limit + 8))[::-1]] self.xor2(b0, b6) self.xor2(b5, b3) self.xor2(b4, b2) self.xor2(b1, b7) self.xor2(b7, b4) self.xor2(b2, b5) self.xor2(b3, b0) self.xor2(b6, b1) self.swap2(b0, b6) self.swap2(b1, b4) self.swap2(b2, b5) self.swap2(b4, b5) self.swap2(b5, b6) def shift_rows(self): x0, x1, x3, x4 = [self.msg_indexes[i] for i in range(0, 4)] x8, x9, x10, x11 = [self.msg_indexes[i] for i in range(8, 12)] self.swap2(x0, x8) self.swap2(x1, x9) self.swap2(x3, x10) self.swap2(x4, x11) def key_expansion(self, constant): self.swap2(self.key_indexes[:4], self.key_indexes[4:8]) self.s_key() for i, bit in enumerate(constant): if bit == '1': self.not1(self.key_indexes[i]) self.xor2(self.key_indexes[:8], self.key_indexes[-8:]) for i, bit in enumerate(constant): if bit == '1': self.not1(self.key_indexes[i]) self.s_key_inv() self.swap2(self.key_indexes[:4], self.key_indexes[4:8]) self.xor2(self.key_indexes[-8:], self.key_indexes[:8]) def saes_qcypher(msg, key): msg_indexes = list(range(0, SIZE_REG)) msg_slice = slice(0, SIZE_REG) key_indexes = list(range(SIZE_REG, 2 * SIZE_REG)) qc = QS_SAES_Circuit(CIRCUIT_SIZE, msg, key, msg_indexes, key_indexes) qc.measure(msg_indexes, msg_indexes) print(qc) backend = AerSimulator(method='matrix_product_state') job = execute(qc, backend, shots=1) counts = job.result().get_counts(qc) result_bin = ''.join(list(list(counts.keys())[0][::-1][msg_slice][::-1])) return result_bin if __name__ == "__main__": msg = '0110111101101011' # input('Insert message: ') key = '1010011100111011' # input('Insert key: ') assert all(list(map(lambda c: c in ALPHABET, msg))) assert all(list(map(lambda c: c in ALPHABET, key))) assert len(msg) == SIZE_REG assert len(msg) == len(key) cypher = saes_qcypher(msg, key) print() print(f'Message: {msg}') print(f'Key: {key}\n') print(f'-> Expected: 0000011100111000') print(f'Cypher text: {cypher}\n')
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 print('AND') for i in range(2 ** 5): a = format(i, '05b')[::-1] SIZE_REG = len(a) a_indexes = list(range(0, SIZE_REG)) result_index = SIZE_REG aux_index = SIZE_REG + 1 CIRCUIT_SIZE = len(a_indexes) + 2 qc = QSCircuit(CIRCUIT_SIZE) qc.set_reg(a, a_indexes) qc.and_list(a_indexes, result_index, aux_index) qc.measure(result_index, 0) backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1) counts = job.result().get_counts(qc) print(i, '-', list(counts.keys())[0][-1]) print('\nOR') for i in range(2 ** 5): a = format(i, '05b')[::-1] SIZE_REG = len(a) a_indexes = list(range(0, SIZE_REG)) result_index = SIZE_REG aux_index = SIZE_REG + 1 CIRCUIT_SIZE = len(a_indexes) + 2 qc = QSCircuit(CIRCUIT_SIZE) qc.set_reg(a, a_indexes) qc.or_list(a_indexes, result_index, aux_index) qc.measure(result_index, 0) backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1) counts = job.result().get_counts(qc) print(i, '-', list(counts.keys())[0][-1])
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/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 from math import log2 SIZE = 2 ** 3 for i in range(0, SIZE): a = format(2 ** i, '0' + str(SIZE) + 'b') SIZE_REG = len(a) LOG_SIZE_REG = int(log2(SIZE_REG)) a_indexes = list(range(0, SIZE_REG)) output_indexes = list(range(SIZE_REG, SIZE_REG + LOG_SIZE_REG)) aux_index = SIZE_REG + LOG_SIZE_REG CIRCUIT_SIZE = SIZE_REG + LOG_SIZE_REG + 1 qc = QSCircuit(CIRCUIT_SIZE) qc.set_reg(a[::-1], a_indexes) qc.encoder(a_indexes, output_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(i, '-', list(counts.keys())[0][-LOG_SIZE_REG:])
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 from math import log2 SIZE_INPUT = 2 ** 1 SIZE_SELECTOR = int(log2(SIZE_INPUT)) for i in range(0, 2 ** SIZE_INPUT): a = format(i, '0' + str(SIZE_INPUT) + 'b') for j in range(0, 2 ** SIZE_SELECTOR): selectors = format(j, '0' + str(SIZE_SELECTOR) + 'b') a_indexes = list(range(0, SIZE_INPUT)) selectors_indexes = list(range(SIZE_INPUT, SIZE_INPUT + SIZE_SELECTOR)) flipped_selectors_indexes = list(range(SIZE_INPUT + SIZE_SELECTOR, SIZE_INPUT + 2 * SIZE_SELECTOR)) output_index = SIZE_INPUT + 2 * SIZE_SELECTOR aux_index = SIZE_INPUT + 2 * SIZE_SELECTOR + 1 CIRCUIT_SIZE = SIZE_INPUT + 2 * SIZE_SELECTOR + 2 qc = QSCircuit(CIRCUIT_SIZE) qc.set_reg(a[::-1], a_indexes) qc.set_reg(selectors[::-1], selectors_indexes) qc.multiplexer(a_indexes, selectors_indexes, flipped_selectors_indexes, output_index, aux_index) qc.measure(output_index, output_index) print(qc) backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1) counts = job.result().get_counts(qc) print(a, '-', selectors, '-', list(counts.keys())[0][::-1][output_index])
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
from s_aes import QS_SAES_Circuit from qiskit import execute from qiskit_aer import AerSimulator SIZE_REG = 16 CIRCUIT_SIZE = SIZE_REG * 2 msg_indexes = list(range(0, SIZE_REG)) msg_slice = slice(0, SIZE_REG) key_indexes = list(range(SIZE_REG, 2 * SIZE_REG)) for i in range(2 ** 4): msg = '0' * 12 + format(i, f'0{4}b') key = '0' * 16 qc = QS_SAES_Circuit(CIRCUIT_SIZE, msg, key, msg_indexes, key_indexes) qc.s_box() qc.measure(range(4), range(4)) backend = AerSimulator(method='matrix_product_state') job = execute(qc, backend, shots=1) counts = job.result().get_counts(qc) result_bin = ''.join(list(list(counts.keys())[0][::-1][:4][::-1])) print(msg, '-', result_bin[:4])
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 import string from qiskit import execute, BasicAer import math from qiskit.circuit.library import SwapGate # ALPHABET = list(string.ascii_uppercase) + [' ', '-', '_', '.', ',', '@'] ALPHABET = ['A', 'B', 'C', 'D'] SIZE_REG = int(math.log2(len(ALPHABET))) def transposition_qcypher(chunk, sequence): SIZE_SEQ = len(sequence) SIZE_CHUNK = len(chunk) SIZE_INDEX = math.ceil(math.log2(SIZE_SEQ)) CIRCUIT_SIZE = 2 * SIZE_CHUNK * SIZE_REG + SIZE_SEQ * SIZE_INDEX msg_indexes = list(range(0, SIZE_CHUNK * SIZE_REG)) key_indexes = list(map(lambda i: list(range(SIZE_CHUNK * SIZE_REG + (i) * SIZE_INDEX, SIZE_CHUNK * SIZE_REG + (i + 1) * SIZE_INDEX)), range(SIZE_SEQ))) measure_indexes = list(range(SIZE_CHUNK * SIZE_REG + SIZE_SEQ * SIZE_INDEX, CIRCUIT_SIZE)) qc = QSCircuit(CIRCUIT_SIZE) for i, letter in enumerate(chunk): msg = format(ALPHABET.index(letter), f'0{SIZE_REG}b')[::-1] qc.set_reg(msg, measure_indexes[i * SIZE_REG: (1 + i) * SIZE_REG]) qc.set_reg(msg, msg_indexes[i * SIZE_REG: (1 + i) * SIZE_REG]) for i, index in enumerate(sequence): index_key = format(index - 1, f'0{SIZE_INDEX}b')[::-1] qc.set_reg(index_key, key_indexes[i]) qc.barrier() for i, index in enumerate(sequence): list_aux = sequence[::] list_aux.remove(i + 1) for index2 in list_aux: swap = SwapGate().control(num_ctrl_qubits=SIZE_INDEX, ctrl_state=(index2 - 1)) for k in range(SIZE_REG): qc.append(swap, [*key_indexes[i], msg_indexes[(index2 - 1) * SIZE_REG + k], measure_indexes[i * SIZE_REG + k]]) qc.barrier() qc.measure(measure_indexes, measure_indexes) print(qc) backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1) counts = job.result().get_counts(qc) tag = list(counts.keys())[0] sep = [tag[i:i+SIZE_REG] for i in range(0, len(tag), SIZE_REG)][:SIZE_CHUNK][::-1] return ''.join([ALPHABET[int(result_bin_chunk, 2) % len(ALPHABET)] for result_bin_chunk in sep]) msg = input('Insert message: ').upper() sequence_str = input('Insert transposition sequence (separated using spaces): ') sequence = list(map(int, sequence_str.split(' '))) assert all(list(map(lambda c: c in ALPHABET, msg))) assert len(msg) % len(sequence) == 0 assert all(list(map(lambda x: x - 1 in range(len(sequence)), sequence))) assert all(list(map(lambda x: x + 1 in sequence, range(len(sequence))))) cypher = '' for i in range(0, len(msg), len(sequence)): chunk = msg[i:i+len(sequence)] result_char = transposition_qcypher(chunk, sequence) cypher += result_char print(f'\nMessage: {msg}') print(f'Key: {sequence_str}') print(f'Cypher text: {cypher}')
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 import string from qiskit import execute, BasicAer import math ALPHABET = list(string.ascii_uppercase) + [' ', '-', '_', '.', ',', '@'] SIZE_REG = int(math.log2(len(ALPHABET))) CIRCUIT_SIZE = SIZE_REG * 2 msg_indexes = list(range(0, SIZE_REG)) key_indexes = list(range(SIZE_REG, 2 * SIZE_REG)) key_slice = slice(SIZE_REG, 2 * SIZE_REG) def vigenere_qcypher(msg, key): qc = QSCircuit(CIRCUIT_SIZE) qc.set_reg(msg, msg_indexes) qc.set_reg(key, key_indexes) qc.xor2(msg_indexes, key_indexes) qc.measure(key_indexes, key_indexes) backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1) counts = job.result().get_counts(qc) result_bin = ''.join(list(list(counts.keys())[0][::-1][key_slice][::-1])) result_char = ALPHABET[int(result_bin, 2) % len(ALPHABET)] return result_char msg = input('Insert message: ').upper() key = input('Insert key: ').upper() assert all(list(map(lambda c: c in ALPHABET, msg))) assert all(list(map(lambda c: c in ALPHABET, key))) cypher = '' for i, msg_char in enumerate(msg): key_char = key[i % len(key)] a = format(ALPHABET.index(msg_char), f'0{SIZE_REG}b')[::-1] b = format(ALPHABET.index(key_char), f'0{SIZE_REG}b')[::-1] result_char = vigenere_qcypher(a, b) cypher += result_char print(f'\nMessage: {msg}') print(f'Key: {key}') print(f'Cypher text: {cypher}')
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
#!/usr/bin/env python3 # Author: Daniel Escanez-Exposito from qiskit import QuantumCircuit from crypto.b92.sender import Sender from crypto.b92.receiver import Receiver import binascii B92_SIMULATOR = 'B92 SIMULATOR' ## An implementation of the B92 protocol ## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html class B92Algorithm: ## Generate a key for Alice and Bob def generate_key(self, backend, original_bits_size, verbose): # Encoder Alice alice = Sender('Alice', original_bits_size) alice.set_values() message = alice.encode_quantum_message() # Interceptor Eve eve = Receiver('Eve', original_bits_size) eve.set_axes() message = eve.decode_quantum_message(message, self.measure_density, backend) # Decoder Bob bob = Receiver('Bob', original_bits_size) bob.set_axes() message = bob.decode_quantum_message(message, 1, backend) # Bob shares his positives reading indexes bob_positive_readings_indexes = bob.share_positive_readings_indexes() # Delete the difference alice.remove_garbage(bob_positive_readings_indexes) bob.remove_garbage(bob_positive_readings_indexes) # Bob share some values of the key to check SHARED_SIZE = round(0.5 * len(bob.key)) shared_key = bob.key[:SHARED_SIZE] if verbose: alice.show_values() eve.show_values() eve.show_axes() bob.show_values() bob.show_axes() alice.show_key() bob.show_key() print('\nShared Bob Key:') print(shared_key) # Alice check the shared key if alice.check_key(shared_key): shared_size = len(shared_key) alice.confirm_key(shared_size) bob.confirm_key(shared_size) if verbose: print('\nFinal Keys') alice.show_key() bob.show_key() print('\nSecure Communication!') elif verbose: print('\nUnsecure Communication! Eve has been detected intercepting messages\n') return alice, bob ## Run the implementation of B92 protocol def run(self, message, backend, original_bits_size, measure_density, n_bits, verbose): ## The original size of the message self.original_bits_size = original_bits_size ## The probability of an interception occurring self.measure_density = measure_density alice, bob = self.generate_key(backend, original_bits_size, verbose) if not (alice.is_safe_key and bob.is_safe_key): if verbose: print('❌ Message not send') return False alice.generate_otp(n_bits) bob.generate_otp(n_bits) encoded_message = alice.xor_otp_message(message) decoded_message = bob.xor_otp_message(encoded_message) if verbose: alice.show_otp() bob.show_otp() print('\nInitial Message:') print(message) print('Encoded Message:') print(encoded_message) print('💡 Decoded Message:') print(decoded_message) if message == decoded_message: print('\n✅ The initial message and the decoded message are identical') else: print('\n❌ The initial message and the decoded message are different') return True
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
#!/usr/bin/env python3 # Author: Daniel Escanez-Exposito from abc import ABC, abstractmethod from qiskit import QuantumCircuit from qiskit.circuit.library import YGate, ZGate from qiskit.circuit.gate import Gate import qiskit.quantum_info as qi from numpy.random import randint import numpy as np from math import ceil ## An abstract class of a participant entity in the Six-State implementation ## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html class Participant(ABC): ## Constructor @abstractmethod def __init__(self, name='', original_bits_size=0): ## The name of the participant self.name = name ## The original size of the message self.original_bits_size = original_bits_size ## The values of the participant self.values = None ## The axes of the participant self.axes = None ## The key of the participant self.key = None ## If the key is determined safe self.is_safe_key = False ## The otp of the participant self.otp = None ## The gate measuring z and y axes self.set_hy() ## Values setter def set_values(self, values=None): if values == None: self.values = list(randint(2, size=self.original_bits_size)) else: self.values = values ## Axes setter def set_axes(self, axes=None): if axes == None: self.axes = list(randint(3, size=self.original_bits_size)) else: self.axes = axes ## Print values def show_values(self): print('\n' + self.name, 'Values:') print(self.values) ## Print axes def show_axes(self): print('\n' + self.name, 'Axes:') print(self.axes) ## Print key def show_key(self): print('\n' + self.name, 'Key:') print(self.key) ## Print otp def show_otp(self): print('\n' + self.name, 'OTP:') print(self.otp) ## Remove the values of the qubits that were measured on the wrong axis def remove_garbage(self, another_axes): self.key = [] for i in range(self.original_bits_size): if self.axes[i] == another_axes[i]: self.key.append(self.values[i]) ## Check if the shared key is equal to the current key def check_key(self, shared_key): return shared_key == self.key[:len(shared_key)] ## Use the rest of the key and validate it def confirm_key(self, shared_size): self.key = self.key[shared_size:] self.is_safe_key = True ## Generate an One-Time Pad def generate_otp(self, n_bits): self.otp = [] for i in range(ceil(len(self.key) / n_bits)): bits_string = ''.join(map(str, self.key[i * n_bits: (i + 1) * n_bits])) self.otp.append(int(bits_string, 2)) ## Performs an XOR operation between the message and the One-Time Pad def xor_otp_message(self, message): final_message = '' CHR_LIMIT = 1114112 if len(self.otp) > 0: for i, char in enumerate(message): final_message += chr((ord(char) ^ self.otp[i % len(self.otp)]) % CHR_LIMIT) return final_message ## New gate setter def set_hy(self): hy_op = qi.Operator(1/np.sqrt(2)*(YGate().to_matrix() + ZGate().to_matrix())) hy_gate = QuantumCircuit(1) hy_gate.unitary(hy_op, [0], label='h_y') self.hy = hy_gate.to_gate()
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
#!/usr/bin/env python3 # Author: Daniel Escanez-Exposito from crypto.six_state.participant import Participant from qiskit import QuantumCircuit from numpy.random import rand from qiskit import transpile ## The Receiver entity in the Six-State implementation ## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html class Receiver(Participant): ## Constructor def __init__(self, name='', original_bits_size=0): super().__init__(name, original_bits_size) ## Decode the message measuring the circuit (density-dependent) def decode_quantum_message(self, message, density, backend): ## The values of the participant self.values = [] for i, qc in enumerate(message): qc.barrier() if rand() < density: if self.axes[i] == 1: qc.h(0) elif self.axes[i] == 2: qc.append(self.hy, [0]) qc.measure(0, 0) transpiled_qc = transpile(qc, backend=backend) result = backend.run(transpiled_qc, shots=1, memory=True).result() measured_bit = int(result.get_memory()[0]) self.values.append(measured_bit) else: self.values.append(-1) return message
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
#!/usr/bin/env python3 # Author: Daniel Escanez-Exposito from crypto.six_state.participant import Participant from qiskit import QuantumCircuit ## The Sender entity in the Six-State implementation ## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html class Sender(Participant): ## Constructor def __init__(self, name='', original_bits_size=0): super().__init__(name, original_bits_size) ## Encode the message (values) using a quantum circuit def encode_quantum_message(self): encoded_message = [] for i in range(len(self.axes)): qc = QuantumCircuit(1, 1) if self.values[i] == 1: qc.x(0) if self.axes[i] == 1: qc.h(0) elif self.axes[i] == 2: qc.append(self.hy, [0]) encoded_message.append(qc) return encoded_message
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
#!/usr/bin/env python3 # Author: Daniel Escanez-Exposito from crypto.six_state.participant import Participant from qiskit import QuantumCircuit ## The Sender entity in the Six-State implementation ## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html class Sender(Participant): ## Constructor def __init__(self, name='', original_bits_size=0): super().__init__(name, original_bits_size) ## Encode the message (values) using a quantum circuit def encode_quantum_message(self): encoded_message = [] for i in range(len(self.axes)): qc = QuantumCircuit(1, 1) if self.values[i] == 1: qc.x(0) if self.axes[i] == 1: qc.h(0) elif self.axes[i] == 2: qc.append(self.hy, [0]) encoded_message.append(qc) return encoded_message
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
#!/usr/bin/env python3 # Author: Daniel Escanez-Exposito from qiskit import execute, QuantumCircuit, QuantumRegister, ClassicalRegister from crypto.e91.sender import Sender from crypto.e91.receiver import Receiver from crypto.e91.eavesdropper import Eveasdropper import binascii E91_SIMULATOR = 'E91 SIMULATOR' ## An implementation of the E91 protocol ## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html class E91Algorithm: ## Get the simplest (and maximal) example of quantum entanglement * (- 1j) def get_bell_pair(self, qr, cr): circuit = QuantumCircuit(qr, cr) circuit.x([0, 1]) circuit.h(0) circuit.cx(0, 1) circuit.s([0, 1]) return circuit ## Generate a key for Alice and Bob def generate_key(self, backend, original_bits_size, verbose): # Initialize the bell pair, quantum and classical registers qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(4, name="cr") singlet = self.get_bell_pair(qr, cr) # Initialize entities Alice, Eve and Bob alice = Sender('Alice', original_bits_size, qr, cr) alice.set_axes() eve = Eveasdropper('Eve', original_bits_size, qr, cr) eve.set_axes(density=self.measure_density) bob = Receiver('Bob', original_bits_size, qr, cr) bob.set_axes() # Create circuits and get results circuits = [] for i in range(original_bits_size): if eve.axes[i] != None: eve_measure = eve.measurements[eve.axes[i][0]] + eve.measurements[eve.axes[i][1]] else: eve_measure = QuantumCircuit(qr, cr) alice_measure = alice.measurements[alice.axes[i]] bob_measure = bob.measurements[bob.axes[i]] circuit = singlet + eve_measure + alice_measure + bob_measure eve_measure_name = '_' + eve.axes[i][0] + '-' + eve.axes[i][1] if eve.axes[i] != None else '' circuit.name = str(i) + ':' + alice.axes[i] + '_' + bob.axes[i] + eve_measure_name circuits.append(circuit) result = execute(circuits, backend=backend, shots=1).result() alice.create_values(result, circuits) bob.create_values(result, circuits) eve.create_values(result, circuits) # Publish the measurements # Obtain values from the circuit measurements count = [[0, 0, 0, 0], # XW observable [0, 0, 0, 0], # XV observable [0, 0, 0, 0], # ZW observable [0, 0, 0, 0]] # ZV observable alice.key = []; eve.key = []; bob.key = [] for i in range(original_bits_size): # If Alice and Bob have measured the spin projections onto the a_2/b_1 or a_3/b_2 directions if (alice.axes[i] == 'a2' and bob.axes[i] == 'b1') or \ (alice.axes[i] == 'a3' and bob.axes[i] == 'b2'): alice.key.append(alice.values[i]) bob.key.append(0 if bob.values[i] == 1 else 1) if eve.values[i] != [None, None]: eve.key.append([eve.values[i][0], 0 if eve.values[i][1] == 1 else 1]) else: eve.key.append([None, None]) else: eve.key.append([None, None]) if (alice.axes[i] == 'a1' or alice.axes[i] == 'a3') and (bob.axes[i] == 'b1' or bob.axes[i] == 'b3'): res = list(result.get_counts(circuits[i]).keys())[0] j = 2 * int(alice.axes[i] == 'a3') + int(bob.axes[i] == 'b3') k = int(res[-2:], base=2) count[j][k] += 1 corr = self.compute_corr(count) keyLength = len(alice.key) info = self.get_mismatches_info(alice, eve, bob) if verbose: alice.show_values() alice.show_measurements() alice.show_axes() eve.show_values() eve.show_measurements() eve.show_axes() bob.show_values() bob.show_measurements() bob.show_axes() alice.show_key() bob.show_key() print('\nNumber of mismatching bits: ' + str(info['alice_bob_key_mismatches'])) print('\nEve\'s knowledge of Alice\'s key: ' + str(round(info['eve_alice_knowledge'] * 100, 2)) + '%') print('Eve\'s knowledge of Bob\'s key: ' + str(round(info['eve_bob_knowledge'] * 100, 2)) + '%') # CHSH inequality test print('CHSH correlation:', corr) # Key length test print('Key length:', len(alice.key)) print('\nCHSH correlation should be close to -2 * √2 ~= -2.8282') print('Key length should be close to', original_bits_size, '* 2 / 9 =', original_bits_size * 2 / 9) if alice.check_corr(corr): alice.confirm_key() bob.confirm_key() if verbose: print('\nCHSH correlation is in −2√2 · (1 ± 0.1)') print('\nFinal Keys') alice.show_key() bob.show_key() print('\nSecure Communication!') elif verbose: print('\nCHSH correlation is not in −2√2 · (1 ± 0.1)') print('Unsecure Communication! Eve has been detected intercepting messages\n') return alice, bob, corr def get_mismatches_info(self, alice, eve, bob): keyLength = len(alice.key) info = { 'alice_bob_key_mismatches': 0, 'eve_alice_key_mismatches': 0, 'eve_bob_key_mismatches': 0, 'eve_alice_knowledge': 0, 'eve_bob_knowledge': 0 } for j in range(keyLength): if alice.key[j] != bob.key[j]: info['alice_bob_key_mismatches'] += 1 if j < len(eve.key): if eve.key[j][0] != alice.key[j]: info['eve_alice_key_mismatches'] += 1 if eve.key[j][1] != bob.key[j]: info['eve_bob_key_mismatches'] += 1 if keyLength > 0 and len(eve.key) > 0: # Eve's knowledge of Bob's key info['eve_alice_knowledge'] = (keyLength - info['eve_alice_key_mismatches']) / keyLength # Eve's knowledge of Alice's key info['eve_bob_knowledge'] = (keyLength - info['eve_bob_key_mismatches']) / keyLength return info ## Calculate correlation def compute_corr(self, count): # Number of the results obtained from the measurements in a particular basis total = [sum(count[0]), sum(count[1]), sum(count[2]), sum(count[3])] check_total = list(map(lambda x: x == 0, total)) if any(check_total): return float('-inf') # Expectation values of XW, XV, ZW and ZV observables expect11 = (count[0][0] - count[0][1] - count[0][2] + count[0][3]) / total[0] # -1 / sqrt(2) expect13 = (count[1][0] - count[1][1] - count[1][2] + count[1][3]) / total[1] # 1 / sqrt(2) expect31 = (count[2][0] - count[2][1] - count[2][2] + count[2][3]) / total[2] # -1 / sqrt(2) expect33 = (count[3][0] - count[3][1] - count[3][2] + count[3][3]) / total[3] # -1 / sqrt(2) return expect11 - expect13 + expect31 + expect33 # Calculate the CHSC correlation value ## Run the implementation of E91 protocol def run(self, message, backend, original_bits_size, measure_density, n_bits, verbose): ## The original size of the message self.original_bits_size = original_bits_size ## The probability of an interception occurring self.measure_density = measure_density alice, bob, corr = self.generate_key(backend, original_bits_size, verbose) if not (alice.is_safe_key and bob.is_safe_key): if verbose: print('❌ Message not send') return False, corr alice.generate_otp(n_bits) bob.generate_otp(n_bits) encoded_message = alice.xor_otp_message(message) decoded_message = bob.xor_otp_message(encoded_message) if verbose: alice.show_otp() bob.show_otp() print('\nInitial Message:') print(message) print('Encoded Message:') print(encoded_message) print('💡 Decoded Message:') print(decoded_message) if message == decoded_message: print('\n✅ The initial message and the decoded message are identical') else: print('\n❌ The initial message and the decoded message are different') return True, corr
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
#!/usr/bin/env python3 # Author: Daniel Escanez-Exposito from crypto.e91.receiver import Receiver from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from numpy.random import uniform ## The Eveasdropper entity in the E91 implementation ## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html class Eveasdropper(Receiver): ## Constructor def __init__(self, name='', original_bits_size=0, qr=QuantumRegister(2, name="qr"), cr=ClassicalRegister(4, name="cr")): super().__init__(name, original_bits_size, qr, cr) ## Chosen measurements setter def set_axes(self, axes=None, density=0.0): self._calculate_measurements() if axes == None: self.axes = [] for _ in range(self.original_bits_size): if uniform(0, 1) <= density: if uniform(0, 1) <= 0.5: # in 50% of cases perform the WW measurement self.axes.append(['ea2', 'eb1']) else: # in 50% of cases perform the ZZ measurement self.axes.append(['ea3', 'eb2']) else: self.axes.append(None) else: self.axes = axes def _calculate_measurements(self): self.measurements = {} qr = self.qr cr = self.cr # Measurement of the spin projection of Alice's qubit onto the a_2 direction (W basis) self.measurements['ea2'] = QuantumCircuit(qr, cr, name='measureEA2') self.measurements['ea2'].s(qr[0]) self.measurements['ea2'].h(qr[0]) self.measurements['ea2'].t(qr[0]) self.measurements['ea2'].h(qr[0]) self.measurements['ea2'].measure(qr[0], cr[2]) # Measurement of the spin projection of Allice's qubit onto the a_3 direction (standard Z basis) self.measurements['ea3'] = QuantumCircuit(qr, cr, name='measureEA3') self.measurements['ea3'].measure(qr[0], cr[2]) # Measurement of the spin projection of Bob's qubit onto the b_1 direction (W basis) self.measurements['eb1'] = QuantumCircuit(qr, cr, name='measureEB1') self.measurements['eb1'].s(qr[1]) self.measurements['eb1'].h(qr[1]) self.measurements['eb1'].t(qr[1]) self.measurements['eb1'].h(qr[1]) self.measurements['eb1'].measure(qr[1], cr[3]) # Measurement of the spin projection of Bob's qubit onto the b_2 direction (standard Z measurement) self.measurements['eb2'] = QuantumCircuit(qr, cr, name='measureEB2') self.measurements['eb2'].measure(qr[1], cr[3]) # Create the key with the circuit measurement results def create_values(self, result, circuits): for i in range(self.original_bits_size): if self.axes[i] != None: res = list(result.get_counts(circuits[i]).keys())[0] self.values.append([int(res[0]), int(res[1])]) else: self.values.append([None, None])
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
#!/usr/bin/env python3 # Author: Daniel Escanez-Exposito from abc import ABC, abstractmethod from qiskit import QuantumCircuit from qiskit.circuit.library import YGate, ZGate from qiskit.circuit.gate import Gate import qiskit.quantum_info as qi from numpy.random import randint import numpy as np from math import ceil ## An abstract class of a participant entity in the Six-State implementation ## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html class Participant(ABC): ## Constructor @abstractmethod def __init__(self, name='', original_bits_size=0): ## The name of the participant self.name = name ## The original size of the message self.original_bits_size = original_bits_size ## The values of the participant self.values = None ## The axes of the participant self.axes = None ## The key of the participant self.key = None ## If the key is determined safe self.is_safe_key = False ## The otp of the participant self.otp = None ## The gate measuring z and y axes self.set_hy() ## Values setter def set_values(self, values=None): if values == None: self.values = list(randint(2, size=self.original_bits_size)) else: self.values = values ## Axes setter def set_axes(self, axes=None): if axes == None: self.axes = list(randint(3, size=self.original_bits_size)) else: self.axes = axes ## Print values def show_values(self): print('\n' + self.name, 'Values:') print(self.values) ## Print axes def show_axes(self): print('\n' + self.name, 'Axes:') print(self.axes) ## Print key def show_key(self): print('\n' + self.name, 'Key:') print(self.key) ## Print otp def show_otp(self): print('\n' + self.name, 'OTP:') print(self.otp) ## Remove the values of the qubits that were measured on the wrong axis def remove_garbage(self, another_axes): self.key = [] for i in range(self.original_bits_size): if self.axes[i] == another_axes[i]: self.key.append(self.values[i]) ## Check if the shared key is equal to the current key def check_key(self, shared_key): return shared_key == self.key[:len(shared_key)] ## Use the rest of the key and validate it def confirm_key(self, shared_size): self.key = self.key[shared_size:] self.is_safe_key = True ## Generate an One-Time Pad def generate_otp(self, n_bits): self.otp = [] for i in range(ceil(len(self.key) / n_bits)): bits_string = ''.join(map(str, self.key[i * n_bits: (i + 1) * n_bits])) self.otp.append(int(bits_string, 2)) ## Performs an XOR operation between the message and the One-Time Pad def xor_otp_message(self, message): final_message = '' CHR_LIMIT = 1114112 if len(self.otp) > 0: for i, char in enumerate(message): final_message += chr((ord(char) ^ self.otp[i % len(self.otp)]) % CHR_LIMIT) return final_message ## New gate setter def set_hy(self): hy_op = qi.Operator(1/np.sqrt(2)*(YGate().to_matrix() + ZGate().to_matrix())) hy_gate = QuantumCircuit(1) hy_gate.unitary(hy_op, [0], label='h_y') self.hy = hy_gate.to_gate()